mattbitzesty commited on
Commit
299ec89
·
verified ·
1 Parent(s): 1cf8ebc

R12 time_only control arm (scripts/hf_gpu_timeonly_job.py)

Browse files
Files changed (1) hide show
  1. scripts/hf_gpu_timeonly_job.py +350 -0
scripts/hf_gpu_timeonly_job.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """HF GPU job (round-10 panel response): time_only physics-ablation arm.
3
+
4
+ Decisive control for the physics-off ablation. The PIMT model has NO positional
5
+ encoding, so time enters ONLY via the physics state tensor (B,T,S,3:
6
+ [x_liquid, log10 OAV, log10 gamma]). The 'off' arm therefore removes the time
7
+ axis entirely. The 'time_only' arm gives the model a clean normalized time index
8
+ (channel 0 = linspace(0,1,T), broadcast over batch+ingredients; channels 1..end
9
+ zero) with zero thermodynamic content, capacity-matched (same state_dim=3).
10
+
11
+ time_only — openpom_256 trained with --physics-mode time_only (state_dim=3,
12
+ molecule split, v10 dataset), seeds 1..10. Drydown-evaled with
13
+ matched time_only conditioning (so the eval tensor matches what the
14
+ model saw during training).
15
+ Artifacts: pimt_timeonly_openpom_256_seed{n}.pt,
16
+ drydown_timeonly_openpom_256_seed{n}.json
17
+
18
+ Self-chains like the W4 / round-10 job: processes runs until the wall budget,
19
+ then relaunches itself (base64-wrapped) for the rest. Resume-safe: skips runs
20
+ whose artifacts are already in the AB repo.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ import shutil
27
+ import subprocess
28
+ import sys
29
+ import time
30
+ from pathlib import Path
31
+
32
+ TOKEN = os.environ.get("HF_TOKEN")
33
+ os.environ.setdefault("HF_HUB_ENABLE_XET", "0")
34
+ os.environ.setdefault("HF_HUB_DISABLE_XET", "1")
35
+
36
+ WORKSPACE = Path("/workspace")
37
+ SOURCE_DIR = WORKSPACE / "pino-fresh"
38
+ DATASET_DIR = WORKSPACE / "pino-dataset"
39
+ OUT_DIR = WORKSPACE / "ab_out"
40
+
41
+ SOURCE_REPO = os.environ.get("PINO_SOURCE_REPO", "mattbitzesty/pino-source-code")
42
+ DATASET_REPO = os.environ.get("PINO_DATASET_REPO", "mattbitzesty/pino-synthetic-dataset-v3")
43
+ AB_REPO = os.environ.get("PINO_AB_REPO", "mattbitzesty/pino-pimt-representation-ab")
44
+
45
+ EPOCHS = int(os.environ.get("PINO_EPOCHS", "20"))
46
+ BATCH = int(os.environ.get("PINO_BATCH", "32"))
47
+ LR = os.environ.get("PINO_LR", "3e-4")
48
+ TRAIN_RATIO = os.environ.get("PINO_TRAIN_RATIO", "0.85")
49
+ 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()]
50
+ ONLY_TAGS = {t for t in os.environ.get("PINO_TAGS", "").split(",") if t.strip()}
51
+
52
+ DATASET_V10 = "empirical_dataset_v10_alltags.jsonl"
53
+
54
+ WALL_BUDGET_S = int(os.environ.get("PINO_WALL_BUDGET_S", "5100")) # ~85 min
55
+ JOB_IMAGE = os.environ.get("PINO_JOB_IMAGE", "pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime")
56
+ JOB_FLAVOR = os.environ.get("PINO_JOB_FLAVOR", "t4-medium")
57
+ JOB_TIMEOUT = os.environ.get("PINO_JOB_TIMEOUT", "21600")
58
+ MAX_RUNS_PER_JOB = int(os.environ.get("PINO_MAX_RUNS_PER_JOB", "0")) # 0 = legacy: fill wall budget
59
+ UPLOAD_CHECKPOINT_FIRST = os.environ.get("PINO_UPLOAD_CHECKPOINT_FIRST", "1") == "1"
60
+ RESUME_REMOTE_CHECKPOINTS = os.environ.get("PINO_RESUME_REMOTE_CHECKPOINTS", "1") == "1"
61
+ _START = time.time()
62
+
63
+
64
+ def log(msg: str) -> None:
65
+ print(f"{time.strftime('%Y-%m-%dT%H:%M:%SZ')} {msg}", flush=True)
66
+
67
+
68
+ def run(cmd: list[str]) -> None:
69
+ log(f"$ {' '.join(cmd)}")
70
+ subprocess.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
71
+
72
+
73
+ def _disable_xet() -> None:
74
+ try:
75
+ import huggingface_hub.utils._runtime as _runtime
76
+ _runtime.is_xet_available = lambda: False
77
+ except Exception as e: # noqa: BLE001
78
+ log(f"[TO] warn: xet-disable patch failed ({e})")
79
+
80
+
81
+ def _retry(fn, what: str, attempts: int = 3, delay_s: int = 10):
82
+ """Small retry wrapper for transient Hub/API failures."""
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"[TO] 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
+ """The full run list: one dict per seed (time_only arm on openpom_256)."""
103
+ return [
104
+ {"family": "timeonly", "mode": "time_only", "seed": seed,
105
+ "tag": f"timeonly_openpom_256_seed{seed}"}
106
+ for seed in SEEDS
107
+ ]
108
+
109
+
110
+ def _expected_artifacts(spec: dict) -> list[str]:
111
+ tag = spec["tag"]
112
+ return [f"pimt_{tag}.pt", f"drydown_{tag}.json"]
113
+
114
+
115
+ def main() -> int:
116
+ run([sys.executable, "-m", "pip", "install", "--quiet",
117
+ "huggingface-hub", "scipy", "tensorboard", "rdkit", "numpy"])
118
+ _disable_xet()
119
+
120
+ from huggingface_hub import snapshot_download, HfApi, hf_hub_download
121
+ SOURCE_DIR.mkdir(parents=True, exist_ok=True)
122
+ DATASET_DIR.mkdir(parents=True, exist_ok=True)
123
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
124
+
125
+ log(f"[TO] downloading source {SOURCE_REPO} + dataset {DATASET_REPO}")
126
+ snapshot_download(repo_id=SOURCE_REPO, repo_type="model", local_dir=str(SOURCE_DIR), token=TOKEN)
127
+ snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", local_dir=str(DATASET_DIR), token=TOKEN)
128
+
129
+ reg_src = DATASET_DIR / "registry.db"
130
+ if reg_src.exists():
131
+ shutil.copy2(reg_src, WORKSPACE / "registry.db")
132
+ os.environ["PINO_REGISTRY_PATH"] = str(WORKSPACE / "registry.db")
133
+ ss = DATASET_DIR / "scalar_stats_v1.json"
134
+ if ss.exists():
135
+ (SOURCE_DIR / "artifacts").mkdir(exist_ok=True)
136
+ shutil.copy2(ss, SOURCE_DIR / "artifacts" / "scalar_stats_v1.json")
137
+
138
+ # Stage genuine-POM assets (openpom_256 backbone needs them).
139
+ pom_src_dir = DATASET_DIR / "artifacts" / "pom"
140
+ if pom_src_dir.exists():
141
+ pom_dst = SOURCE_DIR / "artifacts" / "pom"
142
+ pom_dst.mkdir(parents=True, exist_ok=True)
143
+ for fname in ("pom_embeddings.npy", "pom_index.json", "pom_manifest.json"):
144
+ f = pom_src_dir / fname
145
+ if f.exists():
146
+ shutil.copy2(f, pom_dst / fname)
147
+ log(f"[TO] staged POM assets -> {pom_dst}")
148
+ else:
149
+ log(f"[TO] WARN: no POM assets at {pom_src_dir}; openpom_256 backbone will fail")
150
+
151
+ run([sys.executable, "-m", "pip", "install", "--quiet", "-e", str(SOURCE_DIR)])
152
+ sys.path.insert(0, str(SOURCE_DIR / "src"))
153
+
154
+ import torch # noqa: E402
155
+ device = "cuda" if torch.cuda.is_available() else "cpu"
156
+ log(f"[TO] device={device} seeds={SEEDS}")
157
+
158
+ api = HfApi(token=TOKEN)
159
+ have = set()
160
+ try:
161
+ have = set(api.list_repo_files(AB_REPO, repo_type="model"))
162
+ except Exception as e: # noqa: BLE001
163
+ log(f"[TO] warn: could not list AB repo ({e}); assuming nothing done")
164
+
165
+ def _elapsed() -> float:
166
+ return time.time() - _START
167
+
168
+ specs = _run_specs()
169
+ if ONLY_TAGS:
170
+ specs = [s for s in specs if s["tag"] in ONLY_TAGS]
171
+ log(f"[TO] tag filter active: {sorted(ONLY_TAGS)} -> {len(specs)} run(s)")
172
+ pending = [s for s in specs
173
+ if not all(a in have for a in _expected_artifacts(s))]
174
+ log(f"[TO] {len(specs)} total runs, {len(pending)} pending "
175
+ f"(elapsed {(_elapsed()/60):.1f} min)")
176
+
177
+ completed_now: list[str] = []
178
+ runs_started = 0
179
+ for spec in pending:
180
+ if MAX_RUNS_PER_JOB and runs_started >= MAX_RUNS_PER_JOB:
181
+ log(f"[TO] per-job run cap reached ({MAX_RUNS_PER_JOB}); chaining")
182
+ break
183
+ if _elapsed() > WALL_BUDGET_S:
184
+ log(f"[TO] wall budget reached ({(_elapsed()/60):.1f} min); chaining")
185
+ break
186
+ runs_started += 1
187
+ tag, seed, mode = spec["tag"], spec["seed"], spec["mode"]
188
+ log(f"[TO] ===== {tag} (mode={mode}, {EPOCHS} epochs) =====")
189
+
190
+ # time_only arm: openpom_256 backbone, molecule-disjoint split,
191
+ # --physics-mode time_only (state_dim=3 but channel 0 carries only a
192
+ # normalized time index; channels 1-2 zeroed).
193
+ data_path = str(DATASET_DIR / DATASET_V10)
194
+ train_extra = ["--structural-source", "openpom_256", "--physics-mode", "time_only"]
195
+ ckpt_name = f"pimt_{tag}.pt"
196
+
197
+ ckpt = OUT_DIR / ckpt_name
198
+ if ckpt_name in have and RESUME_REMOTE_CHECKPOINTS:
199
+ log(f"[TO] checkpoint {ckpt_name} already uploaded; resuming eval-only")
200
+ if not ckpt.exists():
201
+ downloaded = str(_retry(
202
+ lambda: hf_hub_download(repo_id=AB_REPO, repo_type="model",
203
+ filename=ckpt_name, local_dir=str(OUT_DIR),
204
+ token=TOKEN),
205
+ f"download {ckpt_name}",
206
+ ))
207
+ if Path(downloaded) != ckpt:
208
+ shutil.copy2(downloaded, ckpt)
209
+ else:
210
+ run([sys.executable, "-m", "pino.train",
211
+ "--data", data_path,
212
+ "--epochs", str(EPOCHS), "--batch-size", str(BATCH), "--lr", LR,
213
+ "--seed", str(seed), "--train-ratio", str(TRAIN_RATIO),
214
+ *train_extra,
215
+ "--output-dir", str(OUT_DIR),
216
+ "--checkpoint-name", ckpt_name,
217
+ "--log-dir", str(OUT_DIR / "runs" / tag)])
218
+
219
+ final_val, best_epoch = None, None
220
+ try:
221
+ blob = torch.load(ckpt, map_location="cpu")
222
+ final_val = float(blob.get("val_loss")) if blob.get("val_loss") is not None else None
223
+ best_epoch = int(blob.get("epoch")) if blob.get("epoch") is not None else None
224
+ except Exception as e: # noqa: BLE001
225
+ log(f"[TO] warn: could not read checkpoint for val stamp ({e})")
226
+
227
+ # Atomicity rule: get the expensive training artifact off the box before
228
+ # running any eval. If HF preempts the container during eval, the next
229
+ # chain hop resumes eval-only instead of repeating the training run.
230
+ if UPLOAD_CHECKPOINT_FIRST and ckpt_name not in have:
231
+ _upload_with_retry(api, ckpt, ckpt_name)
232
+ have.add(ckpt_name)
233
+ log(f"[TO] uploaded checkpoint {ckpt_name}")
234
+
235
+ uploaded_count = 0
236
+ # Drydown eval with matched time_only conditioning.
237
+ dd_name = f"drydown_{tag}.json"
238
+ if dd_name not in have:
239
+ dd_out = OUT_DIR / dd_name
240
+ log(f"[TO] ===== drydown eval {tag} (matched time_only conditioning) =====")
241
+ dd_cmd = [sys.executable, str(SOURCE_DIR / "scripts" / "evaluate_drydown_physics.py"),
242
+ "--checkpoint", str(ckpt), "--data", data_path,
243
+ "--train-ratio", str(TRAIN_RATIO), "--seed", str(seed),
244
+ "--max-eval", "400",
245
+ "--physics-mode", "time_only",
246
+ "--structural-source", "openpom_256",
247
+ "--arm-label", tag, "--output", str(dd_out)]
248
+ run(dd_cmd)
249
+ # Stamp provenance metadata onto the drydown JSON.
250
+ try:
251
+ dj = json.loads(dd_out.read_text())
252
+ dj["final_val_total"] = final_val
253
+ dj["best_epoch"] = best_epoch
254
+ dj["seed"] = seed
255
+ dj["physics_mode"] = mode
256
+ dd_out.write_text(json.dumps(dj, indent=2))
257
+ except Exception as e: # noqa: BLE001
258
+ log(f"[TO] warn: could not stamp drydown JSON ({e})")
259
+ _upload_with_retry(api, dd_out, dd_name)
260
+ have.add(dd_name)
261
+ uploaded_count += 1
262
+
263
+ leak = OUT_DIR / f"split_leakage_report_seed{seed}.json"
264
+ if leak.exists() and leak.name not in have:
265
+ _upload_with_retry(api, leak, leak.name)
266
+ have.add(leak.name)
267
+
268
+ expected = _expected_artifacts(spec)
269
+ if all(a in have for a in expected):
270
+ total_artifacts = len(expected)
271
+ log(f"[TO] completed {tag} ({uploaded_count} eval artifacts uploaded this hop; "
272
+ f"{total_artifacts} expected artifacts present)")
273
+ completed_now.append(tag)
274
+ else:
275
+ missing_after = [a for a in expected if a not in have]
276
+ log(f"[TO] PARTIAL {tag}: missing {missing_after}; next chain hop will resume")
277
+
278
+ remaining = [s for s in pending if s["tag"] not in completed_now]
279
+ log(f"[TO] completed this job: {len(completed_now)} | remaining: {len(remaining)}")
280
+
281
+ summary = {"experiment": "time_only: clean-time-axis physics-off control arm on openpom_256, n=10",
282
+ "arm": "time_only", "seeds": SEEDS, "epochs": EPOCHS,
283
+ "structural_source": "openpom_256",
284
+ "physics_mode": "time_only",
285
+ "tag_filter": sorted(ONLY_TAGS),
286
+ "completed_this_job": completed_now,
287
+ "remaining": [s["tag"] for s in remaining],
288
+ "all_complete": not remaining}
289
+ summary_name = ("gpu_run_summary_timeonly.json" if not ONLY_TAGS else
290
+ f"gpu_run_summary_timeonly_{'_'.join(sorted(ONLY_TAGS))}.json")
291
+ api.upload_file(path_or_fileobj=json.dumps(summary, indent=2).encode(),
292
+ path_in_repo=summary_name, repo_id=AB_REPO, repo_type="model")
293
+
294
+ if remaining:
295
+ rem_seeds = sorted({s["seed"] for s in remaining})
296
+ log(f"[TO] chaining: relaunching for seeds {rem_seeds}")
297
+ try:
298
+ import base64
299
+ _inner = (
300
+ "from huggingface_hub import hf_hub_download; import runpy; "
301
+ f"p=hf_hub_download('{SOURCE_REPO}','scripts/hf_gpu_timeonly_job.py',repo_type='model'); "
302
+ "runpy.run_path(p,run_name='__main__')"
303
+ )
304
+ chain_cmd = (
305
+ "set -e; pip install -q huggingface-hub; "
306
+ f"echo {base64.b64encode(_inner.encode()).decode()} | base64 -d > /tmp/chain_job.py; "
307
+ "python /tmp/chain_job.py"
308
+ )
309
+ new_job = _retry(
310
+ lambda: api.run_job(
311
+ image=JOB_IMAGE,
312
+ command=["bash", "-lc", chain_cmd],
313
+ secrets={
314
+ "HF_TOKEN": TOKEN,
315
+ "PINO_SEEDS": ",".join(str(s) for s in rem_seeds),
316
+ "PINO_TAGS": ",".join(sorted(ONLY_TAGS)),
317
+ "PINO_EPOCHS": str(EPOCHS),
318
+ "PINO_BATCH": str(BATCH),
319
+ "PINO_LR": LR,
320
+ "PINO_TRAIN_RATIO": TRAIN_RATIO,
321
+ "PINO_JOB_FLAVOR": JOB_FLAVOR,
322
+ "PINO_JOB_TIMEOUT": JOB_TIMEOUT,
323
+ "PINO_WALL_BUDGET_S": str(WALL_BUDGET_S),
324
+ "PINO_MAX_RUNS_PER_JOB": str(MAX_RUNS_PER_JOB),
325
+ "PINO_UPLOAD_CHECKPOINT_FIRST": "1" if UPLOAD_CHECKPOINT_FIRST else "0",
326
+ "PINO_RESUME_REMOTE_CHECKPOINTS": "1" if RESUME_REMOTE_CHECKPOINTS else "0",
327
+ },
328
+ flavor=JOB_FLAVOR,
329
+ timeout=int(JOB_TIMEOUT),
330
+ namespace="mattbitzesty",
331
+ ),
332
+ "chain relaunch",
333
+ )
334
+ log(f"[TO] chained job started: {getattr(new_job,'id',new_job)} for seeds {rem_seeds}")
335
+ except Exception as e: # noqa: BLE001
336
+ log(f"[TO] ERROR: chain relaunch failed ({e}); rerun manually")
337
+ return 2
338
+ else:
339
+ log("[TO] DONE - all time_only seeds complete")
340
+ return 0
341
+
342
+
343
+ if __name__ == "__main__":
344
+ try:
345
+ raise SystemExit(main())
346
+ except Exception as exc: # noqa: BLE001
347
+ import traceback
348
+ traceback.print_exc()
349
+ print(f"[TO] FAILED: {exc}", flush=True)
350
+ raise SystemExit(1)