davanstrien HF Staff Claude Fable 5 commited on
Commit
398713e
·
1 Parent(s): a154d89

Fan-out hardening from first production runs (16M rows embedded today)

Browse files

- Zero-copy float32 Arrow shard writer: the old add_column([e.tolist()...])
materialized ~18GB of Python floats at 1.2M rows and swap-wedged workers
silently; also halves shard size (float32 fixed_size_list vs list<double>)
- Passthrough consolidator: per-file download->upload, peak disk = ONE shard
(34GB wiki merge in 293s on cpu-xl); normalizes old list<double> shards to
fixed_size_list<float32> so mixed-version runs still merge loadable
- --streaming: file-level IterableDataset sharding, each rank streams only its
own files, bounded-memory part writes (very-big-dataset mode; text only)
- Input revision pinned at launch and recorded in the manifest - every rank
and any later --retry-rank slices the identical snapshot
- 'writing' heartbeat state so post-encode is visible, not silent
- --consolidate-flavor; retry exit-code check; manifest-driven retries

Validated on Jobs: wikipedia-en 6,407,814 rows (8x l4x1) and fineweb-edu
sample-10BT 9,672,101 rows (8x l4x1, 56 min end-to-end); streaming smoke green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

Files changed (4) hide show
  1. README.md +5 -3
  2. consolidate-shards.py +122 -49
  3. generate-embeddings.py +159 -17
  4. launch-embedding-fleet.py +37 -14
README.md CHANGED
@@ -58,9 +58,11 @@ Every shard is idempotent (a rank overwrites only its own files), so recovery is
58
  `--consolidate-only --run-id <id>` re-runs the merge. Each worker's timeout gives a **hard cost
59
  ceiling**: a fleet can never cost more than `N × flavor-rate × timeout`.
60
 
61
- Scale note: workers shard row-wise after loading the split, so each rank still downloads the full
62
- split first — fine up to a few tens of millions of rows; beyond that, shard at the file level or
63
- stream (planned follow-up).
 
 
64
 
65
  ## Which model?
66
 
 
58
  `--consolidate-only --run-id <id>` re-runs the merge. Each worker's timeout gives a **hard cost
59
  ceiling**: a fleet can never cost more than `N × flavor-rate × timeout`.
60
 
61
+ Scale note: by default workers shard row-wise after loading the split, so each rank downloads the
62
+ full split first — fine up to a few tens of millions of rows. Past that, add `--streaming`: workers
63
+ then shard at the **file** level and each rank streams only its own files (text only; needs
64
+ `num_files ≥ num_shards`). The launcher pins the input dataset revision either way, so every rank
65
+ — including a `--retry-rank` weeks later — slices the identical snapshot.
66
 
67
  ## Which model?
68
 
consolidate-shards.py CHANGED
@@ -1,18 +1,25 @@
1
  # /// script
2
  # requires-python = ">=3.10"
3
  # dependencies = [
4
- # "datasets",
5
  # "huggingface-hub>=1.12",
 
6
  # ]
7
  # ///
