Add --resume: one command converges any fan-out run

#1
by davanstrien HF Staff - opened
Files changed (2) hide show
  1. README.md +14 -4
  2. launch-embedding-fleet.py +74 -7
README.md CHANGED
@@ -53,10 +53,20 @@ uv run https://huggingface.co/datasets/uv-scripts/embeddings/raw/main/launch-emb
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: 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
 
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 failures never cost you the
57
+ run. Workers that fail are auto-retried once; past that, one command converges any run no need
58
+ to know which rank failed or why:
59
+
60
+ ```bash
61
+ uv run launch-embedding-fleet.py <in> <out> --run-id <id> --resume # re-runs ONLY missing shards, then merges
62
+ ```
63
+
64
+ (`--retry-rank`/`--consolidate-only` remain for surgical control.) Each worker's timeout gives a
65
+ **hard cost ceiling**: a fleet can never cost more than `N × flavor-rate × timeout`.
66
+
67
+ Watch a run live — progress, ETA, live ~$ vs ceiling, GPU utilization, replica health — in the
68
+ [fleet dashboard Space](https://huggingface.co/spaces/davanstrien/embedding-fleet-dashboard)
69
+ (the launcher prints your run's deep link).
70
 
71
  Scale note: by default workers shard row-wise after loading the split, so each rank downloads the
72
  full split first — fine up to a few tens of millions of rows. Past that, add `--streaming`: workers
launch-embedding-fleet.py CHANGED
@@ -104,7 +104,10 @@ def main():
104
  p.add_argument("--embed-args", nargs=argparse.REMAINDER, default=[],
105
  help="Everything after --embed-args is passed through to generate-embeddings.py "
106
  "verbatim — put it LAST (any launcher flags after it are swallowed too).")
107
- p.add_argument("--run-id", default=None, help="Attach to an existing run (with --retry-rank/--consolidate-only)")
 
 
 
108
  p.add_argument("--retry-rank", type=int, default=None, help="Re-spawn a single failed shard of --run-id")
109
  p.add_argument("--consolidate-only", action="store_true", help="Just run consolidation for --run-id")
110
  p.add_argument("--no-wait", action="store_true",
@@ -122,8 +125,8 @@ def main():
122
  namespace = whoami(token=token)["name"]
123
  bucket = args.bucket or f"{namespace}/embedding-runs"
124
 
125
- if (args.retry_rank is not None or args.consolidate_only) and not args.run_id:
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:
@@ -188,7 +191,67 @@ def main():
188
  f"merges shards → {args.output_dataset}")
189
  return job
190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  # --- attach-to-existing-run paths ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  if args.retry_rank is not None:
193
  manifest = read_manifest(args.run_id)
194
  if not 0 <= args.retry_rank < manifest["num_shards"]:
@@ -269,12 +332,16 @@ def main():
269
 
270
  logger.info("Waiting for workers…")
271
  infos = wait_for_job([j.id for j in jobs], token=token)
272
- failed = [(rank, j.id) for rank, (j, i) in enumerate(zip(jobs, infos))
273
  if i.status.stage != JobStage.COMPLETED]
274
  if failed:
275
- logger.error(f"{len(failed)} worker(s) did not complete: {failed}")
276
- logger.error(f"Re-run each with --run-id {run_id} --retry-rank <rank>, then --consolidate-only.")
277
- sys.exit(1)
 
 
 
 
278
 
279
  job = spawn_consolidator(run_id)
280
  info = wait_for_job(job.id, token=token)
 
104
  p.add_argument("--embed-args", nargs=argparse.REMAINDER, default=[],
105
  help="Everything after --embed-args is passed through to generate-embeddings.py "
106
  "verbatim — put it LAST (any launcher flags after it are swallowed too).")
107
+ p.add_argument("--run-id", default=None, help="Attach to an existing run (with --resume/--retry-rank/--consolidate-only)")
108
+ p.add_argument("--resume", action="store_true",
109
+ help="Converge an existing --run-id: find ranks without a 'done' status, re-run "
110
+ "exactly those, then consolidate. Idempotent — safe to run repeatedly.")
111
  p.add_argument("--retry-rank", type=int, default=None, help="Re-spawn a single failed shard of --run-id")
112
  p.add_argument("--consolidate-only", action="store_true", help="Just run consolidation for --run-id")
113
  p.add_argument("--no-wait", action="store_true",
 
125
  namespace = whoami(token=token)["name"]
126
  bucket = args.bucket or f"{namespace}/embedding-runs"
127
 
128
+ if (args.retry_rank is not None or args.consolidate_only or args.resume) and not args.run_id:
129
+ p.error("--resume / --retry-rank / --consolidate-only need --run-id")
130
  if args.num_shards < 1:
131
  p.error(f"--num-shards must be >= 1 (got {args.num_shards})")
132
  if args.streaming and args.max_samples:
 
191
  f"merges shards → {args.output_dataset}")
192
  return job
193
 
194
+ def execute_workers(ranks, manifest):
195
+ """Spawn the given ranks, wait, auto-retry failures ONCE, return still-failed ranks."""
196
+ for attempt in (1, 2):
197
+ jobs = {rank: spawn_worker(rank, manifest) for rank in ranks}
198
+ infos = wait_for_job([j.id for j in jobs.values()], token=token)
199
+ ranks = [rank for (rank, job), info in zip(jobs.items(), infos)
200
+ if info.status.stage != JobStage.COMPLETED]
201
+ if not ranks:
202
+ return []
203
+ if attempt == 1:
204
+ logger.warning(f"{len(ranks)} worker(s) failed; auto-retrying once: {ranks}")
205
+ return ranks
206
+
207
+ def done_ranks(run_id, n):
208
+ """Ranks whose bucket status reports state == 'done' (works for both shard modes)."""
209
+ import tempfile
210
+ from pathlib import Path
211
+ done = set()
212
+ with tempfile.TemporaryDirectory() as td:
213
+ pairs = [(f"runs/{run_id}/status/{i:05d}.json", Path(td) / f"{i}.json") for i in range(n)]
214
+ download_bucket_files(bucket, pairs, token=token)
215
+ for i, (_, dst) in enumerate(pairs):
216
+ if dst.exists() and json.loads(dst.read_text()).get("state") == "done":
217
+ done.add(i)
218
+ return done
219
+
220
  # --- attach-to-existing-run paths ---
221
+ if args.resume:
222
+ manifest = read_manifest(args.run_id)
223
+ n = manifest["num_shards"]
224
+ # Don't double-spawn ranks that are still running — wait for them, then diff.
225
+ from huggingface_hub import list_jobs
226
+ try:
227
+ in_flight = [j for j in list_jobs(labels={"embedding-fleet-run": args.run_id},
228
+ namespace=namespace, token=token)
229
+ if j.status.stage in (JobStage.RUNNING, JobStage.SCHEDULING)
230
+ and (j.labels or {}).get("rank") is not None]
231
+ except Exception as e:
232
+ logger.warning(f"in-flight check skipped ({e})")
233
+ in_flight = []
234
+ if in_flight:
235
+ ranks = sorted({j.labels["rank"] for j in in_flight})
236
+ logger.info(f"{len(in_flight)} worker(s) still in flight (ranks {ranks}) — waiting before resuming.")
237
+ wait_for_job([j.id for j in in_flight], token=token)
238
+ todo = sorted(set(range(n)) - done_ranks(args.run_id, n))
239
+ if todo:
240
+ logger.info(f"Resume {args.run_id}: {n - len(todo)}/{n} shards done; re-running {todo}")
241
+ still_failed = execute_workers(todo, manifest)
242
+ if still_failed:
243
+ logger.error(f"Ranks still failing after retry: {still_failed} — investigate, then --resume again.")
244
+ sys.exit(1)
245
+ else:
246
+ logger.info(f"Resume {args.run_id}: all {n} shards already done — consolidating.")
247
+ job = spawn_consolidator(args.run_id)
248
+ info = wait_for_job(job.id, token=token)
249
+ if info.status.stage != JobStage.COMPLETED:
250
+ logger.error(f"Consolidation failed (job {job.id}); run --resume again.")
251
+ sys.exit(1)
252
+ logger.info(f"✅ https://huggingface.co/datasets/{manifest['output_dataset']}")
253
+ return
254
+
255
  if args.retry_rank is not None:
256
  manifest = read_manifest(args.run_id)
257
  if not 0 <= args.retry_rank < manifest["num_shards"]:
 
332
 
333
  logger.info("Waiting for workers…")
334
  infos = wait_for_job([j.id for j in jobs], token=token)
335
+ failed = [rank for rank, (j, i) in enumerate(zip(jobs, infos))
336
  if i.status.stage != JobStage.COMPLETED]
337
  if failed:
338
+ logger.warning(f"{len(failed)} worker(s) did not complete; auto-retrying: {failed}")
339
+ still_failed = execute_workers(failed, manifest)
340
+ if still_failed:
341
+ logger.error(f"Ranks still failing after retries: {still_failed}")
342
+ logger.error(f"Investigate (job logs / heartbeat age), then converge with: "
343
+ f"--run-id {run_id} --resume")
344
+ sys.exit(1)
345
 
346
  job = spawn_consolidator(run_id)
347
  info = wait_for_job(job.id, token=token)