Datasets:

ArXiv:
Maurice Weber commited on
Commit
fbbd8c2
1 Parent(s): fde171d

simplify interface

Browse files
Files changed (1) hide show
  1. RedPajama-Data-V2.py +178 -215
RedPajama-Data-V2.py CHANGED
@@ -21,16 +21,16 @@ import datasets
21
  import traceback
22
  import os
23
  import gzip
 
24
 
25
  logger = datasets.logging.get_logger(__name__)
26
 
27
  _DESCRIPTION = """\
28
- RedPajama V2 is a Data Foundation of Web Text Documents with Quality Annotations.
29
  """
30
 
31
  _URL_BASE = 'https://data.together.xyz/redpajama-data-v2/v1.0.0'
32
  _LANGUAGES = ("en", "de", "fr", "es", "it")
33
- _SAMPLE_SNAPSHOT_ID = "2023-06"
34
  _LISTINGS_PATTERN = "listings/{language}-{snapshot}-{partition}.txt"
35
 
36
  _CC_SNAPSHOT_IDS = (
@@ -124,120 +124,53 @@ _CC_SNAPSHOT_IDS = (
124
  class RedPajamaDataV2Config(datasets.BuilderConfig):
125
  """BuilderConfig for RedPajama."""
126
 
127
- def __init__(self, *args, language, partition, snapshots, **kwargs):
128
  """BuilderConfig for RedPajama.
129
  Args:
130
  **kwargs: keyword arguments forwarded to super.
131
  """
132
  super(RedPajamaDataV2Config, self).__init__(**kwargs)
133
- self.partition = partition
134
- self.snapshots = snapshots
135
- self.language = language
136
-
137
-
138
- _BUILDER_CONFIGS = [
139
- RedPajamaDataV2Config(
140
- name=f'_sample',
141
- partition='sample',
142
- snapshots=None,
143
- language=None,
144
- version=datasets.Version("1.0.0", ""),
145
- description=f"RedPajamaV2 Sample",
146
- ),
147
- # this one is just an alias for the sample
148
- RedPajamaDataV2Config(
149
- name=f'sample',
150
- partition='sample',
151
- snapshots=None,
152
- language=None,
153
- version=datasets.Version("1.0.0", ""),
154
- description=f"RedPajamaV2 Sample",
155
- )
156
- ]
157
-
158
- for lang in _LANGUAGES:
159
- _BUILDER_CONFIGS.extend(
160
- [
161
- # single snapshot
162
- RedPajamaDataV2Config(
163
- name=f'{lang}-head-middle-{snapshot}',
164
- partition='head_middle',
165
- snapshots=[snapshot],
166
- language=lang,
167
- version=datasets.Version("1.0.0", ""),
168
- description=f"RedPajamaV2 head-middle {lang}-{snapshot}",
169
- )
170
- for snapshot in _CC_SNAPSHOT_IDS
171
- ] + [
172
- # all snapshots
173
- RedPajamaDataV2Config(
174
- name=f'{lang}-head-middle-all',
175
- partition='head_middle',
176
- snapshots=_CC_SNAPSHOT_IDS,
177
- language=lang,
178
- version=datasets.Version("1.0.0", ""),
179
- description=f"RedPajamaV2 head-middle {lang}"
180
- )
181
- ]
182
- )
183
-
184
- _BUILDER_CONFIGS.extend(
185
- [
186
- # single snapshot
187
- RedPajamaDataV2Config(
188
- name=f'{lang}-tail-{snapshot}',
189
- partition='tail',
190
- snapshots=[snapshot],
191
- language=lang,
192
- version=datasets.Version("1.0.0", ""),
193
- description=f"RedPajamaV2 tail {lang}-{snapshot}",
194
- )
195
- for snapshot in _CC_SNAPSHOT_IDS
196
- ] + [
197
- # all snapshots
198
- RedPajamaDataV2Config(
199
- name=f'{lang}-tail-all',
200
- partition='tail',
201
- snapshots=_CC_SNAPSHOT_IDS,
202
- language=lang,
203
- version=datasets.Version("1.0.0", ""),
204
- description=f"RedPajamaV2 tail {lang}"
205
- )
206
- ]
207
- )
208
 
209
 
210
  class RedPajamaV2(datasets.GeneratorBasedBuilder):
211
  """ RedPajama V2: Quality annotated Web Text Documents. """
212
 
213
- BUILDER_CONFIGS = _BUILDER_CONFIGS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
 
215
  def _info(self):
216
- if self.config.partition == "tail":
217
- return datasets.DatasetInfo(
218
- description=_DESCRIPTION,
219
- features=datasets.Features(
220
- {
221
- "raw_content": datasets.Value("string"),
222
- "doc_id": datasets.Value("string"),
223
- "meta": datasets.Value("string"),
224
- }
225
- ),
226
- supervised_keys=None,
227
- )
228
- else:
229
- return datasets.DatasetInfo(
230
- description=_DESCRIPTION,
231
- features=datasets.Features(
232
- {
233
- "raw_content": datasets.Value("string"),
234
- "doc_id": datasets.Value("string"),
235
- "meta": datasets.Value("string"),
236
- "quality_signals": datasets.Value("string")
237
- }
238
- ),
239
- supervised_keys=None,
240
- )
241
 
242
  def _split_generators_sample(self, dl_manager):
243
  # fetch documents
@@ -248,15 +181,15 @@ class RedPajamaV2(datasets.GeneratorBasedBuilder):
248
  listings = [line.strip() for line in fd]
249
 
250
  # fetch documents
251
- docs_files = dl_manager.download({
252
- _SAMPLE_SNAPSHOT_ID: [
253
  f"sample/documents/{lst}.json.gz" for lst in listings
254
  ]
255
  })
256
 
257
  # fetch quality signals
258
- signals_files = dl_manager.download({
259
- _SAMPLE_SNAPSHOT_ID: [
260
  f"sample/quality_signals/{lst}.signals.json.gz"
261
  for lst in listings
262
  ]
@@ -266,74 +199,78 @@ class RedPajamaV2(datasets.GeneratorBasedBuilder):
266
  datasets.SplitGenerator(
267
  name=datasets.Split.TRAIN,
268
  gen_kwargs={
269
- "documents_files": {
270
- _SAMPLE_SNAPSHOT_ID: docs_files[_SAMPLE_SNAPSHOT_ID]
271
- },
272
- "quality_signals_files": {
273
- _SAMPLE_SNAPSHOT_ID: signals_files[_SAMPLE_SNAPSHOT_ID]
274
- }
275
  }
276
  )
277
  ]
278
 
279
  def _split_generators_full(self, dl_manager):
280
- url_lists = dl_manager.download_and_extract({
281
- snapshot_id: _LISTINGS_PATTERN.format(
282
- language=self.config.language,
283
- snapshot=snapshot_id,
284
- partition=self.config.partition,
285
- )
286
- for snapshot_id in self.config.snapshots
287
- })
288
-
289
- listings_ids = {}
290
-
291
- for snapshot_id, listings_file in url_lists.items():
292
- with open(listings_file, encoding="utf-8") as f:
293
- listings_ids[snapshot_id] = [line.strip() for line in f]
294
-
295
- # build urls pointing to documents
296
- document_urls = {
297
- snapshot_id: [
298
- os.path.join(_URL_BASE, f"documents/{lst_id}.json.gz")
299
- for lst_id in listings_ids[snapshot_id]
300
- ]
301
- for snapshot_id in self.config.snapshots
302
- }
303
 
304
- documents_files = dl_manager.download(document_urls)
 
305
 
306
- # build urls pointing to quality signals
307
- if self.config.partition == "head_middle":
308
- quality_signals_urls = {
309
- snapshot_id: [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  os.path.join(
311
- _URL_BASE,
312
- f"quality_signals/{lst_id}.signals.json.gz"
313
  )
314
- for lst_id in listings_ids[snapshot_id]
315
- ]
316
- for snapshot_id in self.config.snapshots
317
- }
318
 
319
- quality_signals_files = dl_manager.download(
320
- quality_signals_urls
321
- )
322
- else:
323
- quality_signals_files = {}
324
 
325
  return [
326
  datasets.SplitGenerator(
327
  name=datasets.Split.TRAIN,
328
  gen_kwargs={
329
- "documents_files": {
330
- snapshot_id: documents_files[snapshot_id]
331
- for snapshot_id in self.config.snapshots
332
- },
333
- "quality_signals_files": {
334
- snapshot_id: quality_signals_files.get(snapshot_id)
335
- for snapshot_id in self.config.snapshots
336
- }
337
  }
338
  )
339
  ]
@@ -344,58 +281,84 @@ class RedPajamaV2(datasets.GeneratorBasedBuilder):
344
 
345
  return self._split_generators_full(dl_manager)
346
 
347
- def _generate_examples(self, documents_files, quality_signals_files):
348
- """ This function returns examples """
349
- snapshots = list(documents_files.keys())
350
-
351
  key = 0
352
- for snapshot in snapshots:
353
- docs_files = documents_files[snapshot]
354
- if self.config.partition in ("head_middle", "sample"):
355
- qs_files = quality_signals_files[snapshot]
356
- else:
357
- qs_files = None
358
-
359
- assert len(docs_files) == len(qs_files)
360
-
361
- for doc_file, qs_file in zip(docs_files, qs_files):
362
- with gzip.open(doc_file, "rt", encoding="utf-8") as df:
363
- with gzip.open(qs_file, "rt", encoding="utf-8") as qf:
364
- for row, (doc, qs) in enumerate(zip(df, qf)):
365
-
366
- try:
367
- doc = json.loads(doc)
368
- qs = json.loads(qs)
369
- doc_id = qs["id"]
370
-
371
- meta = {
372
- "url": doc["url"],
373
- "language": doc["language"],
374
- "source_domain": doc["source_domain"],
375
- "date_download": doc["date_download"],
376
- "digest": doc["digest"],
377
- }
378
-
379
- if self.config.partition == "tail":
380
- yield key, {
381
- "raw_content": doc["raw_content"],
382
- "doc_id": doc_id,
383
- "meta": json.dumps(meta),
384
- }
385
- else:
386
- yield key, {
387
- "raw_content": doc["raw_content"],
388
- "doc_id": doc_id,
389
- "meta": json.dumps(meta),
390
- "quality_signals": json.dumps(
391
- qs["quality_signals"]
392
- ),
393
- }
394
- key += 1
395
- except Exception as e:
396
- print(f'doc_file: {doc_file}')
397
- print(f'qs_file: {qs_file}')
398
- print(f'row: {row}')
399
- traceback.print_exc()
400
-
401
- raise e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  import traceback
22
  import os
23
  import gzip
24
+ from typing import List
25
 
26
  logger = datasets.logging.get_logger(__name__)
27
 
28
  _DESCRIPTION = """\
29
+ RedPajama V2: an Open Dataset for Training Large Language Models
30
  """
31
 
32
  _URL_BASE = 'https://data.together.xyz/redpajama-data-v2/v1.0.0'
33
  _LANGUAGES = ("en", "de", "fr", "es", "it")
 
34
  _LISTINGS_PATTERN = "listings/{language}-{snapshot}-{partition}.txt"
35
 
36
  _CC_SNAPSHOT_IDS = (
 
124
  class RedPajamaDataV2Config(datasets.BuilderConfig):
125
  """BuilderConfig for RedPajama."""
126
 
127
+ def __init__(self, *args, **kwargs):
128
  """BuilderConfig for RedPajama.
129
  Args:
130
  **kwargs: keyword arguments forwarded to super.
131
  """
132
  super(RedPajamaDataV2Config, self).__init__(**kwargs)
133
+ self.partition: str = kwargs.pop("partition", "all")
134
+ self.snapshots: List[str] = kwargs.pop("snapshots", _CC_SNAPSHOT_IDS)
135
+ self.languages: List[str] = kwargs.pop("languages", _LANGUAGES)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
 
138
  class RedPajamaV2(datasets.GeneratorBasedBuilder):
139
  """ RedPajama V2: Quality annotated Web Text Documents. """
140
 
141
+ BUILDER_CONFIGS = [
142
+ RedPajamaDataV2Config(
143
+ name='_sample',
144
+ version=datasets.Version("1.0.0", ""),
145
+ description=f"RedPajamaV2 Sample",
146
+ ),
147
+ # this one is just an alias for the sample
148
+ RedPajamaDataV2Config(
149
+ name='sample',
150
+ version=datasets.Version("1.0.0", ""),
151
+ description=f"RedPajamaV2 Sample",
152
+ ),
153
+
154
+ RedPajamaDataV2Config(
155
+ name='default',
156
+ version=datasets.Version("1.0.0", ""),
157
+ description=f"RedPajamaV2",
158
+ )
159
+ ]
160
 
161
  def _info(self):
162
+ return datasets.DatasetInfo(
163
+ description=_DESCRIPTION,
164
+ features=datasets.Features(
165
+ {
166
+ "raw_content": datasets.Value("string"),
167
+ "doc_id": datasets.Value("string"),
168
+ "meta": datasets.Value("string"),
169
+ "quality_signals": datasets.Value("string")
170
+ }
171
+ ),
172
+ supervised_keys=None,
173
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
  def _split_generators_sample(self, dl_manager):
176
  # fetch documents
 
181
  listings = [line.strip() for line in fd]
182
 
183
  # fetch documents
184
+ documents_files = dl_manager.download({
185
+ "head_middle": [
186
  f"sample/documents/{lst}.json.gz" for lst in listings
187
  ]
188
  })
189
 
190
  # fetch quality signals
191
+ quality_signals_files = dl_manager.download({
192
+ "head_middle": [
193
  f"sample/quality_signals/{lst}.signals.json.gz"
194
  for lst in listings
195
  ]
 
199
  datasets.SplitGenerator(
200
  name=datasets.Split.TRAIN,
201
  gen_kwargs={
202
+ "listings_ids": {"head_middle": listings},
203
+ "documents_files": documents_files,
204
+ "quality_signals_files": quality_signals_files
 
 
 
205
  }
206
  )
207
  ]
208
 
209
  def _split_generators_full(self, dl_manager):
210
+ snapshots = getattr(self.config, 'snapshots', _CC_SNAPSHOT_IDS)
211
+ languages = getattr(self.config, 'languages', _LANGUAGES)
212
+ partition = getattr(self.config, 'partition', 'all')
213
+
214
+ partitions = {
215
+ "all": ["head_middle", "tail"]
216
+ }.get(partition, [partition])
217
+
218
+ # nested structure: partition -> urls
219
+ listings_files_urls = {}
220
+ for part in partitions:
221
+ listings_files_urls[part] = []
222
+ for snapshot_id in snapshots:
223
+ for lang in languages:
224
+ listings_files_urls[part].append(
225
+ _LISTINGS_PATTERN.format(
226
+ language=lang,
227
+ snapshot=snapshot_id,
228
+ partition=part,
229
+ )
230
+ )
 
 
231
 
232
+ # fetch listings from hub
233
+ listings_files = dl_manager.download_and_extract(listings_files_urls)
234
 
235
+ # fetch listings
236
+ listings_ids = {}
237
+ for part, part_listings_files in listings_files.items():
238
+ listings_ids[part] = []
239
+ for listings_file in part_listings_files:
240
+ with open(listings_file, encoding="utf-8") as f:
241
+ listings_ids[part].extend([
242
+ line.strip() for line in f
243
+ ])
244
+
245
+ # build urls pointing to documents and quality signals
246
+ document_urls = {}
247
+ quality_signals_urls = {}
248
+ for part, part_listings_ids in listings_ids.items():
249
+ document_urls[part] = []
250
+ quality_signals_urls[part] = []
251
+ for lst_id in part_listings_ids:
252
+ document_urls[part].append(
253
+ os.path.join(_URL_BASE, f"documents/{lst_id}.json.gz")
254
+ )
255
+ if part != "head_middle":
256
+ continue
257
+
258
+ quality_signals_urls[part].append(
259
  os.path.join(
260
+ _URL_BASE, f"quality_signals/{lst_id}.signals.json.gz"
 
261
  )
262
+ )
 
 
 
263
 
264
+ documents_files = dl_manager.download(document_urls)
265
+ quality_signals_files = dl_manager.download(quality_signals_urls)
 
 
 
266
 
267
  return [
268
  datasets.SplitGenerator(
269
  name=datasets.Split.TRAIN,
270
  gen_kwargs={
271
+ "listings_ids": listings_ids,
272
+ "documents_files": documents_files,
273
+ "quality_signals_files": quality_signals_files
 
 
 
 
 
274
  }
275
  )
276
  ]
 
281
 
282
  return self._split_generators_full(dl_manager)
283
 
284
+ def _generate_examples(
285
+ self, listings_ids, documents_files, quality_signals_files
286
+ ):
 
287
  key = 0
288
+ for part in documents_files.keys():
289
+ part_docs_files = documents_files[part]
290
+ part_qs_files = quality_signals_files[part]
291
+ part_listings_ids = listings_ids[part]
292
+
293
+ if len(part_qs_files) == 0:
294
+ for sample in self._handle_tail_partition(
295
+ part, part_docs_files, part_listings_ids
296
+ ):
297
+ yield key, sample
298
+ key += 1
299
+ continue
300
+
301
+ for sample in self._handle_head_middle_partition(
302
+ part, part_docs_files, part_qs_files, part_listings_ids
303
+ ):
304
+ yield key, sample
305
+ key += 1
306
+
307
+ def _handle_tail_partition(self, part, docs_files, listings_ids):
308
+ for doc_file, listing_id in zip(docs_files, listings_ids):
309
+ with gzip.open(doc_file, "rt", encoding="utf-8") as df:
310
+ for row, doc in enumerate(df):
311
+ doc_id = f"{listing_id}.json.gz/{row}"
312
+ try:
313
+ yield self.handle_record(part, doc_id, doc, None)
314
+ except Exception as e:
315
+ print(f'doc_file: {doc_file}')
316
+ print(f'row: {row}')
317
+ traceback.print_exc()
318
+ raise e
319
+
320
+ def _handle_head_middle_partition(
321
+ self, part, docs_files, qs_files, listings_ids
322
+ ):
323
+ assert len(docs_files) == len(qs_files)
324
+
325
+ listings_ids = listings_ids[:len(docs_files)]
326
+
327
+ for doc_file, qs_file, listings_id in zip(
328
+ docs_files, qs_files, listings_ids
329
+ ):
330
+ with gzip.open(doc_file, "rt", encoding="utf-8") as df:
331
+ with gzip.open(qs_file, "rt", encoding="utf-8") as qf:
332
+ for row, (doc, qs) in enumerate(zip(df, qf)):
333
+ doc_id = f"{listings_id}.json.gz/{row}"
334
+ try:
335
+ yield self.handle_record(part, doc_id, doc, qs)
336
+ except Exception as e:
337
+ print(f'doc_file: {doc_file}')
338
+ print(f'qs_file: {qs_file}')
339
+ print(f'row: {row}')
340
+ traceback.print_exc()
341
+ raise e
342
+
343
+ @staticmethod
344
+ def handle_record(part, doc_id, doc, qs):
345
+ doc = json.loads(doc)
346
+ qs = json.loads(qs) if qs is not None else {}
347
+
348
+ meta = {
349
+ "url": doc["url"],
350
+ "partition": part,
351
+ "language": doc["language"],
352
+ "source_domain": doc["source_domain"],
353
+ "date_download": doc["date_download"],
354
+ "digest": doc["digest"],
355
+ }
356
+
357
+ quality_signals = json.dumps(qs.get("quality_signals", {}))
358
+
359
+ return {
360
+ "raw_content": doc["raw_content"],
361
+ "doc_id": doc_id,
362
+ "meta": json.dumps(meta),
363
+ "quality_signals": quality_signals,
364
+ }