8
  """
9
- Merge the parquet shards of a fan-out embedding run (see launch-embedding-fleet.py)
10
- into the final Hub dataset, in one commit, with a provenance card.
11
 
12
- Reads runs/<run-id>/run.json from the run bucket, verifies all shards are present,
13
- downloads them, and pushes the concatenated dataset. Deliberately the ONLY step in
14
- the fleet that commits to a dataset repo workers write bucket objects, so N-way
15
- commit contention (412s) can't happen by construction.
 
 
 
 
 
 
 
16
 
17
  Usually spawned as a cpu Job by the launcher; can also run locally:
18
  uv run consolidate-shards.py --bucket you/embedding-runs --run-id 20260709-1200-abc123
@@ -21,6 +28,7 @@ import argparse
21
  import json
22
  import logging
23
  import os
 
24
  import sys
25
  import tempfile
26
  import time
@@ -30,6 +38,54 @@ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(mess
30
  logger = logging.getLogger("consolidate-shards")
31
 
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  def main():
34
  p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
35
  p.add_argument("--bucket", required=True, help="Run bucket, e.g. you/embedding-runs")
@@ -37,12 +93,14 @@ def main():
37
  p.add_argument("--private", action="store_true")
38
  args = p.parse_args()
39
 
40
- from datasets import load_dataset
41
- from huggingface_hub import DatasetCard, download_bucket_files, list_bucket_tree, login
 
42
 
43
  token = os.environ.get("HF_TOKEN")
44
  if token:
45
  login(token=token)
 
46
 
47
  prefix = f"runs/{args.run_id}"
48
  workdir = Path(tempfile.mkdtemp(prefix=f"consolidate-{args.run_id}-"))
@@ -53,27 +111,61 @@ def main():
53
  n = run["num_shards"]
54
  out_repo = run["output_dataset"]
55
 
56
- shard_paths = sorted(
57
- f.path for f in list_bucket_tree(args.bucket, prefix=f"{prefix}/data/", recursive=True)
58
- if getattr(f, "path", "").endswith(".parquet")
59
- )
60
- expected = [f"{prefix}/data/{i:05d}.parquet" for i in range(n)]
61
- missing = sorted(set(expected) - set(shard_paths))
 
 
 
 
 
62
  if missing:
63
- logger.error(f"Missing {len(missing)}/{n} shard(s): {missing}")
64
  logger.error("Re-run those ranks (launch-embedding-fleet.py --retry-rank), then consolidate again.")
65
  sys.exit(1)
 
 
66
 
67
- logger.info(f"Downloading {n} shards from {args.bucket}/{prefix}/data/")
68
- local = [(path, workdir / Path(path).name) for path in expected]
69
- download_bucket_files(args.bucket, local, raise_on_missing_files=True)
70
-
71
- ds = load_dataset("parquet", data_files=[str(dst) for _, dst in local], split="train")
72
- logger.info(f"Merged {n} shards → {len(ds):,} rows (manifest says {run['rows_total']:,})")
73
- if run.get("rows_total") and len(ds) != run["rows_total"]:
74
- logger.warning("Row count differs from manifest — check for a re-run with different --max-samples.")
75
 
76
- # Read final worker statuses for the card's timing/throughput line (best effort).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  stats_line = ""
78
  try:
79
  status_files = [(f"{prefix}/status/{i:05d}.json", workdir / f"status-{i:05d}.json") for i in range(n)]
@@ -92,15 +184,18 @@ def main():
92
  origin = ("Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
93
  if on_jobs else "Generated")
94
  jobs_tag = "\n- hf-jobs" if on_jobs else ""
 
 
95
  job_list = "".join(f" - shard {i}: `{jid}`\n" for i, jid in enumerate(run.get("job_ids", [])))
96
  card = DatasetCard(
97
  f"---\ntags:\n- embeddings\n- uv-script\n- generated{jobs_tag}\n---\n\n"
98
  f"# {out_repo}\n\n"
99
  f"Embeddings of [`{run['input_dataset']}`](https://huggingface.co/datasets/{run['input_dataset']}) "
100
- f"column `{run['column']}`, computed by a fleet of {n} parallel Jobs.\n\n"
101
  f"- Model: [`{run['model']}`](https://huggingface.co/{run['model']})\n"
 
102
  f"- Fleet: {n} × `{run['flavor']}` · run `{run['run_id']}`\n"
103
- f"{stats_line}"
104
  f"- Worker jobs:\n{job_list}\n"
105
  f"## Reproduction\n\n"
106
  f"{origin} with the [`generate-embeddings.py`]({script_url}) recipe from "
@@ -110,28 +205,6 @@ def main():
110
  f" {run['input_dataset']} <output-dataset> --column {run['column']} "
111
  f"--model {run['model']} --num-shards {n} --flavor {run['flavor']}\n```\n"
112
  )
113
-
114
- # Same retry + XET-disable fallback as generate-embeddings.py: a transient upload
115
- # failure here would waste the whole fleet's (paid) work.
116
- private = args.private or run.get("private", False)
117
- logger.info(f"Pushing to {out_repo} (private={private})")
118
- max_retries = 3
119
- for attempt in range(1, max_retries + 1):
120
- try:
121
- if attempt > 1:
122
- logger.warning("Disabling XET (fallback to HTTP upload)")
123
- os.environ["HF_HUB_DISABLE_XET"] = "1"
124
- ds.push_to_hub(out_repo, private=private)
125
- break
126
- except Exception as e:
127
- logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
128
- if attempt < max_retries:
129
- delay = 30 * (2 ** (attempt - 1))
130
- logger.info(f"Retrying in {delay}s...")
131
- time.sleep(delay)
132
- else:
133
- logger.error("All upload attempts failed. Shards remain in the bucket — re-run consolidation.")
134
- sys.exit(1)
135
  try:
136
  card.push_to_hub(out_repo, repo_type="dataset")
137
  except Exception as e:
 
1
  # /// script
2
  # requires-python = ">=3.10"
3
  # dependencies = [
 
4
  # "huggingface-hub>=1.12",
5
+ # "pyarrow",
6
  # ]
7
  # ///
8
  """
9
+ Assemble the parquet shards of a fan-out embedding run (see launch-embedding-fleet.py)
10
+ into the final Hub dataset, one file at a time, with a provenance card.
11
 
12
+ Pass-through design: worker shards are ALREADY valid parquet in final order, so nothing
13
+ is loaded or re-serialized each file is downloaded, its footer row count read, and the
14
+ file uploaded to the dataset repo as data/train-XXXXX-of-YYYYY.parquet. Peak disk = one
15
+ shard, so any total run size fits on a small CPU flavor. Deliberately the ONLY step in
16
+ the fleet that writes to a dataset repo — workers write bucket objects, so N-way commit
17
+ contention (412s) can't happen by construction.
18
+
19
+ Accepts both worker output namings: <rank>.parquet (row mode) and <rank>.partNNNN.parquet
20
+ (streaming mode). Re-running is idempotent for same-named files; if a re-run has FEWER
21
+ files than a previous consolidation of the same repo, stale data/ files from the earlier
22
+ attempt are removed first.
23
 
24
  Usually spawned as a cpu Job by the launcher; can also run locally:
25
  uv run consolidate-shards.py --bucket you/embedding-runs --run-id 20260709-1200-abc123
 
28
  import json
29
  import logging
30
  import os
31
+ import re
32
  import sys
33
  import tempfile
34
  import time
 
38
  logger = logging.getLogger("consolidate-shards")
39
 
40
 
