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

chemformer.py 25 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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
  1. import os
  2. from argparse import Namespace
  3. from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
  4. import numpy as np
  5. import pandas as pd
  6. import pytorch_lightning as pl
  7. import torch
  8. from omegaconf import DictConfig, ListConfig
  9. from torch.utils.data import DataLoader
  10. from molbart.data import DataCollection
  11. import molbart.utils.data_utils as util
  12. from molbart.models import BARTModel, UnifiedModel
  13. from molbart.utils.samplers import BeamSearchSampler
  14. from molbart.utils.tokenizers import ChemformerTokenizer
  15. from molbart.utils import trainer_utils
  16. DEFAULT_WEIGHT_DECAY = 0
  17. class Chemformer:
  18. """
  19. Class for building (synthesis) Chemformer model, fine-tuning seq-seq model,
  20. and predicting/scoring model.
  21. """
  22. def __init__(
  23. self,
  24. config: DictConfig,
  25. ) -> None:
  26. """
  27. Args:
  28. config: OmegaConf config loaded by hydra. Contains the input args of the model,
  29. including vocabulary, model checkpoint, beam size, etc.
  30. The config includes the following arguments:
  31. # Trainer args
  32. seed: 1
  33. batch_size: 128
  34. n_gpus (int): Number of GPUs to use.
  35. i_chunk: 0 # For inference
  36. n_chunks: 1 # For inference
  37. limit_val_batches: 1.0 # For training
  38. n_buckets: 12 # For training
  39. n_nodes: 1 # For training
  40. acc_batches: 1 # For training
  41. accelerator: null # For training
  42. # Data args
  43. data_path (str): path to data used for training or inference
  44. backward_predictions (str): path to sampled smiles (for round-trip inference)
  45. dataset_part (str): Which dataset split to run inference on. ["full", "train", "val", "test"]
  46. dataset_type (str): The specific dataset type used as input.
  47. datamodule_type (Optinal[str]): The type of datamodule to build (seq2seq).
  48. vocabulary_path (str): path to bart_vocabulary.
  49. task (str): the model task ["forward_prediction", "backward_prediction"]
  50. data_device (str): device used for handling the data in optimized beam search (use cpu if memor issues).
  51. # Model args
  52. model_path (Optional[str]): Path to model weights.
  53. model_type (str): the model type ["bart", "unified"]
  54. n_beams (int): Number of beams / predictions from the sampler.
  55. n_unique_beams (Optional[int]): Restrict number of unique predictions.
  56. If None => return all unique solutions.
  57. train_mode(str): Whether to train the model ("training") or use
  58. model for evaluations ("eval").
  59. train_mode (str): Whether to train the model ("training") or use
  60. model for evaluations ("eval").
  61. device (str): Which device to run model and beam search on ("cuda" / "cpu").
  62. resume_training (bool): Whether to continue training from the supplied
  63. .ckpt file.
  64. learning_rate (float): the learning rate (for training/fine-tuning)
  65. weight_decay (float): the weight decay (for training/fine-tuning)
  66. # Molbart model parameters
  67. d_model (int): 512
  68. n_layers (int): 6
  69. n_heads (int): 8
  70. d_feedforward (int): 2048
  71. callbacks: list of Callbacks
  72. datamodule: the DataModule to use
  73. # Inference args
  74. scorers: list of Scores to evaluate sampled smiles against target smiles
  75. output_score_data: null
  76. output_sampled_smiles: null
  77. """
  78. self.config = config
  79. self.train_mode = config.train_mode
  80. print(f"train mode: {self.train_mode}")
  81. self.train_tokens = config.get("train_tokens")
  82. self.n_buckets = config.get("n_buckets")
  83. self.resume_training = False
  84. if self.train_mode.startswith("train"):
  85. self.resume_training = config.resume
  86. if self.resume_training:
  87. print("Resuming training.")
  88. device = config.get("device", "cuda")
  89. data_device = config.get("data_device", "cuda")
  90. if config.n_gpus < 1:
  91. device = "cpu"
  92. data_device = "cpu"
  93. self.device = device
  94. self.tokenizer = ChemformerTokenizer(filename=config.vocabulary_path)
  95. self.model_type = config.model_type
  96. self.model_path = config.model_path
  97. self.n_gpus = config.n_gpus
  98. self.is_data_setup = False
  99. self.set_datamodule(datamodule_type=config.get("datamodule"))
  100. print("Vocabulary_size: " + str(len(self.tokenizer)))
  101. self.vocabulary_size = len(self.tokenizer)
  102. if self.train_mode.startswith("train"):
  103. self.train_steps = trainer_utils.calc_train_steps(config, self.datamodule, self.n_gpus)
  104. print(f"Train steps: {self.train_steps}")
  105. sample_unique = config.get("n_unique_beams") is not None
  106. self.sampler = BeamSearchSampler(
  107. self.tokenizer,
  108. trainer_utils.instantiate_scorers(self.config.get("scorers")),
  109. util.DEFAULT_MAX_SEQ_LEN,
  110. device=device,
  111. data_device=data_device,
  112. sample_unique=sample_unique,
  113. )
  114. self.build_model(config)
  115. self.model.num_beams = config.n_beams
  116. if sample_unique:
  117. self.model.n_unique_beams = np.min(np.array([self.model.num_beams, config.n_unique_beams]))
  118. self.trainer = None
  119. if "trainer" in self.config:
  120. self.trainer = trainer_utils.build_trainer(config, self.n_gpus)
  121. self.model = self.model.to(device)
  122. return
  123. def encode(
  124. self,
  125. dataset: str = "full",
  126. dataloader: Optional[DataLoader] = None,
  127. ) -> List[torch.Tensor]:
  128. """
  129. Compute memory from transformer inputs.
  130. Args:
  131. dataset (str): (Which part of the dataset to use (["train", "val", "test",
  132. "full"]).)
  133. dataloader (DataLoader): (If None -> dataloader
  134. will be retrieved from self.datamodule)
  135. Returns:
  136. List[torch.Tensor]: Tranformer memory
  137. """
  138. self.model.to(self.device)
  139. self.model.eval()
  140. if dataloader is None:
  141. dataloader = self.get_dataloader(dataset)
  142. X_encoded = []
  143. for b_idx, batch in enumerate(dataloader):
  144. batch = self.on_device(batch)
  145. with torch.no_grad():
  146. batch_encoded = self.model.encode(batch).permute(
  147. 1, 0, 2
  148. ) # Return on shape [n_samples, n_tokens, max_seq_length]
  149. X_encoded.extend(batch_encoded)
  150. return X_encoded
  151. def decode(
  152. self,
  153. memory: torch.Tensor,
  154. memory_pad_mask: torch.Tensor,
  155. decoder_input: torch.Tensor,
  156. ) -> torch.Tensor:
  157. """
  158. Output token probabilities from a given decoder input
  159. Args:
  160. memory_input (torch.Tensor): tensor from encoded input of shape (src_len,
  161. batch_size, d_model)
  162. memory_pad_mask (torch.Tensor): bool tensor of memory padding mask of shape
  163. (src_len, batch_size)
  164. decoder_input (torch.Tensor): tensor of decoder token_ids of shape (tgt_len,
  165. batch_size)
  166. """
  167. self.model.to(self.device)
  168. self.model.eval()
  169. batch_input = {
  170. "memory_input": memory,
  171. "memory_pad_mask": memory_pad_mask.permute(1, 0),
  172. "decoder_input": decoder_input.permute(1, 0),
  173. "decoder_pad_mask": torch.zeros_like(decoder_input, dtype=bool).permute(1, 0),
  174. }
  175. with torch.no_grad():
  176. return self.model.decode(batch_input)
  177. def set_datamodule(
  178. self,
  179. datamodule: Optional[pl.LightningDataModule] = None,
  180. datamodule_type: Optional[ListConfig] = None,
  181. ) -> None:
  182. """
  183. Create a new datamodule by either supplying a datamodule (created elsewhere) or
  184. a pre-defined datamodule type as input.
  185. Args:
  186. datamodule (Optional[pl.LightningDataModule]): pytorchlightning datamodule
  187. datamodule_type (Optional[str]): The type of datamodule to build if no
  188. datamodule is given as input.
  189. """
  190. if datamodule is None and datamodule_type is not None:
  191. data_collection = DataCollection(self.config, self.tokenizer)
  192. self.datamodule = data_collection.get_datamodule(datamodule_type)
  193. elif datamodule is None:
  194. print("Did not initialize datamodule.")
  195. return
  196. else:
  197. self.datamodule = datamodule
  198. self.datamodule.setup()
  199. n_cpus = len(os.sched_getaffinity(0))
  200. if self.n_gpus > 0:
  201. n_workers = n_cpus // self.n_gpus
  202. else:
  203. n_workers = n_cpus
  204. self.datamodule._num_workers = n_workers
  205. print(f"Using {str(n_workers)} workers for data module.")
  206. return
  207. def fit(self) -> None:
  208. """
  209. Fit model to training data in self.datamodule and using parameters specified in
  210. the trainer object.
  211. """
  212. self.trainer.fit(self.model, datamodule=self.datamodule)
  213. return
  214. def parameters(self) -> Iterator:
  215. return self.model.parameters()
  216. def _random_initialization(
  217. self, args: Namespace, extra_args: Dict[str, Any], pad_token_idx: int
  218. ) -> Union[BARTModel, UnifiedModel]:
  219. """
  220. Constructing a model with randomly initialized weights.
  221. Args:
  222. args (Namespace): Grouped model arguments.
  223. extra_args (Dict[str, Any]): Extra arguments passed to the BARTModel.
  224. Will be saved as hparams by pytorchlightning.
  225. pad_token_idx: The index denoting padding in the vocabulary.
  226. """
  227. if self.train_mode.startswith("train"):
  228. total_steps = self.train_steps + 1
  229. else:
  230. total_steps = 0
  231. if self.model_type == "bart":
  232. model = BARTModel(
  233. self.sampler,
  234. pad_token_idx,
  235. self.vocabulary_size,
  236. args.d_model,
  237. args.n_layers,
  238. args.n_heads,
  239. args.d_feedforward,
  240. args.get("learning_rate"),
  241. DEFAULT_WEIGHT_DECAY,
  242. util.DEFAULT_ACTIVATION,
  243. total_steps,
  244. util.DEFAULT_MAX_SEQ_LEN,
  245. schedule=args.get("schedule"),
  246. dropout=util.DEFAULT_DROPOUT,
  247. warm_up_steps=args.get("warm_up_steps"),
  248. **extra_args,
  249. )
  250. elif self.model_type == "unified":
  251. model = UnifiedModel(
  252. self.sampler,
  253. pad_token_idx,
  254. self.vocabulary_size,
  255. args.d_model,
  256. args.n_layers,
  257. args.n_heads,
  258. args.d_feedforward,
  259. args.get("learning_rate"),
  260. DEFAULT_WEIGHT_DECAY,
  261. util.DEFAULT_ACTIVATION,
  262. total_steps,
  263. util.DEFAULT_MAX_SEQ_LEN,
  264. schedule=args.get("schedule"),
  265. dropout=util.DEFAULT_DROPOUT,
  266. warm_up_steps=args.get("warm_up_steps"),
  267. **extra_args,
  268. )
  269. else:
  270. raise ValueError(f"Unknown model type [bart, unified]: {self.model_type}")
  271. return model
  272. def _initialize_from_ckpt(
  273. self, args: Namespace, extra_args: Dict[str, Any], pad_token_idx: int
  274. ) -> Union[BARTModel, UnifiedModel]:
  275. """
  276. Constructing a model with weights from a ckpt-file.
  277. Args:
  278. args (Namespace): Grouped model arguments.
  279. extra_args (Dict[str, Any]): Extra arguments passed to the BARTModel.
  280. Will be saved as hparams by pytorchlightning.
  281. pad_token_idx: The index denoting padding in the vocabulary.
  282. """
  283. if self.train_mode == "training" or self.train_mode == "train":
  284. total_steps = self.train_steps + 1
  285. if self.model_type == "bart":
  286. if self.train_mode == "training" or self.train_mode == "train":
  287. if self.resume_training:
  288. model = BARTModel.load_from_checkpoint(
  289. self.model_path,
  290. decode_sampler=self.sampler,
  291. num_steps=total_steps,
  292. pad_token_idx=pad_token_idx,
  293. vocabulary_size=self.vocabulary_size,
  294. )
  295. else:
  296. model = BARTModel.load_from_checkpoint(
  297. self.model_path,
  298. decode_sampler=self.sampler,
  299. pad_token_idx=pad_token_idx,
  300. vocabulary_size=self.vocabulary_size,
  301. num_steps=total_steps,
  302. lr=args.learning_rate,
  303. weight_decay=args.weight_decay,
  304. schedule=args.schedule,
  305. warm_up_steps=args.warm_up_steps,
  306. **extra_args,
  307. )
  308. elif (
  309. self.train_mode == "validation"
  310. or self.train_mode == "val"
  311. or self.train_mode == "test"
  312. or self.train_mode == "testing"
  313. or self.train_mode == "eval"
  314. ):
  315. model = BARTModel.load_from_checkpoint(self.model_path, decode_sampler=self.sampler)
  316. model.eval()
  317. else:
  318. raise ValueError(f"Unknown training mode: {self.train_mode}")
  319. elif self.model_type == "unified":
  320. if self.train_mode == "training" or self.train_mode == "train":
  321. if self.resume_training:
  322. model = UnifiedModel.load_from_checkpoint(self.model_path, decode_sampler=self.sampler)
  323. model.train()
  324. else:
  325. model = UnifiedModel.load_from_checkpoint(
  326. self.model_path,
  327. decode_sampler=self.sampler,
  328. pad_token_idx=pad_token_idx,
  329. vocabulary_size=self.vocabulary_size,
  330. num_steps=total_steps,
  331. lr=args.learning_rate,
  332. weight_decay=args.weight_decay,
  333. schedule=args.schedule,
  334. warm_up_steps=args.warm_up_steps,
  335. **extra_args,
  336. )
  337. elif (
  338. self.train_mode == "validation"
  339. or self.train_mode == "val"
  340. or self.train_mode == "test"
  341. or self.train_mode == "testing"
  342. or self.train_mode == "eval"
  343. ):
  344. model = UnifiedModel.load_from_checkpoint(self.model_path, decode_sampler=self.sampler)
  345. model.eval()
  346. else:
  347. raise ValueError(f"Unknown training mode: {self.train_mode}")
  348. else:
  349. raise ValueError(f"Unknown model type [bart, unified]: {self.model_type}")
  350. return model
  351. def build_model(self, args: Namespace) -> None:
  352. """
  353. Build transformer model, either
  354. 1. By loading pre-trained model from checkpoint file, or
  355. 2. Initializing new model with random weight initialization
  356. Args:
  357. args (Namespace): Grouped model arguments.
  358. """
  359. pad_token_idx = self.tokenizer["pad"]
  360. # These args don't affect the model directly but will be saved by lightning as hparams
  361. # Tensorboard doesn't like None so we need to convert to string
  362. train_tokens = "None" if self.train_tokens is None else self.train_tokens
  363. n_buckets = "None" if self.n_buckets is None else self.n_buckets
  364. if self.train_mode == "training" or self.train_mode == "train":
  365. extra_args = {
  366. "batch_size": self.datamodule.batch_size,
  367. "acc_batches": args.acc_batches,
  368. "epochs": args.n_epochs,
  369. "clip_grad": args.clip_grad,
  370. "augment": args.augmentation_strategy,
  371. "aug_prob": args.augmentation_probability,
  372. "train_tokens": train_tokens,
  373. "n_buckets": n_buckets,
  374. "limit_val_batches": args.limit_val_batches,
  375. }
  376. else:
  377. extra_args = {}
  378. # If no model is given, use random init
  379. if not self.model_path:
  380. self.model = self._random_initialization(args, extra_args, pad_token_idx)
  381. else:
  382. self.model = self._initialize_from_ckpt(args, extra_args, pad_token_idx)
  383. return
  384. def get_dataloader(self, dataset: str, datamodule: Optional[pl.LightningDataModule] = None) -> DataLoader:
  385. """
  386. Get the dataloader for a subset of the data from a specific datamodule.
  387. Args:
  388. dataset (str): One in ["full", "train", "val", "test"].
  389. Specifies which part of the data to return.
  390. datamodule (Optional[pl.LightningDataModule]): pytorchlightning datamodule.
  391. If None -> Will use self.datamodule.
  392. """
  393. if dataset not in ["full", "train", "val", "test"]:
  394. raise ValueError(f"Unknown dataset : {dataset}. Should be either 'full', 'train', 'val' or 'test'.")
  395. if datamodule is None:
  396. datamodule = self.datamodule
  397. dataloader = None
  398. if dataset == "full":
  399. dataloader = datamodule.full_dataloader()
  400. elif dataset == "train":
  401. dataloader = datamodule.train_dataloader()
  402. elif dataset == "val":
  403. dataloader = datamodule.val_dataloader()
  404. elif dataset == "test":
  405. dataloader = datamodule.test_dataloader()
  406. return dataloader
  407. @torch.no_grad()
  408. def log_likelihood(
  409. self,
  410. dataset: str = "full",
  411. dataloader: Optional[DataLoader] = None,
  412. ) -> List[float]:
  413. """
  414. Computing the likelihood of the encoder_input SMILES and decoder_input SMILES
  415. pairs.
  416. Args:
  417. dataset (str): Which part of the dataset to use (["train", "val", "test",
  418. "full"]).
  419. dataloader (Optional[DataLoader]): If None -> dataloader
  420. will be retrieved from self.datamodule.
  421. Returns:
  422. List[float]: List with log-likelihoods of each reactant/product pairs.
  423. """
  424. if dataloader is None:
  425. dataloader = self.get_dataloader(dataset)
  426. self.model.to(self.device)
  427. self.model.eval()
  428. log_likelihoods = []
  429. for batch in dataloader:
  430. batch = self.on_device(batch)
  431. output = self.model.forward(batch)
  432. log_probabilities = self.model.generator(output["model_output"])
  433. target_ids_lst = batch["decoder_input"].permute(1, 0)
  434. for target_ids, log_prob in zip(target_ids_lst[:, 1::], log_probabilities.permute(1, 0, 2)):
  435. llhs = 0.0
  436. for i_token, token in enumerate(target_ids):
  437. llhs += log_prob[i_token, token].item()
  438. break_condition = token == self.tokenizer["end"] or token == self.tokenizer["pad"]
  439. if break_condition:
  440. break
  441. log_likelihoods.append(llhs)
  442. return log_likelihoods
  443. def on_device(self, batch: Dict[str, Any]) -> Dict[str, Any]:
  444. """
  445. Move data in "batch" to the current model device.
  446. Args:
  447. batch (Dict[str, Any]): batch input data to model.
  448. Returns:
  449. Dict[str, Any]: batch data on current device.
  450. """
  451. device_batch = {
  452. key: val.to(self.device) if isinstance(val, torch.Tensor) else val for key, val in batch.items()
  453. }
  454. return device_batch
  455. def predict(
  456. self,
  457. dataset: str = "full",
  458. dataloader: Optional[DataLoader] = None,
  459. return_tokenized: bool = False,
  460. ) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]:
  461. """
  462. Predict SMILES output given dataloader, specified by 'dataset'.
  463. Args:
  464. dataset: Which part of the dataset to use (["train", "val", "test",
  465. "full"]).
  466. dataloader: If None -> dataloader
  467. will be retrieved from self.datamodule.
  468. return_tokenized: Whether to return the tokenized beam search
  469. solutions instead of strings.
  470. Returns:
  471. (sampled_smiles List[np.ndarray], log_lhs List[np.ndarray], target_smiles List[np.ndarray])
  472. """
  473. if dataloader is None:
  474. dataloader = self.get_dataloader(dataset)
  475. self.model.to(self.device)
  476. self.model.eval()
  477. sampled_smiles = []
  478. log_lhs = []
  479. target_smiles = []
  480. for batch in dataloader:
  481. batch = self.on_device(batch)
  482. with torch.no_grad():
  483. smiles_batch, log_lhs_batch = self.model.sample_molecules(
  484. batch, sampling_alg="beam", return_tokenized=return_tokenized
  485. )
  486. if self.model.sampler.sample_unique:
  487. smiles_batch = self.sampler.smiles_unique
  488. log_lhs_batch = self.sampler.log_lhs_unique
  489. sampled_smiles.extend(smiles_batch)
  490. log_lhs.extend(log_lhs_batch)
  491. target_smiles.extend(batch["target_smiles"])
  492. return sampled_smiles, log_lhs, target_smiles
  493. def score_model(
  494. self,
  495. n_unique_beams: Optional[int] = None,
  496. dataset: str = "full",
  497. dataloader: Optional[DataLoader] = None,
  498. output_scores: Optional[str] = None,
  499. output_sampled_smiles: Optional[str] = None,
  500. ) -> Union[Tuple[pd.DataFrame, pd.DataFrame], pd.DataFrame]:
  501. """
  502. Score model performance on dataset in terms of accuracy (top-1 and top-K) and
  503. similarity of top-1 molecules. Also collects basic logging scores (loss, etc.).
  504. Args:
  505. n_unique_beams: Number of unique beams after canonicalizing sampled
  506. SMILES strings.
  507. dataset: Which part of the dataset to use (["train", "val", "test",
  508. "full"]).
  509. dataloader (DataLoader): If None -> dataloader will be
  510. retrieved from self.datamodule.
  511. output_scores: Path to output .csv file with model performance. If None ->
  512. Will not write DataFrame to file.
  513. output_sampled_smiles: Path to output .json file with sampled smiles.
  514. If None -> Will not write DataFrame to file.
  515. Returns:
  516. [pandas.DataFrame with calculated scores/metrics, pandas.DataFrame with
  517. sampled SMILES]
  518. or
  519. pandas.DataFrame with calculated scores/metrics
  520. """
  521. if output_scores and output_sampled_smiles:
  522. for callback in self.trainer.callbacks:
  523. if hasattr(callback, "set_output_files"):
  524. callback.set_output_files(output_scores, output_sampled_smiles)
  525. if n_unique_beams is None and self.sampler.smiles_unique:
  526. n_unique_beams = self.model.num_beams
  527. self.model.n_unique_beams = n_unique_beams
  528. if dataloader is None:
  529. dataloader = self.get_dataloader(dataset)
  530. self.model.eval()
  531. self.model.to(self.device)
  532. for b_idx, batch in enumerate(dataloader):
  533. batch = self.on_device(batch)
  534. metrics = self.model.test_step(batch, b_idx)
  535. if self.model.sampler.sample_unique:
  536. sampled_smiles_unique = self.model.sampler.smiles_unique
  537. log_lhs_unique = self.model.sampler.log_lhs_unique
  538. # Get data of unique SMILES/solutions (keeping both non-unique
  539. # and unique metrics)
  540. metrics_unique = self.model.sampler.compute_sampling_metrics(
  541. sampled_smiles_unique, metrics["target_smiles"], is_canonical=False
  542. )
  543. metrics_unique.update(
  544. {
  545. "sampled_molecules": sampled_smiles_unique,
  546. "log_lhs": log_lhs_unique,
  547. }
  548. )
  549. drop_cols = [
  550. "fraction_invalid",
  551. "fraction_unique",
  552. "top1_tanimoto_similarity",
  553. ]
  554. metrics_unique = {f"{key}(unique)": val for key, val in metrics_unique.items() if key not in drop_cols}
  555. metrics.update(metrics_unique)
  556. for callback in self.trainer.callbacks:
  557. if not isinstance(callback, pl.callbacks.progress.ProgressBar):
  558. callback.on_test_batch_end(self.trainer, self.model, metrics, batch, b_idx, 0)
Tip!

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

Comments

Loading...