Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

base_transformer.py 9.9 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
  1. # from email.generator import Generator
  2. import math
  3. from functools import partial
  4. import pytorch_lightning as pl
  5. import torch
  6. import torch.nn as nn
  7. from torch.optim.lr_scheduler import OneCycleLR
  8. from molbart.models.util import FuncLR
  9. # ----------------------------------------------------------------------------------------------------------
  10. # ----------------------------------------- Base Transformer Model -----------------------------------------
  11. # ----------------------------------------------------------------------------------------------------------
  12. class _AbsTransformerModel(pl.LightningModule):
  13. def __init__(
  14. self,
  15. pad_token_idx,
  16. vocabulary_size,
  17. d_model,
  18. num_layers,
  19. num_heads,
  20. d_feedforward,
  21. lr,
  22. weight_decay,
  23. activation,
  24. num_steps,
  25. max_seq_len,
  26. schedule,
  27. warm_up_steps,
  28. dropout=0.1,
  29. num_beams=10,
  30. **kwargs,
  31. ):
  32. super().__init__()
  33. self.pad_token_idx = pad_token_idx
  34. self.vocabulary_size = vocabulary_size
  35. self.d_model = d_model
  36. self.num_layers = num_layers
  37. self.num_heads = num_heads
  38. self.d_feedforward = d_feedforward
  39. self.lr = lr
  40. self.weight_decay = weight_decay
  41. self.activation = activation
  42. self.num_steps = num_steps
  43. self.max_seq_len = max_seq_len
  44. self.schedule = schedule
  45. self.warm_up_steps = warm_up_steps
  46. self.dropout = dropout
  47. if self.schedule == "transformer":
  48. assert warm_up_steps is not None, "A value for warm_up_steps is required for transformer LR schedule"
  49. # Additional args passed in to **kwargs in init will also be saved
  50. self.save_hyperparameters()
  51. # These must be set by subclasses
  52. self.sampler = None
  53. self.val_sampling_alg = "greedy"
  54. self.test_sampling_alg = "beam"
  55. self.num_beams = num_beams
  56. self.n_unique_beams = num_beams
  57. self.emb = nn.Embedding(vocabulary_size, d_model, padding_idx=pad_token_idx)
  58. self.dropout = nn.Dropout(dropout)
  59. self.register_buffer("pos_emb", self._positional_embs())
  60. def forward(self, x):
  61. raise NotImplementedError()
  62. def _calc_loss(self, batch_input, model_output):
  63. """Calculate the loss for the model
  64. Args:
  65. batch_input (dict): Input given to model,
  66. model_output (dict): Output from model
  67. Returns:
  68. loss (singleton tensor)
  69. """
  70. raise NotImplementedError()
  71. def sample_molecules(self, batch_input, sampling_alg="greedy"):
  72. """Sample molecules from the model
  73. Args:
  74. batch_input (dict): Input given to model
  75. sampling_alg (str): Algorithm to use to sample SMILES strings from model
  76. Returns:
  77. ([[str]], [[float]]): Tuple of molecule SMILES strings and log lhs (outer dimension is batch)
  78. """
  79. raise NotImplementedError()
  80. def training_step(self, batch, batch_idx):
  81. self.train()
  82. model_output = self.forward(batch)
  83. loss = self._calc_loss(batch, model_output)
  84. self.log("training_loss", loss, on_step=True, logger=True, sync_dist=True)
  85. return loss
  86. def validation_step(self, batch, batch_idx):
  87. self.eval()
  88. with torch.no_grad():
  89. model_output = self.forward(batch)
  90. target_smiles = batch["target_smiles"]
  91. loss = self._calc_loss(batch, model_output)
  92. token_acc = self._calc_token_acc(batch, model_output)
  93. sampled_smiles, _ = self.sample_molecules(batch, sampling_alg=self.val_sampling_alg)
  94. sampled_metrics = self.sampler.compute_sampling_metrics(sampled_smiles, target_smiles)
  95. metrics = {
  96. "validation_loss": loss,
  97. "val_token_accuracy": token_acc,
  98. }
  99. metrics.update(sampled_metrics)
  100. return metrics
  101. def validation_epoch_end(self, outputs):
  102. avg_outputs = self._avg_dicts(outputs)
  103. self._log_dict(avg_outputs)
  104. return
  105. def test_step(self, batch, batch_idx):
  106. self.eval()
  107. with torch.no_grad():
  108. model_output = self.forward(batch)
  109. target_smiles = batch["target_smiles"]
  110. loss = self._calc_loss(batch, model_output)
  111. token_acc = self._calc_token_acc(batch, model_output)
  112. sampled_smiles, log_likelihoods = self.sample_molecules(batch, sampling_alg=self.test_sampling_alg)
  113. sampled_metrics = self.sampler.compute_sampling_metrics(sampled_smiles, target_smiles)
  114. metrics = {
  115. "batch_idx": batch_idx,
  116. "test_loss": loss.item(),
  117. "test_token_accuracy": token_acc,
  118. "log_lhs": log_likelihoods,
  119. "sampled_molecules": sampled_smiles,
  120. "target_smiles": target_smiles,
  121. }
  122. metrics.update(sampled_metrics)
  123. return metrics
  124. def test_epoch_end(self, outputs):
  125. # avg_outputs = self._avg_dicts(outputs)
  126. # self._log_dict(avg_outputs)
  127. return
  128. def configure_optimizers(self):
  129. params = self.parameters()
  130. optim = torch.optim.Adam(params, lr=self.lr, weight_decay=self.weight_decay, betas=(0.9, 0.999))
  131. if self.schedule == "const":
  132. print("Using constant LR schedule.")
  133. const_sch = FuncLR(optim, lr_lambda=self._const_lr)
  134. sch = {"scheduler": const_sch, "interval": "step"}
  135. elif self.schedule == "cycle":
  136. print("Using cyclical LR schedule.")
  137. cycle_sch = OneCycleLR(optim, self.lr, total_steps=self.num_steps)
  138. sch = {"scheduler": cycle_sch, "interval": "step"}
  139. elif self.schedule == "transformer":
  140. print("Using original transformer schedule.")
  141. trans_sch = FuncLR(optim, lr_lambda=self._transformer_lr)
  142. sch = {"scheduler": trans_sch, "interval": "step"}
  143. else:
  144. raise ValueError(f"Unknown schedule {self.schedule}")
  145. return [optim], [sch]
  146. def _transformer_lr(self, step):
  147. mult = self.d_model**-0.5
  148. step = 1 if step == 0 else step # Stop div by zero errors
  149. lr = min(step**-0.5, step * (self.warm_up_steps**-1.5))
  150. return self.lr * mult * lr
  151. def _const_lr(self, step):
  152. if self.warm_up_steps is not None and step < self.warm_up_steps:
  153. return (self.lr / self.warm_up_steps) * step
  154. return self.lr
  155. def _construct_input(self, token_ids, sentence_masks=None):
  156. seq_len, _ = tuple(token_ids.size())
  157. token_embs = self.emb(token_ids)
  158. # Scaling the embeddings like this is done in other transformer libraries
  159. token_embs = token_embs * math.sqrt(self.d_model)
  160. positional_embs = self.pos_emb[:seq_len, :].unsqueeze(0).transpose(0, 1)
  161. embs = token_embs + positional_embs
  162. embs = self.dropout(embs)
  163. return embs
  164. def _positional_embs(self):
  165. """Produces a tensor of positional embeddings for the model
  166. Returns a tensor of shape (self.max_seq_len, self.d_model) filled with positional embeddings,
  167. which are created from sine and cosine waves of varying wavelength
  168. """
  169. encs = torch.tensor([dim / self.d_model for dim in range(0, self.d_model, 2)])
  170. encs = 10000**encs
  171. encs = [(torch.sin(pos / encs), torch.cos(pos / encs)) for pos in range(self.max_seq_len)]
  172. encs = [torch.stack(enc, dim=1).flatten()[: self.d_model] for enc in encs]
  173. encs = torch.stack(encs)
  174. return encs
  175. def _generate_square_subsequent_mask(self, sz, device="cpu"):
  176. """
  177. Method copied from Pytorch nn.Transformer.
  178. Generate a square mask for the sequence. The masked positions are filled with float('-inf').
  179. Unmasked positions are filled with float(0.0).
  180. Args:
  181. sz (int): Size of mask to generate
  182. Returns:
  183. torch.Tensor: Square autoregressive mask for decode
  184. """
  185. mask = (torch.triu(torch.ones((sz, sz), device=device)) == 1).transpose(0, 1)
  186. mask = mask.float().masked_fill(mask == 0, float("-inf")).masked_fill(mask == 1, float(0.0))
  187. return mask
  188. def _init_params(self):
  189. """
  190. Apply Xavier uniform initialisation of learnable weights
  191. """
  192. for p in self.parameters():
  193. if p.dim() > 1:
  194. nn.init.xavier_uniform_(p)
  195. def _calc_perplexity(self, batch_input, model_output):
  196. target_ids = batch_input["target"]
  197. target_mask = batch_input["target_mask"]
  198. vocab_dist_output = model_output["token_output"]
  199. inv_target_mask = ~(target_mask > 0)
  200. log_probs = vocab_dist_output.gather(2, target_ids.unsqueeze(2)).squeeze(2)
  201. log_probs = log_probs * inv_target_mask
  202. log_probs = log_probs.sum(dim=0)
  203. seq_lengths = inv_target_mask.sum(dim=0)
  204. exp = -(1 / seq_lengths)
  205. perp = torch.pow(log_probs.exp(), exp)
  206. return perp.mean()
  207. def _calc_token_acc(self, batch_input, model_output):
  208. token_ids = batch_input["target"]
  209. target_mask = batch_input["target_mask"]
  210. token_output = model_output["token_output"]
  211. target_mask = ~(target_mask > 0)
  212. _, pred_ids = torch.max(token_output.float(), dim=2)
  213. correct_ids = torch.eq(token_ids, pred_ids)
  214. correct_ids = correct_ids * target_mask
  215. num_correct = correct_ids.sum().float()
  216. total = target_mask.sum().float()
  217. accuracy = num_correct / total
  218. return accuracy
  219. def _avg_dicts(self, colls):
  220. complete_dict = {key: [] for key, val in colls[0].items()}
  221. for coll in colls:
  222. [complete_dict[key].append(coll[key]) for key in complete_dict.keys()]
  223. avg_dict = {key: sum(l) / len(l) for key, l in complete_dict.items()}
  224. return avg_dict
  225. def _log_dict(self, coll):
  226. for key, val in coll.items():
  227. self.log(key, val, sync_dist=True)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...