41
+ def normalize_embeddings_column(local, out_col):
42
+ """Rewrite the file in place if its embeddings column isn't fixed_size_list<float32>.
43
+
44
+ Shards written by different script versions can disagree (old: list<double>, new:
45
+ fixed_size_list<float32>); a repo with mixed parquet schemas breaks load_dataset, so
46
+ the consolidator is the place to unify. Returns the file's row count."""
47
+ import pyarrow as pa
48
+ import pyarrow.compute as pc
49
+ import pyarrow.parquet as pq
50
+ pf = pq.ParquetFile(local)
51
+ schema = pf.schema_arrow
52
+ if out_col not in schema.names:
53
+ return pf.metadata.num_rows # nothing to normalize (unexpected, but not fatal here)
54
+ field = schema.field(out_col)
55
+ if pa.types.is_fixed_size_list(field.type) and field.type.value_type == pa.float32():
56
+ return pf.metadata.num_rows
57
+ t = pq.read_table(local)
58
+ col = t[out_col].combine_chunks()
59
+ dim = len(col[0].as_py())
60
+ values = pc.cast(pc.list_flatten(col), pa.float32())
61
+ fixed = pa.FixedSizeListArray.from_arrays(values, dim)
62
+ idx = t.schema.get_field_index(out_col)
63
+ t = t.set_column(idx, pa.field(out_col, fixed.type), fixed)
64
+ logger.info(f" normalized {Path(local).name}: {field.type} → {fixed.type}")
65
+ pq.write_table(t, local)
66
+ return t.num_rows
67
+
68
+
69
+ def upload_with_retry(api, local, repo_id, path_in_repo, max_retries=3):
70
+ for attempt in range(1, max_retries + 1):
71
+ try:
72
+ if attempt > 1:
73
+ logger.warning("Disabling XET (fallback to HTTP upload)")
74
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
75
+ api.upload_file(path_or_fileobj=local, path_in_repo=path_in_repo,
76
+ repo_id=repo_id, repo_type="dataset")
77
+ return
78
+ except Exception as e:
79
+ logger.error(f"Upload attempt {attempt}/{max_retries} for {path_in_repo} failed: {e}")
80
+ if attempt < max_retries:
81
+ delay = 30 * (2 ** (attempt - 1))
82
+ logger.info(f"Retrying in {delay}s...")
83
+ time.sleep(delay)
84
+ else:
85
+ logger.error("All upload attempts failed. Shards remain in the bucket — re-run consolidation.")
86
+ sys.exit(1)
87
+
88
+
89
  def main():
90
  p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
91
  p.add_argument("--bucket", required=True, help="Run bucket, e.g. you/embedding-runs")
 
93
  p.add_argument("--private", action="store_true")
94
  args = p.parse_args()
95
 
96
+ import pyarrow.parquet as pq
97
+ from huggingface_hub import (DatasetCard, HfApi, download_bucket_files,
98
+ list_bucket_tree, login)
99
 
100
  token = os.environ.get("HF_TOKEN")
101
  if token:
102
  login(token=token)
103
+ api = HfApi()
104
 
105
  prefix = f"runs/{args.run_id}"
106
  workdir = Path(tempfile.mkdtemp(prefix=f"consolidate-{args.run_id}-"))
 
111
  n = run["num_shards"]
112
  out_repo = run["output_dataset"]
113
 
114
+ # Collect shard files: <rank>.parquet (row mode) or <rank>.partNNNN.parquet (streaming).
115
+ pat = re.compile(r"^(\d{5})(?:\.part(\d{4}))?\.parquet$")
116
+ shard_files = [] # (rank, part, bucket_path)
117
+ for f in list_bucket_tree(args.bucket, prefix=f"{prefix}/data/", recursive=True):
118
+ name = Path(getattr(f, "path", "")).name
119
+ m = pat.match(name)
120
+ if m:
121
+ shard_files.append((int(m.group(1)), int(m.group(2) or 0), f.path))
122
+ shard_files.sort()
123
+ ranks_present = {r for r, _, _ in shard_files}
124
+ missing = sorted(set(range(n)) - ranks_present)
125
  if missing:
126
+ logger.error(f"Missing output from {len(missing)}/{n} rank(s): {missing}")
127
  logger.error("Re-run those ranks (launch-embedding-fleet.py --retry-rank), then consolidate again.")
128
  sys.exit(1)
129
+ total_files = len(shard_files)
130
+ logger.info(f"{total_files} shard file(s) across {n} rank(s)")
131
 
132
+ private = args.private or run.get("private", False)
133
+ api.create_repo(out_repo, repo_type="dataset", private=private, exist_ok=True)
 
 
 
 
 
 
134
 
