LSTM.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from __future__ import annotations
  2. import json
  3. import os
  4. import torch
  5. from safetensors.torch import load_model as load_safetensors_model
  6. from safetensors.torch import save_model as save_safetensors_model
  7. from torch import nn
  8. class LSTM(nn.Module):
  9. """Bidirectional LSTM running over word embeddings."""
  10. def __init__(
  11. self,
  12. word_embedding_dimension: int,
  13. hidden_dim: int,
  14. num_layers: int = 1,
  15. dropout: float = 0,
  16. bidirectional: bool = True,
  17. ):
  18. nn.Module.__init__(self)
  19. self.config_keys = ["word_embedding_dimension", "hidden_dim", "num_layers", "dropout", "bidirectional"]
  20. self.word_embedding_dimension = word_embedding_dimension
  21. self.hidden_dim = hidden_dim
  22. self.num_layers = num_layers
  23. self.dropout = dropout
  24. self.bidirectional = bidirectional
  25. self.embeddings_dimension = hidden_dim
  26. if self.bidirectional:
  27. self.embeddings_dimension *= 2
  28. self.encoder = nn.LSTM(
  29. word_embedding_dimension,
  30. hidden_dim,
  31. num_layers=num_layers,
  32. dropout=dropout,
  33. bidirectional=bidirectional,
  34. batch_first=True,
  35. )
  36. def forward(self, features):
  37. token_embeddings = features["token_embeddings"]
  38. sentence_lengths = torch.clamp(features["sentence_lengths"], min=1)
  39. packed = nn.utils.rnn.pack_padded_sequence(
  40. token_embeddings, sentence_lengths.cpu(), batch_first=True, enforce_sorted=False
  41. )
  42. packed = self.encoder(packed)
  43. unpack = nn.utils.rnn.pad_packed_sequence(packed[0], batch_first=True)[0]
  44. features.update({"token_embeddings": unpack})
  45. return features
  46. def get_word_embedding_dimension(self) -> int:
  47. return self.embeddings_dimension
  48. def tokenize(self, text: str, **kwargs) -> list[int]:
  49. raise NotImplementedError()
  50. def save(self, output_path: str, safe_serialization: bool = True):
  51. with open(os.path.join(output_path, "lstm_config.json"), "w") as fOut:
  52. json.dump(self.get_config_dict(), fOut, indent=2)
  53. device = next(self.parameters()).device
  54. if safe_serialization:
  55. save_safetensors_model(self.cpu(), os.path.join(output_path, "model.safetensors"))
  56. self.to(device)
  57. else:
  58. torch.save(self.state_dict(), os.path.join(output_path, "pytorch_model.bin"))
  59. def get_config_dict(self):
  60. return {key: self.__dict__[key] for key in self.config_keys}
  61. @staticmethod
  62. def load(input_path: str):
  63. with open(os.path.join(input_path, "lstm_config.json")) as fIn:
  64. config = json.load(fIn)
  65. model = LSTM(**config)
  66. if os.path.exists(os.path.join(input_path, "model.safetensors")):
  67. load_safetensors_model(model, os.path.join(input_path, "model.safetensors"))
  68. else:
  69. model.load_state_dict(
  70. torch.load(
  71. os.path.join(input_path, "pytorch_model.bin"), map_location=torch.device("cpu"), weights_only=True
  72. )
  73. )
  74. return model