mattbitzesty commited on
Commit
7d3c72d
·
verified ·
1 Parent(s): 0849c07

round-10: atomic isolated seed-10 tail jobs

Browse files
Files changed (1) hide show
  1. scripts/hf_gpu_round10_job.py +142 -61
scripts/hf_gpu_round10_job.py CHANGED
@@ -61,6 +61,7 @@ TRAIN_RATIO = os.environ.get("PINO_TRAIN_RATIO", "0.85")
61
  SEEDS = [int(s) for s in os.environ.get("PINO_SEEDS", "1,2,3,4,5,6,7,8,9,10").split(",") if s.strip()]
62
  FAMILIES = tuple(f for f in os.environ.get("PINO_FAMILIES", "physoff,fact,direct").split(",") if f)
63
  FACT_MODES = ("full", "off", "gamma_only", "headspace_only")
 
64
 
65
  DATASET_V10 = "empirical_dataset_v10_alltags.jsonl"
66
  DATASET_V9G = "empirical_dataset_v9_gamma.jsonl"
@@ -69,6 +70,9 @@ WALL_BUDGET_S = int(os.environ.get("PINO_WALL_BUDGET_S", "5100")) # ~85 min
69
  JOB_IMAGE = os.environ.get("PINO_JOB_IMAGE", "pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime")
70
  JOB_FLAVOR = os.environ.get("PINO_JOB_FLAVOR", "t4-medium")
71
  JOB_TIMEOUT = os.environ.get("PINO_JOB_TIMEOUT", "21600")
 
 
 
72
  _START = time.time()
73
 
74
 
@@ -89,6 +93,26 @@ def _disable_xet() -> None:
89
  log(f"[R10] warn: xet-disable patch failed ({e})")
90
 
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  def _run_specs() -> list[dict]:
93
  """The full run list: one dict per (family, mode, seed)."""
94
  specs: list[dict] = []
@@ -120,7 +144,7 @@ def main() -> int:
120
  "huggingface-hub", "scipy", "tensorboard", "rdkit", "numpy"])
121
  _disable_xet()
122
 
123
- from huggingface_hub import snapshot_download, HfApi
124
  SOURCE_DIR.mkdir(parents=True, exist_ok=True)
125
  DATASET_DIR.mkdir(parents=True, exist_ok=True)
126
  OUT_DIR.mkdir(parents=True, exist_ok=True)
@@ -169,16 +193,24 @@ def main() -> int:
169
  return time.time() - _START
170
 
171
  specs = _run_specs()
 
 
 
172
  pending = [s for s in specs
173
  if not all(a in have for a in _expected_artifacts(s))]
174
  log(f"[R10] {len(specs)} total runs, {len(pending)} pending "
175
  f"(elapsed {(_elapsed()/60):.1f} min)")
176
 
177
  completed_now: list[str] = []
 
178
  for spec in pending:
 
 
 
179
  if _elapsed() > WALL_BUDGET_S:
180
  log(f"[R10] wall budget reached ({(_elapsed()/60):.1f} min); chaining")
181
  break
 
182
  tag, seed, family, mode = spec["tag"], spec["seed"], spec["family"], spec["mode"]
183
  log(f"[R10] ===== {tag} (family={family} mode={mode}, {EPOCHS} epochs) =====")
184
 
@@ -196,15 +228,27 @@ def main() -> int:
196
  train_extra = ["--structural-source", "morgan_2048_direct"]
197
  ckpt_name = f"pimt_ab_{tag}.pt"
198
 
199
- run([sys.executable, "-m", "pino.train",
200
- "--data", data_path,
201
- "--epochs", str(EPOCHS), "--batch-size", str(BATCH), "--lr", LR,
202
- "--seed", str(seed), "--train-ratio", str(TRAIN_RATIO),
203
- *train_extra,
204
- "--output-dir", str(OUT_DIR),
205
- "--checkpoint-name", ckpt_name,
206
- "--log-dir", str(OUT_DIR / "runs" / tag)])
207
  ckpt = OUT_DIR / ckpt_name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
 
209
  final_val, best_epoch = None, None
210
  try:
@@ -214,66 +258,87 @@ def main() -> int:
214
  except Exception as e: # noqa: BLE001
215
  log(f"[R10] warn: could not read checkpoint for val stamp ({e})")
216
 