135
+ # Remove stale data/ files from any earlier consolidation with a different file count.
136
+ expected = {f"data/train-{i:05d}-of-{total_files:05d}.parquet" for i in range(total_files)}
137
+ try:
138
+ existing = [f for f in api.list_repo_files(out_repo, repo_type="dataset")
139
+ if f.startswith("data/") and f.endswith(".parquet") and f not in expected]
140
+ for stale in existing:
141
+ logger.warning(f"Deleting stale {stale} from a previous consolidation")
142
+ api.delete_file(stale, repo_id=out_repo, repo_type="dataset")
143
+ except Exception as e:
144
+ logger.warning(f"stale-file check skipped: {e}")
145
+
146
+ # Embedding column name: default unless overridden via the run's embed_args.
147
+ ea = run.get("embed_args") or []
148
+ out_col = ea[ea.index("--output-column") + 1] if "--output-column" in ea else "embeddings"
149
+
150
+ # Pass each file through: download → normalize schema if needed → upload → delete local.
151
+ rows_total = 0
152
+ t0 = time.time()
153
+ for seq, (rank, part, bucket_path) in enumerate(shard_files):
154
+ local = workdir / Path(bucket_path).name
155
+ download_bucket_files(args.bucket, [(bucket_path, local)], raise_on_missing_files=True)
156
+ rows = normalize_embeddings_column(local, out_col)
157
+ rows_total += rows
158
+ dest = f"data/train-{seq:05d}-of-{total_files:05d}.parquet"
159
+ logger.info(f"[{seq + 1}/{total_files}] rank {rank} part {part}: {rows:,} rows → {dest}")
160
+ upload_with_retry(api, local, out_repo, dest)
161
+ local.unlink()
162
+
163
+ logger.info(f"Assembled {rows_total:,} rows in {time.time() - t0:.0f}s "
164
+ f"(manifest says {run.get('rows_total')})")
165
+ if run.get("rows_total") and rows_total != run["rows_total"]:
166
+ logger.warning("Row count differs from manifest — check for a re-run with different settings.")
167
+
168
+ # Timing/throughput line from final worker statuses (best effort).
169
  stats_line = ""
170
  try:
171
  status_files = [(f"{prefix}/status/{i:05d}.json", workdir / f"status-{i:05d}.json") for i in range(n)]
 
184
  origin = ("Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
185
  if on_jobs else "Generated")
186
  jobs_tag = "\n- hf-jobs" if on_jobs else ""
187
+ mode = "streaming file-shards" if run.get("streaming") else "row shards"
188
+ rev_line = f"- Input revision: `{run['revision']}`\n" if run.get("revision") else ""
189
  job_list = "".join(f" - shard {i}: `{jid}`\n" for i, jid in enumerate(run.get("job_ids", [])))
190
  card = DatasetCard(
191
  f"---\ntags:\n- embeddings\n- uv-script\n- generated{jobs_tag}\n---\n\n"
192
  f"# {out_repo}\n\n"
193
  f"Embeddings of [`{run['input_dataset']}`](https://huggingface.co/datasets/{run['input_dataset']}) "
194
+ f"column `{run['column']}`, computed by a fleet of {n} parallel Jobs ({mode}).\n\n"
195
  f"- Model: [`{run['model']}`](https://huggingface.co/{run['model']})\n"
196
+ f"- Rows: {rows_total:,}\n"
197
  f"- Fleet: {n} × `{run['flavor']}` · run `{run['run_id']}`\n"
198
+ f"{rev_line}{stats_line}"
199
  f"- Worker jobs:\n{job_list}\n"
200
  f"## Reproduction\n\n"
201
  f"{origin} with the [`generate-embeddings.py`]({script_url}) recipe from "
 
205
  f" {run['input_dataset']} <output-dataset> --column {run['column']} "
206
  f"--model {run['model']} --num-shards {n} --flavor {run['flavor']}\n```\n"
207
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  try:
209
  card.push_to_hub(out_repo, repo_type="dataset")
210
  except Exception as e:
generate-embeddings.py CHANGED
@@ -271,6 +271,100 @@ class StatusReporter:
271
  logger.warning(f"status write skipped ({e})")
272
 
273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
  def main():
275
  p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
276
  p.add_argument("input_dataset", help="Input dataset ID on the Hugging Face Hub")
@@ -310,6 +404,14 @@ def main():
310
  help="Fan-out: bucket for shard parquets + status (env OUTPUT_BUCKET).")
311
  p.add_argument("--run-id", default=os.environ.get("RUN_ID"),
312
  help="Fan-out: run identifier grouping shards under runs/<run-id>/ (env RUN_ID).")
 
 
 
 
 
 
 
 
313
  args = p.parse_args()
314
 
315
  def int_or_error(val, name):
@@ -335,6 +437,14 @@ def main():
335
  elif args.shard_index is not None:
336
  p.error("--shard-index requires --num-shards.")
337
 
 
 
 
 
 
 
 
 
338
  import torch
339
  from datasets import load_dataset
340
  from huggingface_hub import DatasetCard, login
@@ -346,18 +456,35 @@ def main():
346
  if not torch.cuda.is_available():
347
  logger.warning("No CUDA — running on CPU (much slower). Prefer a GPU flavor, e.g. --flavor l4x1.")
348
 
349
- logger.info(f"Loading {args.input_dataset} [{args.split}]")
350
- ds = (load_dataset(args.input_dataset, args.config, split=args.split) if args.config
351
- else load_dataset(args.input_dataset, split=args.split))
352
- if args.column not in ds.column_names:
353
- logger.error(f"Column {args.column!r} not found. Available: {ds.column_names}")
354
- sys.exit(1)
355
- if args.output_column in ds.column_names:
356
- logger.error(f"Output column {args.output_column!r} already exists — choose another --output-column.")
357
- sys.exit(1)
358
- if args.max_samples:
 
 
 
 
 
 
359
  ds = ds.select(range(min(args.max_samples, len(ds))))
360
- if sharded:
 
 
 
 
 
 
 
 
 
 
 
361
  # Contiguous slices keep row order reconstructable at consolidation. Note the whole
362
  # split was still downloaded above — acceptable at few-M rows, not at corpus scale.
363
  ds = ds.shard(num_shards=args.num_shards, index=args.shard_index, contiguous=True)
@@ -366,7 +493,8 @@ def main():
366
  logger.error(f"Shard {args.shard_index} is empty — num_shards exceeds the row count. "
367
  f"Lower --num-shards (or raise --max-samples).")
