mattbitzesty commited on
Commit
0849c07
·
verified ·
1 Parent(s): 63f6c7c

round-10: physics-factorial + direct-2048 chain (scripts/hf_gpu_round10_job.py)

Browse files
Files changed (1) hide show
  1. scripts/hf_gpu_round10_job.py +319 -0
scripts/hf_gpu_round10_job.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """HF GPU job (round-10 panel response): physics-pathway trained ablation +
3
+ drydown factorial at n=10 + direct-2048 Morgan arm. Self-chaining.
4
+
5
+ Three run families answering the round-10 critique panel:
6
+
7
+ C1b "physoff" — openpom_256 trained with --physics-mode off (state_dim=2,
8
+ molecule split, v10 dataset), seeds 1..10. Pairs with the
9
+ existing physics-on A/B checkpoints
10
+ (pimt_ab_openpom_256_seed{n}.pt) to test whether the REAL
11
+ FiLM headspace pathway moves the trained readout, on/off arms
12
+ evaluated with matched (zeroed) conditioning by the frozen
13
+ evaluator. Also drydown-evaled.
14
+ Artifacts: pimt_physoff_openpom_256_seed{n}.pt,
15
+ frozen_eval_physoff_openpom_256_seed{n}.json,
16
+ drydown_physoff_openpom_256_seed{n}.json
17
+
18
+ C2 "fact" — drydown factorial at n=10 (was n=3): morgan + --use-gamma +
19
+ formula split, physics-mode in {full,off,gamma_only,
20
+ headspace_only}. Drydown eval only (same protocol as the
21
+ round-9 factorial job, extended seeds).
22
+ Artifacts: pimt_fact_{mode}_seed{n}.pt,
23
+ drydown_fact_{mode}_seed{n}.json
24
+
25
+ C3 "direct" — morgan_2048_direct arm (2071-D token -> LEARNED projection;
26
+ no random-projection subspace constraint), seeds 1..10.
27
+ Frozen eval. Artifacts: pimt_ab_morgan_2048_direct_seed{n}.pt,
28
+ frozen_eval_morgan_2048_direct_seed{n}.json
29
+
30
+ Self-chains like the W4 job: processes runs until the wall budget, then
31
+ relaunches itself (base64-wrapped) for the rest. Resume-safe: skips runs whose
32
+ artifacts are already in the AB repo.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ import os
38
+ import shutil
39
+ import subprocess
40
+ import sys
41
+ import time
42
+ from pathlib import Path
43
+
44
+ TOKEN = os.environ.get("HF_TOKEN")
45
+ os.environ.setdefault("HF_HUB_ENABLE_XET", "0")
46
+ os.environ.setdefault("HF_HUB_DISABLE_XET", "1")
47
+
48
+ WORKSPACE = Path("/workspace")
49
+ SOURCE_DIR = WORKSPACE / "pino-fresh"
50
+ DATASET_DIR = WORKSPACE / "pino-dataset"
51
+ OUT_DIR = WORKSPACE / "ab_out"
52
+
53
+ SOURCE_REPO = os.environ.get("PINO_SOURCE_REPO", "mattbitzesty/pino-source-code")
54
+ DATASET_REPO = os.environ.get("PINO_DATASET_REPO", "mattbitzesty/pino-synthetic-dataset-v3")
55
+ AB_REPO = os.environ.get("PINO_AB_REPO", "mattbitzesty/pino-pimt-representation-ab")
56
+
57
+ EPOCHS = int(os.environ.get("PINO_EPOCHS", "20"))
58
+ BATCH = int(os.environ.get("PINO_BATCH", "32"))
59
+ LR = os.environ.get("PINO_LR", "3e-4")
60
+ 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"
67
+
68
+ 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
+
75
+ def log(msg: str) -> None:
76
+ print(f"{time.strftime('%Y-%m-%dT%H:%M:%SZ')} {msg}", flush=True)
77
+
78
+
79
+ def run(cmd: list[str]) -> None:
80
+ log(f"$ {' '.join(cmd)}")
81
+ subprocess.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
82
+
83
+
84
+ def _disable_xet() -> None:
85
+ try:
86
+ import huggingface_hub.utils._runtime as _runtime
87
+ _runtime.is_xet_available = lambda: False
88
+ except Exception as e: # noqa: BLE001
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] = []
95
+ for seed in SEEDS:
96
+ if "physoff" in FAMILIES:
97
+ specs.append({"family": "physoff", "mode": "off", "seed": seed,
98
+ "tag": f"physoff_openpom_256_seed{seed}"})
99
+ if "fact" in FAMILIES:
100
+ for mode in FACT_MODES:
101
+ specs.append({"family": "fact", "mode": mode, "seed": seed,
102
+ "tag": f"fact_{mode}_seed{seed}"})
103
+ if "direct" in FAMILIES:
104
+ specs.append({"family": "direct", "mode": "full", "seed": seed,
105
+ "tag": f"morgan_2048_direct_seed{seed}"})
106
+ return specs
107
+
108
+
109
+ def _expected_artifacts(spec: dict) -> list[str]:
110
+ tag = spec["tag"]
111
+ if spec["family"] == "physoff":
112
+ return [f"pimt_{tag}.pt", f"frozen_eval_{tag}.json", f"drydown_{tag}.json"]
113
+ if spec["family"] == "fact":
114
+ return [f"pimt_{tag}.pt", f"drydown_{tag}.json"]
115
+ return [f"pimt_ab_{tag}.pt", f"frozen_eval_{tag}.json"]
116
+
117
+
118
+ def main() -> int:
119
+ run([sys.executable, "-m", "pip", "install", "--quiet",
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)
127
+
128
+ log(f"[R10] downloading source {SOURCE_REPO} + dataset {DATASET_REPO}")
129
+ snapshot_download(repo_id=SOURCE_REPO, repo_type="model", local_dir=str(SOURCE_DIR), token=TOKEN)
130
+ snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", local_dir=str(DATASET_DIR), token=TOKEN)
131
+
132
+ reg_src = DATASET_DIR / "registry.db"
133
+ if reg_src.exists():
134
+ shutil.copy2(reg_src, WORKSPACE / "registry.db")
135
+ os.environ["PINO_REGISTRY_PATH"] = str(WORKSPACE / "registry.db")
136
+ ss = DATASET_DIR / "scalar_stats_v1.json"
137
+ if ss.exists():
138
+ (SOURCE_DIR / "artifacts").mkdir(exist_ok=True)
139
+ shutil.copy2(ss, SOURCE_DIR / "artifacts" / "scalar_stats_v1.json")
140
+
141
+ # Stage genuine-POM assets (openpom arms need them).
142
+ pom_src_dir = DATASET_DIR / "artifacts" / "pom"
143
+ if pom_src_dir.exists():
144
+ pom_dst = SOURCE_DIR / "artifacts" / "pom"
145
+ pom_dst.mkdir(parents=True, exist_ok=True)
146
+ for fname in ("pom_embeddings.npy", "pom_index.json", "pom_manifest.json"):
147
+ f = pom_src_dir / fname
148
+ if f.exists():
149
+ shutil.copy2(f, pom_dst / fname)
150
+ log(f"[R10] staged POM assets -> {pom_dst}")
151
+ else:
152
+ log(f"[R10] WARN: no POM assets at {pom_src_dir}; openpom arms will fail")
153
+
154
+ run([sys.executable, "-m", "pip", "install", "--quiet", "-e", str(SOURCE_DIR)])
155
+ sys.path.insert(0, str(SOURCE_DIR / "src"))
156
+
157
+ import torch # noqa: E402
158
+ device = "cuda" if torch.cuda.is_available() else "cpu"
159
+ log(f"[R10] device={device} families={FAMILIES} seeds={SEEDS}")
160
+
161
+ api = HfApi(token=TOKEN)
162
+ have = set()
163
+ try:
164
+ have = set(api.list_repo_files(AB_REPO, repo_type="model"))
165
+ except Exception as e: # noqa: BLE001
166
+ log(f"[R10] warn: could not list AB repo ({e}); assuming nothing done")
167
+
168
+ def _elapsed() -> float:
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
+
185
+ if family == "fact":
186
+ data_path = str(DATASET_DIR / DATASET_V9G)
187
+ train_extra = ["--structural-source", "morgan", "--split-strategy", "formula",
188
+ "--use-gamma", "--physics-mode", mode]
189
+ ckpt_name = f"pimt_{tag}.pt"
190
+ elif family == "physoff":
191
+ data_path = str(DATASET_DIR / DATASET_V10)
192
+ train_extra = ["--structural-source", "openpom_256", "--physics-mode", "off"]
193
+ ckpt_name = f"pimt_{tag}.pt"
194
+ else: # direct
195
+ data_path = str(DATASET_DIR / DATASET_V10)
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:
211
+ blob = torch.load(ckpt, map_location="cpu")
212
+ final_val = float(blob.get("val_loss")) if blob.get("val_loss") is not None else None
213
+ best_epoch = int(blob.get("epoch")) if blob.get("epoch") is not None else None
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})
280
+ log(f"[R10] chaining: relaunching for seeds {rem_seeds}")
281
+ try:
282
+ import base64
283
+ _inner = (
284
+ "from huggingface_hub import hf_hub_download; import runpy; "
285
+ f"p=hf_hub_download('{SOURCE_REPO}','scripts/hf_gpu_round10_job.py',repo_type='model'); "
286
+ "runpy.run_path(p,run_name='__main__')"
287
+ )
288
+ chain_cmd = (
289
+ "set -e; pip install -q huggingface-hub; "
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
305
+ log(f"[R10] ERROR: chain relaunch failed ({e}); rerun manually")
306
+ return 2
307
+ else:
308
+ log("[R10] DONE - all families complete")
309
+ return 0
310
+
311
+
312
+ if __name__ == "__main__":
313
+ try:
314
+ raise SystemExit(main())
315
+ except Exception as exc: # noqa: BLE001
316
+ import traceback
317
+ traceback.print_exc()
318
+ print(f"[R10] FAILED: {exc}", flush=True)
319
+ raise SystemExit(1)