217
- uploads: list[tuple[Path, str]] = [(ckpt, ckpt_name)]
 
 
 
 
 
 
218
 
 
219
  if family in ("physoff", "direct"):
220
  eval_name = f"frozen_eval_{tag}.json"
221
- eval_out = OUT_DIR / eval_name
222
- source = "openpom_256" if family == "physoff" else "morgan_2048_direct"
223
- log(f"[R10] ===== frozen-benchmark eval {tag} =====")
224
- run([sys.executable, str(SOURCE_DIR / "scripts" / "evaluate_frozen_benchmarks.py"),
225
- "--checkpoint", str(ckpt),
226
- "--structural-source", source,
227
- "--arm-label", tag,
228
- "--output", str(eval_out)])
229
- try:
230
- ej = json.loads(eval_out.read_text())
231
- ej["final_val_total"] = final_val
232
- ej["best_epoch"] = best_epoch
233
- ej["seed"] = seed
234
- ej["physics_mode"] = mode
235
- eval_out.write_text(json.dumps(ej, indent=2))
236
- except Exception as e: # noqa: BLE001
237
- log(f"[R10] warn: could not stamp eval JSON ({e})")
238
- uploads.append((eval_out, eval_name))
 
 
 
239
 
240
  if family in ("physoff", "fact"):
241
  dd_name = f"drydown_{tag}.json"
242
- dd_out = OUT_DIR / dd_name
243
- log(f"[R10] ===== drydown eval {tag} (matched conditioning) =====")
244
- dd_cmd = [sys.executable, str(SOURCE_DIR / "scripts" / "evaluate_drydown_physics.py"),
245
- "--checkpoint", str(ckpt), "--data", data_path,
246
- "--train-ratio", str(TRAIN_RATIO), "--seed", str(seed),
247
- "--max-eval", "400",
248
- "--physics-mode", mode,
249
- "--arm-label", tag, "--output", str(dd_out)]
250
- if family == "fact":
251
- dd_cmd += ["--structural-source", "morgan", "--split", "formula", "--use-gamma"]
252
- else:
253
- dd_cmd += ["--structural-source", "openpom_256"]
254
- run(dd_cmd)
255
- uploads.append((dd_out, dd_name))
256
-
257
- for local, remote in uploads:
258
- api.upload_file(path_or_fileobj=str(local), path_in_repo=remote,
259
- repo_id=AB_REPO, repo_type="model")
260
  leak = OUT_DIR / f"split_leakage_report_seed{seed}.json"
261
- if leak.exists():
262
- api.upload_file(path_or_fileobj=str(leak), path_in_repo=leak.name,
263
- repo_id=AB_REPO, repo_type="model")
264
- log(f"[R10] uploaded {tag} ({len(uploads)} artifacts)")
265
- completed_now.append(tag)
 
 
 
 
 
 
 
 
266
 
267
  remaining = [s for s in pending if s["tag"] not in completed_now]
268
  log(f"[R10] completed this job: {len(completed_now)} | remaining: {len(remaining)}")
269
 
270
  summary = {"experiment": "round-10: physics-pathway trained ablation + drydown factorial n=10 + direct-2048 arm",
271
  "families": FAMILIES, "seeds": SEEDS, "epochs": EPOCHS,
 
272
  "completed_this_job": completed_now,
273
  "remaining": [s["tag"] for s in remaining],
274
  "all_complete": not remaining}
 
 
275
  api.upload_file(path_or_fileobj=json.dumps(summary, indent=2).encode(),
276
- path_in_repo="gpu_run_summary_round10.json", repo_id=AB_REPO, repo_type="model")
277
 
278
  if remaining:
279
  rem_seeds = sorted({s["seed"] for s in remaining})
@@ -290,15 +355,31 @@ def main() -> int:
290
  f"echo {base64.b64encode(_inner.encode()).decode()} | base64 -d > /tmp/chain_job.py; "
291
  "python /tmp/chain_job.py"
292
  )
293
- new_job = api.run_job(
294
- image=JOB_IMAGE,
295
- command=["bash", "-lc", chain_cmd],
296
- secrets={"HF_TOKEN": TOKEN, "PINO_SEEDS": ",".join(str(s) for s in rem_seeds),
297
- "PINO_FAMILIES": ",".join(FAMILIES), "PINO_EPOCHS": str(EPOCHS),
298
- "PINO_JOB_FLAVOR": JOB_FLAVOR},
299
- flavor=JOB_FLAVOR,
300
- timeout=int(JOB_TIMEOUT),
301
- namespace="mattbitzesty",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  )
303
  log(f"[R10] chained job started: {getattr(new_job,'id',new_job)} for seeds {rem_seeds}")
