davanstrien HF Staff Claude Fable 5 commited on
Commit
852e5bf
·
1 Parent(s): f5c7d6e

Add fan-out mode: shard one run across N Jobs

Browse files

generate-embeddings.py gains an env-driven shard mode (RANK/NUM_SHARDS/RUN_ID/
OUTPUT_BUCKET): each worker embeds an exact contiguous slice, writes its parquet
+ progress heartbeats to a Bucket (object PUTs, no commit contention), and
new launch-embedding-fleet.py / consolidate-shards.py handle spawn, wait,
per-rank retry, and the single final merge commit with fleet provenance.
Unsharded behavior is unchanged.

Smoke-tested on Jobs: 20k rows x 2 t4-small workers -> exact 20,000-row output;
kill-one-worker -> --retry-rank -> --consolidate-only recovery verified.

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

README.md CHANGED
@@ -21,6 +21,7 @@ their dependencies (sentence-transformers vs vLLM vs Lance) are too different to
21
  | `generate-embeddings.py` | The default. Text or images. Simple, fast, runs anywhere. | sentence-transformers |
22
  | `generate-embeddings-vllm.py` | Max throughput on large *decoder* embedding models (Qwen3-Embedding). | vLLM pooling |
23
  | `embed-to-lance.py` | Get a **searchable vector index as a Hub dataset** (the "vector DB" path). | sentence-transformers + Lance |
 
24
 
25
  ## Quick start
26
 
@@ -38,6 +39,29 @@ hf jobs uv run --flavor l4x1 -s HF_TOKEN \
38
 
39
  Always try `--max-samples 100 --private` first.
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  ## Which model?
42
 
43
  **Find the *current* best — don't trust a fixed list** (embedding quality moves fast). Check the
 
21
  | `generate-embeddings.py` | The default. Text or images. Simple, fast, runs anywhere. | sentence-transformers |
22
  | `generate-embeddings-vllm.py` | Max throughput on large *decoder* embedding models (Qwen3-Embedding). | vLLM pooling |
23
  | `embed-to-lance.py` | Get a **searchable vector index as a Hub dataset** (the "vector DB" path). | sentence-transformers + Lance |
24
+ | `launch-embedding-fleet.py` | **Fan one run out across N parallel Jobs** (+ `consolidate-shards.py`). | run_uv_job + Buckets |
25
 
26
  ## Quick start
27
 
 
39
 
40
  Always try `--max-samples 100 --private` first.
41
 
42
+ ## Fan-out: N Jobs in parallel
43
+
44
+ One L4 does ~900 rows/s with `all-MiniLM-L6-v2`; a fleet of 8 does ~7k. `launch-embedding-fleet.py`
45
+ splits the run into exact, non-overlapping shards (one Job each), workers stream shard parquets +
46
+ progress heartbeats to a [Bucket](https://huggingface.co/docs/hub/storage-buckets) (object writes —
47
+ no repo-commit contention), and a final CPU Job merges everything into the output dataset in one
48
+ commit, with full provenance on the card.
49
+
50
+ ```bash
51
+ # 8 L4s over a corpus; runs from your laptop, workers run on Jobs
52
+ uv run https://huggingface.co/datasets/uv-scripts/embeddings/raw/main/launch-embedding-fleet.py \
53
+ your-name/corpus your-name/corpus-embeddings --num-shards 8 --flavor l4x1 --timeout 1h
54
+ ```
55
+
56
+ Every shard is idempotent (a rank overwrites only its own files), so recovery is trivial:
57
+ `--retry-rank 3 --run-id <id>` re-runs one failed shard with the run's original config,
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
 
67
  **Find the *current* best — don't trust a fixed list** (embedding quality moves fast). Check the
