dittops commited on
Commit
33ff81e
·
verified ·
1 Parent(s): 7abff71

Mirror smolinstruct eval data (hf)

Browse files
Files changed (5) hide show
  1. .gitignore +2 -0
  2. SMolInstruct.py +338 -0
  3. data.zip +3 -0
  4. fig/statistics.png +3 -0
  5. fig/tasks.png +3 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .DS_Store
2
+ *.ipynb
SMolInstruct.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
+ #
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
+ """SMolInstruct: A Large-Scale, Comprehensive, High-Quality Instruction Tuning Dataset for Small Molecules"""
15
+
16
+
17
+ import json
18
+ import os
19
+
20
+ import datasets
21
+
22
+
23
+ # Add BibTeX citation
24
+ # Find for instance the citation on arxiv or on the dataset repo/website
25
+ _CITATION = """\
26
+ @article{yu2024llasmol,
27
+ title={LlaSMol: Advancing Large Language Models for Chemistry with a Large-Scale, Comprehensive, High-Quality Instruction Tuning Dataset},
28
+ author={Botao Yu and Frazier N. Baker and Ziqi Chen and Xia Ning and Huan Sun},
29
+ journal={arXiv preprint arXiv:2402.09391},
30
+ year={2024}
31
+ }
32
+ """
33
+
34
+ # Add description of the dataset here
35
+ # You can copy an official description
36
+ _DESCRIPTION = """\
37
+ SMolInstruct is a large-scale instruction tuning dataset for chemistry tasks and centers around small molecules. It contains a total of 14 chemistry tasks and over 3 million samples. It is designed to be large-scale, comprehensive, and high-quality.
38
+ """
39
+
40
+ # Add a link to an official homepage for the dataset here
41
+ _HOMEPAGE = "https://osu-nlp-group.github.io/LLM4Chem/"
42
+
43
+ # Add the licence for the dataset here if you can find it
44
+ _LICENSE = "cc-by-4.0"
45
+
46
+ # Add link to the official dataset URLs here
47
+ # The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
48
+ # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
49
+ # _URLS = {
50
+ # "first_domain": "https://huggingface.co/great-new-dataset-first_domain.zip",
51
+ # "second_domain": "https://huggingface.co/great-new-dataset-second_domain.zip",
52
+ # }
53
+
54
+
55
+ TASKS = (
56
+ 'forward_synthesis',
57
+ 'retrosynthesis',
58
+ 'molecule_captioning',
59
+ 'molecule_generation',
60
+ 'name_conversion-i2f',
61
+ 'name_conversion-i2s',
62
+ 'name_conversion-s2f',
63
+ 'name_conversion-s2i',
64
+ 'property_prediction-esol',
65
+ 'property_prediction-lipo',
66
+ 'property_prediction-bbbp',
67
+ 'property_prediction-clintox',
68
+ 'property_prediction-hiv',
69
+ 'property_prediction-sider',
70
+ )
71
+
72
+
73
+ class SmolInstructDatasetConfig(datasets.BuilderConfig):
74
+ def __init__(self, tasks=None, sample_group='instruction_tuning', insert_core_tags=True, use_selfies=False, use_test_subset=False, use_first=None, **kwargs):
75
+ """BuilderConfig for MyDataset
76
+ Args:
77
+ data_url: `string`, url to the dataset (word or raw level)
78
+ **kwargs: keyword arguments forwarded to super.
79
+ """
80
+ super(SmolInstructDatasetConfig, self).__init__(
81
+ **kwargs,
82
+ )
83
+ if tasks is None:
84
+ tasks = TASKS
85
+ else:
86
+ tasks = set(tasks)
87
+ all_tasks = set(TASKS)
88
+ assert len(tasks - all_tasks) == 0, 'Unsupported task(s): {tasks}'.format(tasks=(tasks - all_tasks))
89
+ self.tasks = tasks
90
+ self.sample_group = sample_group
91
+ self.insert_core_tags = insert_core_tags
92
+ self.use_selfies = use_selfies
93
+ if 'split' in kwargs:
94
+ self.split = kwargs['split']
95
+ else:
96
+ self.split = None
97
+ self.use_test_subset = use_test_subset
98
+ if use_first is not None:
99
+ assert use_first > 0, "use_first must be a positive integer."
100
+ use_first = int(use_first)
101
+ self.use_first = use_first
102
+
103
+
104
+ class SMolInstruct(datasets.GeneratorBasedBuilder):
105
+ """SMolInstruct: A large-scale chemistry instruction tuning dataset."""
106
+
107
+ VERSION = datasets.Version("1.3.0")
108
+
109
+ # This is an example of a dataset with multiple configurations.
110
+ # If you don't want/need to define several sub-sets in your dataset,
111
+ # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
112
+
113
+ # If you need to make complex sub-parts in the datasets with configurable options
114
+ # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
115
+ BUILDER_CONFIG_CLASS = SmolInstructDatasetConfig
116
+
117
+ # You will be able to load one or the other configurations in the following list with
118
+ # data = datasets.load_dataset('my_dataset', 'first_domain')
119
+ # data = datasets.load_dataset('my_dataset', 'second_domain')
120
+ # BUILDER_CONFIGS = [
121
+ # datasets.BuilderConfig(name="instruction_tuning", version=VERSION, description="Default set for instruction tuning."),
122
+ # datasets.BuilderConfig(name="second_domain", version=VERSION, description="This part of my dataset covers a second domain"),
123
+ # ]
124
+ # BUILDER_CONFIGS = [
125
+ # CheMIDatasetConfig(
126
+ # name='instruction',
127
+ # tasks=TASKS,
128
+ # sample_group='instruction_tuning',
129
+ # description="Molecule instructions.",
130
+ # ),
131
+ # CheMIDatasetConfig(
132
+ # name='raw',
133
+ # tasks=TASKS,
134
+ # sample_group=None,
135
+ # description="Molecule raw data.",
136
+ # ),
137
+ # ]
138
+
139
+ # DEFAULT_CONFIG_NAME = "instruction" # It's not mandatory to have a default configuration. Just use one if it make sense.
140
+
141
+ def _info(self):
142
+ # This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
143
+
144
+ features = datasets.Features(
145
+ {
146
+ "sample_id": datasets.Value("string"),
147
+ "input": datasets.Value("string"),
148
+ "output": datasets.Value("string"),
149
+ "raw_input": datasets.Value("string"),
150
+ "raw_output": datasets.Value("string"),
151
+ "split": datasets.Value("string"),
152
+ "task": datasets.Value("string"),
153
+ 'input_core_tag_left': datasets.Value("string"),
154
+ 'input_core_tag_right': datasets.Value("string"),
155
+ 'output_core_tag_left': datasets.Value("string"),
156
+ 'output_core_tag_right': datasets.Value("string"),
157
+ 'target': datasets.Value("string"),
158
+ }
159
+ )
160
+
161
+ return datasets.DatasetInfo(
162
+ # This is the description that will appear on the datasets page.
163
+ description=_DESCRIPTION,
164
+ # This defines the different columns of the dataset and their types
165
+ features=features, # Here we define them above because they are different between the two configurations
166
+ # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
167
+ # specify them. They'll be used if as_supervised=True in builder.as_dataset.
168
+ # supervised_keys=("sentence", "label"),
169
+ # # Homepage of the dataset for documentation
170
+ homepage=_HOMEPAGE,
171
+ # License for the dataset if available
172
+ license=_LICENSE,
173
+ # Citation for the dataset
174
+ citation=_CITATION,
175
+ )
176
+
177
+ def _split_generators(self, dl_manager):
178
+ # This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
179
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
180
+
181
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
182
+ # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
183
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
184
+ # urls = _URLS[self.config.name]
185
+ root = dl_manager.download_and_extract('./data.zip')
186
+
187
+ sample_group = self.config.sample_group
188
+ insert_core_tags = self.config.insert_core_tags
189
+ use_selfies = self.config.use_selfies
190
+ use_test_subset = self.config.use_test_subset
191
+ use_first = self.config.use_first
192
+
193
+ return [
194
+ datasets.SplitGenerator(
195
+ name=datasets.Split.TRAIN,
196
+ # These kwargs will be passed to _generate_examples
197
+ gen_kwargs={
198
+ "root": root,
199
+ "sample_group": sample_group,
200
+ "split": "train",
201
+ "tasks": self.config.tasks,
202
+ "insert_core_tags": insert_core_tags,
203
+ "use_selfies": use_selfies,
204
+ "use_test_subset": False,
205
+ "use_first": use_first,
206
+ },
207
+ ),
208
+ datasets.SplitGenerator(
209
+ name=datasets.Split.VALIDATION,
210
+ # These kwargs will be passed to _generate_examples
211
+ gen_kwargs={
212
+ "root": root,
213
+ "sample_group": sample_group,
214
+ "split": "dev",
215
+ "tasks": self.config.tasks,
216
+ "insert_core_tags": insert_core_tags,
217
+ "use_selfies": use_selfies,
218
+ "use_test_subset": False,
219
+ "use_first": use_first,
220
+ },
221
+ ),
222
+ datasets.SplitGenerator(
223
+ name=datasets.Split.TEST,
224
+ # These kwargs will be passed to _generate_examples
225
+ gen_kwargs={
226
+ "root": root,
227
+ "sample_group": sample_group,
228
+ "split": "test",
229
+ "tasks": self.config.tasks,
230
+ "insert_core_tags": insert_core_tags,
231
+ "use_selfies": use_selfies,
232
+ "use_test_subset": use_test_subset,
233
+ "use_first": use_first,
234
+ },
235
+ ),
236
+ ]
237
+
238
+ def _generate_instruction_examples(self, root, sample_group, split, tasks, insert_core_tags, use_selfies, use_test_subset, use_first):
239
+ if split == 'test' and use_test_subset is True:
240
+ real_split = 'test_subset'
241
+ else:
242
+ real_split = split
243
+
244
+ for task in tasks:
245
+ with open(os.path.join(root, 'sample', sample_group, real_split, task + '.json'), 'r') as fs:
246
+ sample_record = json.load(fs)
247
+ assert sample_record['task'] == task, (sample_record['task'], task, os.path.join(root, 'sample', sample_group, real_split, task + '.json'))
248
+ assert sample_record['split'] == real_split
249
+ template_name = sample_record['template_name']
250
+ samples = sample_record['samples']
251
+
252
+ with open(os.path.join(root, 'template', template_name, task + '.json'), 'r') as f:
253
+ templates = json.load(f)
254
+ if use_selfies:
255
+ for template in templates:
256
+ input_template = template['input']
257
+ output_template = template['output']
258
+ input_template = input_template.replace("SMILES", "SELFIES")
259
+ output_template = output_template.replace("SMILES", "SELFIES")
260
+ template['input'] = input_template
261
+ template['output'] = output_template
262
+
263
+ data = []
264
+ with open(os.path.join(root, 'raw_selfies' if use_selfies else 'raw', split, task + '.jsonl'), 'r') as fr:
265
+ for line in fr:
266
+ item = json.loads(line)
267
+ data.append(item)
268
+
269
+ with open(os.path.join(root, 'core_tag', task + '.json'), 'r') as f:
270
+ core_tags = json.load(f)
271
+ input_core_tag_left = core_tags['input'][0]
272
+ input_core_tag_right = core_tags['input'][1]
273
+ if use_selfies and input_core_tag_left == '<SMILES>':
274
+ assert input_core_tag_right == '</SMILES>'
275
+ input_core_tag_left = '<SELFIES>'
276
+ input_core_tag_right = '</SELFIES>'
277
+ output_core_tag_left = core_tags['output'][0]
278
+ output_core_tag_right = core_tags['output'][1]
279
+ if use_selfies and output_core_tag_left == '<SMILES>':
280
+ assert output_core_tag_right == '</SMILES>'
281
+ output_core_tag_left = '<SELFIES>'
282
+ output_core_tag_right = '</SELFIES>'
283
+
284
+ for sample_item in (samples if use_first is None else samples[:use_first]):
285
+ try:
286
+ data_item = data[sample_item['idx']]
287
+ except IndexError:
288
+ raise IndexError('In %s for %s, data index exceeds the number of samples. The data size is %d, while the index is %d.' % (real_split, task, len(data), sample_item['idx']))
289
+ assert data_item['task'] == task
290
+ assert data_item['split'] == split
291
+ template_id = sample_item['template_id']
292
+ template = templates[template_id]
293
+ input_template = template['input']
294
+ output_template = template['output']
295
+ input_data = data_item['input']
296
+ if insert_core_tags and input_core_tag_left is not None:
297
+ assert input_core_tag_right is not None
298
+ input_data_str = '%s %s %s' % (input_core_tag_left, input_data, input_core_tag_right)
299
+ else:
300
+ input_data_str = input_data
301
+ input_str = input_template.replace('<INPUT>', input_data_str)
302
+ output_data = data_item['output']
303
+ if isinstance(output_data, str):
304
+ target = None
305
+ elif isinstance(output_data, dict):
306
+ target = sample_item['target']
307
+ output_data = output_data[target]
308
+ else:
309
+ raise ValueError
310
+ if insert_core_tags and output_core_tag_left is not None:
311
+ assert output_core_tag_right is not None
312
+ output_data_str = '%s %s %s' % (output_core_tag_left, output_data, output_core_tag_right)
313
+ else:
314
+ output_data_str = output_data
315
+ output_str = output_template.replace('<OUTPUT>', output_data_str)
316
+ sample_id = '%s.%s.%d.%s' % (task, split, sample_item['idx'], str(target))
317
+ output_sample = {
318
+ 'sample_id': sample_id,
319
+ 'input': input_str,
320
+ 'output': output_str,
321
+ 'raw_input': input_data,
322
+ 'raw_output': output_data,
323
+ 'task': task,
324
+ 'split': real_split,
325
+ 'input_core_tag_left': input_core_tag_left,
326
+ 'input_core_tag_right': input_core_tag_right,
327
+ 'output_core_tag_left': output_core_tag_left,
328
+ 'output_core_tag_right': output_core_tag_right,
329
+ 'target': target,
330
+ }
331
+ yield sample_id, output_sample
332
+
333
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
334
+ def _generate_examples(self, *args, **kwargs):
335
+ # This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
336
+ # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
337
+
338
+ return self._generate_instruction_examples(*args, **kwargs)
data.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8598664507b0b7768ed34f70db194625e60fc67a14e6fa4fa415952d52c45150
3
+ size 692308728
fig/statistics.png ADDED

Git LFS Details

  • SHA256: bbeb4188506889987beeb4140d4dfcd16046b2c2515196a9805c0602a1c6311e
  • Pointer size: 131 Bytes
  • Size of remote file: 558 kB
fig/tasks.png ADDED

Git LFS Details

  • SHA256: dab7f0a001600b8c6ab3caee0ebb4b78cd501f21e11bdc51839a3740897a584f
  • Pointer size: 132 Bytes
  • Size of remote file: 1.73 MB