mattbitzesty commited on
Commit
6444728
·
verified ·
1 Parent(s): 839e0b9

review-response: upload scripts/hf_gpu_ab_multiseed_job.py

Browse files
Files changed (1) hide show
  1. scripts/hf_gpu_ab_multiseed_job.py +232 -0
scripts/hf_gpu_ab_multiseed_job.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """HF GPU job: multi-seed representation A/B + TOST equivalence analysis.
3
+
4
+ Addresses the review requests that are REAL experiments (not paper edits):
5
+ * Item 4: >=5 seeds, TOST/equivalence analysis instead of a 'bounded null'.
6
+ * Item 3: OpenPOM pretraining-overlap handled via the novelty-weighted
7
+ prospective readout wired into evaluate_frozen_benchmarks.py (a fully-disjoint
8
+ re-eval is impossible on this benchmark -- overlap is near-total, ~94%).
9
+ * Item 2: the molecule-disjoint split's zero-intersection assertion is emitted
10
+ per run (split_leakage_report_seed{seed}.json); the connected-components split
11
+ was evaluated and REJECTED as infeasible/degenerate for this corpus (see
12
+ scripts/split_leakage_analysis.py).
13
+
14
+ Design:
15
+ * Trains TWO arms (morgan, openpom_256) x N seeds on the corrected v10 corpus.
16
+ pom_alltags is EXCLUDED: its 575-dim objective is not prospective-comparable
17
+ and would burn a full GPU-day for no TOST-relevant readout.
18
+ * Same molecule-disjoint split logic per seed (seed-driven), identical corpus.
19
+ * After each (arm, seed): run the frozen evaluator, stamp final_val_total +
20
+ best_epoch from the training return, upload checkpoint + eval + leakage report.
21
+ * Finally: run multiseed_tost_analysis.py over the paired per-seed evals and
22
+ upload the TOST report.
23
+
24
+ Non-destructive: writes NEW per-seed artifacts (pimt_ab_{arm}_seed{seed}.pt,
25
+ frozen_eval_{arm}_seed{seed}.json); existing *_v2 artifacts are untouched.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ import os
31
+ import shutil
32
+ import subprocess
33
+ import sys
34
+ import time
35
+ from pathlib import Path
36
+
37
+ TOKEN = os.environ.get("HF_TOKEN")
38
+ os.environ.setdefault("HF_HUB_ENABLE_XET", "0")
39
+ os.environ.setdefault("HF_HUB_DISABLE_XET", "1")
40
+
41
+ WORKSPACE = Path("/workspace")
42
+ SOURCE_DIR = WORKSPACE / "pino-fresh"
43
+ DATASET_DIR = WORKSPACE / "pino-dataset"
44
+ OUT_DIR = WORKSPACE / "ab_out"
45
+
46
+ SOURCE_REPO = os.environ.get("PINO_SOURCE_REPO", "mattbitzesty/pino-source-code")
47
+ DATASET_REPO = os.environ.get("PINO_DATASET_REPO", "mattbitzesty/pino-synthetic-dataset-v3")
48
+ AB_REPO = os.environ.get("PINO_AB_REPO", "mattbitzesty/pino-pimt-representation-ab")
49
+
50
+ EPOCHS = int(os.environ.get("PINO_EPOCHS", "20"))
51
+ BATCH = int(os.environ.get("PINO_BATCH", "32"))
52
+ LR = os.environ.get("PINO_LR", "3e-4")
53
+ TRAIN_RATIO = os.environ.get("PINO_TRAIN_RATIO", "0.85")
54
+ DATASET_NAME = "empirical_dataset_v10_alltags.jsonl"
55
+ ARMS = tuple(a for a in os.environ.get("PINO_ARMS", "morgan,openpom_256").split(",") if a)
56
+ SEEDS = [int(s) for s in os.environ.get("PINO_SEEDS", "1,2,3,4,5").split(",") if s.strip()]
57
+ TOST_DELTA = os.environ.get("PINO_TOST_DELTA", "0.05")
58
+
59
+
60
+ def log(msg: str) -> None:
61
+ print(f"{time.strftime('%Y-%m-%dT%H:%M:%SZ')} {msg}", flush=True)
62
+
63
+
64
+ def run(cmd: list[str]) -> None:
65
+ log(f"$ {' '.join(cmd)}")
66
+ subprocess.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
67
+
68
+
69
+ def _disable_xet() -> None:
70
+ try:
71
+ import huggingface_hub.utils._runtime as _runtime
72
+ _runtime.is_xet_available = lambda: False
73
+ except Exception as e: # noqa: BLE001
74
+ log(f"[AB] warn: xet-disable patch failed ({e})")
75
+
76
+
77
+ def main() -> int:
78
+ run([sys.executable, "-m", "pip", "install", "--quiet",
79
+ "huggingface-hub", "scipy", "tensorboard", "rdkit", "numpy"])
80
+ _disable_xet()
81
+
82
+ from huggingface_hub import snapshot_download, HfApi
83
+ SOURCE_DIR.mkdir(parents=True, exist_ok=True)
84
+ DATASET_DIR.mkdir(parents=True, exist_ok=True)
85
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
86
+
87
+ log(f"[AB] downloading source {SOURCE_REPO}")
88
+ snapshot_download(repo_id=SOURCE_REPO, repo_type="model", local_dir=str(SOURCE_DIR), token=TOKEN)
89
+ log(f"[AB] downloading dataset {DATASET_REPO}")
90
+ snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", local_dir=str(DATASET_DIR), token=TOKEN)
91
+
92
+ reg_src = DATASET_DIR / "registry.db"
93
+ if reg_src.exists():
94
+ shutil.copy2(reg_src, WORKSPACE / "registry.db")
95
+ os.environ["PINO_REGISTRY_PATH"] = str(WORKSPACE / "registry.db")
96
+ ss = DATASET_DIR / "scalar_stats_v1.json"
97
+ if ss.exists():
98
+ (SOURCE_DIR / "artifacts").mkdir(exist_ok=True)
99
+ shutil.copy2(ss, SOURCE_DIR / "artifacts" / "scalar_stats_v1.json")
100
+
101
+ # Stage genuine-POM assets for the openpom arm.
102
+ pom_src_dir = DATASET_DIR / "artifacts" / "pom"
103
+ if pom_src_dir.exists():
104
+ pom_dst = SOURCE_DIR / "artifacts" / "pom"
105
+ pom_dst.mkdir(parents=True, exist_ok=True)
106
+ for fname in ("pom_embeddings.npy", "pom_index.json", "pom_manifest.json"):
107
+ f = pom_src_dir / fname
108
+ if f.exists():
109
+ shutil.copy2(f, pom_dst / fname)
110
+ log(f"[AB] staged POM assets -> {pom_dst}")
111
+ else:
112
+ log(f"[AB] WARN: no POM assets at {pom_src_dir}; openpom arm will fail")
113
+
114
+ # OpenPOM overlap proxy corpus (lives in the source tree's data/).
115
+ if not (SOURCE_DIR / "data" / "openpom_curated_4983.csv").exists():
116
+ for cand in (DATASET_DIR / "data" / "openpom_curated_4983.csv", DATASET_DIR / "openpom_curated_4983.csv"):
117
+ if cand.exists():
118
+ (SOURCE_DIR / "data").mkdir(exist_ok=True)
119
+ shutil.copy2(cand, SOURCE_DIR / "data" / "openpom_curated_4983.csv")
120
+ log("[AB] staged openpom_curated_4983.csv for overlap audit")
121
+ break
122
+
123
+ run([sys.executable, "-m", "pip", "install", "--quiet", "-e", str(SOURCE_DIR)])
124
+ sys.path.insert(0, str(SOURCE_DIR / "src"))
125
+
126
+ import torch # noqa: E402
127
+ device = "cuda" if torch.cuda.is_available() else "cpu"
128
+ log(f"[AB] device={device} cuda_devices={torch.cuda.device_count()} arms={ARMS} seeds={SEEDS}")
129
+
130
+ data_path = str(DATASET_DIR / DATASET_NAME)
131
+ api = HfApi(token=TOKEN)
132
+ results: dict[str, dict] = {}
133
+
134
+ for seed in SEEDS:
135
+ for arm in ARMS:
136
+ tag = f"{arm}_seed{seed}"
137
+ ckpt_name = f"pimt_ab_{tag}.pt"
138
+ eval_name = f"frozen_eval_{tag}.json"
139
+ eval_out = OUT_DIR / eval_name
140
+ logdir = OUT_DIR / "runs" / tag
141
+ log(f"[AB] ===== seed={seed} arm={arm} ({EPOCHS} epochs) =====")
142
+ run([sys.executable, "-m", "pino.train",
143
+ "--data", data_path,
144
+ "--structural-source", arm,
145
+ "--epochs", str(EPOCHS),
146
+ "--batch-size", str(BATCH),
147
+ "--lr", LR,
148
+ "--seed", str(seed),
149
+ "--train-ratio", str(TRAIN_RATIO),
150
+ "--output-dir", str(OUT_DIR),
151
+ "--checkpoint-name", ckpt_name,
152
+ "--log-dir", str(logdir)])
153
+ ckpt = OUT_DIR / ckpt_name
154
+
155
+ # Stamp final_val_total + best_epoch from the checkpoint (eval JSON otherwise omits it).
156
+ final_val, best_epoch = None, None
157
+ try:
158
+ blob = torch.load(ckpt, map_location="cpu")
159
+ final_val = float(blob.get("val_loss")) if blob.get("val_loss") is not None else None
160
+ best_epoch = int(blob.get("epoch")) if blob.get("epoch") is not None else None
161
+ except Exception as e: # noqa: BLE001
162
+ log(f"[AB] warn: could not read checkpoint for val_total stamp ({e})")
163
+
164
+ log(f"[AB] ===== frozen-benchmark eval {tag} =====")
165
+ run([sys.executable, str(SOURCE_DIR / "scripts" / "evaluate_frozen_benchmarks.py"),
166
+ "--checkpoint", str(ckpt),
167
+ "--structural-source", arm,
168
+ "--arm-label", tag,
169
+ "--output", str(eval_out)])
170
+
171
+ # Stamp training-loss summary into the eval JSON.
172
+ try:
173
+ ej = json.loads(eval_out.read_text())
174
+ ej["final_val_total"] = final_val
175
+ ej["best_epoch"] = best_epoch
176
+ ej["seed"] = seed
177
+ eval_out.write_text(json.dumps(ej, indent=2))
178
+ except Exception as e: # noqa: BLE001
179
+ log(f"[AB] warn: could not stamp eval JSON ({e})")
180
+
181
+ # Upload checkpoint + eval + per-seed leakage report immediately.
182
+ api.upload_file(path_or_fileobj=str(ckpt), path_in_repo=ckpt_name,
183
+ repo_id=AB_REPO, repo_type="model")
184
+ api.upload_file(path_or_fileobj=str(eval_out), path_in_repo=eval_name,
185
+ repo_id=AB_REPO, repo_type="model")
186
+ leak = OUT_DIR / f"split_leakage_report_seed{seed}.json"
187
+ if leak.exists():
188
+ api.upload_file(path_or_fileobj=str(leak), path_in_repo=leak.name,
189
+ repo_id=AB_REPO, repo_type="model")
190
+ log(f"[AB] uploaded {tag} checkpoint + eval + leakage report")
191
+ results[tag] = {"checkpoint": ckpt_name, "eval": eval_name,
192
+ "final_val_total": final_val, "best_epoch": best_epoch}
193
+
194
+ # ---- TOST equivalence analysis across paired seeds -------------------------
195
+ tost_report = None
196
+ try:
197
+ tost_out = OUT_DIR / "multiseed_tost_analysis.json"
198
+ run([sys.executable, str(SOURCE_DIR / "scripts" / "multiseed_tost_analysis.py"),
199
+ "--eval-dir", str(OUT_DIR),
200
+ "--glob", "frozen_eval_{arm}_seed{seed}.json",
201
+ "--arm-a", "openpom_256", "--arm-b", "morgan",
202
+ "--seeds", ",".join(str(s) for s in SEEDS),
203
+ "--metric", "prospective_cosine",
204
+ "--delta", TOST_DELTA,
205
+ "--output", str(tost_out)])
206
+ tost_report = json.loads(tost_out.read_text())
207
+ api.upload_file(path_or_fileobj=str(tost_out), path_in_repo="multiseed_tost_analysis.json",
208
+ repo_id=AB_REPO, repo_type="model")
209
+ log("[AB] uploaded TOST analysis")
210
+ except Exception as e: # noqa: BLE001
211
+ log(f"[AB] warn: TOST analysis failed ({e})")
212
+
213
+ summary = {"epochs": EPOCHS, "batch": BATCH, "lr": LR, "seeds": SEEDS, "arms": ARMS,
214
+ "train_ratio": TRAIN_RATIO, "device": device, "dataset": DATASET_NAME,
215
+ "tost_delta": TOST_DELTA, "tost": tost_report,
216
+ "results": results,
217
+ "note": "multi-seed representation A/B + TOST equivalence on corrected v10 labels; "
218
+ "openpom overlap via novelty-weighted prospective; split zero-intersection asserted per seed."}
219
+ api.upload_file(path_or_fileobj=json.dumps(summary, indent=2).encode(),
220
+ path_in_repo="gpu_run_summary_multiseed.json", repo_id=AB_REPO, repo_type="model")
221
+ log("[AB] DONE")
222
+ return 0
223
+
224
+
225
+ if __name__ == "__main__":
226
+ try:
227
+ raise SystemExit(main())
228
+ except Exception as exc: # noqa: BLE001
229
+ import traceback
230
+ traceback.print_exc()
231
+ print(f"[AB] FAILED: {exc}", flush=True)
232
+ raise SystemExit(1)