368
  sys.exit(1)
369
- logger.info(f"{len(ds)} rows; modality={args.modality}")
 
370
 
371
  device = "cuda" if torch.cuda.is_available() else "cpu"
372
  model = SentenceTransformer(args.model, device=device, trust_remote_code=True)
@@ -379,6 +507,9 @@ def main():
379
  prompt_str = None # None = let encode_query/encode_document choose natively
380
  if args.modality == "text":
381
  prompt_str = resolve_prompt(model, args.model, is_query=args.query_mode, args=args)
 
 
 
382
  items = [t if isinstance(t, str) and t.strip() else " " for t in ds[args.column]]
383
  else:
384
  if args.prompt or args.prompt_name:
@@ -443,15 +574,24 @@ def main():
443
  secs = time.perf_counter() - t0
444
  logger.info(f"Embedded {len(items)} in {secs:.1f}s ({len(items)/secs:.0f} rows/s), dim={dim}")
445
 
446
- ds = ds.add_column(args.output_column, [e.tolist() for e in emb])
447
-
448
  if sharded:
449
  # Shard mode: no repo commit here (N workers committing → 412 contention). Write this
450
  # rank's parquet to the run bucket; consolidate-shards.py makes the single final commit.
451
- out_path = f"/tmp/shard-{args.shard_index:05d}.parquet"
452
- dest = f"runs/{args.run_id}/data/{args.shard_index:05d}.parquet"
 
 
 
 
 
 
453
  try:
454
- ds.to_parquet(out_path)
 
 
 
 
 
455
  logger.info(f"Uploading shard parquet → {args.output_bucket}/{dest}")
456
  put_bucket_files(args.output_bucket, [(out_path, dest)])
457
  except Exception:
@@ -461,6 +601,8 @@ def main():
461
  logger.info(f"✅ shard {args.shard_index + 1}/{args.num_shards} of run {args.run_id} uploaded")
462
  return
463
 
 
 
464
  # For the card: record the effective prefix (explicit, else the model's registered one).
465
  side_keys = ("query",) if args.query_mode else ("document", "passage", "corpus")
466
  effective = prompt_str if prompt_str is not None else next(
 
271
  logger.warning(f"status write skipped ({e})")
272
 
273
 
274
+ def run_streaming_shard(ds, model, prompt_str, args):
275
+ """Streaming fan-out worker: iterate this rank's FILE-shard, encode in chunks, and flush
276
+ parquet PARTS to the bucket every ~250k rows, so memory and disk stay bounded no matter
277
+ how big the shard is. Output keys: runs/<run-id>/data/<rank>.part<p>.parquet — the
278
+ consolidator accepts both this and row mode's single <rank>.parquet naming."""
279
+ import itertools
280
+ import pyarrow as pa
281
+ import pyarrow.parquet as pq
282
+
283
+ encode_fn = model.encode_query if args.query_mode else model.encode_document
284
+ encode_kwargs = {"prompt": prompt_str} if prompt_str is not None else {}
285
+
286
+ def clean(t):
287
+ return t if isinstance(t, str) and t.strip() else " "
288
+
289
+ # Buffer a head sample for token sniffing + the auto-batch probe, then chain it back.
290
+ it = iter(ds)
291
+ head = list(itertools.islice(it, 1024))
292
+ if not head:
293
+ logger.error(f"File-shard {args.shard_index} yielded no rows.")
294
+ sys.exit(1)
295
+ if args.column not in head[0]:
296
+ logger.error(f"Column {args.column!r} not in rows. Available: {sorted(head[0])}")
297
+ sys.exit(1)
298
+ if args.output_column in head[0]:
299
+ logger.error(f"Output column {args.output_column!r} already exists — choose another --output-column.")
300
+ sys.exit(1)
301
+ head_texts = [clean(r[args.column]) for r in head]
302
+ median_tok = sniff_token_lengths(model, head_texts, args.max_seq_len)
303
+ if str(args.batch_size).lower() == "auto":
304
+ if median_tok is None or median_tok >= 256:
305
+ candidates = (32, 64, 128, 256)
306
+ elif median_tok >= 64:
307
+ candidates = (64, 128, 256, 512)
308
+ else:
309
+ candidates = (128, 256, 512, 1024)
310
+ batch_size = find_batch_size(model, head_texts, args.normalize, candidates=candidates)
311
+ else:
312
+ batch_size = int(args.batch_size)
313
+
314
+ reporter = StatusReporter(args.output_bucket, args.run_id, args.shard_index,
315
+ rows_total=None, tokens_per_row=median_tok)
316
+ reporter.report(0, force=True)
317
+
318
+ chunk_rows, part_rows = 25_000, 250_000
319
+ prog = {"part_idx": 0, "rows_done": 0}
320
+ buf_rows, buf_texts, part_buf = [], [], []
321
+
322
+ def flush_part():
323
+ if not part_buf:
324
+ return
325
+ path = f"/tmp/part-{args.shard_index:05d}-{prog['part_idx']:04d}.parquet"
326
+ pq.write_table(pa.Table.from_pylist(part_buf), path)
327
+ dest = f"runs/{args.run_id}/data/{args.shard_index:05d}.part{prog['part_idx']:04d}.parquet"
328
+ logger.info(f"Uploading {len(part_buf):,}-row part → {args.output_bucket}/{dest}")
329
+ put_bucket_files(args.output_bucket, [(path, dest)])
330
+ os.remove(path)
331
+ part_buf.clear()
332
+ prog["part_idx"] += 1
333
+
334
+ def encode_chunk():
335
+ if not buf_rows:
336
+ return
337
+ emb = encode_fn(buf_texts, batch_size=batch_size, show_progress_bar=False,
338
+ convert_to_numpy=True, normalize_embeddings=args.normalize, **encode_kwargs)
339
+ for r, e in zip(buf_rows, emb):
340
+ r[args.output_column] = e.tolist()
341
+ part_buf.extend(buf_rows)
342
+ prog["rows_done"] += len(buf_rows)
343
+ buf_rows.clear()
344
+ buf_texts.clear()
345
+ reporter.report(prog["rows_done"])
346
+ if len(part_buf) >= part_rows:
347
+ flush_part()
348
+
349
+ t0 = time.perf_counter()
350
+ try:
351
+ for row in itertools.chain(head, it):
352
+ buf_rows.append(dict(row))
353
+ buf_texts.append(clean(row[args.column]))
354
+ if len(buf_rows) >= chunk_rows:
355
+ encode_chunk()
356
+ encode_chunk()
357
+ flush_part()
358
+ except Exception:
359
+ reporter.report(state="error", force=True)
360
+ raise
361
+ secs = time.perf_counter() - t0
362
+ logger.info(f"Embedded {prog['rows_done']:,} rows in {secs:.0f}s "
363
+ f"({prog['rows_done'] / max(secs, 1e-6):.0f} rows/s), {prog['part_idx']} part(s)")
364
+ reporter.report(prog["rows_done"], state="done", force=True)
365
+ logger.info(f"✅ streaming shard {args.shard_index + 1}/{args.num_shards} of run {args.run_id} uploaded")
366
+
367
+
368
  def main():
369
  p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
370
  p.add_argument("input_dataset", help="Input dataset ID on the Hugging Face Hub")
 
404
  help="Fan-out: bucket for shard parquets + status (env OUTPUT_BUCKET).")
