jordi-ai2 commited on
Commit
30b20f0
·
verified ·
1 Parent(s): 17ece0a

Update bulk_download.py

Browse files
Files changed (1) hide show
  1. bulk_download.py +146 -103
bulk_download.py CHANGED
@@ -3,7 +3,7 @@
3
  Downloads whole shard tars from allenai/molmobot-data, decompresses each
4
  inner .tar.zst archive, and extracts its contents into:
5
 
6
- <target_dir>/<task_config>/part<X>/train/…
7
 
8
  A local JSON manifest tracks progress per-shard so that interrupted
9
  downloads can be resumed without re-extracting already-completed shards.
@@ -74,8 +74,10 @@ def _load_manifest(target_dir: str) -> dict:
74
 
75
  {
76
  "<config_name>": {
77
- "num_completed_entries": [120, 124, ...]
78
- "completed_shards": [0, 1, ...]
 
 
79
  },
80
  ...
81
  }
@@ -99,13 +101,13 @@ def _save_manifest(target_dir: str, manifest: dict) -> None:
99
  tmp.replace(p)
100
 
101
 
102
- def load_entries(config_name: str) -> list[dict]:
103
  """Load the parquet arrow table for a task config as a list of dicts."""
104
- ds = load_dataset(REPO, name=config_name, split="pkgs")
105
  return [row for row in ds]
106
 
107
 
108
- def summarize_config(config_name: str, entries: list[dict]) -> dict:
109
  """Return a summary dict with sizes, shard/part counts."""
110
  compressed = sum(e["size"] for e in entries)
111
  inflated = sum(e.get("inflated_size", 0) for e in entries)
@@ -126,6 +128,7 @@ def summarize_config(config_name: str, entries: list[dict]) -> dict:
126
 
