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

transformer_models.py 18 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
  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 import _AbsTransformerModel
  9. from molbart.models.util import PreNormDecoderLayer, PreNormEncoderLayer
  10. # ----------------------------------------------------------------------------------------------------------
  11. # -------------------------------------------- Pre-train Models --------------------------------------------
  12. # ----------------------------------------------------------------------------------------------------------
  13. class BARTModel(_AbsTransformerModel):
  14. def __init__(
  15. self,
  16. decode_sampler,
  17. pad_token_idx,
  18. vocabulary_size,
  19. d_model,
  20. num_layers,
  21. num_heads,
  22. d_feedforward,
  23. lr,
  24. weight_decay,
  25. activation,
  26. num_steps,
  27. max_seq_len,
  28. schedule="cycle",
  29. warm_up_steps=None,
  30. dropout=0.1,
  31. **kwargs,
  32. ):
  33. super().__init__(
  34. pad_token_idx,
  35. vocabulary_size,
  36. d_model,
  37. num_layers,
  38. num_heads,
  39. d_feedforward,
  40. lr,
  41. weight_decay,
  42. activation,
  43. num_steps,
  44. max_seq_len,
  45. schedule,
  46. warm_up_steps,
  47. dropout,
  48. **kwargs,
  49. )
  50. self.sampler = decode_sampler
  51. self.val_sampling_alg = "greedy"
  52. self.test_sampling_alg = "beam"
  53. self.encoder = nn.TransformerEncoder(
  54. PreNormEncoderLayer(d_model, num_heads, d_feedforward, dropout, activation),
  55. num_layers,
  56. norm=nn.LayerNorm(d_model),
  57. )
  58. self.decoder = nn.TransformerDecoder(
  59. PreNormDecoderLayer(d_model, num_heads, d_feedforward, dropout, activation),
  60. num_layers,
  61. norm=nn.LayerNorm(d_model),
  62. )
  63. self.loss_function = nn.CrossEntropyLoss(reduction="none", ignore_index=pad_token_idx)
  64. self.token_fc = nn.Linear(d_model, vocabulary_size)
  65. self.log_softmax = nn.LogSoftmax(dim=2)
  66. self._init_params()
  67. def forward(self, x):
  68. """Apply SMILES strings to model
  69. The dictionary returned will be passed to other functions, so its contents are fairly flexible,
  70. except that it must contain the key "token_output" which is the output of the model
  71. (possibly after any fully connected layers) for each token.
  72. Arg:
  73. x (dict {
  74. "encoder_input": tensor of token_ids of shape (src_len, batch_size),
  75. "encoder_pad_mask": bool tensor of padded elems of shape (src_len, batch_size),
  76. "decoder_input": tensor of decoder token_ids of shape (tgt_len, batch_size)
  77. "decoder_pad_mask": bool tensor of decoder padding mask of shape (tgt_len, batch_size)
  78. }):
  79. Returns:
  80. Output from model (dict containing key "token_output" and "model_output")
  81. """
  82. encoder_input = x["encoder_input"]
  83. decoder_input = x["decoder_input"]
  84. encoder_pad_mask = x["encoder_pad_mask"].transpose(0, 1)
  85. decoder_pad_mask = x["decoder_pad_mask"].transpose(0, 1)
  86. encoder_embs = self._construct_input(encoder_input)
  87. decoder_embeddings = self._construct_input(decoder_input)
  88. seq_len, _, _ = tuple(decoder_embeddings.size())
  89. tgt_mask = self._generate_square_subsequent_mask(seq_len, device=encoder_embs.device)
  90. memory = self.encoder(encoder_embs, src_key_padding_mask=encoder_pad_mask)
  91. model_output = self.decoder(
  92. decoder_embeddings,
  93. memory,
  94. tgt_mask=tgt_mask,
  95. tgt_key_padding_mask=decoder_pad_mask,
  96. memory_key_padding_mask=encoder_pad_mask.clone(),
  97. )
  98. token_output = self.token_fc(model_output)
  99. output = {"model_output": model_output, "token_output": token_output}
  100. return output
  101. def encode(self, batch):
  102. """Construct the memory embedding for an encoder input
  103. Args:
  104. batch (dict {
  105. "encoder_input": tensor of token_ids of shape (src_len, batch_size),
  106. "encoder_pad_mask": bool tensor of padded elems of shape (src_len, batch_size),
  107. })
  108. Returns:
  109. encoder memory (Tensor of shape (seq_len, batch_size, d_model))
  110. """
  111. encoder_input = batch["encoder_input"]
  112. encoder_pad_mask = batch["encoder_pad_mask"].transpose(0, 1)
  113. encoder_embs = self._construct_input(encoder_input)
  114. model_output = self.encoder(encoder_embs, src_key_padding_mask=encoder_pad_mask)
  115. return model_output
  116. def decode(self, batch):
  117. """Construct an output from a given decoder input
  118. Args:
  119. batch (dict {
  120. "decoder_input": tensor of decoder token_ids of shape (tgt_len, batch_size)
  121. "decoder_pad_mask": bool tensor of decoder padding mask of shape (tgt_len, batch_size)
  122. "memory_input": tensor from encoded input of shape (src_len, batch_size, d_model)
  123. "memory_pad_mask": bool tensor of memory padding mask of shape (src_len, batch_size)
  124. })
  125. """
  126. decoder_input = batch["decoder_input"]
  127. decoder_pad_mask = batch["decoder_pad_mask"].transpose(0, 1)
  128. memory_input = batch["memory_input"]
  129. memory_pad_mask = batch["memory_pad_mask"].transpose(0, 1)
  130. decoder_embeddings = self._construct_input(decoder_input)
  131. sequence_length, _, _ = tuple(decoder_embeddings.size())
  132. tgt_mask = self._generate_square_subsequent_mask(sequence_length, device=decoder_embeddings.device)
  133. decoder_output = self.decoder(
  134. decoder_embeddings,
  135. memory_input,
  136. tgt_key_padding_mask=decoder_pad_mask,
  137. memory_key_padding_mask=memory_pad_mask,
  138. tgt_mask=tgt_mask,
  139. )
  140. token_log_probabilities = self.generator(decoder_output)
  141. return token_log_probabilities
  142. def generator(self, decoder_output):
  143. token_log_probabilities = self.log_softmax(self.token_fc(decoder_output))
  144. return token_log_probabilities
  145. def _calc_loss(self, batch_input, model_output):
  146. """Calculate the loss for the model
  147. Args:
  148. batch_input (dict): Input given to model,
  149. model_output (dict): Output from model
  150. Returns:
  151. loss (singleton tensor),
  152. """
  153. tokens = batch_input["target"]
  154. pad_mask = batch_input["target_mask"]
  155. token_output = model_output["token_output"]
  156. token_mask_loss = self._calc_mask_loss(token_output, tokens, pad_mask)
  157. return token_mask_loss
  158. def _calc_mask_loss(self, token_output, target, target_mask):
  159. """Calculate the loss for the token prediction task
  160. Args:
  161. token_output (Tensor of shape (seq_len, batch_size, vocabulary_size)): token output from transformer
  162. target (Tensor of shape (seq_len, batch_size)): Original (unmasked) SMILES token ids from the tokeniser
  163. target_mask (Tensor of shape (seq_len, batch_size)): Pad mask for target tokens
  164. Output:
  165. loss (singleton Tensor): Loss computed using cross-entropy,
  166. """
  167. seq_len, batch_size = tuple(target.size())
  168. token_pred = token_output.reshape((seq_len * batch_size, -1)).float()
  169. loss = self.loss_function(token_pred, target.reshape(-1)).reshape((seq_len, batch_size))
  170. inv_target_mask = ~(target_mask > 0)
  171. num_tokens = inv_target_mask.sum()
  172. loss = loss.sum() / num_tokens
  173. return loss
  174. def sample_molecules(self, batch_input, sampling_alg="greedy", return_tokenized=False):
  175. """Sample molecules from the model
  176. Args:
  177. batch_input (dict): Input given to model
  178. sampling_alg (str): Algorithm to use to sample SMILES strings from model
  179. Returns:
  180. ([[str]], [[float]]): Tuple of molecule SMILES strings and log lhs (outer dimension is batch)
  181. """
  182. # Freezing the weights reduces the amount of memory leakage in the transformer
  183. self.freeze()
  184. if hasattr(self.sampler, "sample_molecules"):
  185. mol_strs, log_lhs = self.sampler.sample_molecules(
  186. self,
  187. batch_input,
  188. self.num_beams,
  189. sampling_alg,
  190. return_tokenized=return_tokenized,
  191. )
  192. else:
  193. enc_input = batch_input["encoder_input"]
  194. enc_mask = batch_input["encoder_pad_mask"]
  195. encode_input = {"encoder_input": enc_input, "encoder_pad_mask": enc_mask}
  196. memory = self.encode(encode_input)
  197. mem_mask = enc_mask.clone()
  198. _, batch_size, _ = tuple(memory.size())
  199. decode_fn = partial(self._decode_fn, memory=memory, mem_pad_mask=mem_mask)
  200. if sampling_alg == "greedy":
  201. mol_strs, log_lhs = self.sampler.greedy_decode(decode_fn, batch_size, memory.device)
  202. elif sampling_alg == "beam":
  203. mol_strs, log_lhs = self.sampler.beam_decode(decode_fn, batch_size, memory.device, k=self.num_beams)
  204. else:
  205. raise ValueError(f"Unknown sampling algorithm {sampling_alg}")
  206. # Must remember to unfreeze!
  207. self.unfreeze()
  208. return mol_strs, log_lhs
  209. def _decode_fn(self, token_ids, pad_mask, memory, mem_pad_mask):
  210. decode_input = {
  211. "decoder_input": token_ids,
  212. "decoder_pad_mask": pad_mask,
  213. "memory_input": memory,
  214. "memory_pad_mask": mem_pad_mask,
  215. }
  216. model_output = self.decode(decode_input)
  217. return model_output
  218. def decode_batch(self, batch, return_last=True):
  219. """Construct an output from a given decoder input
  220. Args:
  221. batch (dict {
  222. "decoder_input": tensor of decoder token_ids of shape (tgt_len, batch_size)
  223. "decoder_pad_mask": bool tensor of decoder padding mask of shape (tgt_len, batch_size)
  224. "memory_input": tensor from encoded input of shape (src_len, batch_size, d_model)
  225. "memory_pad_mask": bool tensor of memory padding mask of shape (src_len, batch_size)
  226. })
  227. """
  228. decoder_input = batch["decoder_input"].transpose(0, 1)
  229. memory_input = batch["memory_input"].permute(1, 0, 2)
  230. memory_pad_mask = batch["memory_pad_mask"]
  231. decoder_embeddings = self._construct_input(decoder_input)
  232. seq_len, _, _ = tuple(decoder_embeddings.size())
  233. tgt_mask = self._generate_square_subsequent_mask(seq_len, device=decoder_embeddings.device).to(
  234. decoder_embeddings.device
  235. )
  236. decoder_output = self.decoder(
  237. decoder_embeddings,
  238. memory_input,
  239. memory_key_padding_mask=memory_pad_mask,
  240. tgt_mask=tgt_mask,
  241. )
  242. token_probabilities = self.generator(decoder_output)
  243. if return_last:
  244. return token_probabilities[-1, :, :]
  245. else:
  246. return token_probabilities
  247. class UnifiedModel(_AbsTransformerModel):
  248. def __init__(
  249. self,
  250. decode_sampler,
  251. pad_token_idx,
  252. vocabulary_size,
  253. d_model,
  254. num_layers,
  255. num_heads,
  256. d_feedforward,
  257. lr,
  258. weight_decay,
  259. activation,
  260. num_steps,
  261. max_seq_len,
  262. schedule="cycle",
  263. warm_up_steps=None,
  264. dropout=0.1,
  265. **kwargs,
  266. ):
  267. super().__init__(
  268. pad_token_idx,
  269. vocabulary_size,
  270. d_model,
  271. num_layers,
  272. num_heads,
  273. d_feedforward,
  274. lr,
  275. weight_decay,
  276. activation,
  277. num_steps,
  278. max_seq_len,
  279. schedule,
  280. warm_up_steps,
  281. dropout,
  282. **kwargs,
  283. )
  284. self.sampler = decode_sampler
  285. self.val_sampling_alg = "greedy"
  286. self.test_sampling_alg = "beam"
  287. enc_norm = nn.LayerNorm(d_model)
  288. enc_layer = PreNormEncoderLayer(d_model, num_heads, d_feedforward, dropout, activation)
  289. self.encoder = nn.TransformerEncoder(enc_layer, num_layers, norm=enc_norm)
  290. self.token_fc = nn.Linear(d_model, vocabulary_size)
  291. self.loss_function = nn.CrossEntropyLoss(reduction="none", ignore_index=pad_token_idx)
  292. self.log_softmax = nn.LogSoftmax(dim=2)
  293. self._init_params()
  294. def forward(self, x):
  295. """Apply SMILES strings to model
  296. The dictionary returned will be passed to other functions, so its contents are fairly flexible,
  297. except that it must contain the key "token_output" which is the output of the model
  298. (possibly after any fully connected layers) for each token.
  299. Arg:
  300. x (dict {
  301. "encoder_input": tensor of token_ids of shape (src_len, batch_size),
  302. "encoder_pad_mask": bool tensor of padded elems of shape (src_len, batch_size),
  303. "decoder_input": tensor of decoder token_ids of shape (tgt_len, batch_size)
  304. "decoder_pad_mask": bool tensor of decoder padding mask of shape (tgt_len, batch_size)
  305. }):
  306. Returns:
  307. Output from model (dict containing key "token_output" and "model_output")
  308. """
  309. enc_input = x["encoder_input"]
  310. enc_mask = x["encoder_pad_mask"]
  311. dec_input = x["decoder_input"]
  312. dec_mask = x["decoder_pad_mask"]
  313. att_mask = x["attention_mask"]
  314. model_input = torch.cat((enc_input, dec_input), dim=0)
  315. pad_mask = torch.cat((enc_mask, dec_mask), dim=0).transpose(0, 1)
  316. embs = self._construct_input(model_input)
  317. model_output = self.encoder(embs, mask=att_mask, src_key_padding_mask=pad_mask)
  318. token_output = self.token_fc(model_output)
  319. output = {"model_output": model_output, "token_output": token_output}
  320. return output
  321. def _calc_loss(self, batch_input, model_output):
  322. """Calculate the loss for the model
  323. Args:
  324. batch_input (dict): Input given to model,
  325. model_output (dict): Output from model
  326. Returns:
  327. loss (singleton tensor),
  328. """
  329. tokens = batch_input["target"]
  330. tgt_mask = batch_input["target_mask"]
  331. token_output = model_output["token_output"]
  332. token_mask_loss = self._calc_mask_loss(token_output, tokens, tgt_mask)
  333. return token_mask_loss
  334. def _calc_mask_loss(self, token_output, target, target_mask):
  335. """Calculate the loss for the token prediction task
  336. Args:
  337. token_output (Tensor of shape (seq_len, batch_size, vocabulary_size)): token output from transformer
  338. target (Tensor of shape (seq_len, batch_size)): Original (unmasked) SMILES token ids from the tokeniser
  339. target_mask (Tensor of shape (seq_len, batch_size)): Pad mask for target tokens
  340. Output:
  341. loss (singleton Tensor): Loss computed using cross-entropy,
  342. """
  343. seq_len, batch_size, _ = tuple(token_output.size())
  344. tgt_len, tgt_batch_size = tuple(target.size())
  345. assert seq_len == tgt_len
  346. assert batch_size == tgt_batch_size
  347. token_pred = token_output.reshape((seq_len * batch_size, -1)).float()
  348. loss = self.loss_function(token_pred, target.reshape(-1)).reshape((seq_len, batch_size))
  349. inv_target_mask = ~target_mask
  350. num_tokens = inv_target_mask.sum()
  351. loss = loss * inv_target_mask
  352. loss = loss.sum() / num_tokens
  353. return loss
  354. def sample_molecules(self, batch_input, sampling_alg="greedy"):
  355. """Sample molecules from the model
  356. Args:
  357. batch_input (dict): Input given to model
  358. sampling_alg (str): Algorithm to use to sample SMILES strings from model
  359. Returns:
  360. ([[str]], [[float]]): Tuple of molecule SMILES strings and log lhs (outer dimension is batch)
  361. """
  362. enc_token_ids = batch_input["encoder_input"]
  363. enc_pad_mask = batch_input["encoder_pad_mask"]
  364. # Freezing the weights reduces the amount of memory leakage in the transformer
  365. self.freeze()
  366. enc_seq_len, batch_size = tuple(enc_token_ids.size())
  367. self.sampler.max_seq_len = self.max_seq_len - enc_seq_len
  368. decode_fn = partial(self._decode_fn, enc_token_ids=enc_token_ids, enc_pad_mask=enc_pad_mask)
  369. if sampling_alg == "greedy":
  370. mol_strs, log_lhs = self.sampler.greedy_decode(decode_fn, batch_size, enc_token_ids.device)
  371. elif sampling_alg == "beam":
  372. mol_strs, log_lhs = self.sampler.beam_decode(decode_fn, batch_size, enc_token_ids.device, k=self.num_beams)
  373. else:
  374. raise ValueError(f"Unknown sampling algorithm {sampling_alg}")
  375. # Must remember to unfreeze!
  376. self.unfreeze()
  377. return mol_strs, log_lhs
  378. def _decode_fn(self, token_ids, pad_mask, enc_token_ids, enc_pad_mask):
  379. # Strip off the start token for the decoded sequence
  380. dec_token_ids = token_ids[1:, :]
  381. enc_length, _ = tuple(enc_token_ids.shape)
  382. dec_length, _ = tuple(dec_token_ids.shape)
  383. att_mask = self._build_att_mask(enc_length - 1, dec_length + 1, device=dec_token_ids.device)
  384. model_input = {
  385. "encoder_input": enc_token_ids,
  386. "encoder_pad_mask": enc_pad_mask,
  387. "decoder_input": dec_token_ids,
  388. "decoder_pad_mask": pad_mask[1:, :],
  389. "attention_mask": att_mask,
  390. }
  391. token_output = self.forward(model_input)["token_output"]
  392. token_probs = self.log_softmax(token_output)
  393. return token_probs
  394. def _build_att_mask(self, enc_length, dec_length, device="cpu"):
  395. seq_len = enc_length + dec_length
  396. enc_mask = torch.zeros((seq_len, enc_length), device=device)
  397. upper_dec_mask = torch.ones((enc_length, dec_length), device=device)
  398. lower_dec_mask = torch.ones((dec_length, dec_length), device=device).triu_(1)
  399. dec_mask = torch.cat((upper_dec_mask, lower_dec_mask), dim=0)
  400. mask = torch.cat((enc_mask, dec_mask), dim=1)
  401. mask = mask.masked_fill(mask == 1, float("-inf"))
  402. return mask
Tip!

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

Comments

Loading...