405
  p.add_argument("--run-id", default=os.environ.get("RUN_ID"),
406
  help="Fan-out: run identifier grouping shards under runs/<run-id>/ (env RUN_ID).")
407
+ p.add_argument("--streaming", action="store_true",
408
+ default=os.environ.get("STREAMING") == "1",
409
+ help="Fan-out: stream the dataset and shard at the FILE level (env STREAMING=1). "
410
+ "Each rank downloads only its own files — use for very big datasets. "
411
+ "Text modality only; incompatible with --max-samples.")
412
+ p.add_argument("--revision", default=os.environ.get("REVISION"),
413
+ help="Input dataset revision (commit sha). Pin this in fan-out runs so every "
414
+ "rank slices the identical snapshot (env REVISION).")
415
  args = p.parse_args()
416
 
417
  def int_or_error(val, name):
 
437
  elif args.shard_index is not None:
438
  p.error("--shard-index requires --num-shards.")
439
 
440
+ if args.streaming:
441
+ if not sharded:
442
+ p.error("--streaming is a fan-out mode — it needs --num-shards/--shard-index.")
443
+ if args.modality != "text":
444
+ p.error("--streaming currently supports text modality only.")
445
+ if args.max_samples:
446
+ p.error("--max-samples is incompatible with --streaming (use row mode for capped test runs).")
447
+
448
  import torch
449
  from datasets import load_dataset
450
  from huggingface_hub import DatasetCard, login
 
456
  if not torch.cuda.is_available():
457
  logger.warning("No CUDA — running on CPU (much slower). Prefer a GPU flavor, e.g. --flavor l4x1.")
458
 
459
+ logger.info(f"Loading {args.input_dataset} [{args.split}]"
460
+ + (f" @ {args.revision[:12]}" if args.revision else "")
461
+ + (" (streaming)" if args.streaming else ""))
462
+ load_kwargs = {"split": args.split, "streaming": args.streaming}
463
+ if args.revision:
464
+ load_kwargs["revision"] = args.revision
465
+ ds = (load_dataset(args.input_dataset, args.config, **load_kwargs) if args.config
466
+ else load_dataset(args.input_dataset, **load_kwargs))
467
+ if ds.column_names is not None:
468
+ if args.column not in ds.column_names:
469
+ logger.error(f"Column {args.column!r} not found. Available: {ds.column_names}")
470
+ sys.exit(1)
471
+ if args.output_column in ds.column_names:
472
+ logger.error(f"Output column {args.output_column!r} already exists — choose another --output-column.")
473
+ sys.exit(1)
474
+ if args.max_samples and not args.streaming:
475
  ds = ds.select(range(min(args.max_samples, len(ds))))
476
+ if sharded and args.streaming:
477
+ # File-level split: each rank reads ONLY its own data files. Sizes vary per rank and
478
+ # rows_total is unknown upfront; correctness (exact, deterministic, idempotent) holds
479
+ # as long as every rank pins the same --revision.
480
+ if ds.n_shards < args.num_shards:
481
+ logger.error(f"Dataset has {ds.n_shards} file shard(s) < --num-shards {args.num_shards}. "
482
+ f"Lower --num-shards or use row mode.")
483
+ sys.exit(1)
484
+ ds = ds.shard(num_shards=args.num_shards, index=args.shard_index)
485
+ logger.info(f"Fan-out file-shard {args.shard_index + 1}/{args.num_shards} of run {args.run_id} "
486
+ f"({ds.n_shards} file(s) for this rank)")
487
+ elif sharded:
488
  # Contiguous slices keep row order reconstructable at consolidation. Note the whole
