mattbitzesty commited on
Commit
a7cf629
·
verified ·
1 Parent(s): 1289050

Upload scripts/hf_idea3_drydown_physics_job.py with huggingface_hub

Browse files
scripts/hf_idea3_drydown_physics_job.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """IDEA 3 (clean paired run): does the physics channel improve the PIMT
2
+ transformer's prediction of the time-evolved descriptor pyramid?
3
+
4
+ Prior steps:
5
+ * Idea 2 (probes): physics trajectory DOUBLES explained variance on drydown.
6
+ * Idea 3 (inference ablation): physics-on halves BCE vs zeroed physics -- but
7
+ this confounds "physics is used" with "physics adds capability" (zeroing
8
+ disrupts a model trained WITH physics).
9
+
10
+ Clean test: train two models identically except the physics channel --
11
+ physics_off : state_dim=2 physics zeroed during TRAINING (the ablation arm)
12
+ physics_gamma : state_dim=3 with the UNIFAC gamma blend-interaction channel
13
+ and evaluate EACH on the drydown pyramid task with its own matching physics.
14
+ If physics_gamma achieves lower objective BCE / higher base-tier cosine than
15
+ physics_off, the physics channel adds real predictive capability for the
16
+ time-evolved profile. Paired across seeds.
17
+
18
+ physics_off is trained with physics zeroed via --physics-off-train (FiLM gets a
19
+ zero state every step), so it is a fair baseline, not an inference-time shock.
20
+
21
+ Self-chains via PINO_SKIP_DONE to survive the ~90 min t4 wall-clock.
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
+ WORKSPACE = Path("/workspace")
35
+ SOURCE_DIR = WORKSPACE / "pino-fresh"
36
+ DATASET_DIR = WORKSPACE / "pino-dataset"
37
+ OUT_DIR = WORKSPACE / "idea3_out"
38
+
39
+ SOURCE_REPO = os.environ.get("PINO_SOURCE_REPO", "mattbitzesty/pino-source-code")
40
+ DATASET_REPO = os.environ.get("PINO_DATASET_REPO", "mattbitzesty/pino-synthetic-dataset-v3")
41
+ OUT_REPO = os.environ.get("PINO_IDEA3_REPO", "mattbitzesty/pino-pimt-drydown-physics")
42
+
43
+ EPOCHS = int(os.environ.get("PINO_EPOCHS", "20"))
44
+ BATCH = int(os.environ.get("PINO_BATCH", "32"))
45
+ LR = os.environ.get("PINO_LR", "3e-4")
46
+ TRAIN_RATIO = os.environ.get("PINO_TRAIN_RATIO", "0.85")
47
+ SEEDS = [int(s) for s in os.environ.get("PINO_SEEDS", "42,123,2026").split(",")]
48
+ DATASET_NAME = "empirical_dataset_v9_gamma.jsonl"
49
+
50
+ # (arm_label, use_gamma, physics_off_train)
51
+ ARMS = (
52
+ ("physics_off", False, True),
53
+ ("physics_gamma", True, False),
54
+ )
55
+
56
+
57
+ def log(msg: str) -> None:
58
+ print(f"{time.strftime('%Y-%m-%dT%H:%M:%SZ')} {msg}", flush=True)
59
+
60
+
61
+ def run(cmd: list[str]) -> None:
62
+ log(f"$ {' '.join(cmd)}")
63
+ subprocess.check_call(cmd, stdout=sys.stdout, stderr=sys.stdout)
64
+
65
+
66
+ def main() -> int:
67
+ run([sys.executable, "-m", "pip", "install", "--quiet",
68
+ "huggingface-hub", "scipy", "tensorboard", "rdkit", "numpy"])
69
+ from huggingface_hub import HfApi, snapshot_download
70
+
71
+ SOURCE_DIR.mkdir(parents=True, exist_ok=True)
72
+ DATASET_DIR.mkdir(parents=True, exist_ok=True)
73
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
74
+ log(f"[idea3] downloading source {SOURCE_REPO} + dataset {DATASET_REPO}")
75
+ snapshot_download(repo_id=SOURCE_REPO, repo_type="model", local_dir=str(SOURCE_DIR), token=TOKEN)
76
+ snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", local_dir=str(DATASET_DIR), token=TOKEN)
77
+ reg = DATASET_DIR / "registry.db"
78
+ if reg.exists():
79
+ shutil.copy2(reg, WORKSPACE / "registry.db")
80
+ os.environ["PINO_REGISTRY_PATH"] = str(WORKSPACE / "registry.db")
81
+ ss = DATASET_DIR / "scalar_stats_v1.json"
82
+ if ss.exists():
83
+ (SOURCE_DIR / "artifacts").mkdir(exist_ok=True)
84
+ shutil.copy2(ss, SOURCE_DIR / "artifacts" / "scalar_stats_v1.json")
85
+ run([sys.executable, "-m", "pip", "install", "--quiet", "-e", str(SOURCE_DIR)])
86
+ sys.path.insert(0, str(SOURCE_DIR / "src"))
87
+
88
+ import torch # noqa: E402
89
+ device = "cuda" if torch.cuda.is_available() else "cpu"
90
+ log(f"[idea3] device={device}")
91
+ data_path = str(DATASET_DIR / DATASET_NAME)
92
+ api = HfApi(token=TOKEN)
93
+ try:
94
+ api.create_repo(OUT_REPO, repo_type="model", exist_ok=True, private=False)
95
+ except Exception as e:
96
+ log(f"[idea3] warn: create_repo ({e})")
97
+
98
+ skip_done = os.environ.get("PINO_SKIP_DONE", "1") == "1"
99
+ have = set()
100
+ if skip_done:
101
+ try:
102
+ have = set(api.list_repo_files(OUT_REPO, repo_type="model"))
103
+ except Exception as e:
104
+ log(f"[idea3] warn: could not list repo ({e})")
105
+
106
+ results = {}
107
+ for seed in SEEDS:
108
+ for arm_label, use_gamma, phys_off in ARMS:
109
+ tag = f"{arm_label}_s{seed}"
110
+ ckpt_name = f"pimt_idea3_{tag}.pt"
111
+ eval_name = f"drydown_eval_{tag}.json"
112
+ if skip_done and eval_name in have:
113
+ log(f"[idea3] skipping {tag}")
114
+ continue
115
+ log(f"[idea3] ===== train {tag} (gamma={use_gamma}, physics_off_train={phys_off}) =====")
116
+ cmd = [sys.executable, "-m", "pino.train",
117
+ "--data", data_path, "--structural-source", "morgan",
118
+ "--epochs", str(EPOCHS), "--batch-size", str(BATCH), "--lr", LR,
119
+ "--seed", str(seed), "--train-ratio", str(TRAIN_RATIO),
120
+ "--split-strategy", "formula",
121
+ "--output-dir", str(OUT_DIR), "--checkpoint-name", ckpt_name,
122
+ "--log-dir", str(OUT_DIR / "runs" / tag)]
123
+ if use_gamma:
124
+ cmd.append("--use-gamma")
125
+ if phys_off:
126
+ cmd.append("--physics-off-train")
127
+ run(cmd)
128
+ ckpt = OUT_DIR / ckpt_name
129
+ log(f"[idea3] ===== drydown eval {tag} =====")
130
+ eval_out = OUT_DIR / eval_name
131
+ run([sys.executable, str(SOURCE_DIR / "scripts" / "evaluate_drydown_physics.py"),
132
+ "--checkpoint", str(ckpt), "--data", data_path,
133
+ "--structural-source", "morgan", "--train-ratio", str(TRAIN_RATIO),
134
+ "--seed", str(seed), "--split", "formula", "--max-eval", "400",
135
+ "--arm-label", tag, "--output", str(eval_out)] + (["--use-gamma"] if use_gamma else []))
136
+ api.upload_file(path_or_fileobj=str(ckpt), path_in_repo=ckpt_name, repo_id=OUT_REPO, repo_type="model")
137
+ api.upload_file(path_or_fileobj=str(eval_out), path_in_repo=eval_name, repo_id=OUT_REPO, repo_type="model")
138
+ log(f"[idea3] uploaded {tag}")
139
+ results[tag] = {"use_gamma": use_gamma, "seed": seed}
140
+
141
+ summary = {"experiment": "idea3 clean paired drydown-physics",
142
+ "arms": results, "seeds": SEEDS, "epochs": EPOCHS,
143
+ "rationale": "idea2 (probes) + idea3 (inference ablation) showed physics helps "
144
+ "drydown prediction; this is the clean trained-baseline comparison. "
145
+ "physics_off is trained with zeroed physics (fair ablation arm)."}
146
+ api.upload_file(path_or_fileobj=json.dumps(summary, indent=2).encode(),
147
+ path_in_repo="idea3_run_summary.json", repo_id=OUT_REPO, repo_type="model")
148
+ log("[idea3] DONE")
149
+ return 0
150
+
151
+
152
+ if __name__ == "__main__":
153
+ try:
154
+ raise SystemExit(main())
155
+ except Exception as exc: # noqa: BLE001
156
+ import traceback
157
+ traceback.print_exc()
158
+ print(f"[idea3] FAILED: {exc}", flush=True)
159
+ raise SystemExit(1)