304
  except Exception as e: # noqa: BLE001
 
61
  SEEDS = [int(s) for s in os.environ.get("PINO_SEEDS", "1,2,3,4,5,6,7,8,9,10").split(",") if s.strip()]
62
  FAMILIES = tuple(f for f in os.environ.get("PINO_FAMILIES", "physoff,fact,direct").split(",") if f)
63
  FACT_MODES = ("full", "off", "gamma_only", "headspace_only")
64
+ ONLY_TAGS = {t for t in os.environ.get("PINO_TAGS", "").split(",") if t.strip()}
65
 
66
  DATASET_V10 = "empirical_dataset_v10_alltags.jsonl"
67
  DATASET_V9G = "empirical_dataset_v9_gamma.jsonl"
 
70
  JOB_IMAGE = os.environ.get("PINO_JOB_IMAGE", "pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime")
71
  JOB_FLAVOR = os.environ.get("PINO_JOB_FLAVOR", "t4-medium")
72
  JOB_TIMEOUT = os.environ.get("PINO_JOB_TIMEOUT", "21600")
73
+ MAX_RUNS_PER_JOB = int(os.environ.get("PINO_MAX_RUNS_PER_JOB", "0")) # 0 = legacy: fill wall budget
74
+ UPLOAD_CHECKPOINT_FIRST = os.environ.get("PINO_UPLOAD_CHECKPOINT_FIRST", "1") == "1"
75
+ RESUME_REMOTE_CHECKPOINTS = os.environ.get("PINO_RESUME_REMOTE_CHECKPOINTS", "1") == "1"
76
  _START = time.time()
77
 
78
 
 
93
  log(f"[R10] warn: xet-disable patch failed ({e})")
94
 
95
 
96
+ def _retry(fn, what: str, attempts: int = 3, delay_s: int = 10):
97
+ """Small retry wrapper for transient Hub/API failures."""
98
+ for attempt in range(1, attempts + 1):
99
+ try:
100
+ return fn()
101
+ except Exception as e: # noqa: BLE001
102
+ if attempt == attempts:
103
+ raise
104
+ log(f"[R10] warn: {what} failed (attempt {attempt}/{attempts}): {e}; retrying in {delay_s}s")
105
+ time.sleep(delay_s)
106
+
107
+
108
+ def _upload_with_retry(api, local: Path, remote: str) -> None:
109
+ _retry(
110
+ lambda: api.upload_file(path_or_fileobj=str(local), path_in_repo=remote,
111
+ repo_id=AB_REPO, repo_type="model"),
112
+ f"upload {remote}",
113
+ )
114
+
115
+
116
  def _run_specs() -> list[dict]:
117
  """The full run list: one dict per (family, mode, seed)."""
118
  specs: list[dict] = []
 
144
  "huggingface-hub", "scipy", "tensorboard", "rdkit", "numpy"])
145
  _disable_xet()
146
 
147
+ from huggingface_hub import snapshot_download, HfApi, hf_hub_download
148
  SOURCE_DIR.mkdir(parents=True, exist_ok=True)
149
  DATASET_DIR.mkdir(parents=True, exist_ok=True)
150
  OUT_DIR.mkdir(parents=True, exist_ok=True)
 
193
  return time.time() - _START
194
 
195
  specs = _run_specs()
196
+ if ONLY_TAGS:
197
+ specs = [s for s in specs if s["tag"] in ONLY_TAGS]
198
+ log(f"[R10] tag filter active: {sorted(ONLY_TAGS)} -> {len(specs)} run(s)")
199
  pending = [s for s in specs
200
  if not all(a in have for a in _expected_artifacts(s))]
201
  log(f"[R10] {len(specs)} total runs, {len(pending)} pending "
202
  f"(elapsed {(_elapsed()/60):.1f} min)")
203
 
204
  completed_now: list[str] = []
205
+ runs_started = 0
206
  for spec in pending:
207
+ if MAX_RUNS_PER_JOB and runs_started >= MAX_RUNS_PER_JOB:
208
+ log(f"[R10] per-job run cap reached ({MAX_RUNS_PER_JOB}); chaining")
209
+ break
210
  if _elapsed() > WALL_BUDGET_S:
211
  log(f"[R10] wall budget reached ({(_elapsed()/60):.1f} min); chaining")
212
  break
213
+ runs_started += 1
214
  tag, seed, family, mode = spec["tag"], spec["seed"], spec["family"], spec["mode"]
215
  log(f"[R10] ===== {tag} (family={family} mode={mode}, {EPOCHS} epochs) =====")
216
 
 
228
  train_extra = ["--structural-source", "morgan_2048_direct"]
229
  ckpt_name = f"pimt_ab_{tag}.pt"
230
 
 
 
 
 
 
 
 
 
231
  ckpt = OUT_DIR / ckpt_name
232
+ if ckpt_name in have and RESUME_REMOTE_CHECKPOINTS:
233
+ log(f"[R10] checkpoint {ckpt_name} already uploaded; resuming eval-only")
234
+ if not ckpt.exists():
235
+ downloaded = str(_retry(
236
+ lambda: hf_hub_download(repo_id=AB_REPO, repo_type="model",
237
+ filename=ckpt_name, local_dir=str(OUT_DIR),
238
+ token=TOKEN),
239
+ f"download {ckpt_name}",
240
+ ))
241
+ if Path(downloaded) != ckpt:
242
+ shutil.copy2(downloaded, ckpt)
243
+ else:
244
+ run([sys.executable, "-m", "pino.train",
245
+ "--data", data_path,
246
+ "--epochs", str(EPOCHS), "--batch-size", str(BATCH), "--lr", LR,
247
+ "--seed", str(seed), "--train-ratio", str(TRAIN_RATIO),
248
+ *train_extra,
249
+ "--output-dir", str(OUT_DIR),
250
+ "--checkpoint-name", ckpt_name,
251
+ "--log-dir", str(OUT_DIR / "runs" / tag)])
252
 
253
  final_val, best_epoch = None, None
254
  try:
 
258
  except Exception as e: # noqa: BLE001
259
  log(f"[R10] warn: could not read checkpoint for val stamp ({e})")
260
 
261
+ # Atomicity rule: get the expensive training artifact off the box before
262
+ # running any eval. If HF preempts the container during eval, the next
263
+ # chain hop resumes eval-only instead of repeating the training run.
264
+ if UPLOAD_CHECKPOINT_FIRST and ckpt_name not in have:
265
+ _upload_with_retry(api, ckpt, ckpt_name)
266
+ have.add(ckpt_name)
267
+ log(f"[R10] uploaded checkpoint {ckpt_name}")
268
 
269
+ uploaded_count = 0
270
  if family in ("physoff", "direct"):
271
  eval_name = f"frozen_eval_{tag}.json"
272
+ if eval_name not in have:
273
+ eval_out = OUT_DIR / eval_name
274
+ source = "openpom_256" if family == "physoff" else "morgan_2048_direct"
275
+ log(f"[R10] ===== frozen-benchmark eval {tag} =====")
276
+ run([sys.executable, str(SOURCE_DIR / "scripts" / "evaluate_frozen_benchmarks.py"),
277
+ "--checkpoint", str(ckpt),
278
+ "--structural-source", source,
279
+ "--arm-label", tag,
280
+ "--output", str(eval_out)])
281
+ try:
282
+ ej = json.loads(eval_out.read_text())
283
+ ej["final_val_total"] = final_val
284
+ ej["best_epoch"] = best_epoch
285
+ ej["seed"] = seed
286
+ ej["physics_mode"] = mode
287
+ eval_out.write_text(json.dumps(ej, indent=2))
288
+ except Exception as e: # noqa: BLE001
289
+ log(f"[R10] warn: could not stamp eval JSON ({e})")
290
+ _upload_with_retry(api, eval_out, eval_name)
291
+ have.add(eval_name)
292
+ uploaded_count += 1
293
 
294
  if family in ("physoff", "fact"):
295
  dd_name = f"drydown_{tag}.json"