489
  # split was still downloaded above — acceptable at few-M rows, not at corpus scale.
490
  ds = ds.shard(num_shards=args.num_shards, index=args.shard_index, contiguous=True)
 
493
  logger.error(f"Shard {args.shard_index} is empty — num_shards exceeds the row count. "
494
  f"Lower --num-shards (or raise --max-samples).")
495
  sys.exit(1)
496
+ if not args.streaming:
497
+ logger.info(f"{len(ds)} rows; modality={args.modality}")
498
 
499
  device = "cuda" if torch.cuda.is_available() else "cpu"
500
  model = SentenceTransformer(args.model, device=device, trust_remote_code=True)
 
507
  prompt_str = None # None = let encode_query/encode_document choose natively
508
  if args.modality == "text":
509
  prompt_str = resolve_prompt(model, args.model, is_query=args.query_mode, args=args)
510
+ if args.streaming:
511
+ run_streaming_shard(ds, model, prompt_str, args)
512
+ return
513
  items = [t if isinstance(t, str) and t.strip() else " " for t in ds[args.column]]
514
  else:
515
  if args.prompt or args.prompt_name:
 
574
  secs = time.perf_counter() - t0
575
  logger.info(f"Embedded {len(items)} in {secs:.1f}s ({len(items)/secs:.0f} rows/s), dim={dim}")
576
 
 
 
577
  if sharded:
578
  # Shard mode: no repo commit here (N workers committing → 412 contention). Write this
579
  # rank's parquet to the run bucket; consolidate-shards.py makes the single final commit.
580
+ #
581
+ # Build the embedding column as zero-copy float32 Arrow — NEVER as Python floats.
582
+ # `[e.tolist() for e in emb]` on an 800k-row shard is ~10 GB of PyFloat objects and
583
+ # swap-thrashed L4 workers into multi-hour silent stalls (wiki fleet, 2026-07-09).
584
+ import numpy as np
585
+ import pyarrow as pa
586
+ import pyarrow.parquet as pq
587
+ reporter.report(len(items), state="writing", force=True)
588
  try:
589
+ emb32 = np.ascontiguousarray(emb, dtype=np.float32)
590
+ emb_col = pa.FixedSizeListArray.from_arrays(pa.array(emb32.ravel()), emb32.shape[1])
591
+ table = ds.with_format("arrow")[:].append_column(args.output_column, emb_col)
592
+ out_path = f"/tmp/shard-{args.shard_index:05d}.parquet"
593
+ dest = f"runs/{args.run_id}/data/{args.shard_index:05d}.parquet"
594
+ pq.write_table(table, out_path)
595
  logger.info(f"Uploading shard parquet → {args.output_bucket}/{dest}")
596
  put_bucket_files(args.output_bucket, [(out_path, dest)])
597
  except Exception:
 
601
  logger.info(f"✅ shard {args.shard_index + 1}/{args.num_shards} of run {args.run_id} uploaded")
602
  return
603
 
604
+ ds = ds.add_column(args.output_column, [e.tolist() for e in emb])
605
+
606
  # For the card: record the effective prefix (explicit, else the model's registered one).
607
  side_keys = ("query",) if args.query_mode else ("document", "passage", "corpus")
608
  effective = prompt_str if prompt_str is not None else next(
launch-embedding-fleet.py CHANGED
@@ -97,6 +97,9 @@ def main():
97
  "(1 TB) when total shard size approaches ~20 GB.")
98
  p.add_argument("--rows-total", type=int, default=None,
99
  help="Override when the dataset has no split metadata")
 
 
 
100
  p.add_argument("--private", action="store_true", help="Final output dataset is private")
101
  p.add_argument("--embed-args", nargs=argparse.REMAINDER, default=[],
102
  help="Everything after --embed-args is passed through to generate-embeddings.py "
@@ -123,6 +126,8 @@ def main():
123
  p.error("--retry-rank / --consolidate-only need --run-id")
124
  if args.num_shards < 1:
125
  p.error(f"--num-shards must be >= 1 (got {args.num_shards})")
 
 
126
 
127
  def read_manifest(run_id):
128
  import tempfile
@@ -144,17 +149,22 @@ def main():
144
  if manifest.get("max_samples"):
145
  script_args += ["--max-samples", str(manifest["max_samples"])]
146
  script_args += list(manifest.get("embed_args") or [])
 
 
 
 
 
 
 
 
 
 
147
  job = run_uv_job(
148
  args.script,
149
  script_args=script_args,
150
  flavor=manifest["flavor"],
151
  timeout=manifest["timeout"],
152
- env={
153
- "RANK": str(rank),
154
- "NUM_SHARDS": str(manifest["num_shards"]),
155
- "RUN_ID": manifest["run_id"],
156
- "OUTPUT_BUCKET": bucket,
157
- },
158
  secrets={"HF_TOKEN": token},
159
  labels={"embedding-fleet-run": manifest["run_id"], "rank": str(rank)},
160
  token=token,
@@ -200,13 +210,20 @@ def main():
200
 
201
  # --- fresh run ---
202
  rows_total = args.rows_total or rows_in_split(args.input_dataset, args.config, args.split)
203
- if rows_total is None:
204
  p.error("Couldn't determine the split's row count — pass --rows-total.")
205
- if args.max_samples:
206
- rows_total = min(rows_total, args.max_samples)
207
- if args.num_shards > rows_total:
208
- p.error(f"--num-shards {args.num_shards} exceeds the row count ({rows_total}) — "
209
- f"some shards would be empty.")
 
 
 
 
 
 
 
210
 
211
  run_id = time.strftime("%Y%m%d-%H%M%S") + "-" + pysecrets.token_hex(3)
212
  create_bucket(bucket, private=True, exist_ok=True, token=token)
@@ -226,12 +243,18 @@ def main():
226
  "timeout": args.timeout,
227
  "private": args.private,
228
  "embed_args": list(args.embed_args),
 
 
229
  "started_at": time.time(),
230
  "job_ids": [],
231
  }
232
  put_json(bucket, f"runs/{run_id}/run.json", manifest, token=token)
233
- logger.info(f"Run {run_id}: {rows_total:,} rows {args.num_shards} shards "
234
- f"(~{rows_total // args.num_shards:,} rows each) on {args.flavor}")
 
 
 
 
235
 
236
  jobs = [spawn_worker(rank, manifest) for rank in range(args.num_shards)]
237
  manifest["job_ids"] = [j.id for j in jobs]
 
97
  "(1 TB) when total shard size approaches ~20 GB.")
