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.py 19 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
  1. """ Module containing a class for the DataSet used as well as base-classes for DataModules"""
  2. import functools
  3. import os
  4. import random
  5. from collections import defaultdict
  6. from typing import Any, Dict, List, Sequence, Tuple
  7. import pandas as pd
  8. import pytorch_lightning as pl
  9. import torch
  10. from pysmilesutils.augment import SMILESAugmenter
  11. from pysmilesutils.datautils import TokenSampler
  12. from rdkit import Chem
  13. from torch.utils.data import DataLoader, Dataset, SequentialSampler
  14. from pysmilesutils.datautils import ChunkBatchSampler
  15. from molbart.data.util import BatchEncoder, build_attention_mask, build_target_mask
  16. from molbart.utils.tokenizers import ChemformerTokenizer, TokensMasker
  17. class ChemistryDataset(Dataset):
  18. """
  19. Generic dataset that consists of a dictionary, where each
  20. value is an equal-sized sequence of data.
  21. Such a dictionary can be seen as a dictionary representation
  22. of a pandas DataFrame, but indexing a DataFrame object is slow
  23. and therefore the data is stored as a dictionary.
  24. One can obtain the length of the dataset using the `len` operator
  25. and individual "rows" of the data can be accessed by indexing
  26. .. code-block::
  27. row = dataset[10]
  28. the `row` variable returned is also a dictionary, but each value
  29. is a single value. The keys are the same as in the original dictionary.
  30. As such a batch of such rows sampled by a DataLoader is a list of dictionaries.
  31. And one can obtain invidiual lists with e.g.
  32. .. code-block::
  33. molecules = [item["molecules"] for item in batch]
  34. :param data: the dataset
  35. """
  36. def __init__(self, data: Dict[str, Any]) -> None:
  37. self._data = data
  38. if self._data:
  39. key_zero = list(self._data.keys())[0]
  40. self._len = len(self._data[key_zero])
  41. else:
  42. self._len = 0
  43. def __len__(self) -> int:
  44. return self._len
  45. def __getitem__(self, item: int) -> Dict[str, Any]:
  46. return {key: values[item] for key, values in self._data.items()}
  47. @property
  48. def seq_lengths(self) -> List[int]:
  49. """Return the sequence lengths data if such data exists"""
  50. if "seq_lengths" in self._data:
  51. return self._data["seq_lengths"]
  52. if "lengths" in self._data:
  53. return self._data["lengths"]
  54. raise KeyError("This dataset does not store any sequence lengths")
  55. class _AbsDataModule(pl.LightningDataModule):
  56. """Base class for all DataModules"""
  57. def __init__(
  58. self,
  59. dataset_path: str,
  60. tokenizer: ChemformerTokenizer,
  61. batch_size: int,
  62. max_seq_len: int,
  63. train_token_batch_size: int = None,
  64. num_buckets: int = None,
  65. val_idxs: Sequence[int] = None,
  66. test_idxs: Sequence[int] = None,
  67. train_idxs: Sequence[int] = None,
  68. train_set_rest: bool = True,
  69. split_perc: float = 0.2,
  70. pin_memory: bool = True,
  71. unified_model: bool = False,
  72. i_chunk: int = 0,
  73. n_chunks: int = 1,
  74. **kwargs,
  75. ) -> None:
  76. super().__init__()
  77. if val_idxs is not None and test_idxs is not None:
  78. idxs_intersect = set(val_idxs).intersection(set(test_idxs))
  79. if len(idxs_intersect) > 0:
  80. raise ValueError("Val idxs and test idxs overlap")
  81. if train_token_batch_size is not None and num_buckets is not None:
  82. print(
  83. f"""Training with approx. {train_token_batch_size} tokens per batch"""
  84. f""" and {num_buckets} buckets in the sampler."""
  85. )
  86. else:
  87. print(f"Using a batch size of {str(batch_size)}.")
  88. self.dataset_path = dataset_path
  89. self.tokenizer = tokenizer
  90. self.batch_size = batch_size
  91. self.max_seq_len = max_seq_len
  92. self.train_token_batch_size = train_token_batch_size
  93. self.num_buckets = num_buckets
  94. self.val_idxs = val_idxs
  95. self.test_idxs = test_idxs
  96. self.train_idxs = train_idxs
  97. self.train_set_rest = train_set_rest
  98. self.split_perc = split_perc
  99. self.pin_memory = pin_memory
  100. self.unified_model = unified_model
  101. self._num_workers = len(os.sched_getaffinity(0))
  102. self.train_dataset = None
  103. self.val_dataset = None
  104. self.test_dataset = None
  105. self.i_chunk = i_chunk
  106. self.n_chunks = n_chunks
  107. if self.n_chunks > 1:
  108. print("Using chunk of data:")
  109. print(f"- i_chunk: {i_chunk}, n_chunks: {n_chunks}")
  110. self._all_data: Dict[str, Any] = {}
  111. def train_dataloader(self) -> DataLoader:
  112. """Returns the DataLoader for the training set"""
  113. if self.train_token_batch_size is None:
  114. if self.n_chunks > 1:
  115. # Should only be used for inference / postprocessing
  116. dataloader = self._create_chunk_dataloader(self.train_dataset, self._collate)
  117. return dataloader
  118. dataloader = self._create_basic_dataloader(self.train_dataset, self._collate, shuffle=True)
  119. return dataloader
  120. sampler = TokenSampler(
  121. self.num_buckets,
  122. self.train_dataset.seq_lengths,
  123. self.train_token_batch_size,
  124. shuffle=True,
  125. )
  126. dataloader = DataLoader(
  127. self.train_dataset,
  128. batch_sampler=sampler,
  129. num_workers=self._num_workers,
  130. collate_fn=self._collate,
  131. pin_memory=self.pin_memory,
  132. )
  133. return dataloader
  134. def val_dataloader(self):
  135. """Returns the DataLoader for the validation set"""
  136. if self.n_chunks > 1:
  137. dataloader = self._create_chunk_dataloader(self.val_dataset, functools.partial(self._collate, train=False))
  138. return dataloader
  139. dataloader = self._create_basic_dataloader(self.val_dataset, functools.partial(self._collate, train=False))
  140. return dataloader
  141. def test_dataloader(self):
  142. """Returns the DataLoader for the test set"""
  143. if self.n_chunks > 1:
  144. dataloader = self._create_chunk_dataloader(self.test_dataset, functools.partial(self._collate, train=False))
  145. return dataloader
  146. dataloader = self._create_basic_dataloader(self.test_dataset, functools.partial(self._collate, train=False))
  147. return dataloader
  148. def full_dataloader(self, train=False):
  149. """Returns the DataLoader for the test set"""
  150. if self.n_chunks > 1:
  151. dataloader = self._create_chunk_dataloader(
  152. ChemistryDataset(self._all_data), functools.partial(self._collate, train=train)
  153. )
  154. return dataloader
  155. dataloader = self._create_basic_dataloader(
  156. ChemistryDataset(self._all_data), functools.partial(self._collate, train=train)
  157. )
  158. return dataloader
  159. def setup(self, stage=None):
  160. """Load and split the dataset"""
  161. self._load_all_data()
  162. self._split_dataset()
  163. def _all_data_len(self) -> int:
  164. return len(ChemistryDataset(self._all_data))
  165. def _build_attention_mask(self, enc_length: int, dec_length: int) -> torch.Tensor:
  166. return build_attention_mask(enc_length, dec_length)
  167. def _collate(self, batch: List[Dict[str, Any]], train: bool = True) -> Dict[str, Any]:
  168. (
  169. encoder_ids,
  170. encoder_mask,
  171. decoder_ids,
  172. decoder_mask,
  173. smiles,
  174. ) = self._transform_batch(batch, train)
  175. if self.unified_model:
  176. return self._make_unified_model_batch(encoder_ids, encoder_mask, decoder_ids, decoder_mask, smiles)
  177. return {
  178. "encoder_input": encoder_ids,
  179. "encoder_pad_mask": encoder_mask,
  180. "decoder_input": decoder_ids[:-1, :],
  181. "decoder_pad_mask": decoder_mask[:-1, :],
  182. "target": decoder_ids.clone()[1:, :],
  183. "target_mask": decoder_mask.clone()[1:, :],
  184. "target_smiles": smiles,
  185. }
  186. def _create_chunk_dataloader(self, dataset, collate_fn):
  187. sampler = SequentialSampler(dataset)
  188. batch_sampler = ChunkBatchSampler(
  189. sampler=sampler, batch_size=self.batch_size, drop_last=False, i_chunk=self.i_chunk, n_chunks=self.n_chunks
  190. )
  191. dataloader = DataLoader(
  192. dataset,
  193. batch_sampler=batch_sampler,
  194. num_workers=self._num_workers,
  195. collate_fn=collate_fn,
  196. pin_memory=self.pin_memory,
  197. )
  198. return dataloader
  199. def _create_basic_dataloader(self, dataset, collate_fn, shuffle=False) -> DataLoader:
  200. dataloader = DataLoader(
  201. dataset,
  202. batch_size=self.batch_size,
  203. num_workers=self._num_workers,
  204. collate_fn=collate_fn,
  205. shuffle=shuffle,
  206. pin_memory=self.pin_memory,
  207. )
  208. return dataloader
  209. def _load_all_data(self) -> None:
  210. raise NotImplementedError("Data loading is not implemented in base class")
  211. def _make_random_split_indices(self) -> None:
  212. dataset_len = self._all_data_len()
  213. val_len = round(dataset_len * self.split_perc)
  214. test_len = round(dataset_len * self.split_perc)
  215. all_idxs = range(dataset_len)
  216. idxs = random.sample(all_idxs, val_len + test_len)
  217. self.val_idxs = idxs[:val_len]
  218. self.test_idxs = idxs[val_len:]
  219. self.train_idxs = [idx for idx in all_idxs if idx not in idxs]
  220. def _make_unified_model_batch(
  221. self,
  222. encoder_ids: torch.Tensor,
  223. encoder_mask: torch.Tensor,
  224. decoder_ids: torch.Tensor,
  225. decoder_mask: torch.Tensor,
  226. smiles: List[str],
  227. ) -> Dict[str, Any]:
  228. decoder_ids = decoder_ids[1:]
  229. decoder_mask = decoder_mask[1:]
  230. enc_length, batch_size = tuple(encoder_ids.shape)
  231. dec_length, _ = tuple(decoder_ids[:-1, :].shape)
  232. att_mask = self._build_attention_mask(enc_length, dec_length)
  233. target = torch.cat((encoder_ids.clone()[:-1, :], decoder_ids.clone()), dim=0)
  234. target_mask = build_target_mask(enc_length, dec_length, batch_size)
  235. target_mask = target_mask + (torch.cat((encoder_mask[:-1, :], decoder_mask), dim=0))
  236. return {
  237. "encoder_input": encoder_ids,
  238. "encoder_pad_mask": encoder_mask,
  239. "decoder_input": decoder_ids[:-1, :],
  240. "decoder_pad_mask": decoder_mask[:-1, :],
  241. "attention_mask": att_mask,
  242. "target": target,
  243. "target_mask": target_mask,
  244. "target_smiles": smiles,
  245. }
  246. def _set_split_indices_from_dataframe(self, df: pd.DataFrame) -> None:
  247. # Don't set idx if they were provided as input to the class
  248. if self.val_idxs is not None or self.test_idxs is not None or self.train_idxs is not None:
  249. return
  250. val_idxs = df.query("set in ['val','valid','validation']").index.tolist()
  251. train_idxs = df.query("set in ['train','Train']").index.tolist()
  252. test_idxs = df.index[df["set"] == "test"].tolist()
  253. idxs_intersect = set(val_idxs).intersection(set(test_idxs))
  254. if len(idxs_intersect) > 0:
  255. raise ValueError("Val idxs and test idxs overlap")
  256. self.val_idxs = val_idxs
  257. self.test_idxs = test_idxs
  258. self.train_idxs = train_idxs
  259. def _split_dataset(self) -> None:
  260. def _subsample_data(indices):
  261. data = defaultdict(list)
  262. for idx in indices:
  263. for key in self._all_data.keys():
  264. data[key].append(self._all_data[key][idx])
  265. return dict(data)
  266. if self.val_idxs is None and self.test_idxs is None:
  267. self._make_random_split_indices()
  268. elif self.val_idxs is None:
  269. self.val_idxs = []
  270. elif self.test_idxs is None:
  271. self.test_idxs = []
  272. self.val_dataset = ChemistryDataset(_subsample_data(self.val_idxs))
  273. self.test_dataset = ChemistryDataset(_subsample_data(self.test_idxs))
  274. if self.train_set_rest:
  275. # Below assumes all that is not test and val is train if not specified.
  276. all_idxs = set(range(self._all_data_len()))
  277. self.train_idxs = all_idxs - set(self.val_idxs).union(set(self.test_idxs))
  278. if self.train_idxs is None:
  279. self.train_idxs = []
  280. self.train_dataset = ChemistryDataset(_subsample_data(self.train_idxs))
  281. def _transform_batch(
  282. self, batch: List[Dict[str, Any]], train: bool
  283. ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, List[str]]:
  284. raise NotImplementedError("Batch transformation is not implemented in base class")
  285. class MoleculeListDataModule(_AbsDataModule):
  286. """
  287. DataModule that is used for sampling molecules. Can be
  288. used as base class for other DataModules that samples molecules.
  289. The molecules are read from a text-file containing SMILES strings,
  290. one on each row
  291. The `task` argument can be:
  292. * mask - the molecule tokens of the encoder are masked
  293. * aug - the molecules of the decoder are augmented
  294. * aug_mask - a combination of the above
  295. :param task: the model task, can be "mask", "aug" or "aug_mask"
  296. :param augment: if True, will augment the SMILES
  297. :param masker: the masker to use when `task` is "mask" or "aug_mask"
  298. :param dataset_path: the path to the dataset on disc
  299. :param tokenizer: the tokenizer to use
  300. :param batch_size: the batch size to use
  301. :param max_seq_len: the maximum allowed sequence length
  302. :param train_token_batch_size: if given, a `TokenSampler` is used
  303. :param num_buckets: the number of buckets for the `TokenSampler`
  304. :param val_idxs: if given, selects the validation set
  305. :param test_idxs: if given, selects the test set
  306. :param split_perc: determines the percentage of data that goes into validation and test sets
  307. :param pin_memory: if True, pins the memory of the DataLoader
  308. :param unified_model: if True, collate batches for unified model, not BART
  309. """
  310. def __init__(
  311. self,
  312. task: str = "mask",
  313. augment_prob: float = 0.0,
  314. masker: TokensMasker = None,
  315. **kwargs,
  316. ):
  317. super().__init__(**kwargs)
  318. if "mask" in task and TokensMasker is None:
  319. raise ValueError(f"Need to provide a masker with task = {task}")
  320. self._augmenter = SMILESAugmenter(augment_prob=augment_prob)
  321. self._encoder = BatchEncoder(tokenizer=self.tokenizer, masker=masker, max_seq_len=self.max_seq_len)
  322. self.task = task
  323. self.augment = augment_prob > 0.0
  324. def _augment_batch(self, batch: List[str]) -> Tuple[List[str], List[str]]:
  325. if self.augment:
  326. encoder_smiles = self._augmenter(batch)
  327. else:
  328. encoder_smiles = batch[:]
  329. if "aug" in self.task:
  330. decoder_smiles = self._augmenter(encoder_smiles)
  331. else:
  332. decoder_smiles = encoder_smiles[:]
  333. return encoder_smiles, decoder_smiles
  334. def _load_all_data(self):
  335. with open(self.dataset_path, "r") as fileobj:
  336. self._all_data = {"smiles": fileobj.read().splitlines()}
  337. def _transform_batch(
  338. self, batch: List[Dict[str, Any]], train: bool
  339. ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, List[str]]:
  340. smiles = [item["smiles"] for item in batch]
  341. encoder_smiles, decoder_smiles = self._augment_batch(smiles)
  342. encoder_ids, encoder_mask = self._encoder(
  343. encoder_smiles, mask="mask" in self.task, add_sep_token=self.unified_model
  344. )
  345. decoder_ids, decoder_mask = self._encoder(decoder_smiles, mask=False)
  346. # Ensure that the canonical form is used for evaluation
  347. dec_mols = [Chem.MolFromSmiles(smi) for smi in decoder_smiles]
  348. canon_targets = [Chem.MolToSmiles(mol) for mol in dec_mols]
  349. return encoder_ids, encoder_mask, decoder_ids, decoder_mask, canon_targets
  350. class ReactionListDataModule(_AbsDataModule):
  351. """
  352. DataModule that is used for sampling reactions. It also serves
  353. as the base class for other DataModules that samples sequences
  354. to sequence data.
  355. The reactions are read from a text-file containing reactions
  356. SMILES strings, one on each row.
  357. If only sinlge molecules are provided in the text-file, the
  358. product and reactants are intepreted to be equal.
  359. :param augment_prob: the probability of augmenting the sequences in training
  360. :param reverse: if True, will return the encoder data as the decoder data and vice versa
  361. :param dataset_path: the path to the dataset on disc
  362. :param tokenizer: the tokenizer to use
  363. :param batch_size: the batch size to use
  364. :param max_seq_len: the maximum allowed sequence length
  365. :param train_token_batch_size: if given, a `TokenSampler` is used
  366. :param num_buckets: the number of buckets for the `TokenSampler`
  367. :param val_idxs: if given, selects the validation set
  368. :param test_idxs: if given, selects the test set
  369. :param split_perc: determines the percentage of data that goes into validation and test sets
  370. :param pin_memory: if True, pins the memory of the DataLoader
  371. :param unified_model: if True, collate batches for unified model, not BART
  372. """
  373. def __init__(self, augment_prob: float = 0.0, reverse: bool = False, **kwargs):
  374. super().__init__(**kwargs)
  375. self._batch_augmenter = SMILESAugmenter(augment_prob=augment_prob)
  376. self._encoder = BatchEncoder(tokenizer=self.tokenizer, masker=None, max_seq_len=self.max_seq_len)
  377. self.reverse = reverse
  378. def _build_attention_mask(self, enc_length: int, dec_length: int) -> torch.Tensor:
  379. return build_attention_mask(enc_length - 1, dec_length + 1)
  380. def _get_sequences(self, batch: List[Dict[str, Any]], train: bool) -> Tuple[List[str], List[str]]:
  381. reactants = [item["reactants"] for item in batch]
  382. products = [item["products"] for item in batch]
  383. if train and self._batch_augmenter.augment_prob > 0.0:
  384. reactants = self._batch_augmenter(reactants)
  385. products = self._batch_augmenter(products)
  386. return reactants, products
  387. def _load_all_data(self) -> None:
  388. with open(self.dataset_path, "r") as fileobj:
  389. lines = fileobj.read().splitlines()
  390. if ">>" in lines[0]:
  391. reactants, products = zip(*[line.split(">>") for line in lines])
  392. else:
  393. reactants = lines
  394. products = lines.copy()
  395. self._all_data = {"reactants": reactants, "products": products}
  396. def _transform_batch(
  397. self, batch: List[Dict[str, Any]], train: bool
  398. ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, List[str]]:
  399. encoder_smiles, decoder_smiles = self._get_sequences(batch, train)
  400. encoder_ids, encoder_mask = self._encoder(encoder_smiles, add_sep_token=self.unified_model and not self.reverse)
  401. decoder_ids, decoder_mask = self._encoder(decoder_smiles, add_sep_token=self.unified_model and self.reverse)
  402. if not self.reverse:
  403. return encoder_ids, encoder_mask, decoder_ids, decoder_mask, decoder_smiles
  404. return decoder_ids, decoder_mask, encoder_ids, encoder_mask, encoder_smiles
Tip!

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

Comments

Loading...