mattbitzesty commited on
Commit
d9cfed5
·
verified ·
1 Parent(s): f7f1afd

Factorial channel ablation: --physics-mode (gamma_only/headspace_only) in train.py + evaluator matching + factorial job script

Browse files
Files changed (1) hide show
  1. scripts/hf_factorial_drydown_job.py +166 -0
scripts/hf_factorial_drydown_job.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """IDEA 3 factorial follow-up: WHICH physics channel carries the drydown gain?
2
+
3
+ The clean paired run (idea-3) showed the full physics channel (state_dim=3 with
4
+ the UNIFAC gamma blend-interaction channel) beats a zeroed-physics trained
5
+ baseline on the time-evolved descriptor pyramid (BCE 0.197->0.175, drydown
6
+ cosine 0.449->0.533, every seed). The MoE review panel's top methodological
7
+ demand: isolate the channel. The physics tensor has three channels:
8
+
9
+ [0] x_liquid (liquid mole fraction -- E2: ~76% MW-recoverable)
10
+ [1] log10 OAV (headspace odor activity -- representation-recoverable)
11
+ [2] log10 gamma (UNIFAC blend-interaction -- the one quantity a
12
+ single-molecule embedding CANNOT encode)
13
+
14
+ Factorial arms (all state_dim=3 via --use-gamma, exact parameter parity with
15
+ the physics_gamma arm; channels masked during BOTH train and val so each is a
16
+ fair trained baseline, evaluated with its own matching conditioning):
17
+
18
+ gamma_only : keep channel 2, zero 0-1 (does gamma alone carry it?)
19
+ headspace_only : keep 0-1, zero channel 2 (does the redundant part?)
20
+
21
+ Interpretation against the existing arms (same repo, same protocol):
22
+ physics_gamma (full) BCE 0.175 / cosine 0.533
23
+ physics_off BCE 0.197 / cosine 0.449
24
+ - If gamma_only ~= physics_gamma: the blend-interaction channel is sufficient.
25
+ - If headspace_only ~= physics_off: gamma is necessary.
26
+ Together those isolate gamma as THE active ingredient, answering the panel.
27
+
28
+ Self-chains via PINO_SKIP_DONE to survive the ~90 min t4 wall-clock: eval JSONs
29
+ already in the repo are skipped, so relaunching the same job resumes.
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import json
34
+ import os
35
+ import shutil
36
+ import subprocess
37
+ import sys
38
+ import time
39
+ from pathlib import Path
40
+
41
+ TOKEN = os.environ.get("HF_TOKEN")
42
+ WORKSPACE = Path("/workspace")
43
+ SOURCE_DIR = WORKSPACE / "pino-fresh"
44
+ DATASET_DIR = WORKSPACE / "pino-dataset"
45
+ OUT_DIR = WORKSPACE / "factorial_out"
46
+
47
+ SOURCE_REPO = os.environ.get("PINO_SOURCE_REPO", "mattbitzesty/pino-source-code")
48
+ DATASET_REPO = os.environ.get("PINO_DATASET_REPO", "mattbitzesty/pino-synthetic-dataset-v3")
49
+ OUT_REPO = os.environ.get("PINO_IDEA3_REPO", "mattbitzesty/pino-pimt-drydown-physics")
50
+
51
+ EPOCHS = int(os.environ.get("PINO_EPOCHS", "12"))
52
+ BATCH = int(os.environ.get("PINO_BATCH", "32"))
53
+ LR = os.environ.get("PINO_LR", "3e-4")
54
+ TRAIN_RATIO = os.environ.get("PINO_TRAIN_RATIO", "0.85")
55
+ SEEDS = [int(s) for s in os.environ.get("PINO_SEEDS", "42,123,2026").split(",")]
56
+ DATASET_NAME = "empirical_dataset_v9_gamma.jsonl"
57
+
58
+ # (arm_label, physics_mode) -- all arms use --use-gamma (state_dim=3 parity)
59
+ ARMS = (
60
+ ("gamma_only", "gamma_only"),
61
+ ("headspace_only", "headspace_only"),
62
+ )
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.stdout)
72
+
73
+
74
+ def main() -> int:
75
+ run([sys.executable, "-m", "pip", "install", "--quiet",
76
+ "huggingface-hub", "scipy", "tensorboard", "rdkit", "numpy"])
77
+ from huggingface_hub import HfApi, snapshot_download
78
+
79
+ SOURCE_DIR.mkdir(parents=True, exist_ok=True)
80
+ DATASET_DIR.mkdir(parents=True, exist_ok=True)
81
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
82
+ log(f"[factorial] downloading source {SOURCE_REPO} + dataset {DATASET_REPO}")
83
+ snapshot_download(repo_id=SOURCE_REPO, repo_type="model", local_dir=str(SOURCE_DIR), token=TOKEN)
84
+ snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", local_dir=str(DATASET_DIR), token=TOKEN)
85
+ reg = DATASET_DIR / "registry.db"
86
+ if reg.exists():
87
+ shutil.copy2(reg, WORKSPACE / "registry.db")
88
+ os.environ["PINO_REGISTRY_PATH"] = str(WORKSPACE / "registry.db")
89
+ ss = DATASET_DIR / "scalar_stats_v1.json"
90
+ if ss.exists():
91
+ (SOURCE_DIR / "artifacts").mkdir(exist_ok=True)
92
+ shutil.copy2(ss, SOURCE_DIR / "artifacts" / "scalar_stats_v1.json")
93
+ run([sys.executable, "-m", "pip", "install", "--quiet", "-e", str(SOURCE_DIR)])
94
+ sys.path.insert(0, str(SOURCE_DIR / "src"))
95
+
96
+ import torch # noqa: E402
97
+ device = "cuda" if torch.cuda.is_available() else "cpu"
98
+ log(f"[factorial] device={device}")
99
+ data_path = str(DATASET_DIR / DATASET_NAME)
100
+ api = HfApi(token=TOKEN)
101
+ try:
102
+ api.create_repo(OUT_REPO, repo_type="model", exist_ok=True, private=False)
103
+ except Exception as e:
104
+ log(f"[factorial] warn: create_repo ({e})")
105
+
106
+ skip_done = os.environ.get("PINO_SKIP_DONE", "1") == "1"
107
+ have = set()
108
+ if skip_done:
109
+ try:
110
+ have = set(api.list_repo_files(OUT_REPO, repo_type="model"))
111
+ except Exception as e:
112
+ log(f"[factorial] warn: could not list repo ({e})")
113
+
114
+ results = {}
115
+ for seed in SEEDS:
116
+ for arm_label, mode in ARMS:
117
+ tag = f"{arm_label}_s{seed}"
118
+ ckpt_name = f"pimt_factorial_{tag}.pt"
119
+ eval_name = f"drydown_eval_{tag}.json"
120
+ if skip_done and eval_name in have:
121
+ log(f"[factorial] skipping {tag}")
122
+ continue
123
+ log(f"[factorial] ===== train {tag} (use-gamma, physics-mode={mode}) =====")
124
+ cmd = [sys.executable, "-m", "pino.train",
125
+ "--data", data_path, "--structural-source", "morgan",
126
+ "--epochs", str(EPOCHS), "--batch-size", str(BATCH), "--lr", LR,
127
+ "--seed", str(seed), "--train-ratio", str(TRAIN_RATIO),
128
+ "--split-strategy", "formula", "--use-gamma",
129
+ "--physics-mode", mode,
130
+ "--output-dir", str(OUT_DIR), "--checkpoint-name", ckpt_name,
131
+ "--log-dir", str(OUT_DIR / "runs" / tag)]
132
+ run(cmd)
133
+ ckpt = OUT_DIR / ckpt_name
134
+ log(f"[factorial] ===== drydown eval {tag} (matching conditioning) =====")
135
+ eval_out = OUT_DIR / eval_name
136
+ run([sys.executable, str(SOURCE_DIR / "scripts" / "evaluate_drydown_physics.py"),
137
+ "--checkpoint", str(ckpt), "--data", data_path,
138
+ "--structural-source", "morgan", "--train-ratio", str(TRAIN_RATIO),
139
+ "--seed", str(seed), "--split", "formula", "--max-eval", "400",
140
+ "--use-gamma", "--physics-mode", mode,
141
+ "--arm-label", tag, "--output", str(eval_out)])
142
+ api.upload_file(path_or_fileobj=str(ckpt), path_in_repo=ckpt_name, repo_id=OUT_REPO, repo_type="model")
143
+ api.upload_file(path_or_fileobj=str(eval_out), path_in_repo=eval_name, repo_id=OUT_REPO, repo_type="model")
144
+ log(f"[factorial] uploaded {tag}")
145
+ results[tag] = {"physics_mode": mode, "seed": seed}
146
+
147
+ summary = {"experiment": "idea3 factorial channel-isolation drydown-physics",
148
+ "arms": results, "seeds": SEEDS, "epochs": EPOCHS,
149
+ "rationale": "paired run showed full physics channel helps drydown; "
150
+ "this factorial isolates WHICH channel (gamma blend-interaction "
151
+ "vs E2-redundant headspace channels). All arms state_dim=3 "
152
+ "with masked channels (parameter parity with physics_gamma)."}
153
+ api.upload_file(path_or_fileobj=json.dumps(summary, indent=2).encode(),
154
+ path_in_repo="factorial_run_summary.json", repo_id=OUT_REPO, repo_type="model")
155
+ log("[factorial] DONE")
156
+ return 0
157
+
158
+
159
+ if __name__ == "__main__":
160
+ try:
161
+ raise SystemExit(main())
162
+ except Exception as exc: # noqa: BLE001
163
+ import traceback
164
+ traceback.print_exc()
165
+ print(f"[factorial] FAILED: {exc}", flush=True)
166
+ raise SystemExit(1)