98
  p.add_argument("--rows-total", type=int, default=None,
99
  help="Override when the dataset has no split metadata")
100
+ p.add_argument("--streaming", action="store_true",
101
+ help="Workers stream + shard at the FILE level (no full-split download per "
102
+ "rank) — for very big datasets. Text only; incompatible with --max-samples.")
103
  p.add_argument("--private", action="store_true", help="Final output dataset is private")
104
  p.add_argument("--embed-args", nargs=argparse.REMAINDER, default=[],
105
  help="Everything after --embed-args is passed through to generate-embeddings.py "
 
126
  p.error("--retry-rank / --consolidate-only need --run-id")
127
  if args.num_shards < 1:
128
  p.error(f"--num-shards must be >= 1 (got {args.num_shards})")
129
+ if args.streaming and args.max_samples:
130
+ p.error("--streaming is incompatible with --max-samples (use row mode for capped tests)")
131
 
132
  def read_manifest(run_id):
133
  import tempfile
 
149
  if manifest.get("max_samples"):
150
  script_args += ["--max-samples", str(manifest["max_samples"])]
151
  script_args += list(manifest.get("embed_args") or [])
152
+ env = {
153
+ "RANK": str(rank),
154
+ "NUM_SHARDS": str(manifest["num_shards"]),
155
+ "RUN_ID": manifest["run_id"],
156
+ "OUTPUT_BUCKET": bucket,
157
+ }
158
+ if manifest.get("revision"):
159
+ env["REVISION"] = manifest["revision"]
160
+ if manifest.get("streaming"):
161
+ env["STREAMING"] = "1"
162
  job = run_uv_job(
163
  args.script,
164
  script_args=script_args,
165
  flavor=manifest["flavor"],
166
  timeout=manifest["timeout"],
167
+ env=env,
 
 
 
 
 
168
  secrets={"HF_TOKEN": token},
169
  labels={"embedding-fleet-run": manifest["run_id"], "rank": str(rank)},
170
  token=token,
 
210
 
211
  # --- fresh run ---
212
  rows_total = args.rows_total or rows_in_split(args.input_dataset, args.config, args.split)
213
+ if rows_total is None and not args.streaming:
214
  p.error("Couldn't determine the split's row count — pass --rows-total.")
215
+ if rows_total is not None:
216
+ if args.max_samples:
217
+ rows_total = min(rows_total, args.max_samples)
218
+ if not args.streaming and args.num_shards > rows_total:
219
+ p.error(f"--num-shards {args.num_shards} exceeds the row count ({rows_total}) — "
220
+ f"some shards would be empty.")
221
+
222
+ # Pin the input snapshot: every rank (and any later --retry-rank) must slice the IDENTICAL
223
+ # revision, or a mid-run commit to the input dataset silently breaks the exact partition.
224
+ from huggingface_hub import dataset_info
225
+ revision = dataset_info(args.input_dataset, token=token).sha
226
+ logger.info(f"Pinned input revision: {revision[:12]}")
227
 
228
  run_id = time.strftime("%Y%m%d-%H%M%S") + "-" + pysecrets.token_hex(3)
229
  create_bucket(bucket, private=True, exist_ok=True, token=token)
 
243
  "timeout": args.timeout,
244
  "private": args.private,
245
  "embed_args": list(args.embed_args),
246
+ "streaming": args.streaming,
247
+ "revision": revision,
248
  "started_at": time.time(),
249
  "job_ids": [],
250
  }
251
  put_json(bucket, f"runs/{run_id}/run.json", manifest, token=token)
252
+ if rows_total is not None:
253
+ logger.info(f"Run {run_id}: {rows_total:,} rows {args.num_shards} shards "
254
+ f"(~{rows_total // args.num_shards:,} rows each) on {args.flavor}")
255
+ else:
256
+ logger.info(f"Run {run_id}: streaming file-shards × {args.num_shards} on {args.flavor} "
257
+ f"(row count unknown upfront)")
258
 
259
  jobs = [spawn_worker(rank, manifest) for rank in range(args.num_shards)]
260
  manifest["job_ids"] = [j.id for j in jobs]