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

augment.py 11 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
  1. # Copyright (c) 2022, NVIDIA CORPORATION.
  2. # SPDX-License-Identifier: Apache-2.0
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import torch
  15. from nemo.utils import logging
  16. from rdkit import Chem
  17. import math
  18. from pysmilesutils.augment import SMILESAugmenter
  19. from typing import List
  20. import numpy as np
  21. import math
  22. import random
  23. from nemo.collections.common.tokenizers.char_tokenizer import TokenizerSpec
  24. __all__ = ['MoleculeEnumeration']
  25. # FIXME: apply masking on ids instead of tokens
  26. class MoleculeEnumeration(object):
  27. def __init__(self, tokenizer: TokenizerSpec, seq_length: int,
  28. encoder_augment: bool, encoder_mask: bool,
  29. decoder_augment: bool, decoder_mask: bool,
  30. canonicalize_input: bool, pad_size_divisible_by_8: bool,
  31. mask_scheme: str, mask_prob: float, span_lambda: float,
  32. **kwargs):
  33. self.tokenizer = tokenizer
  34. self.seq_length = seq_length
  35. self.encoder_augment = encoder_augment
  36. self.encoder_mask = encoder_mask
  37. self.decoder_augment = decoder_augment
  38. self.decoder_mask = decoder_mask
  39. self.canonicalize_input = canonicalize_input
  40. self.pad_size_divisible_by_8 = pad_size_divisible_by_8 # workaround for CUDA alignment bug
  41. self.mask_scheme = mask_scheme
  42. self.mask_prob = mask_prob
  43. self.span_lambda = span_lambda
  44. # self.aug = CanonicalSMILESAugmenter().randomize_mol_restricted
  45. def _smiles_augmeter_func(self, smiles: str, augment_data: bool, canonicalize_input: bool):
  46. """Regularize SMILES by coverting to RDKit mol objects and back
  47. Args:
  48. smiles (str): Input SMILES from dataset
  49. canonicalize_input (bool, optional): Canonicalize by default. Defaults to False.
  50. smiles_augmenter: Function to augment/randomize SMILES. Defaults to None
  51. """
  52. mol = Chem.MolFromSmiles(smiles)
  53. canon_smiles = Chem.MolToSmiles(mol, canonical=True) if canonicalize_input else smiles
  54. if augment_data:
  55. # aug_mol = self.aug(mol)
  56. atom_order = list(range(mol.GetNumAtoms()))
  57. np.random.shuffle(atom_order)
  58. aug_mol = Chem.RenumberAtoms(mol, atom_order) # TODO how to use PySMILESutils for this
  59. # There is a very rare possibility that RDKit will not be able to generate
  60. # the SMILES for the augmented mol. In this case we just use the canonical
  61. # mol to generate the SMILES
  62. try:
  63. aug_smiles = Chem.MolToSmiles(aug_mol, canonical=False)
  64. except RuntimeError:
  65. logging.info(f'Could not generate smiles for {smiles} after augmenting. Forcing canonicalization')
  66. aug_smiles = canon_smiles if canonicalize_input else Chem.MolToSmiles(mol, canonical=True)
  67. else:
  68. aug_smiles = Chem.MolToSmiles(mol, canonical=False)
  69. assert len(aug_smiles) > 0, AssertionError('Augmented SMILES string is empty')
  70. assert len(canon_smiles) > 0, AssertionError('Canonical SMILES string is empty')
  71. return aug_smiles, canon_smiles
  72. def _check_seq_len(self, tokens: List[List[str]], mask: List[List[int]]):
  73. """ Warn user and shorten sequence if the tokens are too long, otherwise return original
  74. Args:
  75. tokens (List[List[str]]): List of token sequences
  76. mask (List[List[int]]): List of mask sequences
  77. Returns:
  78. tokens (List[List[str]]): List of token sequences (shortened, if necessary)
  79. mask (List[List[int]]): List of mask sequences (shortened, if necessary)
  80. """
  81. seq_len = max([len(ts) for ts in tokens])
  82. if seq_len > self.seq_length:
  83. tokens_short = [ts[:self.seq_length] for ts in tokens]
  84. mask_short = [ms[:self.seq_length] for ms in mask]
  85. return (tokens_short, mask_short)
  86. return (tokens, mask)
  87. def _prepare_tokens(self, batch: List[str], mask_data: bool = False):
  88. """Prepare tokens for encoder or decoder from batch of input SMILES strings
  89. Args:
  90. batch (List[str]): Batch of input SMILES strings
  91. augment_data (bool): Augment SMILES
  92. mask_data (bool, optional): Mask decoder tokens. Defaults to False.
  93. Returns:
  94. dict: token output
  95. """
  96. # Tokenize with optional masking, padding is done later due to differences in encoder/decoder bos/eos tokens
  97. token_output = self.tokenize(batch, mask=mask_data)
  98. if mask_data:
  99. tokens = token_output['masked_tokens']
  100. mask = token_output['token_masks']
  101. else:
  102. tokens = token_output['original_tokens']
  103. mask = [[True] * len(ts) for ts in tokens] # 1/True = Active, 0/False = Inactive
  104. # Verify sequence length
  105. tokens, mask = self._check_seq_len(tokens, mask)
  106. token_output = {
  107. "tokens": tokens,
  108. "mask": mask
  109. }
  110. return token_output
  111. def _pad_seqs(self, seqs, pad_token):
  112. # TODO: switch to torch.nn.utils.rnn.pad_sequence
  113. pad_length = max([len(seq) for seq in seqs])
  114. if self.pad_size_divisible_by_8:
  115. pad_length = int(math.ceil(pad_length/8) * 8)
  116. padded = [seq + ([pad_token] * (pad_length - len(seq))) for seq in seqs]
  117. masks = [([1] * len(seq)) + ([0] * (pad_length - len(seq))) for seq in seqs] # 1/True = Active, 0/False = Inactive
  118. return padded, masks
  119. def collate_fn(self, batch: List[str], label_pad: int = -1):
  120. """Collate function for NeMo MegaMolBART. Format of data has been altered for NeMo per 'NB' comments.
  121. This code should be cleaned up and validated once new tokenizer from NeMo is incorporated."""
  122. # Dimensions required by NeMo: [batch, sequence + padding]
  123. # Encoder
  124. encoder_smiles_list = [self._smiles_augmeter_func(smiles, augment_data=self.encoder_augment, canonicalize_input=self.canonicalize_input)
  125. for smiles in batch]
  126. encoder_smiles = [x[0] for x in encoder_smiles_list]
  127. canon_targets = [x[1] for x in encoder_smiles_list]
  128. encoder_dict = self._prepare_tokens(encoder_smiles, mask_data=self.encoder_mask)
  129. encoder_tokens = encoder_dict['tokens'] # TODO boolean masks are never used from this function -- remove
  130. enc_token_ids = [self.tokenizer.token_to_ids(t) for t in encoder_tokens]
  131. enc_token_ids, encoder_mask = self._pad_seqs(enc_token_ids, self.tokenizer.pad_id)
  132. enc_token_ids = torch.tensor(enc_token_ids, dtype=torch.int64)
  133. encoder_mask = torch.tensor(encoder_mask, dtype=torch.int64)
  134. # Decoder
  135. if self.decoder_augment:
  136. decoder_smiles_list = [self._smiles_augmeter_func(smiles, augment_data=self.decoder_augment, canonicalize_input=False)
  137. for smiles in encoder_smiles]
  138. decoder_smiles = [x[0] for x in decoder_smiles_list]
  139. else:
  140. decoder_smiles = encoder_smiles
  141. decoder_dict = self._prepare_tokens(decoder_smiles, mask_data=self.decoder_mask)
  142. decoder_tokens = decoder_dict['tokens']
  143. dec_token_ids = [self.tokenizer.token_to_ids(t) for t in decoder_tokens]
  144. label_ids = [sample + [self.tokenizer.eos_id] for sample in dec_token_ids] # assign label_ids before adding bos_id to decoder
  145. dec_token_ids = [[self.tokenizer.bos_id] + sample for sample in dec_token_ids]
  146. dec_token_ids, decoder_mask = self._pad_seqs(dec_token_ids, self.tokenizer.pad_id)
  147. dec_token_ids = torch.tensor(dec_token_ids, dtype=torch.int64)
  148. decoder_mask = torch.tensor(decoder_mask, dtype=torch.int64)
  149. label_token_ids, loss_mask = self._pad_seqs(label_ids, self.tokenizer.pad_id)
  150. label_token_ids = torch.tensor(label_token_ids, dtype=torch.int64)
  151. loss_mask = torch.tensor(loss_mask, dtype=torch.int64)
  152. label_token_ids[~loss_mask.to(torch.bool)] = label_pad
  153. collate_output = {'text_enc': enc_token_ids,
  154. 'enc_mask': encoder_mask,
  155. 'text_dec': dec_token_ids,
  156. 'dec_mask': decoder_mask,
  157. 'labels': label_token_ids,
  158. 'loss_mask': loss_mask,
  159. 'target_smiles': canon_targets} # smiles strings
  160. return collate_output
  161. def tokenize(self, sents1, mask=False):
  162. # TODO this function needs cleanup
  163. tokens = [self.tokenizer.text_to_tokens(s) for s in sents1]
  164. m_tokens, token_masks = self.mask_tokens(tokens, empty_mask=not mask)
  165. output = {}
  166. output["original_tokens"] = tokens
  167. if mask:
  168. output["masked_tokens"] = m_tokens
  169. output["token_masks"] = token_masks
  170. return output
  171. def mask_tokens(self, tokens, empty_mask=False):
  172. if empty_mask:
  173. mask = [[True] * len(ts) for ts in tokens]
  174. return tokens, mask
  175. masked_tokens = []
  176. token_masks = []
  177. for ts in tokens:
  178. # FIXME: add config
  179. # if self.mask_scheme == "replace":
  180. # masked, token_mask = self._mask_replace(ts)
  181. # elif self.mask_scheme == "span":
  182. masked, token_mask = self._mask_span(ts)
  183. # else:
  184. # raise ValueError(f"Unrecognised mask scheme: {self.mask_scheme}")
  185. masked_tokens.append(masked)
  186. token_masks.append(token_mask)
  187. return masked_tokens, token_masks
  188. def _mask_replace(self, ts):
  189. mask_bools = [True, False]
  190. weights = [self.mask_prob, 1 - self.mask_prob]
  191. token_mask = random.choices(mask_bools, weights=weights, k=len(ts))
  192. masked = [self._mask_token(ts[i]) if m else ts[i] for i, m in enumerate(token_mask)]
  193. return masked, token_mask
  194. def _mask_span(self, ts):
  195. curr_token = 0
  196. masked = []
  197. token_mask = []
  198. mask_bools = [True, False]
  199. weights = [self.mask_prob, 1 - self.mask_prob]
  200. sampled_mask = random.choices(mask_bools, weights=weights, k=len(ts))
  201. while curr_token < len(ts):
  202. # If mask, sample from a poisson dist to get length of mask
  203. if sampled_mask[curr_token]:
  204. mask_len = torch.poisson(torch.tensor(self.span_lambda)).long().item()
  205. masked.append(self.tokenizer.mask_token)
  206. token_mask.append(True)
  207. curr_token += mask_len
  208. # Otherwise don't mask
  209. else:
  210. masked.append(ts[curr_token])
  211. token_mask.append(False)
  212. curr_token += 1
  213. return masked, token_mask
  214. def _mask_token(self, token):
  215. # FIXME: not working
  216. rand = random.random()
  217. if rand < self.show_mask_token_prob:
  218. return self.tokenizer.mask_token
  219. elif rand < self.show_mask_token_prob + ((1 - self.show_mask_token_prob) / 2):
  220. token_idx = random.choice(self.chem_token_idxs)
  221. return self.decode_vocab[token_idx]
  222. else:
  223. return token
Tip!

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

Comments

Loading...