127
  return {
128
  "config": config_name,
 
129
  "entries": len(entries),
130
  "compressed": compressed,
131
  "inflated": inflated if has_inflated else None,
@@ -147,7 +150,11 @@ def print_summary(summary: dict) -> None:
147
  print(f" Extracted size: (unknown)")
148
  for p, info in sorted(summary["per_part"].items()):
149
  dl = _format_size(info["compressed"])
150
- ex = _format_size(info["inflated"]) if info["inflated"] is not None else "unknown"
 
 
 
 
151
  print(f" part {p}: {info['entries']} entries, dl {dl}, extracted {ex}")
152
 
153
 
@@ -163,7 +170,9 @@ def main() -> None:
163
  parser = argparse.ArgumentParser(
164
  description="Download molmobot training data from Hugging Face.",
165
  formatter_class=argparse.RawDescriptionHelpFormatter,
166
- epilog=("Available task configs:\n" + "\n".join(f" - {c}" for c in TASK_CONFIGS)),
 
 
167
  )
168
  parser.add_argument(
169
  "target_dir",
@@ -201,6 +210,12 @@ def main() -> None:
201
  action="store_true",
202
  help="Skip confirmation prompts.",
203
  )
 
 
 
 
 
 
204
  parser.add_argument(
205
  "--max_part_shards",
206
  type=int,
@@ -220,8 +235,15 @@ def main() -> None:
220
  else:
221
  parser.error("Specify --config <NAME>, --all, or --list.")
222
 
 
 
 
 
 
 
 
223
  # Load entries and compute summaries
224
- all_entries: dict[str, list[dict]] = {}
225
  total_compressed = 0
226
  total_inflated = 0
227
  has_all_inflated = True
@@ -230,86 +252,100 @@ def main() -> None:
230
 
231
  manifest = _load_manifest(args.target_dir)
232
 
233
- configs_to_skip = set()
234
  for config_name in configs_to_process:
235
- part_to_shard_to_entries: dict[int, dict[int, list[dict]]] = {}
236
- entries = load_entries(config_name)
237
-
238
- part_entries = defaultdict(list)
239
- for e in entries:
240
- part_entries[e["part"]].append(e)
241
-
242
- for part in part_entries:
243
- shard_to_entries = defaultdict(list)
244
- for e in part_entries[part]:
245
- shard_to_entries[e["shard_id"]].append(e)
246
- part_to_shard_to_entries[part] = {**shard_to_entries}
247
-
248
- if args.part is not None:
249
- if args.part not in part_to_shard_to_entries:
250
- print(f" {config_name} has no part {args.part}. Skipping")
251
- configs_to_skip.add(config_name)
252
- continue
253
- if args.max_part_shards is not None:
254
- shard_to_entries = part_to_shard_to_entries[args.part]
255
- shards = sorted(shard_to_entries.keys())[: args.max_part_shards]
256
- part_to_shard_to_entries = {args.part: {s: shard_to_entries[s] for s in shards}}
257
- else:
258
- if args.max_part_shards is not None:
259
- for part in part_to_shard_to_entries:
260
- shard_to_entries = part_to_shard_to_entries[part]
261
  shards = sorted(shard_to_entries.keys())[: args.max_part_shards]
262
- part_to_shard_to_entries[part] = {s: shard_to_entries[s] for s in shards}
263
-
264
- # Show resume status and filter out fully-completed configs
265
- cfg_m = manifest.get(config_name, {})
266
- done_shards = set(cfg_m.get("completed_shards", []))
267
- if done_shards:
268
- required_shards = set(
269
- sum(
270
- [
271
- list(shard_to_entries.keys())
272
- for part, shard_to_entries in part_to_shard_to_entries.items()
273
- ],
274
- [],
275
- )
276
- )
277
- missing_shards = required_shards - done_shards
278
- if not missing_shards:
279
- print(f" {config_name}: already fully extracted, skipping")
280
- configs_to_skip.add(config_name)
281
- continue
282
  else:
283
- print(
284
- f" {config_name}: {len(missing_shards)}/{len(required_shards)} "
285
- f"shards pending extraction (will resume)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  )
287
-
288
- entries = [
289
- e
290
- for part, shard_to_entries in part_to_shard_to_entries.items()
291
- for shard, entries in shard_to_entries.items()
292
- for e in entries
293
- if shard not in done_shards
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  ]
 
 
295
 
296
- all_entries[config_name] = entries
297
- summary = summarize_config(config_name, entries)
298
-
299
- print_summary(summary)
300
- total_compressed += summary["compressed"]
301
- if summary["inflated"] is not None:
302
- total_inflated += summary["inflated"]
303
- else:
304
- has_all_inflated = False
305
- print()
306
-
307
- configs_to_process = [
308
- config_name for config_name in configs_to_process if config_name not in configs_to_skip
309
- ]
310
 
311
- if len(configs_to_process) > 1:
312
- print(f"Total across {len(configs_to_process)} configs:")
313
  print(f" Download size: {_format_size(total_compressed)}")
314
  if has_all_inflated:
315
  print(f" Extracted size: {_format_size(total_inflated)}")
@@ -330,21 +366,23 @@ def main() -> None:
330
  print("Aborted.")
331
  return
332
 
333
- for config_name in configs_to_process:
334
- print(f"\n{'=' * 60}")
335
- print(f" {config_name}")
336
- print(f"{'=' * 60}")
337
- try:
338
- download_and_extract_config(
339
- config_name,
340
- args.target_dir,
341
- entries=all_entries[config_name],
342
- )
343
- except KeyboardInterrupt:
344
- print("\nInterrupted. Progress has been saved; re-run to resume.")
345
- raise SystemExit(1)
346
- except Exception as e:
347
- print(f"FAILED: {config_name} — {e}")
 
 
348
 
349
  print("\nAll done.")
350
 
@@ -352,20 +390,21 @@ def main() -> None:
352
  def download_and_extract_config(
353
  config_name: str,
354
  target_dir: str,
 
355
  entries: list[dict] | None = None,
356
  ) -> None:
357
  """Download and extract all shards for a single task config.
358
 
359
  Whole shard tars are downloaded via ``hf_hub_download`` (which caches
360
  them). Each inner ``.tar.zst`` member is decompressed and extracted
361
- into ``<target_dir>/<config_name>/part<X>/train/``.
362
 
363
  Progress is tracked per-shard in a local manifest so that interrupted
364
  runs can be resumed.
365
  """
366
  if entries is None:
367
  print(f"Loading entry table for {config_name}...")
368
- entries = load_entries(config_name)
369
 
370
  # Build lookup: path -> entry (for part resolution)
371
  path_to_entry = {e["path"]: e for e in entries}
@@ -378,7 +417,7 @@ def download_and_extract_config(
378
 
379
  # Load manifest for resume
380
  manifest = _load_manifest(target_dir)
381
- cfg_manifest = manifest.setdefault(config_name, {})
382
  completed_shards: set[int] = set(cfg_manifest.get("completed_shards", []))
383
  num_completed_entries: list[int] = cfg_manifest.get("num_completed_entries", [])
384
 
@@ -393,7 +432,9 @@ def download_and_extract_config(
393
  print(f"All shards for {config_name} already extracted.")
394
  return
395
 
396
- print(f"Downloading & extracting {len(remaining_shards)} shard(s) for {config_name}...")
 
 
397
 
398
  # Use a temporary cache dir so shard downloads don't accumulate
399
  # in the default HF cache (~/.cache/huggingface/hub/).
@@ -404,7 +445,7 @@ def download_and_extract_config(
404
  for shard_id in tqdm(remaining_shards, desc=f"{config_name} shards"):
405
  entries_count = 0
406
 
407
- shard_filename = f"{config_name}/shards/{shard_id:05d}.tar"
408
 
409
  shard_local = hf_hub_download(
410
  repo_id=REPO,
@@ -428,7 +469,9 @@ def download_and_extract_config(
428
  continue
429
 
430
  part = entry["part"]
431
- extract_dir = os.path.join(target_dir, config_name, f"part{part}", "train")
 
 
432
  os.makedirs(extract_dir, exist_ok=True)
433
 
434
  fobj = shard_tar.extractfile(member)
 
3
  Downloads whole shard tars from allenai/molmobot-data, decompresses each
4
  inner .tar.zst archive, and extracts its contents into:
5
 
6
+ <target_dir>/<task_config>/part<X>/<split>/…
7
 
8
  A local JSON manifest tracks progress per-shard so that interrupted
9
  downloads can be resumed without re-extracting already-completed shards.
 
74
 
75
  {
76
  "<config_name>": {
77
+ "<split>": {
78
+ "num_completed_entries": [120, 124, ...],
79
+ "completed_shards": [0, 1, ...],
80
+ }
81
  },
82
  ...
83
  }
 
101
  tmp.replace(p)
102
 
103
 
104
+ def load_entries(config_name: str, split: str) -> list[dict]:
105
  """Load the parquet arrow table for a task config as a list of dicts."""
106
+ ds = load_dataset(REPO, name=config_name, split=f"{split}_pkgs")
107
  return [row for row in ds]
108
 
109
 
110
+ def summarize_config(config_name: str, split: str, entries: list[dict]) -> dict:
111
  """Return a summary dict with sizes, shard/part counts."""
112
  compressed = sum(e["size"] for e in entries)
113
  inflated = sum(e.get("inflated_size", 0) for e in entries)
 
128
 
129
  return {
130
  "config": config_name,
131
+ "split": split,
132
  "entries": len(entries),
133
  "compressed": compressed,
134
  "inflated": inflated if has_inflated else None,
 
150
  print(f" Extracted size: (unknown)")
151
  for p, info in sorted(summary["per_part"].items()):
152
  dl = _format_size(info["compressed"])
153
+ ex = (
154
+ _format_size(info["inflated"])
155
+ if info["inflated"] is not None
156
+ else "unknown"
157
+ )
158
  print(f" part {p}: {info['entries']} entries, dl {dl}, extracted {ex}")
159
 
160
 
 
170
  parser = argparse.ArgumentParser(
171
  description="Download molmobot training data from Hugging Face.",
172
  formatter_class=argparse.RawDescriptionHelpFormatter,
173
+ epilog=(
174
+ "Available task configs:\n" + "\n".join(f" - {c}" for c in TASK_CONFIGS)
175
+ ),
176
  )
177
  parser.add_argument(
178
  "target_dir",
 
210
  action="store_true",
211
  help="Skip confirmation prompts.",
212
  )
213
+ parser.add_argument(
214
+ "--split",
215
+ type=str,
216
+ default="all",
217
+ help="Extract only the given split (`train`, `val`, or `all`). Default is `all`.",
218
+ )
219
  parser.add_argument(
220
  "--max_part_shards",
221
  type=int,
 
235
  else:
236
  parser.error("Specify --config <NAME>, --all, or --list.")
237
 
238
+ split_choices = dict(
239
+ train=["train"],
240
+ val=["val"],
241
+ all=["val", "train"],
242
+ )
243
+ splits = split_choices[args.split]
244
+
245
  # Load entries and compute summaries
246
+ all_entries: dict[str, dict[str, list[dict]]] = {split: {} for split in splits}
247
  total_compressed = 0
248
  total_inflated = 0
249
  has_all_inflated = True
 
252
 
253
  manifest = _load_manifest(args.target_dir)
254
 
255
+ configs_to_skip = {split: set() for split in splits}
256
  for config_name in configs_to_process:
257
+ for split in splits:
258
+ part_to_shard_to_entries: dict[int, dict[int, list[dict]]] = {}
259
+ entries = load_entries(config_name, split)
260
+
261
+ part_entries = defaultdict(list)
262
+ for e in entries:
263
+ part_entries[e["part"]].append(e)
264
+
265
+ for part in part_entries:
266
+ shard_to_entries = defaultdict(list)
267
+ for e in part_entries[part]:
268
+ shard_to_entries[e["shard_id"]].append(e)
269
+ part_to_shard_to_entries[part] = {**shard_to_entries}
270
+
271
+ if args.part is not None:
272
+ if args.part not in part_to_shard_to_entries:
273
+ print(f" {config_name} has no part {args.part}. Skipping")
274
+ configs_to_skip[split].add(config_name)
275
+ continue
276
+ if args.max_part_shards is not None:
277
+ shard_to_entries = part_to_shard_to_entries[args.part]
 
 
 
 
 
278
  shards = sorted(shard_to_entries.keys())[: args.max_part_shards]
279
+ part_to_shard_to_entries = {
280
+ args.part: {s: shard_to_entries[s] for s in shards}
281
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  else:
283
+ if args.max_part_shards is not None:
284
+ for part in part_to_shard_to_entries:
285
+ shard_to_entries = part_to_shard_to_entries[part]
286
+ shards = sorted(shard_to_entries.keys())[: args.max_part_shards]
287
+ part_to_shard_to_entries[part] = {
288
+ s: shard_to_entries[s] for s in shards
289
+ }
290
+
291
+ # Show resume status and filter out fully-completed configs
292
+ cfg_m = manifest.get(config_name, {}).get(split, {})
293
+ done_shards = set(cfg_m.get("completed_shards", []))
294
+ if done_shards:
295
+ required_shards = set(
296
+ sum(
297
+ [
298
+ list(shard_to_entries.keys())
299
+ for part, shard_to_entries in part_to_shard_to_entries.items()
300
+ ],
301
+ [],
302
+ )
303
  )
304
+ missing_shards = required_shards - done_shards
305
+ if not missing_shards:
306
+ print(f" {config_name}: already fully extracted, skipping")
307
+ configs_to_skip[split].add(config_name)
308
+ continue
309
+ else:
310
+ print(
311
+ f" {config_name}: {len(missing_shards)}/{len(required_shards)} "
312
+ f"shards pending extraction (will resume)"
313
+ )
314
+
315
+ entries = [
316
+ e
317
+ for part, shard_to_entries in part_to_shard_to_entries.items()
318
+ for shard, entries in shard_to_entries.items()
319
+ for e in entries
320
+ if shard not in done_shards
321
+ ]
322
+
323
+ all_entries[split][config_name] = entries
324
+ summary = summarize_config(config_name, split, entries)
325
+
326
+ print_summary(summary)
327
+ total_compressed += summary["compressed"]
328
+ if summary["inflated"] is not None:
329
+ total_inflated += summary["inflated"]
330
+ else:
331
+ has_all_inflated = False
332
+ print()
333
+
334
+ configs_to_process = {
335
+ split: [
336
+ config_name
337
+ for config_name in configs_to_process
338
+ if config_name not in configs_to_skip[split]
339
  ]
340
+ for split in splits
341
+ }
342
 
343
+ all_configs_to_process = sum(
344
+ len(split_cfg) for split_cfg in configs_to_process.values()
345
+ )
 
 
 
 
 
 
 
 
 
 
 
346
 
347
+ if all_configs_to_process > 1:
348
+ print(f"Total across {all_configs_to_process} configs:")
349
  print(f" Download size: {_format_size(total_compressed)}")
350
  if has_all_inflated:
351
  print(f" Extracted size: {_format_size(total_inflated)}")
 
366
  print("Aborted.")
367
  return
368
 
369
+ for split in splits:
370
+ for config_name in configs_to_process[split]:
371
+ print(f"\n{'=' * 60}")
372
+ print(f" {config_name} {split}")
373
+ print(f"{'=' * 60}")
374
+ try:
375
+ download_and_extract_config(
376
+ config_name,
377
+ args.target_dir,
378
+ split=split,
379
+ entries=all_entries[split][config_name],
380
+ )
381
+ except KeyboardInterrupt:
382
+ print("\nInterrupted. Progress has been saved; re-run to resume.")
383
+ raise SystemExit(1)
384
+ except Exception as e:
385
+ print(f"FAILED: {config_name} {split} — {e}")
386
 
387
  print("\nAll done.")
388
 
 
390
  def download_and_extract_config(
391
  config_name: str,
392
  target_dir: str,
393
+ split: str,
394
  entries: list[dict] | None = None,
395
  ) -> None:
396
  """Download and extract all shards for a single task config.
397
 
398
  Whole shard tars are downloaded via ``hf_hub_download`` (which caches
399
  them). Each inner ``.tar.zst`` member is decompressed and extracted
400
+ into ``<target_dir>/<config_name>/part<X>/<split>/``.
401
 
402
  Progress is tracked per-shard in a local manifest so that interrupted
403
  runs can be resumed.
404
  """
405
  if entries is None:
406
  print(f"Loading entry table for {config_name}...")
407
+ entries = load_entries(config_name, split)
408
 
409
  # Build lookup: path -> entry (for part resolution)
410
  path_to_entry = {e["path"]: e for e in entries}
 
417
 
418
  # Load manifest for resume
419
  manifest = _load_manifest(target_dir)
420
+ cfg_manifest = manifest.setdefault(config_name, {}).setdefault(split, {})
421
  completed_shards: set[int] = set(cfg_manifest.get("completed_shards", []))
422
  num_completed_entries: list[int] = cfg_manifest.get("num_completed_entries", [])
423
 
 
432
  print(f"All shards for {config_name} already extracted.")
433
  return
434
 
435
+ print(
436
+ f"Downloading & extracting {len(remaining_shards)} shard(s) for {config_name} {split}..."
437
+ )
438
 
439
  # Use a temporary cache dir so shard downloads don't accumulate
440
  # in the default HF cache (~/.cache/huggingface/hub/).
 
445
  for shard_id in tqdm(remaining_shards, desc=f"{config_name} shards"):
446
  entries_count = 0
447
 
448
+ shard_filename = f"{config_name}/{split}_shards/{shard_id:05d}.tar"
449
 
450
  shard_local = hf_hub_download(
451
  repo_id=REPO,
 
469
  continue
470
 
471
  part = entry["part"]
472
+ extract_dir = os.path.join(
473
+ target_dir, config_name, f"part{part}", split
474
+ )
475
  os.makedirs(extract_dir, exist_ok=True)
476
 
477
  fobj = shard_tar.extractfile(member)