consolidate-shards.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
19
+ """
20
+ import argparse
21
+ import json
22
+ import logging
23
+ import os
24
+ import sys
25
+ import tempfile
26
+ import time
27
+ from pathlib import Path
28
+
29
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
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")
36
+ p.add_argument("--run-id", required=True)
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}-"))
49
+
50
+ download_bucket_files(args.bucket, [(f"{prefix}/run.json", workdir / "run.json")],
51
+ raise_on_missing_files=True)
52
+ run = json.loads((workdir / "run.json").read_text())
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)]
80
+ download_bucket_files(args.bucket, status_files)
81
+ statuses = [json.loads(dst.read_text()) for _, dst in status_files if dst.exists()]
82
+ if statuses:
83
+ wall = max(s["updated_at"] for s in statuses) - min(s["started_at"] for s in statuses)
84
+ rps = sum(s.get("rows_per_sec") or 0 for s in statuses)
85
+ stats_line = f"- Fleet wall-clock: ~{wall / 60:.1f} min · aggregate ~{rps:,.0f} rows/s\n"
86
+ except Exception as e:
87
+ logger.info(f"status stats skipped: {e}")
88
+
89
+ script_url = "https://huggingface.co/datasets/uv-scripts/embeddings/raw/main/generate-embeddings.py"
90
+ launcher_url = "https://huggingface.co/datasets/uv-scripts/embeddings/raw/main/launch-embedding-fleet.py"
91
+ on_jobs = os.environ.get("JOB_ID") is not None
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 "
107
+ f"[uv-scripts](https://huggingface.co/uv-scripts), fanned out with "
108
+ f"[`launch-embedding-fleet.py`]({launcher_url}):\n\n"
109
+ f"```bash\nuv run {launcher_url} \\\n"
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:
138
+ logger.warning(f"card push skipped: {e}")
139
+ logger.info(f"✅ https://huggingface.co/datasets/{out_repo}")
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()
generate-embeddings.py CHANGED
@@ -7,7 +7,7 @@
7
  # "numpy",
8
  # "pillow",
9
  # "einops",
10
- # "huggingface-hub",
11
  # ]
12
  # ///
13
  """
@@ -56,6 +56,18 @@ Examples:
56
  # Test on a small slice first, keep the output private
57
  hf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings.py \\
58
  stanfordnlp/imdb your-name/imdb-emb --max-samples 100 --private
 
 
 
 
 
 
 
 
 
 
 
 
59
  """
60
  import argparse
61
  import logging
@@ -204,6 +216,61 @@ def sniff_token_lengths(model, texts, max_seq_len, sample=512):
204
  return median
205
 
206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  def main():
208
  p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
209
  p.add_argument("input_dataset", help="Input dataset ID on the Hugging Face Hub")
@@ -232,8 +299,42 @@ def main():
232
  p.add_argument("--normalize", action="store_true", default=True)
233
  p.add_argument("--no-normalize", dest="normalize", action="store_false")
234
  p.add_argument("--private", action="store_true", help="Make the output dataset private")
 
 
 
 
 
 
 
 
 
 
 
235
  args = p.parse_args()
236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  import torch
238
  from datasets import load_dataset
239
  from huggingface_hub import DatasetCard, login
@@ -256,6 +357,15 @@ def main():
256
  sys.exit(1)
257
  if args.max_samples:
258
  ds = ds.select(range(min(args.max_samples, len(ds))))
 
 
 
 
 
 
 
 
 
259
  logger.info(f"{len(ds)} rows; modality={args.modality}")
260
 
261
  device = "cuda" if torch.cuda.is_available() else "cpu"
@@ -302,14 +412,55 @@ def main():
302
  else:
303
  encode_fn = model.encode
304
  encode_kwargs = {}
 
 
 
 
 
 
305
  t0 = time.perf_counter()
306
- emb = encode_fn(items, batch_size=batch_size, show_progress_bar=True,
307
- convert_to_numpy=True, normalize_embeddings=args.normalize, **encode_kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
  secs = time.perf_counter() - t0
309
  logger.info(f"Embedded {len(items)} in {secs:.1f}s ({len(items)/secs:.0f} rows/s), dim={dim}")
310
 
311
  ds = ds.add_column(args.output_column, [e.tolist() for e in emb])
312
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
  # For the card: record the effective prefix (explicit, else the model's registered one).
314
  side_keys = ("query",) if args.query_mode else ("document", "passage", "corpus")
315
  effective = prompt_str if prompt_str is not None else next(
 
7
  # "numpy",
8
  # "pillow",
9
  # "einops",
10
+ # "huggingface-hub>=1.12",
11
  # ]
12
  # ///
13
  """
 
56
  # Test on a small slice first, keep the output private
57
  hf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings.py \\
