mattbitzesty commited on
Commit
7fc837b
·
verified ·
1 Parent(s): d7bd70d

R13 Joback-refit drydown rerun job (7 arms x 10 seeds)

Browse files
Files changed (1) hide show
  1. scripts/hf_gpu_joback_rerun_job.py +356 -0
scripts/hf_gpu_joback_rerun_job.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """HF GPU job (R13 panel response): Joback P_sat-refit drydown reruns.
3
+
4
+ The R13 panel demanded the drydown factorial and the time-index-only control be
5
+ repeated on a cache whose 27% placeholder (1.0 Pa) vapor pressures are replaced
6
+ by Joback-Lee-Kesler group-contribution estimates. This job re-trains all seven
7
+ drydown arms on the refit caches, n=10 seeds each, with drydown evals:
8
+
9
+ fact_jb_{full,off,gamma_only,headspace_only}_seed{n} — morgan backbone,
10
+ --use-gamma (state_dim=3), formula split, refit v9_gamma cache
11
+ (empirical_dataset_v9_gamma_joback.jsonl), matching the round-10
12
+ factorial protocol exactly.
13
+ ab_jb_openpom_256_seed{n} — openpom_256 full physics (default),
14
+ molecule split, refit v10 cache (empirical_dataset_v10_alltags_joback.jsonl).
15
+ physoff_jb_openpom_256_seed{n} — openpom_256 physics-off.
16
+ timeonly_jb_openpom_256_seed{n} — openpom_256 time-index-only control.
17
+
18
+ Artifacts: pimt_{tag}.pt + drydown_{tag}.json in the AB repo.
19
+ Self-chains on the wall budget like the round-10 / timeonly jobs. Resume-safe:
20
+ skips runs whose artifacts are already uploaded. PINO_TAGS filters to a subset
21
+ of arms so parallel root jobs each own one arm family.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ import shutil
28
+ import subprocess
29
+ import sys
30
+ import time
31
+ from pathlib import Path
32
+
33
+ TOKEN = os.environ.get("HF_TOKEN")
34
+ os.environ.setdefault("HF_HUB_ENABLE_XET", "0")
35
+ os.environ.setdefault("HF_HUB_DISABLE_XET", "1")
36
+
37
+ WORKSPACE = Path("/workspace")
38
+ SOURCE_DIR = WORKSPACE / "pino-fresh"
39
+ DATASET_DIR = WORKSPACE / "pino-dataset"
40
+ OUT_DIR = WORKSPACE / "ab_out"
41
+
42
+ SOURCE_REPO = os.environ.get("PINO_SOURCE_REPO", "mattbitzesty/pino-source-code")
43
+ DATASET_REPO = os.environ.get("PINO_DATASET_REPO", "mattbitzesty/pino-synthetic-dataset-v3")
44
+ AB_REPO = os.environ.get("PINO_AB_REPO", "mattbitzesty/pino-pimt-representation-ab")
45
+
46
+ EPOCHS = int(os.environ.get("PINO_EPOCHS", "20"))
47
+ BATCH = int(os.environ.get("PINO_BATCH", "32"))
48
+ LR = os.environ.get("PINO_LR", "3e-4")
49
+ TRAIN_RATIO = os.environ.get("PINO_TRAIN_RATIO", "0.85")
50
+ 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()]
51
+ ONLY_TAGS = {t for t in os.environ.get("PINO_TAGS", "").split(",") if t.strip()}
52
+
53
+ DATASET_V10_JB = "empirical_dataset_v10_alltags_joback.jsonl"
54
+ DATASET_V9G_JB = "empirical_dataset_v9_gamma_joback.jsonl"
55
+ FACT_MODES = ("full", "off", "gamma_only", "headspace_only")
56
+
57
+ WALL_BUDGET_S = int(os.environ.get("PINO_WALL_BUDGET_S", "5100")) # ~85 min
58
+ JOB_IMAGE = os.environ.get("PINO_JOB_IMAGE", "pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime")
59
+ JOB_FLAVOR = os.environ.get("PINO_JOB_FLAVOR", "t4-medium")
60
+ JOB_TIMEOUT = os.environ.get("PINO_JOB_TIMEOUT", "21600")
61
+ MAX_RUNS_PER_JOB = int(os.environ.get("PINO_MAX_RUNS_PER_JOB", "0")) # 0 = fill wall budget
62
+ _START = time.time()
63
+
64
+
65
+ def log(msg: str) -> None:
66
+ print(f"{time.strftime('%Y-%m-%dT%H:%M:%SZ')} {msg}", flush=True)
67
+
68
+
69
+ def run(cmd: list[str]) -> None:
70
+ log(f"$ {' '.join(cmd)}")
71
+ subprocess.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
72
+
73
+
74
+ def _disable_xet() -> None:
75
+ try:
76
+ import huggingface_hub.utils._runtime as _runtime
77
+ _runtime.is_xet_available = lambda: False
78
+ except Exception as e: # noqa: BLE001
79
+ log(f"[JB] warn: xet-disable patch failed ({e})")
80
+
81
+
82
+ def _retry(fn, what: str, attempts: int = 3, delay_s: int = 10):
83
+ for attempt in range(1, attempts + 1):
84
+ try:
85
+ return fn()
86
+ except Exception as e: # noqa: BLE001
87
+ if attempt == attempts:
88
+ raise
89
+ log(f"[JB] warn: {what} failed (attempt {attempt}/{attempts}): {e}; retrying in {delay_s}s")
90
+ time.sleep(delay_s)
91
+
92
+
93
+ def _upload_with_retry(api, local: Path, remote: str) -> None:
94
+ _retry(
95
+ lambda: api.upload_file(path_or_fileobj=str(local), path_in_repo=remote,
96
+ repo_id=AB_REPO, repo_type="model"),
97
+ f"upload {remote}",
98
+ )
99
+
100
+
101
+ def _run_specs() -> list[dict]:
102
+ specs: list[dict] = []
103
+ for seed in SEEDS:
104
+ for mode in FACT_MODES:
105
+ specs.append({
106
+ "family": "factjb", "mode": mode, "seed": seed,
107
+ "tag": f"fact_jb_{mode}_seed{seed}",
108
+ "data": DATASET_V9G_JB,
109
+ "train_extra": ["--structural-source", "morgan", "--split-strategy", "formula",
110
+ "--use-gamma", "--physics-mode", mode],
111
+ "eval_extra": ["--physics-mode", mode, "--structural-source", "morgan",
112
+ "--split", "formula", "--use-gamma"],
113
+ })
114
+ specs.append({
115
+ "family": "abjb", "mode": "full", "seed": seed,
116
+ "tag": f"ab_jb_openpom_256_seed{seed}",
117
+ "data": DATASET_V10_JB,
118
+ "train_extra": ["--structural-source", "openpom_256", "--physics-mode", "full"],
119
+ "eval_extra": ["--physics-mode", "full", "--structural-source", "openpom_256"],
120
+ })
121
+ specs.append({
122
+ "family": "physoffjb", "mode": "off", "seed": seed,
123
+ "tag": f"physoff_jb_openpom_256_seed{seed}",
124
+ "data": DATASET_V10_JB,
125
+ "train_extra": ["--structural-source", "openpom_256", "--physics-mode", "off"],
126
+ "eval_extra": ["--physics-mode", "off", "--structural-source", "openpom_256"],
127
+ })
128
+ specs.append({
129
+ "family": "timeonlyjb", "mode": "time_only", "seed": seed,
130
+ "tag": f"timeonly_jb_openpom_256_seed{seed}",
131
+ "data": DATASET_V10_JB,
132
+ "train_extra": ["--structural-source", "openpom_256", "--physics-mode", "time_only"],
133
+ "eval_extra": ["--physics-mode", "time_only", "--structural-source", "openpom_256"],
134
+ })
135
+ return specs
136
+
137
+
138
+ def _expected_artifacts(spec: dict) -> list[str]:
139
+ tag = spec["tag"]
140
+ return [f"pimt_{tag}.pt", f"drydown_{tag}.json"]
141
+
142
+
143
+ def main() -> int:
144
+ run([sys.executable, "-m", "pip", "install", "--quiet",
145
+ "huggingface-hub", "scipy", "tensorboard", "rdkit", "numpy"])
146
+ _disable_xet()
147
+
148
+ from huggingface_hub import snapshot_download, HfApi, hf_hub_download
149
+
150
+ SOURCE_DIR.mkdir(parents=True, exist_ok=True)
151
+ DATASET_DIR.mkdir(parents=True, exist_ok=True)
152
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
153
+
154
+ log(f"[JB] downloading source {SOURCE_REPO} + dataset {DATASET_REPO}")
155
+ snapshot_download(repo_id=SOURCE_REPO, repo_type="model", local_dir=str(SOURCE_DIR), token=TOKEN)
156
+ snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", local_dir=str(DATASET_DIR), token=TOKEN)
157
+
158
+ reg_src = DATASET_DIR / "registry.db"
159
+ if reg_src.exists():
160
+ shutil.copy2(reg_src, WORKSPACE / "registry.db")
161
+ os.environ["PINO_REGISTRY_PATH"] = str(WORKSPACE / "registry.db")
162
+ ss = DATASET_DIR / "scalar_stats_v1.json"
163
+ if ss.exists():
164
+ (SOURCE_DIR / "artifacts").mkdir(exist_ok=True)
165
+ shutil.copy2(ss, SOURCE_DIR / "artifacts" / "scalar_stats_v1.json")
166
+
167
+ pom_src_dir = DATASET_DIR / "artifacts" / "pom"
168
+ if pom_src_dir.exists():
169
+ pom_dst = SOURCE_DIR / "artifacts" / "pom"
170
+ pom_dst.mkdir(parents=True, exist_ok=True)
171
+ for fname in ("pom_embeddings.npy", "pom_index.json", "pom_manifest.json"):
172
+ f = pom_src_dir / fname
173
+ if f.exists():
174
+ shutil.copy2(f, pom_dst / fname)
175
+ log(f"[JB] staged POM assets -> {pom_dst}")
176
+ else:
177
+ log(f"[JB] WARN: no POM assets at {pom_src_dir}; openpom_256 backbone will fail")
178
+
179
+ run([sys.executable, "-m", "pip", "install", "--quiet", "-e", str(SOURCE_DIR)])
180
+ sys.path.insert(0, str(SOURCE_DIR / "src"))
181
+
182
+ import torch # noqa: E402
183
+ device = "cuda" if torch.cuda.is_available() else "cpu"
184
+ log(f"[JB] device={device} seeds={SEEDS}")
185
+
186
+ api = HfApi(token=TOKEN)
187
+ have = set()
188
+ try:
189
+ have = set(api.list_repo_files(AB_REPO, repo_type="model"))
190
+ except Exception as e: # noqa: BLE001
191
+ log(f"[JB] warn: could not list AB repo ({e}); assuming nothing done")
192
+
193
+ def _elapsed() -> float:
194
+ return time.time() - _START
195
+
196
+ specs = _run_specs()
197
+ if ONLY_TAGS:
198
+ specs = [s for s in specs if any(s["tag"].startswith(t) for t in ONLY_TAGS)]
199
+ log(f"[JB] tag filter active: {sorted(ONLY_TAGS)} -> {len(specs)} run(s)")
200
+ pending = [s for s in specs
201
+ if not all(a in have for a in _expected_artifacts(s))]
202
+ log(f"[JB] {len(specs)} total runs, {len(pending)} pending (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"[JB] per-job run cap reached ({MAX_RUNS_PER_JOB}); chaining")
209
+ break
210
+ if _elapsed() > WALL_BUDGET_S:
211
+ log(f"[JB] wall budget reached ({(_elapsed()/60):.1f} min); chaining")
212
+ break
213
+ runs_started += 1
214
+ tag, seed, mode = spec["tag"], spec["seed"], spec["mode"]
215
+ log(f"[JB] ===== {tag} (family={spec['family']} mode={mode}, {EPOCHS} epochs) =====")
216
+
217
+ data_path = str(DATASET_DIR / spec["data"])
218
+ ckpt_name = f"pimt_{tag}.pt"
219
+ ckpt = OUT_DIR / ckpt_name
220
+ if ckpt_name in have:
221
+ log(f"[JB] checkpoint {ckpt_name} already uploaded; resuming eval-only")
222
+ if not ckpt.exists():
223
+ downloaded = str(_retry(
224
+ lambda: hf_hub_download(repo_id=AB_REPO, repo_type="model",
225
+ filename=ckpt_name, local_dir=str(OUT_DIR),
226
+ token=TOKEN),
227
+ f"download {ckpt_name}",
228
+ ))
229
+ if Path(downloaded) != ckpt:
230
+ shutil.copy2(downloaded, ckpt)
231
+ else:
232
+ run([sys.executable, "-m", "pino.train",
233
+ "--data", data_path,
234
+ "--epochs", str(EPOCHS), "--batch-size", str(BATCH), "--lr", LR,
235
+ "--seed", str(seed), "--train-ratio", str(TRAIN_RATIO),
236
+ *spec["train_extra"],
237
+ "--output-dir", str(OUT_DIR),
238
+ "--checkpoint-name", ckpt_name,
239
+ "--log-dir", str(OUT_DIR / "runs" / tag)])
240
+
241
+ final_val, best_epoch = None, None
242
+ try:
243
+ blob = torch.load(ckpt, map_location="cpu")
244
+ final_val = float(blob.get("val_loss")) if blob.get("val_loss") is not None else None
245
+ best_epoch = int(blob.get("epoch")) if blob.get("epoch") is not None else None
246
+ except Exception as e: # noqa: BLE001
247
+ log(f"[JB] warn: could not read checkpoint for val stamp ({e})")
248
+
249
+ # Upload the expensive training artifact before eval (preemption-safe).
250
+ if ckpt_name not in have:
251
+ _upload_with_retry(api, ckpt, ckpt_name)
252
+ have.add(ckpt_name)
253
+ log(f"[JB] uploaded checkpoint {ckpt_name}")
254
+
255
+ dd_name = f"drydown_{tag}.json"
256
+ if dd_name not in have:
257
+ dd_out = OUT_DIR / dd_name
258
+ log(f"[JB] ===== drydown eval {tag} (matched {mode} conditioning) =====")
259
+ dd_cmd = [sys.executable, str(SOURCE_DIR / "scripts" / "evaluate_drydown_physics.py"),
260
+ "--checkpoint", str(ckpt), "--data", data_path,
261
+ "--train-ratio", str(TRAIN_RATIO), "--seed", str(seed),
262
+ "--max-eval", "400",
263
+ *spec["eval_extra"],
264
+ "--arm-label", tag, "--output", str(dd_out)]
265
+ run(dd_cmd)
266
+ try:
267
+ dj = json.loads(dd_out.read_text())
268
+ dj["final_val_total"] = final_val
269
+ dj["best_epoch"] = best_epoch
270
+ dj["seed"] = seed
271
+ dj["physics_mode"] = mode
272
+ dj["cache"] = "joback_psat_refit"
273
+ dd_out.write_text(json.dumps(dj, indent=2))
274
+ except Exception as e: # noqa: BLE001
275
+ log(f"[JB] warn: could not stamp drydown JSON ({e})")
276
+ _upload_with_retry(api, dd_out, dd_name)
277
+ have.add(dd_name)
278
+
279
+ expected = _expected_artifacts(spec)
280
+ if all(a in have for a in expected):
281
+ log(f"[JB] completed {tag}")
282
+ completed_now.append(tag)
283
+ else:
284
+ missing_after = [a for a in expected if a not in have]
285
+ log(f"[JB] PARTIAL {tag}: missing {missing_after}; next chain hop will resume")
286
+
287
+ remaining = [s for s in pending if s["tag"] not in completed_now]
288
+ log(f"[JB] completed this job: {len(completed_now)} | remaining: {len(remaining)}")
289
+
290
+ summary = {"experiment": "Joback P_sat-refit drydown reruns (R13 panel response), n=10 per arm",
291
+ "families": sorted({s["family"] for s in specs}),
292
+ "seeds": SEEDS, "epochs": EPOCHS,
293
+ "caches": {"factjb": DATASET_V9G_JB, "openpom_arms": DATASET_V10_JB},
294
+ "tag_filter": sorted(ONLY_TAGS),
295
+ "completed_this_job": completed_now,
296
+ "remaining": [s["tag"] for s in remaining],
297
+ "all_complete": not remaining}
298
+ summary_name = ("gpu_run_summary_joback.json" if not ONLY_TAGS else
299
+ f"gpu_run_summary_joback_{'_'.join(sorted(ONLY_TAGS))}.json")
300
+ api.upload_file(path_or_fileobj=json.dumps(summary, indent=2).encode(),
301
+ path_in_repo=summary_name, repo_id=AB_REPO, repo_type="model")
302
+
303
+ if remaining:
304
+ log(f"[JB] chaining: relaunching for {len(remaining)} runs")
305
+ try:
306
+ import base64
307
+ _inner = (
308
+ "from huggingface_hub import hf_hub_download; import runpy; "
309
+ f"p=hf_hub_download('{SOURCE_REPO}','scripts/hf_gpu_joback_rerun_job.py',repo_type='model'); "
310
+ "runpy.run_path(p,run_name='__main__')"
311
+ )
312
+ chain_cmd = (
313
+ "set -e; pip install -q huggingface-hub; "
314
+ f"echo {base64.b64encode(_inner.encode()).decode()} | base64 -d > /tmp/chain_job.py; "
315
+ "python /tmp/chain_job.py"
316
+ )
317
+ new_job = _retry(
318
+ lambda: api.run_job(
319
+ image=JOB_IMAGE,
320
+ command=["bash", "-lc", chain_cmd],
321
+ secrets={
322
+ "HF_TOKEN": TOKEN,
323
+ "PINO_SEEDS": ",".join(str(s) for s in SEEDS),
324
+ "PINO_TAGS": ",".join(sorted(ONLY_TAGS)),
325
+ "PINO_EPOCHS": str(EPOCHS),
326
+ "PINO_BATCH": str(BATCH),
327
+ "PINO_LR": LR,
328
+ "PINO_TRAIN_RATIO": TRAIN_RATIO,
329
+ "PINO_JOB_FLAVOR": JOB_FLAVOR,
330
+ "PINO_JOB_TIMEOUT": JOB_TIMEOUT,
331
+ "PINO_WALL_BUDGET_S": str(WALL_BUDGET_S),
332
+ "PINO_MAX_RUNS_PER_JOB": str(MAX_RUNS_PER_JOB),
333
+ },
334
+ flavor=JOB_FLAVOR,
335
+ timeout=int(JOB_TIMEOUT),
336
+ namespace="mattbitzesty",
337
+ ),
338
+ "chain relaunch",
339
+ )
340
+ log(f"[JB] chained job started: {getattr(new_job,'id',new_job)}")
341
+ except Exception as e: # noqa: BLE001
342
+ log(f"[JB] ERROR: chain relaunch failed ({e}); rerun manually")
343
+ return 2
344
+ else:
345
+ log("[JB] DONE - all joback-refit runs complete")
346
+ return 0
347
+
348
+
349
+ if __name__ == "__main__":
350
+ try:
351
+ raise SystemExit(main())
352
+ except Exception as exc: # noqa: BLE001
353
+ import traceback
354
+ traceback.print_exc()
355
+ print(f"[JB] FAILED: {exc}", flush=True)
356
+ raise SystemExit(1)