296
+ if dd_name not in have:
297
+ dd_out = OUT_DIR / dd_name
298
+ log(f"[R10] ===== drydown eval {tag} (matched conditioning) =====")
299
+ dd_cmd = [sys.executable, str(SOURCE_DIR / "scripts" / "evaluate_drydown_physics.py"),
300
+ "--checkpoint", str(ckpt), "--data", data_path,
301
+ "--train-ratio", str(TRAIN_RATIO), "--seed", str(seed),
302
+ "--max-eval", "400",
303
+ "--physics-mode", mode,
304
+ "--arm-label", tag, "--output", str(dd_out)]
305
+ if family == "fact":
306
+ dd_cmd += ["--structural-source", "morgan", "--split", "formula", "--use-gamma"]
307
+ else:
308
+ dd_cmd += ["--structural-source", "openpom_256"]
309
+ run(dd_cmd)
310
+ _upload_with_retry(api, dd_out, dd_name)
311
+ have.add(dd_name)
312
+ uploaded_count += 1
313
+
314
  leak = OUT_DIR / f"split_leakage_report_seed{seed}.json"
315
+ if leak.exists() and leak.name not in have:
316
+ _upload_with_retry(api, leak, leak.name)
317
+ have.add(leak.name)
318
+
319
+ expected = _expected_artifacts(spec)
320
+ if all(a in have for a in expected):
321
+ total_artifacts = len(expected)
322
+ log(f"[R10] completed {tag} ({uploaded_count} eval artifacts uploaded this hop; "
323
+ f"{total_artifacts} expected artifacts present)")
324
+ completed_now.append(tag)
325
+ else:
326
+ missing_after = [a for a in expected if a not in have]
327
+ log(f"[R10] PARTIAL {tag}: missing {missing_after}; next chain hop will resume")
328
 
329
  remaining = [s for s in pending if s["tag"] not in completed_now]
330
  log(f"[R10] completed this job: {len(completed_now)} | remaining: {len(remaining)}")
331
 
332
  summary = {"experiment": "round-10: physics-pathway trained ablation + drydown factorial n=10 + direct-2048 arm",
333
  "families": FAMILIES, "seeds": SEEDS, "epochs": EPOCHS,
334
+ "tag_filter": sorted(ONLY_TAGS),
335
  "completed_this_job": completed_now,
336
  "remaining": [s["tag"] for s in remaining],
337
  "all_complete": not remaining}
338
+ summary_name = ("gpu_run_summary_round10.json" if not ONLY_TAGS else
339
+ f"gpu_run_summary_round10_{'_'.join(sorted(ONLY_TAGS))}.json")
340
  api.upload_file(path_or_fileobj=json.dumps(summary, indent=2).encode(),
341
+ path_in_repo=summary_name, repo_id=AB_REPO, repo_type="model")
342
 
343
  if remaining:
344
  rem_seeds = sorted({s["seed"] for s in remaining})
 
355
  f"echo {base64.b64encode(_inner.encode()).decode()} | base64 -d > /tmp/chain_job.py; "
356
  "python /tmp/chain_job.py"
357
  )
358
+ new_job = _retry(
359
+ lambda: api.run_job(
360
+ image=JOB_IMAGE,
361
+ command=["bash", "-lc", chain_cmd],
362
+ secrets={
363
+ "HF_TOKEN": TOKEN,
364
+ "PINO_SEEDS": ",".join(str(s) for s in rem_seeds),
365
+ "PINO_FAMILIES": ",".join(FAMILIES),
366
+ "PINO_TAGS": ",".join(sorted(ONLY_TAGS)),
367
+ "PINO_EPOCHS": str(EPOCHS),
368
+ "PINO_BATCH": str(BATCH),
369
+ "PINO_LR": LR,
370
+ "PINO_TRAIN_RATIO": TRAIN_RATIO,
371
+ "PINO_JOB_FLAVOR": JOB_FLAVOR,
372
+ "PINO_JOB_TIMEOUT": JOB_TIMEOUT,
373
+ "PINO_WALL_BUDGET_S": str(WALL_BUDGET_S),
374
+ "PINO_MAX_RUNS_PER_JOB": str(MAX_RUNS_PER_JOB),
375
+ "PINO_UPLOAD_CHECKPOINT_FIRST": "1" if UPLOAD_CHECKPOINT_FIRST else "0",
376
+ "PINO_RESUME_REMOTE_CHECKPOINTS": "1" if RESUME_REMOTE_CHECKPOINTS else "0",
377
+ },
378
+ flavor=JOB_FLAVOR,
379
+ timeout=int(JOB_TIMEOUT),
380
+ namespace="mattbitzesty",
381
+ ),
382
+ "chain relaunch",
383
  )
384
  log(f"[R10] chained job started: {getattr(new_job,'id',new_job)} for seeds {rem_seeds}")
385
  except Exception as e: # noqa: BLE001