58
  stanfordnlp/imdb your-name/imdb-emb --max-samples 100 --private
59
+
60
+ FAN-OUT (multi-job) MODE:
61
+ Split one embedding run across N Jobs with --num-shards/--shard-index (or the RANK /
62
+ NUM_SHARDS / RUN_ID / OUTPUT_BUCKET env vars, so a launcher only varies RANK per job —
63
+ see launch-embedding-fleet.py). Each shard takes an exact, non-overlapping contiguous
64
+ slice, writes its rows to the run's bucket as runs/<run-id>/data/<rank>.parquet (object
65
+ PUTs — no repo-commit contention), and heartbeats progress to
66
+ runs/<run-id>/status/<rank>.json. consolidate-shards.py merges shards into the final
67
+ dataset with one commit. Re-running a failed rank overwrites only its own files (resume).
68
+ Note: --max-samples applies BEFORE sharding, so a capped run still partitions exactly.
69
+ Each rank still downloads the full split before slicing — fine at few-million-row scale;
70
+ for larger corpora shard at the file level or stream instead.
71
  """
72
  import argparse
73
  import logging
 
216
  return median
217
 
218
 
219
+ def put_bucket_files(bucket_id, add, max_retries=3):
220
+ """batch_bucket_files with a short retry — bucket PUTs are cheap object writes but can
221
+ flake transiently; shard data must not be lost to a blip."""
222
+ from huggingface_hub import batch_bucket_files
223
+ for attempt in range(1, max_retries + 1):
224
+ try:
225
+ batch_bucket_files(bucket_id, add=add)
226
+ return True
227
+ except Exception as e:
228
+ if attempt == max_retries:
229
+ raise
230
+ logger.warning(f"bucket PUT attempt {attempt}/{max_retries} failed: {e}; retrying in {5 * attempt}s")
231
+ time.sleep(5 * attempt)
232
+
233
+
234
+ class StatusReporter:
235
+ """Fan-out worker heartbeat: PUTs runs/<run-id>/status/<rank>.json to the run bucket,
236
+ throttled to one write per ~30s (last-writer-wins per key, so N workers never contend).
237
+ A failed status write must never kill a paid embedding run — errors are logged, not raised."""
238
+
239
+ def __init__(self, bucket, run_id, rank, rows_total, tokens_per_row=None):
240
+ self.bucket, self.run_id, self.rank = bucket, run_id, rank
241
+ self.rows_total, self.tokens_per_row = rows_total, tokens_per_row
242
+ self.started_at = time.time()
243
+ self.rows_done = 0
244
+ self._last_write = 0.0
245
+
246
+ def report(self, rows_done=None, state="running", force=False):
247
+ import json
248
+ if rows_done is not None:
249
+ self.rows_done = rows_done
250
+ now = time.time()
251
+ if not force and now - self._last_write < 30:
252
+ return
253
+ elapsed = max(now - self.started_at, 1e-6)
254
+ payload = {
255
+ "run_id": self.run_id,
256
+ "rank": self.rank,
257
+ "state": state,
258
+ "rows_done": self.rows_done,
259
+ "rows_total": self.rows_total,
260
+ "tokens_done_est": int(self.rows_done * self.tokens_per_row) if self.tokens_per_row else None,
261
+ "rows_per_sec": round(self.rows_done / elapsed, 1),
262
+ "started_at": self.started_at,
263
+ "updated_at": now,
264
+ "job_id": os.environ.get("JOB_ID"),
265
+ }
266
+ dest = f"runs/{self.run_id}/status/{self.rank:05d}.json"
267
+ try:
268
+ put_bucket_files(self.bucket, [(json.dumps(payload).encode(), dest)], max_retries=2)
269
+ self._last_write = now
270
+ except Exception as e:
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")
 
299
  p.add_argument("--normalize", action="store_true", default=True)
300
  p.add_argument("--no-normalize", dest="normalize", action="store_false")
301
  p.add_argument("--private", action="store_true", help="Make the output dataset private")
302
+ # Fan-out mode (see docstring). Env-defaulted so a launcher drives workers purely via env.
303
+ # Defaults stay raw strings; int conversion happens after parse so a malformed env var
304
+ # reaches p.error() instead of blowing up argparse construction.
305
+ p.add_argument("--num-shards", default=os.environ.get("NUM_SHARDS"),
306
+ help="Fan-out: total number of shards (env NUM_SHARDS). Enables shard mode.")
307
+ p.add_argument("--shard-index", default=os.environ.get("RANK"),
308
+ help="Fan-out: this worker's shard index, 0-based (env RANK).")
309
+ p.add_argument("--output-bucket", default=os.environ.get("OUTPUT_BUCKET"),
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):
316
+ if val is None:
317
+ return None
318
+ try:
319
+ return int(val)
320
+ except (TypeError, ValueError):
321
+ p.error(f"{name} must be an integer (got {val!r}).")
322
+
323
+ args.num_shards = int_or_error(args.num_shards, "--num-shards / NUM_SHARDS")
324
+ args.shard_index = int_or_error(args.shard_index, "--shard-index / RANK")
325
+
326
+ sharded = args.num_shards is not None
327
+ if sharded:
328
+ if args.num_shards < 1:
329
+ p.error(f"--num-shards must be >= 1 (got {args.num_shards}).")
330
+ if args.shard_index is None or not 0 <= args.shard_index < args.num_shards:
331
+ p.error(f"--shard-index must be in [0, {args.num_shards}) when --num-shards is set "
332
+ f"(got {args.shard_index}).")
333
+ if not (args.output_bucket and args.run_id):
334
+ p.error("fan-out mode needs --output-bucket and --run-id (env OUTPUT_BUCKET / RUN_ID).")
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
 
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)
364
+ logger.info(f"Fan-out shard {args.shard_index + 1}/{args.num_shards} of run {args.run_id}")
365
+ if len(ds) == 0:
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"
 
412
  else:
413
  encode_fn = model.encode
414
  encode_kwargs = {}
415
+ reporter = None
416
+ if sharded:
417
+ reporter = StatusReporter(args.output_bucket, args.run_id, args.shard_index,
418
+ rows_total=len(items), tokens_per_row=median_tok)
419
+ reporter.report(0, force=True)
420
+
421
  t0 = time.perf_counter()
422
+ try:
423
+ if reporter is None:
424
+ emb = encode_fn(items, batch_size=batch_size, show_progress_bar=True,
425
+ convert_to_numpy=True, normalize_embeddings=args.normalize, **encode_kwargs)
426
+ else:
427
+ # Macro-chunks so the heartbeat can report rows_done between encode calls.
428
+ # Chunking doesn't change results — batching happens at batch_size regardless.
429
+ import numpy as np
430
+ chunk_rows = 25_000
431
+ parts = []
432
+ for start in range(0, len(items), chunk_rows):
433
+ chunk = items[start:start + chunk_rows]
434
+ parts.append(encode_fn(chunk, batch_size=batch_size, show_progress_bar=True,
435
+ convert_to_numpy=True, normalize_embeddings=args.normalize,
436
+ **encode_kwargs))
437
+ reporter.report(start + len(chunk))
438
+ emb = np.concatenate(parts) if len(parts) > 1 else parts[0]
439
+ except Exception:
440
+ if reporter:
441
+ reporter.report(state="error", force=True)
442
+ raise
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:
458
+ reporter.report(state="error", force=True)
459
+ raise
460
+ reporter.report(len(items), state="done", force=True)
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(
launch-embedding-fleet.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "datasets",
5
+ # "huggingface-hub>=1.12",
6
+ # ]
7
+ # ///
8
+ """
9
+ Fan one embedding run out across N Hugging Face Jobs, then consolidate.
10
+
11
+ Runs generate-embeddings.py once per shard (each worker gets RANK / NUM_SHARDS /
12
+ RUN_ID / OUTPUT_BUCKET via env), workers write parquet shards + progress heartbeats
13
+ to the run bucket (object PUTs — no repo-commit contention), and when all workers
14
+ finish a consolidation Job merges the shards into the final Hub dataset with one
15
+ commit. Runs locally on your laptop; only the workers/consolidator run on Jobs.
16
+
17
+ Examples:
18
+ # Smoke: 2 small-GPU jobs over a 20k-row slice
19
+ uv run launch-embedding-fleet.py stanfordnlp/imdb your-name/imdb-emb \\
20
+ --max-samples 20000 --num-shards 2 --flavor t4-small --timeout 20m
21
+
22
+ # Mid-size: 8 L4s over a few million rows
23
+ uv run launch-embedding-fleet.py your-name/corpus your-name/corpus-emb \\
24
+ --num-shards 8 --flavor l4x1 --timeout 1h
25
+
26
+ # Re-run one failed shard, then consolidate an existing run
27
+ uv run launch-embedding-fleet.py ... --run-id 20260709-1200-abc123 --retry-rank 3
28
+ uv run launch-embedding-fleet.py ... --run-id 20260709-1200-abc123 --consolidate-only
29
+
30
+ Resume model: every worker writes only runs/<run-id>/data/<rank>.parquet and its own
31
+ status file, so re-running a rank is idempotent. The launcher exiting early never
32
+ orphans a run — --retry-rank / --consolidate-only pick it back up.
33
+ """
34
+ import argparse
35
+ import json
36
+ import logging
37
+ import os
38
+ import secrets as pysecrets
39
+ import sys
40
+ import time
41
+
42
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
43
+ logger = logging.getLogger("launch-embedding-fleet")
44
+
45
+ SCRIPT_BASE = "https://huggingface.co/datasets/uv-scripts/embeddings/raw/main"
46
+
47
+
48
+ def put_json(bucket, path, obj, token=None):
49
+ from huggingface_hub import batch_bucket_files
50
+ batch_bucket_files(bucket, add=[(json.dumps(obj, indent=2).encode(), path)], token=token)
51
+
52
+
53
+ def rows_in_split(input_dataset, config, split):
54
+ """Row count WITHOUT downloading: builder metadata, else the dataset-viewer size API."""
55
+ try:
56
+ from datasets import load_dataset_builder
57
+ b = load_dataset_builder(input_dataset, config) if config else load_dataset_builder(input_dataset)
58
+ n = b.info.splits[split].num_examples
59
+ if n:
60
+ return n
61
+ except Exception as e:
62
+ logger.info(f"builder metadata unavailable ({e}); trying dataset-viewer size API")
63
+ try:
64
+ import huggingface_hub
65
+ r = huggingface_hub.get_session().get(
66
+ "https://datasets-server.huggingface.co/size", params={"dataset": input_dataset}
67
+ )
68
+ r.raise_for_status()
69
+ for s in r.json()["size"]["splits"]:
70
+ if s["split"] == split and (config is None or s["config"] == config):
71
+ return s["num_rows"]
72
+ except Exception as e:
73
+ logger.info(f"size API unavailable ({e})")
74
+ return None
75
+
76
+
77
+ def main():
78
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
79
+ p.add_argument("input_dataset")
80
+ p.add_argument("output_dataset")
81
+ p.add_argument("--model", default="sentence-transformers/all-MiniLM-L6-v2")
82
+ p.add_argument("--column", default="text")
83
+ p.add_argument("--split", default="train")
84
+ p.add_argument("--config", default=None)
85
+ p.add_argument("--max-samples", type=int, default=None)
86
+ p.add_argument("--num-shards", type=int, default=8)
87
+ p.add_argument("--flavor", default="l4x1")
88
+ p.add_argument("--timeout", default="1h", help="Per-worker timeout — also the hard cost ceiling")
89
+ p.add_argument("--bucket", default=None,
90
+ help="Run bucket (default: <namespace>/embedding-runs)")
91
+ p.add_argument("--script", default=f"{SCRIPT_BASE}/generate-embeddings.py",
92
+ help="Worker script: raw URL (default) or a local .py path for dev")
93
+ p.add_argument("--consolidate-script", default=f"{SCRIPT_BASE}/consolidate-shards.py",
94
+ help="Consolidator script: raw URL (default) or local path for dev")
95
+ p.add_argument("--rows-total", type=int, default=None,
96
+ help="Override when the dataset has no split metadata")
97
+ p.add_argument("--private", action="store_true", help="Final output dataset is private")
98
+ p.add_argument("--embed-args", nargs=argparse.REMAINDER, default=[],
99
+ help="Everything after --embed-args is passed through to generate-embeddings.py "
100
+ "verbatim — put it LAST (any launcher flags after it are swallowed too).")
101
+ p.add_argument("--run-id", default=None, help="Attach to an existing run (with --retry-rank/--consolidate-only)")
102
+ p.add_argument("--retry-rank", type=int, default=None, help="Re-spawn a single failed shard of --run-id")
103
+ p.add_argument("--consolidate-only", action="store_true", help="Just run consolidation for --run-id")
104
+ p.add_argument("--no-wait", action="store_true",
105
+ help="Spawn workers and exit (run --consolidate-only later)")
106
+ args = p.parse_args()
107
+
108
+ from huggingface_hub import (JobStage, create_bucket, download_bucket_files, get_token,
109
+ run_uv_job, wait_for_job, whoami)
110
+
111
+ # Workers need a real token as a secret (bucket writes + output push); env may be empty
112
+ # when the user authenticated via `hf auth login` (keyring/hub cache).
113
+ token = os.environ.get("HF_TOKEN") or get_token()
114
+ if not token:
115
+ p.error("No HF token found — set HF_TOKEN or run `hf auth login`.")
116
+ namespace = whoami(token=token)["name"]
117
+ bucket = args.bucket or f"{namespace}/embedding-runs"
118
+
119
+ if (args.retry_rank is not None or args.consolidate_only) and not args.run_id:
120
+ p.error("--retry-rank / --consolidate-only need --run-id")
121
+ if args.num_shards < 1:
122
+ p.error(f"--num-shards must be >= 1 (got {args.num_shards})")
123
+
124
+ def read_manifest(run_id):
125
+ import tempfile
126
+ from pathlib import Path
127
+ with tempfile.TemporaryDirectory() as td:
128
+ dst = Path(td) / "run.json"
129
+ download_bucket_files(bucket, [(f"runs/{run_id}/run.json", dst)],
130
+ raise_on_missing_files=True, token=token)
131
+ return json.loads(dst.read_text())
132
+
133
+ # Workers are always spawned from the run manifest, never from current CLI flags —
134
+ # a --retry-rank months later must reproduce the original slice/model/args exactly.
135
+ def spawn_worker(rank, manifest):
136
+ script_args = [manifest["input_dataset"], manifest["output_dataset"],
137
+ "--model", manifest["model"], "--column", manifest["column"],
138
+ "--split", manifest["split"]]
139
+ if manifest.get("config"):
140
+ script_args += ["--config", manifest["config"]]
141
+ if manifest.get("max_samples"):
142
+ script_args += ["--max-samples", str(manifest["max_samples"])]
143
+ script_args += list(manifest.get("embed_args") or [])
144
+ job = run_uv_job(
145
+ args.script,
146
+ script_args=script_args,
147
+ flavor=manifest["flavor"],
148
+ timeout=manifest["timeout"],
149
+ env={
150
+ "RANK": str(rank),
151
+ "NUM_SHARDS": str(manifest["num_shards"]),
152
+ "RUN_ID": manifest["run_id"],
153
+ "OUTPUT_BUCKET": bucket,
154
+ },
155
+ secrets={"HF_TOKEN": token},
156
+ labels={"embedding-fleet-run": manifest["run_id"], "rank": str(rank)},
157
+ token=token,
158
+ )
159
+ logger.info(f" rank {rank} → job {job.id} ({manifest['flavor']})")
160
+ return job
161
+
162
+ def spawn_consolidator(run_id):
163
+ job = run_uv_job(
164
+ args.consolidate_script,
165
+ script_args=[
166
+ "--bucket", bucket, "--run-id", run_id,
167
+ ] + (["--private"] if args.private else []),
168
+ flavor="cpu-upgrade",
169
+ timeout="30m",
170
+ secrets={"HF_TOKEN": token},
171
+ labels={"embedding-fleet-run": run_id, "role": "consolidate"},
172
+ token=token,
173
+ )
174
+ logger.info(f"Consolidation job {job.id} (cpu-upgrade) — merges shards → {args.output_dataset}")
175
+ return job
176
+
177
+ # --- attach-to-existing-run paths ---
178
+ if args.retry_rank is not None:
179
+ manifest = read_manifest(args.run_id)
180
+ if not 0 <= args.retry_rank < manifest["num_shards"]:
181
+ p.error(f"--retry-rank must be in [0, {manifest['num_shards']}) for run {args.run_id}")
182
+ logger.info(f"Re-spawning rank {args.retry_rank} of run {args.run_id} (config from manifest)")
183
+ job = spawn_worker(args.retry_rank, manifest)
184
+ info = wait_for_job(job.id, token=token)
185
+ if info.status.stage != JobStage.COMPLETED:
186
+ logger.error(f"Retry of rank {args.retry_rank} did not complete "
187
+ f"(stage={info.status.stage}, job {job.id}).")
188
+ sys.exit(1)
189
+ logger.info("Retry completed; run --consolidate-only when all shards are done.")
190
+ return
191
+
192
+ if args.consolidate_only:
193
+ job = spawn_consolidator(args.run_id)
194
+ info = wait_for_job(job.id, token=token)
195
+ sys.exit(0 if info.status.stage == JobStage.COMPLETED else 1)
196
+
197
+ # --- fresh run ---
198
+ rows_total = args.rows_total or rows_in_split(args.input_dataset, args.config, args.split)
199
+ if rows_total is None:
200
+ p.error("Couldn't determine the split's row count — pass --rows-total.")
201
+ if args.max_samples:
202
+ rows_total = min(rows_total, args.max_samples)
203
+ if args.num_shards > rows_total:
204
+ p.error(f"--num-shards {args.num_shards} exceeds the row count ({rows_total}) — "
205
+ f"some shards would be empty.")
206
+
207
+ run_id = time.strftime("%Y%m%d-%H%M%S") + "-" + pysecrets.token_hex(3)
208
+ create_bucket(bucket, private=True, exist_ok=True, token=token)
209
+
210
+ manifest = {
211
+ "run_id": run_id,
212
+ "input_dataset": args.input_dataset,
213
+ "output_dataset": args.output_dataset,
214
+ "model": args.model,
215
+ "column": args.column,
216
+ "split": args.split,
217
+ "config": args.config,
218
+ "max_samples": args.max_samples,
219
+ "num_shards": args.num_shards,
220
+ "rows_total": rows_total,
221
+ "flavor": args.flavor,
222
+ "timeout": args.timeout,
223
+ "private": args.private,
224
+ "embed_args": list(args.embed_args),
225
+ "started_at": time.time(),
226
+ "job_ids": [],
227
+ }
228
+ put_json(bucket, f"runs/{run_id}/run.json", manifest, token=token)
229
+ logger.info(f"Run {run_id}: {rows_total:,} rows → {args.num_shards} shards "
230
+ f"(~{rows_total // args.num_shards:,} rows each) on {args.flavor}")
231
+
232
+ jobs = [spawn_worker(rank, manifest) for rank in range(args.num_shards)]
233
+ manifest["job_ids"] = [j.id for j in jobs]
234
+ put_json(bucket, f"runs/{run_id}/run.json", manifest, token=token)
235
+
236
+ logger.info(f"Manifest: hf://buckets/{bucket}/runs/{run_id}/run.json")
237
+ logger.info(f"Dashboard: https://huggingface.co/spaces/davanstrien/embedding-fleet-dashboard?run={run_id}")
238
+
239
+ if args.no_wait:
240
+ logger.info(f"--no-wait: consolidate later with --run-id {run_id} --consolidate-only")
241
+ return
242
+
243
+ logger.info("Waiting for workers…")
244
+ infos = wait_for_job([j.id for j in jobs], token=token)
245
+ failed = [(rank, j.id) for rank, (j, i) in enumerate(zip(jobs, infos))
246
+ if i.status.stage != JobStage.COMPLETED]
247
+ if failed:
248
+ logger.error(f"{len(failed)} worker(s) did not complete: {failed}")
249
+ logger.error(f"Re-run each with --run-id {run_id} --retry-rank <rank>, then --consolidate-only.")
250
+ sys.exit(1)
251
+
252
+ job = spawn_consolidator(run_id)
253
+ info = wait_for_job(job.id, token=token)
254
+ if info.status.stage != JobStage.COMPLETED:
255
+ logger.error(f"Consolidation failed (job {job.id}); retry with --consolidate-only --run-id {run_id}")
256
+ sys.exit(1)
257
+ logger.info(f"✅ https://huggingface.co/datasets/{args.output_dataset}")
258
+
259
+
260
+ if __name__ == "__main__":
261
+ main()