Matthew Ford commited on
Commit
c9282b0
·
1 Parent(s): ac9ca3b

pimt v9 substantivity gbm train publish path

Browse files

Former-commit-id: 76c6a4bdb47a6c07121f91dcbfdb7da66fa4291d
Former-commit-id: bf1fe10087b50e2382b916ed139e2589a286da89

README.md CHANGED
@@ -38,14 +38,19 @@ python scripts/generate_empirical_bootstrap.py --output data/empirical_dataset_v
38
  # Train locally (5 epochs, smoke-test config)
39
  python src/pino/train.py --epochs 5 --smoke-test
40
 
41
- # Train on Hugging Face Jobs GPU cluster (Python 3.10+ compatible, t4-medium for 30 GB RAM)
42
- hf jobs run -d --flavor t4-medium --timeout 7200 \
43
- --secrets HF_TOKEN \
44
- pytorch/pytorch:2.3.0-cuda12.1-cudnn8-runtime \
45
- bash -c "apt-get update -qq && apt-get install -y -qq git && \
46
- git clone -b main https://huggingface.co/mattbitzesty/pino-source-code /workspace/pino && \
47
- cd /workspace/pino && pip install -q -e . && \
48
- python scripts/hf_train_job.py"
 
 
 
 
 
49
  ```
50
 
51
  ## Repository layout
 
38
  # Train locally (5 epochs, smoke-test config)
39
  python src/pino/train.py --epochs 5 --smoke-test
40
 
41
+ # Publish the validated PIMT v9 substantivity GBM on Hugging Face Jobs.
42
+ # This is the measured-only ~170-row GBM path, not the neural pyramid trainer.
43
+ hf jobs run --detach --flavor cpu-upgrade --timeout 45m --secrets HF_TOKEN \
44
+ python:3.11 bash -lc 'set -euo pipefail
45
+ python -m pip install -q huggingface_hub
46
+ python - <<PY
47
+ import os
48
+ from huggingface_hub import snapshot_download
49
+ snapshot_download(repo_id="mattbitzesty/pino-source-code", repo_type="model", local_dir="/workspace/pino", token=os.environ.get("HF_TOKEN"))
50
+ PY
51
+ cd /workspace/pino
52
+ python -m pip install -q -e .
53
+ python -u scripts/pimt_v9_train_publish.py --upload'
54
  ```
55
 
56
  ## Repository layout
artifacts/pimt_v9_qa.json ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "applicability_domain": {
3
+ "flag_policy": "Flag inputs with no resolvable SMILES/properties or scaffolds absent from the model-ready Poucher set as out-of-domain.",
4
+ "scaffold_class_holdout_error": [
5
+ {
6
+ "mae": 0.43195692249749706,
7
+ "n": 10,
8
+ "scaffold_class": "acyclic"
9
+ },
10
+ {
11
+ "mae": 0.4137310733638503,
12
+ "n": 9,
13
+ "scaffold_class": "murcko"
14
+ },
15
+ {
16
+ "mae": 0.4197856941191041,
17
+ "n": 7,
18
+ "scaffold_class": "unknown"
19
+ }
20
+ ]
21
+ },
22
+ "calibration": [
23
+ {
24
+ "n": 7,
25
+ "observed_mean": 0.9491818732042122,
26
+ "observed_minus_pred_mean": 0.06233808608656526,
27
+ "pred_mean": 0.886843787117647
28
+ },
29
+ {
30
+ "n": 7,
31
+ "observed_mean": 1.071657944122965,
32
+ "observed_minus_pred_mean": -0.10038495690014883,
33
+ "pred_mean": 1.1720429010231135
34
+ },
35
+ {
36
+ "n": 6,
37
+ "observed_mean": 1.6119855020735978,
38
+ "observed_minus_pred_mean": 0.2903074554621797,
39
+ "pred_mean": 1.3216780466114182
40
+ },
41
+ {
42
+ "n": 6,
43
+ "observed_mean": 1.4084438128257222,
44
+ "observed_minus_pred_mean": -0.15604696367325344,
45
+ "pred_mean": 1.5644907764989753
46
+ }
47
+ ],
48
+ "cv_distribution": {
49
+ "delta_r2_range": [
50
+ -0.03,
51
+ 0.29
52
+ ],
53
+ "mean_delta_r2": 0.13,
54
+ "mean_r2_structure": 0.18,
55
+ "r2_structure_range": [
56
+ -0.15,
57
+ 0.4
58
+ ],
59
+ "rho_wins": "16/20",
60
+ "seed_20260710_note": "most favourable of 20 splits, not the headline estimate",
61
+ "structure_r2_wins": "19/20"
62
+ },
63
+ "domain_sanity_check": {
64
+ "long_keyword_mean_pred_log10": 1.566617180266281,
65
+ "long_keyword_n": 3,
66
+ "long_lowest_predictions": [
67
+ {
68
+ "cas": "8023-91-4",
69
+ "name": "Galbanum resin",
70
+ "pred_log10": 1.3702133820702211,
71
+ "pred_raw": 23.453808891417573
72
+ },
73
+ {
74
+ "cas": "9000-72-0",
75
+ "name": "Benzoin",
76
+ "pred_log10": 1.5209245821736217,
77
+ "pred_raw": 33.183682710512805
78
+ },
79
+ {
80
+ "cas": "8050-07-5",
81
+ "name": "Olibanum oil and resin",
82
+ "pred_log10": 1.8087135765549998,
83
+ "pred_raw": 64.37445667005629
84
+ }
85
+ ],
86
+ "passes_directional_check": true,
87
+ "short_highest_predictions": [
88
+ {
89
+ "cas": "103-95-7",
90
+ "name": "Cyclamen aldehyde",
91
+ "pred_log10": 1.8648438226407533,
92
+ "pred_raw": 73.25610482715469
93
+ },
94
+ {
95
+ "cas": "122-40-7",
96
+ "name": "Amyl cinnamic aldehyde",
97
+ "pred_log10": 1.8028574047321797,
98
+ "pred_raw": 63.51223629730795
99
+ },
100
+ {
101
+ "cas": "112-44-7",
102
+ "name": "Undecylic aldehyde",
103
+ "pred_log10": 1.7785579721043443,
104
+ "pred_raw": 60.05621700208701
105
+ },
106
+ {
107
+ "cas": "101-48-4",
108
+ "name": "Phenylacetaldehyde dimethyl acetal",
109
+ "pred_log10": 1.7504969486894548,
110
+ "pred_raw": 56.29851619016742
111
+ },
112
+ {
113
+ "cas": "110-41-8",
114
+ "name": "aldehyde",
115
+ "pred_log10": 1.7109014523998125,
116
+ "pred_raw": 51.39270209934685
117
+ }
118
+ ],
119
+ "short_keyword_mean_pred_log10": 1.44989452040109,
120
+ "short_keyword_n": 15
121
+ },
122
+ "holdout": {
123
+ "delta_r2": 0.3090321370935427,
124
+ "delta_spearman_rho": 0.05014613924470496,
125
+ "fraction_requested": 0.15,
126
+ "metrics_baseline_physical_gbm": {
127
+ "mae": 0.47190496654862646,
128
+ "r2": -0.2404921930593953,
129
+ "spearman_p_value": 0.07838645577054112,
130
+ "spearman_rho": 0.3513664414200905
131
+ },
132
+ "metrics_structure_full_gbm": {
133
+ "mae": 0.42237110554166735,
134
+ "r2": 0.06853994403414743,
135
+ "spearman_p_value": 0.042043155519074595,
136
+ "spearman_rho": 0.40151258066479545
137
+ },
138
+ "n_holdout": 26,
139
+ "n_train": 144,
140
+ "scaffold_overlap": [],
141
+ "seed": 20260712
142
+ },
143
+ "leakage_negative_control": {
144
+ "gate": "shuffled-target holdout R2 < 0.05",
145
+ "metrics": {
146
+ "mae": 0.5445324750053792,
147
+ "r2": -0.52673853973627,
148
+ "spearman_p_value": 0.41213747340331597,
149
+ "spearman_rho": -0.16795521979904618
150
+ },
151
+ "shuffle_seed": 20260712,
152
+ "status": "pass"
153
+ },
154
+ "model_version": "v9",
155
+ "n_model_ready": 170,
156
+ "n_target_rows": 206,
157
+ "reproduction_gate": {
158
+ "baseline": {
159
+ "mae": 0.5135367865016908,
160
+ "r2": 0.24057748815493107,
161
+ "spearman_p_value": 0.00011576052443041632,
162
+ "spearman_rho": 0.6130893034049266
163
+ },
164
+ "checks": {
165
+ "r2_struct": {
166
+ "abs_error": 2.326621011317087e-05,
167
+ "expected": 0.399,
168
+ "observed": 0.3990232662101132,
169
+ "passes": true,
170
+ "tolerance": 0.01
171
+ },
172
+ "rho_struct": {
173
+ "abs_error": 0.0,
174
+ "expected": 0.6633801733693918,
175
+ "observed": 0.6633801733693918,
176
+ "passes": true,
177
+ "tolerance": 0.005
178
+ }
179
+ },
180
+ "n_test": 34,
181
+ "n_train": 136,
182
+ "seed": 20260710,
183
+ "status": "pass",
184
+ "structure": {
185
+ "mae": 0.47140351509641953,
186
+ "r2": 0.3990232662101132,
187
+ "spearman_p_value": 1.902331123811527e-05,
188
+ "spearman_rho": 0.6633801733693918
189
+ }
190
+ },
191
+ "residual_diagnostics": {
192
+ "n_with_vapor_pressure": 16,
193
+ "residual_vs_log10_vapor_pressure_pearson": 0.18962560622438973,
194
+ "residual_vs_log10_vapor_pressure_spearman": 0.2150804090149927,
195
+ "residual_vs_predicted_pearson": -0.23014192153633758,
196
+ "residual_vs_predicted_spearman": -0.12082838584454265
197
+ },
198
+ "target_file_resolved": "/home/hermes/pino/data/poucher_substantivity.jsonl"
199
+ }
artifacts/pimt_v9_qa.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PIMT v9 substantivity QA
2
+
3
+ - Model version: v9
4
+ - Target file: `/home/hermes/pino/data/poucher_substantivity.jsonl`
5
+ - Model-ready rows: 170
6
+ - Holdout n: 26 (seed 20260712)
7
+ - Holdout structure rho/R2: 0.402 / 0.069
8
+ - Holdout baseline rho/R2: 0.351 / -0.240
9
+ - Shuffled-target negative control: pass (R2=-0.527)
10
+
11
+ The model card should lead with the pre-registered multi-seed distribution: mean structure R2 0.18 (range -0.15 to 0.40), structure above baseline on R2 in 19/20 correlated scaffold partitions, mean Delta R2 0.13.
12
+
13
+ ## Applicability Domain
14
+
15
+ Flag inputs with no resolvable SMILES/properties or scaffolds absent from the model-ready Poucher set as out-of-domain.
16
+
17
+ ## Calibration Bins
18
+
19
+ | n | mean predicted log10 | mean observed log10 | observed - predicted |
20
+ | ---: | ---: | ---: | ---: |
21
+ | 7 | 0.887 | 0.949 | 0.062 |
22
+ | 7 | 1.172 | 1.072 | -0.100 |
23
+ | 6 | 1.322 | 1.612 | 0.290 |
24
+ | 6 | 1.564 | 1.408 | -0.156 |
hf_job.yaml CHANGED
@@ -1,28 +1,23 @@
1
- # HF Jobs cluster configuration for PINO v7 5-epoch GPU training
2
- # Mounts the source code as a model volume and the v3 dataset as a dataset volume
3
- # to avoid git clone inside the container.
4
- name: pino-v7-5epoch-pyramid
5
  image: python:3.11
6
  command:
7
  - bash
8
- - -c
9
  - |
10
- set -eux
 
 
11
  cd /workspace/pino
12
- echo "Installing CUDA torch..."
13
- pip install torch --index-url https://download.pytorch.org/whl/cu121
14
- echo "Installing pino package and dependencies..."
15
  pip install -e .
16
- echo "Starting v7 pyramid training job..."
17
- python -u scripts/hf_train_job.py
18
- flavor: t4-small
19
  secrets:
20
  HF_TOKEN: ${HF_TOKEN}
21
  env:
22
- HF_DATA_PATH: empirical_dataset_v9_plus_wisemoor.jsonl
23
- PINO_MODEL_VERSION: v7
24
- volumes:
25
- - hf://mattbitzesty/pino-source-code:/workspace/pino
26
- - hf://datasets/mattbitzesty/pino-synthetic-dataset-v3:/data
27
- # HF_TOKEN secret is passed via CLI: hf jobs run -f hf_job.yaml -s HF_TOKEN
28
- timeout: 2h
 
1
+ # Reference configuration for the PIMT v9 substantivity GBM HF Job.
2
+ # The installed hf CLI in this repo uses `hf jobs run ...` arguments rather
3
+ # than `hf jobs run -f`; keep this file as the reviewed job spec.
4
+ name: pimt-v9-substantivity-gbm
5
  image: python:3.11
6
  command:
7
  - bash
8
+ - -lc
9
  - |
10
+ set -euo pipefail
11
+ python -m pip install -q huggingface_hub
12
+ python -c 'import os; from huggingface_hub import snapshot_download; snapshot_download(repo_id="mattbitzesty/pino-source-code", repo_type="model", local_dir="/workspace/pino", token=os.environ.get("HF_TOKEN"))'
13
  cd /workspace/pino
 
 
 
14
  pip install -e .
15
+ python -u scripts/pimt_v9_train_publish.py --upload
16
+ flavor: cpu-upgrade
17
+ timeout: 45m
18
  secrets:
19
  HF_TOKEN: ${HF_TOKEN}
20
  env:
21
+ PINO_MODEL_VERSION: v9
22
+ PINO_SOURCE_REPO: mattbitzesty/pino-source-code
23
+ PINO_SUBSTANTIVITY_REPO: mattbitzesty/pino-pimt-substantivity
 
 
 
 
scripts/eval_v6.py CHANGED
@@ -21,7 +21,7 @@ from pino.pimt_model import (
21
  PhysicsInformedMixtureTransformer,
22
  )
23
  from pino.train import pad_trajectory_collate
24
- from pino.upload_data import create_molecule_disjoint_split_from_records
25
 
26
 
27
  PYRFUME_SOURCE = "pyrfume-cas"
@@ -37,7 +37,7 @@ def parse_args() -> argparse.Namespace:
37
  parser.add_argument("--data", default="data/empirical_dataset_v8.jsonl", help="Evaluation dataset JSONL.")
38
  parser.add_argument("--batch-size", type=int, default=8)
39
  parser.add_argument("--seed", type=int, default=42)
40
- parser.add_argument("--train-ratio", type=float, default=0.8, help="Molecule-disjoint train molecule ratio used to rebuild validation.")
41
  parser.add_argument("--output", default="metrics_v6_current.json", help="Metrics JSON output path.")
42
  parser.add_argument(
43
  "--hf-repo",
 
21
  PhysicsInformedMixtureTransformer,
22
  )
23
  from pino.train import pad_trajectory_collate
24
+ from pino.upload_data import DEFAULT_TRAIN_RATIO, create_molecule_disjoint_split_from_records
25
 
26
 
27
  PYRFUME_SOURCE = "pyrfume-cas"
 
37
  parser.add_argument("--data", default="data/empirical_dataset_v8.jsonl", help="Evaluation dataset JSONL.")
38
  parser.add_argument("--batch-size", type=int, default=8)
39
  parser.add_argument("--seed", type=int, default=42)
40
+ parser.add_argument("--train-ratio", type=float, default=DEFAULT_TRAIN_RATIO, help="Molecule-disjoint train molecule ratio used to rebuild the 15% holdout validation set.")
41
  parser.add_argument("--output", default="metrics_v6_current.json", help="Metrics JSON output path.")
42
  parser.add_argument(
43
  "--hf-repo",
scripts/generate_paper_artifacts.py CHANGED
@@ -76,9 +76,9 @@ def build_validation_loader(
76
  workers: int = 0,
77
  ) -> tuple[DataLoader, list[dict[str, Any]]]:
78
  """Load the empirical dataset and build a validation-only DataLoader."""
79
- from pino.upload_data import create_molecule_disjoint_split
80
 
81
- split = create_molecule_disjoint_split(data_path, train_ratio=0.8, seed=42)
82
  val_records = list(split["validation"])
83
 
84
  genre_map = {
 
76
  workers: int = 0,
77
  ) -> tuple[DataLoader, list[dict[str, Any]]]:
78
  """Load the empirical dataset and build a validation-only DataLoader."""
79
+ from pino.upload_data import DEFAULT_TRAIN_RATIO, create_molecule_disjoint_split
80
 
81
+ split = create_molecule_disjoint_split(data_path, train_ratio=DEFAULT_TRAIN_RATIO, seed=42)
82
  val_records = list(split["validation"])
83
 
84
  genre_map = {
scripts/hf_train_job.py CHANGED
@@ -8,9 +8,9 @@ import time
8
  import traceback
9
  from pathlib import Path
10
 
11
- # HF Job entrypoint for the v7 pyramid training run.
12
- # Uses snapshot_download to pull fresh source and dataset into a writable
13
- # workspace, avoiding stale/cached model-volume mounts.
14
 
15
  TOKEN = os.environ.get("HF_TOKEN")
16
  # Disable Xet to avoid a hf_xet/huggingface_hub progress-reporter bug that
@@ -22,11 +22,15 @@ WORKSPACE = Path("/workspace")
22
  SOURCE_DIR = WORKSPACE / "pino-fresh"
23
  DATASET_DIR = WORKSPACE / "pino-dataset"
24
  OUTPUT_DIR = WORKSPACE / "models"
25
- MODEL_VERSION = os.environ.get("PINO_MODEL_VERSION", "v7")
26
  CHECKPOINT_NAME = f"pimt_{MODEL_VERSION}.pt"
27
  LOG_DIR = WORKSPACE / "runs" / f"hf_job_{MODEL_VERSION}"
28
  DIAG_LOG = WORKSPACE / "hf_train.log"
29
  DEFAULT_DATASET_NAME = "empirical_dataset_v9_plus_wisemoor.jsonl"
 
 
 
 
30
 
31
  SRC_DIR = SOURCE_DIR / "src"
32
 
@@ -53,7 +57,7 @@ def _upload_log() -> None:
53
  HfApi(token=TOKEN).upload_file(
54
  path_or_fileobj=str(DIAG_LOG),
55
  path_in_repo="hf_train.log",
56
- repo_id="mattbitzesty/pino-synthetic-dataset-v3",
57
  repo_type="dataset",
58
  )
59
  _log("[HF-JOB] Diagnostic log uploaded")
@@ -107,20 +111,20 @@ except Exception as exc:
107
  try:
108
  from huggingface_hub import snapshot_download
109
 
110
- _log("[HF-JOB] Downloading fresh source from mattbitzesty/pino-source-code")
111
  SOURCE_DIR.mkdir(parents=True, exist_ok=True)
112
  snapshot_download(
113
- repo_id="mattbitzesty/pino-source-code",
114
  repo_type="model",
115
  local_dir=str(SOURCE_DIR),
116
  token=TOKEN,
117
  )
118
  _log(f"[HF-JOB] Source downloaded to {SOURCE_DIR}")
119
 
120
- _log("[HF-JOB] Downloading fresh dataset from mattbitzesty/pino-synthetic-dataset-v3")
121
  DATASET_DIR.mkdir(parents=True, exist_ok=True)
122
  snapshot_download(
123
- repo_id="mattbitzesty/pino-synthetic-dataset-v3",
124
  repo_type="dataset",
125
  local_dir=str(DATASET_DIR),
126
  token=TOKEN,
@@ -208,7 +212,7 @@ sys.argv = [
208
  "--data", str(data_path),
209
  "--epochs", "5",
210
  "--batch-size", "8",
211
- "--train-ratio", "0.8",
212
  "--seed", "42",
213
  "--workers", "0",
214
  "--output-dir", str(OUTPUT_DIR),
@@ -231,7 +235,7 @@ except Exception as exc:
231
  _log(f"✅ Training complete. Checkpoint: {checkpoint_path}")
232
 
233
  if TOKEN and checkpoint_path and Path(checkpoint_path).exists():
234
- repo_id = "mattbitzesty/pino-pimt-checkpoint"
235
  _log(f"[HF-JOB] Uploading {checkpoint_path} to {repo_id} as {CHECKPOINT_NAME}")
236
  try:
237
  # Monkey-patch / bypass Xet to avoid a hf_xet/huggingface_hub bug that
 
8
  import traceback
9
  from pathlib import Path
10
 
11
+ # Legacy HF Job entrypoint for the neural pyramid trainer.
12
+ # Do not use this for PIMT v9 substantivity; v9 uses
13
+ # scripts/pimt_v9_train_publish.py and emits a joblib GBM artifact.
14
 
15
  TOKEN = os.environ.get("HF_TOKEN")
16
  # Disable Xet to avoid a hf_xet/huggingface_hub progress-reporter bug that
 
22
  SOURCE_DIR = WORKSPACE / "pino-fresh"
23
  DATASET_DIR = WORKSPACE / "pino-dataset"
24
  OUTPUT_DIR = WORKSPACE / "models"
25
+ MODEL_VERSION = os.environ.get("PINO_MODEL_VERSION", "v9")
26
  CHECKPOINT_NAME = f"pimt_{MODEL_VERSION}.pt"
27
  LOG_DIR = WORKSPACE / "runs" / f"hf_job_{MODEL_VERSION}"
28
  DIAG_LOG = WORKSPACE / "hf_train.log"
29
  DEFAULT_DATASET_NAME = "empirical_dataset_v9_plus_wisemoor.jsonl"
30
+ SOURCE_REPO = os.environ.get("PINO_SOURCE_REPO", "mattbitzesty/pino-source-code")
31
+ DATASET_REPO = os.environ.get("PINO_DATASET_REPO", "mattbitzesty/pino-synthetic-dataset-v3")
32
+ CHECKPOINT_REPO = os.environ.get("PINO_CHECKPOINT_REPO", "mattbitzesty/pino-pimt-checkpoint")
33
+ TRAIN_RATIO = os.environ.get("PINO_TRAIN_RATIO", "0.85")
34
 
35
  SRC_DIR = SOURCE_DIR / "src"
36
 
 
57
  HfApi(token=TOKEN).upload_file(
58
  path_or_fileobj=str(DIAG_LOG),
59
  path_in_repo="hf_train.log",
60
+ repo_id=DATASET_REPO,
61
  repo_type="dataset",
62
  )
63
  _log("[HF-JOB] Diagnostic log uploaded")
 
111
  try:
112
  from huggingface_hub import snapshot_download
113
 
114
+ _log(f"[HF-JOB] Downloading fresh source from {SOURCE_REPO}")
115
  SOURCE_DIR.mkdir(parents=True, exist_ok=True)
116
  snapshot_download(
117
+ repo_id=SOURCE_REPO,
118
  repo_type="model",
119
  local_dir=str(SOURCE_DIR),
120
  token=TOKEN,
121
  )
122
  _log(f"[HF-JOB] Source downloaded to {SOURCE_DIR}")
123
 
124
+ _log(f"[HF-JOB] Downloading fresh dataset from {DATASET_REPO}")
125
  DATASET_DIR.mkdir(parents=True, exist_ok=True)
126
  snapshot_download(
127
+ repo_id=DATASET_REPO,
128
  repo_type="dataset",
129
  local_dir=str(DATASET_DIR),
130
  token=TOKEN,
 
212
  "--data", str(data_path),
213
  "--epochs", "5",
214
  "--batch-size", "8",
215
+ "--train-ratio", TRAIN_RATIO,
216
  "--seed", "42",
217
  "--workers", "0",
218
  "--output-dir", str(OUTPUT_DIR),
 
235
  _log(f"✅ Training complete. Checkpoint: {checkpoint_path}")
236
 
237
  if TOKEN and checkpoint_path and Path(checkpoint_path).exists():
238
+ repo_id = CHECKPOINT_REPO
239
  _log(f"[HF-JOB] Uploading {checkpoint_path} to {repo_id} as {CHECKPOINT_NAME}")
240
  try:
241
  # Monkey-patch / bypass Xet to avoid a hf_xet/huggingface_hub bug that
scripts/pimt_v9_train_publish.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train, QA, package, and optionally upload the validated PIMT v9 substantivity GBM."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import math
8
+ import os
9
+ import sys
10
+ import textwrap
11
+ from collections import defaultdict
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import joblib
16
+ import numpy as np
17
+ from scipy.stats import pearsonr, spearmanr
18
+ from sklearn.ensemble import HistGradientBoostingRegressor
19
+ from sklearn.impute import SimpleImputer
20
+ from sklearn.metrics import mean_absolute_error, r2_score
21
+ from sklearn.pipeline import make_pipeline
22
+
23
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
24
+ import train_substantivity as train # noqa: E402
25
+
26
+
27
+ MODEL_VERSION = "v9"
28
+ HF_REPO_ID = "mattbitzesty/pino-pimt-substantivity"
29
+ EXPECTED_READY_MIN = 150
30
+ EXPECTED_READY_MAX = 190
31
+ LARGE_DATASET_ABORT_AT = 1000
32
+ GATE_SEED = 20260710
33
+ GATE_TEST_FRACTION = 0.2
34
+ GATE_EXPECTED = {
35
+ "rho_struct": 0.6633801733693918,
36
+ "r2_struct": 0.399,
37
+ }
38
+ GATE_TOLERANCE = {
39
+ "rho_struct": 0.005,
40
+ "r2_struct": 0.01,
41
+ }
42
+ CV_DISTRIBUTION = {
43
+ "mean_r2_structure": 0.18,
44
+ "r2_structure_range": [-0.15, 0.40],
45
+ "structure_r2_wins": "19/20",
46
+ "mean_delta_r2": 0.13,
47
+ "delta_r2_range": [-0.03, 0.29],
48
+ "rho_wins": "16/20",
49
+ "seed_20260710_note": "most favourable of 20 splits, not the headline estimate",
50
+ }
51
+
52
+
53
+ def _finite_float(value: Any) -> float | None:
54
+ try:
55
+ out = float(value)
56
+ except Exception:
57
+ return None
58
+ return out if math.isfinite(out) else None
59
+
60
+
61
+ def _corr(x: list[float], y: list[float], method: str) -> float:
62
+ if len(x) < 3 or len(set(x)) < 2 or len(set(y)) < 2:
63
+ return float("nan")
64
+ if method == "spearman":
65
+ value, _ = spearmanr(x, y)
66
+ else:
67
+ value, _ = pearsonr(x, y)
68
+ return float(value) if value == value else float("nan")
69
+
70
+
71
+ def gbm_pipeline():
72
+ model = make_pipeline(
73
+ SimpleImputer(strategy="median"),
74
+ HistGradientBoostingRegressor(
75
+ max_iter=200,
76
+ learning_rate=0.04,
77
+ l2_regularization=0.1,
78
+ random_state=17,
79
+ ),
80
+ )
81
+ final = model.steps[-1][1]
82
+ if not isinstance(final, HistGradientBoostingRegressor):
83
+ raise AssertionError(f"Wrong model class: {type(final)!r}")
84
+ return model
85
+
86
+
87
+ def load_payload(fetch_pubchem: bool) -> dict[str, Any]:
88
+ target_path = train.POUCHER_TARGET_PATH.resolve()
89
+ if not target_path.is_file():
90
+ raise FileNotFoundError(f"Target file missing; aborting instead of empty fallback: {target_path}")
91
+ target_rows = train.load_poucher_targets(target_path)
92
+ measured = [_finite_float(row.get("poucher_coefficient")) for row in target_rows]
93
+ measured = [value for value in measured if value is not None and value > 0]
94
+ if not measured:
95
+ raise AssertionError("Target populated assertion failed: zero positive measured coefficients.")
96
+ if float(np.std(measured)) <= 0.0:
97
+ raise AssertionError("Target variance assertion failed: measured coefficients are constant.")
98
+
99
+ rows = train.enrich_rows(fetch_pubchem)
100
+ ready = [
101
+ row
102
+ for row in rows
103
+ if row.get("smiles") or any(row["features"].get(name) is not None for name in train.FEATURE_NAMES)
104
+ ]
105
+ n_ready = len(ready)
106
+ if n_ready >= LARGE_DATASET_ABORT_AT:
107
+ raise AssertionError(f"Wrong training set: {n_ready} rows looks like the large v9-plus dataset.")
108
+ if not EXPECTED_READY_MIN <= n_ready <= EXPECTED_READY_MAX:
109
+ raise AssertionError(
110
+ f"Wrong model-ready row count: {n_ready}; expected about 170 "
111
+ f"({EXPECTED_READY_MIN}-{EXPECTED_READY_MAX})."
112
+ )
113
+ y = np.asarray([row["target_log10"] for row in ready], dtype=float)
114
+ if y.size == 0 or float(np.std(y)) <= 0.0:
115
+ raise AssertionError("Target has no variance after model-ready filtering.")
116
+ x_base, base_names = train.design_matrix(ready, include_structural=False)
117
+ x_full, full_names = train.design_matrix(ready, include_structural=True)
118
+ return {
119
+ "target_path": str(target_path),
120
+ "target_rows": len(target_rows),
121
+ "rows": ready,
122
+ "n_model_ready": n_ready,
123
+ "y": y,
124
+ "x_base": x_base,
125
+ "x_full": x_full,
126
+ "base_feature_names": base_names,
127
+ "full_feature_names": full_names,
128
+ }
129
+
130
+
131
+ def fit_predict(x: np.ndarray, y: np.ndarray, train_idx: np.ndarray, test_idx: np.ndarray) -> np.ndarray:
132
+ model = gbm_pipeline()
133
+ model.fit(x[train_idx], y[train_idx])
134
+ return np.asarray(model.predict(x[test_idx]), dtype=float)
135
+
136
+
137
+ def metrics(y_true: np.ndarray, pred: np.ndarray) -> dict[str, float]:
138
+ rho, p_value = spearmanr(y_true, pred)
139
+ return {
140
+ "spearman_rho": float(rho) if rho == rho else float("nan"),
141
+ "spearman_p_value": float(p_value) if p_value == p_value else float("nan"),
142
+ "r2": float(r2_score(y_true, pred)),
143
+ "mae": float(mean_absolute_error(y_true, pred)),
144
+ }
145
+
146
+
147
+ def reproduction_gate(payload: dict[str, Any]) -> dict[str, Any]:
148
+ rows = payload["rows"]
149
+ y = payload["y"]
150
+ train_idx, test_idx = train.greedy_scaffold_split(rows, GATE_TEST_FRACTION, GATE_SEED)
151
+ pred_struct = fit_predict(payload["x_full"], y, train_idx, test_idx)
152
+ pred_base = fit_predict(payload["x_base"], y, train_idx, test_idx)
153
+ struct_metrics = metrics(y[test_idx], pred_struct)
154
+ base_metrics = metrics(y[test_idx], pred_base)
155
+ checks = {
156
+ "rho_struct": {
157
+ "observed": struct_metrics["spearman_rho"],
158
+ "expected": GATE_EXPECTED["rho_struct"],
159
+ "tolerance": GATE_TOLERANCE["rho_struct"],
160
+ },
161
+ "r2_struct": {
162
+ "observed": struct_metrics["r2"],
163
+ "expected": GATE_EXPECTED["r2_struct"],
164
+ "tolerance": GATE_TOLERANCE["r2_struct"],
165
+ },
166
+ }
167
+ for item in checks.values():
168
+ item["abs_error"] = abs(float(item["observed"]) - float(item["expected"]))
169
+ item["passes"] = item["abs_error"] <= float(item["tolerance"])
170
+ status = "pass" if all(item["passes"] for item in checks.values()) else "fail"
171
+ if status != "pass":
172
+ raise AssertionError(f"Reproduction gate failed: {json.dumps(checks, indent=2)}")
173
+ return {
174
+ "status": status,
175
+ "seed": GATE_SEED,
176
+ "n_train": int(len(train_idx)),
177
+ "n_test": int(len(test_idx)),
178
+ "structure": struct_metrics,
179
+ "baseline": base_metrics,
180
+ "checks": checks,
181
+ }
182
+
183
+
184
+ def scaffold_error(rows: list[dict[str, Any]], test_idx: np.ndarray, y_true: np.ndarray, pred: np.ndarray) -> list[dict[str, Any]]:
185
+ grouped: dict[str, list[float]] = defaultdict(list)
186
+ for pos, idx in enumerate(test_idx):
187
+ key = str(rows[int(idx)]["scaffold"])
188
+ grouped[key.split(":", 1)[0]].append(abs(float(y_true[pos] - pred[pos])))
189
+ return [
190
+ {"scaffold_class": key, "n": len(vals), "mae": float(np.mean(vals))}
191
+ for key, vals in sorted(grouped.items(), key=lambda item: (-len(item[1]), item[0]))
192
+ ]
193
+
194
+
195
+ def calibration_bins(y_true: np.ndarray, pred: np.ndarray, n_bins: int = 4) -> list[dict[str, Any]]:
196
+ order = np.argsort(pred)
197
+ bins: list[dict[str, Any]] = []
198
+ for chunk in np.array_split(order, n_bins):
199
+ if len(chunk) == 0:
200
+ continue
201
+ bins.append({
202
+ "n": int(len(chunk)),
203
+ "pred_mean": float(np.mean(pred[chunk])),
204
+ "observed_mean": float(np.mean(y_true[chunk])),
205
+ "observed_minus_pred_mean": float(np.mean(y_true[chunk] - pred[chunk])),
206
+ })
207
+ return bins
208
+
209
+
210
+ def domain_sanity(rows: list[dict[str, Any]], pred_all: np.ndarray) -> dict[str, Any]:
211
+ long_terms = ("musk", "amber", "resin", "benzoin", "labdanum", "civet")
212
+ short_terms = ("citrus", "lemon", "orange", "bergamot", "aldehyde", "acetaldehyde")
213
+ long_rows = []
214
+ short_rows = []
215
+ for row, pred in zip(rows, pred_all, strict=True):
216
+ name = str(row.get("name", "")).lower()
217
+ item = {"cas": row["cas"], "name": row["name"], "pred_log10": float(pred), "pred_raw": float(10 ** pred)}
218
+ if any(term in name for term in long_terms):
219
+ long_rows.append(item)
220
+ if any(term in name for term in short_terms):
221
+ short_rows.append(item)
222
+ long_mean = float(np.mean([r["pred_log10"] for r in long_rows])) if long_rows else float("nan")
223
+ short_mean = float(np.mean([r["pred_log10"] for r in short_rows])) if short_rows else float("nan")
224
+ return {
225
+ "long_keyword_n": len(long_rows),
226
+ "short_keyword_n": len(short_rows),
227
+ "long_keyword_mean_pred_log10": long_mean,
228
+ "short_keyword_mean_pred_log10": short_mean,
229
+ "passes_directional_check": bool(long_rows and short_rows and long_mean > short_mean),
230
+ "long_lowest_predictions": sorted(long_rows, key=lambda r: r["pred_log10"])[:5],
231
+ "short_highest_predictions": sorted(short_rows, key=lambda r: r["pred_log10"], reverse=True)[:5],
232
+ }
233
+
234
+
235
+ def qa_and_train(payload: dict[str, Any], holdout_fraction: float, holdout_seed: int, shuffle_seed: int) -> dict[str, Any]:
236
+ rows = payload["rows"]
237
+ y = payload["y"]
238
+ train_idx, holdout_idx = train.greedy_scaffold_split(rows, holdout_fraction, holdout_seed)
239
+
240
+ model = gbm_pipeline()
241
+ baseline = gbm_pipeline()
242
+ model.fit(payload["x_full"][train_idx], y[train_idx])
243
+ baseline.fit(payload["x_base"][train_idx], y[train_idx])
244
+ holdout_pred = np.asarray(model.predict(payload["x_full"][holdout_idx]), dtype=float)
245
+ holdout_base_pred = np.asarray(baseline.predict(payload["x_base"][holdout_idx]), dtype=float)
246
+ holdout_metrics = metrics(y[holdout_idx], holdout_pred)
247
+ holdout_base_metrics = metrics(y[holdout_idx], holdout_base_pred)
248
+
249
+ rng = np.random.default_rng(shuffle_seed)
250
+ shuffled = np.array(y[train_idx], copy=True)
251
+ rng.shuffle(shuffled)
252
+ shuffled_model = gbm_pipeline()
253
+ shuffled_model.fit(payload["x_full"][train_idx], shuffled)
254
+ shuffled_pred = np.asarray(shuffled_model.predict(payload["x_full"][holdout_idx]), dtype=float)
255
+ shuffled_metrics = metrics(y[holdout_idx], shuffled_pred)
256
+ leakage_pass = bool(shuffled_metrics["r2"] < 0.05)
257
+ if not leakage_pass:
258
+ raise AssertionError(f"Leakage negative control failed: shuffled-target R2={shuffled_metrics['r2']:.6f}")
259
+
260
+ residuals = y[holdout_idx] - holdout_pred
261
+ vapor = [
262
+ _finite_float(rows[int(idx)]["features"].get("log10_vapor_pressure_pa"))
263
+ for idx in holdout_idx
264
+ ]
265
+ vapor_pairs = [(float(residuals[i]), float(v)) for i, v in enumerate(vapor) if v is not None]
266
+ pred_all = np.asarray(model.predict(payload["x_full"]), dtype=float)
267
+
268
+ return {
269
+ "model": model,
270
+ "baseline_model": baseline,
271
+ "holdout_idx": holdout_idx,
272
+ "train_idx": train_idx,
273
+ "qa": {
274
+ "model_version": MODEL_VERSION,
275
+ "target_file_resolved": payload["target_path"],
276
+ "n_target_rows": payload["target_rows"],
277
+ "n_model_ready": payload["n_model_ready"],
278
+ "holdout": {
279
+ "seed": holdout_seed,
280
+ "fraction_requested": holdout_fraction,
281
+ "n_train": int(len(train_idx)),
282
+ "n_holdout": int(len(holdout_idx)),
283
+ "metrics_structure_full_gbm": holdout_metrics,
284
+ "metrics_baseline_physical_gbm": holdout_base_metrics,
285
+ "delta_r2": float(holdout_metrics["r2"] - holdout_base_metrics["r2"]),
286
+ "delta_spearman_rho": float(holdout_metrics["spearman_rho"] - holdout_base_metrics["spearman_rho"]),
287
+ "scaffold_overlap": sorted({rows[int(i)]["scaffold"] for i in train_idx} & {rows[int(i)]["scaffold"] for i in holdout_idx}),
288
+ },
289
+ "leakage_negative_control": {
290
+ "shuffle_seed": shuffle_seed,
291
+ "status": "pass",
292
+ "gate": "shuffled-target holdout R2 < 0.05",
293
+ "metrics": shuffled_metrics,
294
+ },
295
+ "applicability_domain": {
296
+ "scaffold_class_holdout_error": scaffold_error(rows, holdout_idx, y[holdout_idx], holdout_pred),
297
+ "flag_policy": "Flag inputs with no resolvable SMILES/properties or scaffolds absent from the model-ready Poucher set as out-of-domain.",
298
+ },
299
+ "residual_diagnostics": {
300
+ "residual_vs_predicted_spearman": _corr(residuals.tolist(), holdout_pred.tolist(), "spearman"),
301
+ "residual_vs_predicted_pearson": _corr(residuals.tolist(), holdout_pred.tolist(), "pearson"),
302
+ "residual_vs_log10_vapor_pressure_spearman": _corr([p[0] for p in vapor_pairs], [p[1] for p in vapor_pairs], "spearman"),
303
+ "residual_vs_log10_vapor_pressure_pearson": _corr([p[0] for p in vapor_pairs], [p[1] for p in vapor_pairs], "pearson"),
304
+ "n_with_vapor_pressure": len(vapor_pairs),
305
+ },
306
+ "domain_sanity_check": domain_sanity(rows, pred_all),
307
+ "calibration": calibration_bins(y[holdout_idx], holdout_pred),
308
+ "cv_distribution": CV_DISTRIBUTION,
309
+ },
310
+ }
311
+
312
+
313
+ def write_markdown(qa: dict[str, Any], path: Path) -> None:
314
+ holdout = qa["holdout"]
315
+ leakage = qa["leakage_negative_control"]
316
+ lines = [
317
+ "# PIMT v9 substantivity QA",
318
+ "",
319
+ f"- Model version: {qa['model_version']}",
320
+ f"- Target file: `{qa['target_file_resolved']}`",
321
+ f"- Model-ready rows: {qa['n_model_ready']}",
322
+ f"- Holdout n: {holdout['n_holdout']} (seed {holdout['seed']})",
323
+ f"- Holdout structure rho/R2: {holdout['metrics_structure_full_gbm']['spearman_rho']:.3f} / {holdout['metrics_structure_full_gbm']['r2']:.3f}",
324
+ f"- Holdout baseline rho/R2: {holdout['metrics_baseline_physical_gbm']['spearman_rho']:.3f} / {holdout['metrics_baseline_physical_gbm']['r2']:.3f}",
325
+ f"- Shuffled-target negative control: {leakage['status']} (R2={leakage['metrics']['r2']:.3f})",
326
+ "",
327
+ "The model card should lead with the pre-registered multi-seed distribution: mean structure R2 0.18 (range -0.15 to 0.40), structure above baseline on R2 in 19/20 correlated scaffold partitions, mean Delta R2 0.13.",
328
+ "",
329
+ "## Applicability Domain",
330
+ "",
331
+ qa["applicability_domain"]["flag_policy"],
332
+ "",
333
+ "## Calibration Bins",
334
+ "",
335
+ "| n | mean predicted log10 | mean observed log10 | observed - predicted |",
336
+ "| ---: | ---: | ---: | ---: |",
337
+ ]
338
+ for row in qa["calibration"]:
339
+ lines.append(
340
+ f"| {row['n']} | {row['pred_mean']:.3f} | {row['observed_mean']:.3f} | {row['observed_minus_pred_mean']:.3f} |"
341
+ )
342
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
343
+
344
+
345
+ def write_model_package(payload: dict[str, Any], result: dict[str, Any], out_dir: Path) -> None:
346
+ out_dir.mkdir(parents=True, exist_ok=True)
347
+ model_path = out_dir / "pimt_v9_substantivity_gbm.joblib"
348
+ if model_path.suffix == ".pt":
349
+ raise AssertionError("Refusing to emit a .pt artifact for the GBM v9 model.")
350
+ joblib.dump(
351
+ {
352
+ "model_version": MODEL_VERSION,
353
+ "model": result["model"],
354
+ "baseline_model": result["baseline_model"],
355
+ "feature_names": payload["full_feature_names"],
356
+ "baseline_feature_names": payload["base_feature_names"],
357
+ "feature_names_note": "Features are generated by scripts/train_substantivity.py design_matrix.",
358
+ "target": "Poucher measured log10 coefficient only.",
359
+ },
360
+ model_path,
361
+ )
362
+ (out_dir / "inference.py").write_text(
363
+ textwrap.dedent(
364
+ '''
365
+ """Minimal loader for the PIMT v9 substantivity GBM artifact."""
366
+ from __future__ import annotations
367
+
368
+ import joblib
369
+
370
+
371
+ def load_model(path="pimt_v9_substantivity_gbm.joblib"):
372
+ return joblib.load(path)
373
+
374
+
375
+ def predict_from_feature_matrix(x, path="pimt_v9_substantivity_gbm.joblib"):
376
+ bundle = load_model(path)
377
+ return bundle["model"].predict(x)
378
+ '''
379
+ ).lstrip(),
380
+ encoding="utf-8",
381
+ )
382
+ qa = result["qa"]
383
+ holdout = qa["holdout"]
384
+ readme = f"""---
385
+ license: other
386
+ library_name: scikit-learn
387
+ tags:
388
+ - fragrance
389
+ - substantivity
390
+ - gradient-boosting
391
+ - rdkit
392
+ ---
393
+
394
+ # PIMT {MODEL_VERSION} substantivity GBM
395
+
396
+ This private model repo contains the validated substantivity-only GBM for PIMT {MODEL_VERSION}. It is not the void neural v7/v9 run and does not use the 3,057-row v9-plus WiseMoor overlap set.
397
+
398
+ Across 20 pre-registered scaffold-disjoint splits, the structure-rich model explains a mean R2 of 0.18 (range -0.15 to 0.40) versus 0.05 for the physicochemical baseline. It exceeds the baseline on R2 in 19 of 20 correlated scaffold partitions, with mean Delta R2 = 0.13 (range -0.03 to 0.29), and on rank correlation in 16 of 20.
399
+
400
+ The locked holdout is reported as a single confirmatory point, not a precise estimate: n={holdout['n_holdout']}, rho={holdout['metrics_structure_full_gbm']['spearman_rho']:.3f}, R2={holdout['metrics_structure_full_gbm']['r2']:.3f}; baseline rho={holdout['metrics_baseline_physical_gbm']['spearman_rho']:.3f}, baseline R2={holdout['metrics_baseline_physical_gbm']['r2']:.3f}.
401
+
402
+ The seed-20260710 split (rho=0.663, R2=0.399) is the most favourable of the 20 splits and is not used as the headline performance estimate. Tier disagreement in the source material is 47.9%, which is treated as source noise context rather than a formal predictability bound.
403
+
404
+ ## Artifact
405
+
406
+ - `pimt_v9_substantivity_gbm.joblib`: scikit-learn `SimpleImputer(strategy="median")` plus `HistGradientBoostingRegressor(max_iter=200, learning_rate=0.04, l2_regularization=0.1, random_state=17)`.
407
+ - `inference.py`: minimal artifact loader for precomputed feature matrices.
408
+ - `pimt_v9_qa.json`: leakage control, holdout metrics, applicability-domain, residual, sanity, and calibration diagnostics.
409
+ """
410
+ (out_dir / "README.md").write_text(readme, encoding="utf-8")
411
+ (out_dir / "pimt_v9_qa.json").write_text(json.dumps(qa, indent=2, sort_keys=True) + "\n", encoding="utf-8")
412
+
413
+
414
+ def upload_model(out_dir: Path, repo_id: str, private: bool) -> dict[str, Any]:
415
+ from huggingface_hub import HfApi, create_repo
416
+
417
+ token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")
418
+ api = HfApi(token=token)
419
+ create_repo(repo_id=repo_id, repo_type="model", private=private, exist_ok=True, token=token)
420
+ commit = api.upload_folder(
421
+ folder_path=str(out_dir),
422
+ repo_id=repo_id,
423
+ repo_type="model",
424
+ commit_message=f"Publish PIMT {MODEL_VERSION} substantivity GBM",
425
+ )
426
+ return {"repo_id": repo_id, "private": private, "commit": str(commit)}
427
+
428
+
429
+ def main() -> None:
430
+ parser = argparse.ArgumentParser()
431
+ parser.add_argument("--fetch-pubchem", action="store_true")
432
+ parser.add_argument("--holdout-fraction", type=float, default=0.15)
433
+ parser.add_argument("--holdout-seed", type=int, default=20260712)
434
+ parser.add_argument("--shuffle-seed", type=int, default=20260712)
435
+ parser.add_argument("--qa-json", default="artifacts/pimt_v9_qa.json")
436
+ parser.add_argument("--qa-md", default="artifacts/pimt_v9_qa.md")
437
+ parser.add_argument("--model-dir", default="models/pimt_v9_substantivity")
438
+ parser.add_argument("--repo-id", default=HF_REPO_ID)
439
+ parser.add_argument("--upload", action="store_true")
440
+ args = parser.parse_args()
441
+
442
+ payload = load_payload(args.fetch_pubchem)
443
+ gate = reproduction_gate(payload)
444
+ result = qa_and_train(payload, args.holdout_fraction, args.holdout_seed, args.shuffle_seed)
445
+ result["qa"]["reproduction_gate"] = gate
446
+
447
+ qa_json = Path(args.qa_json)
448
+ qa_md = Path(args.qa_md)
449
+ qa_json.parent.mkdir(parents=True, exist_ok=True)
450
+ qa_json.write_text(json.dumps(result["qa"], indent=2, sort_keys=True) + "\n", encoding="utf-8")
451
+ write_markdown(result["qa"], qa_md)
452
+ model_dir = Path(args.model_dir)
453
+ write_model_package(payload, result, model_dir)
454
+ upload = upload_model(model_dir, args.repo_id, private=True) if args.upload else None
455
+ print(json.dumps({
456
+ "model_version": MODEL_VERSION,
457
+ "n_model_ready": payload["n_model_ready"],
458
+ "reproduction_gate": gate["status"],
459
+ "holdout_n": result["qa"]["holdout"]["n_holdout"],
460
+ "holdout_structure": result["qa"]["holdout"]["metrics_structure_full_gbm"],
461
+ "negative_control": result["qa"]["leakage_negative_control"],
462
+ "model_dir": str(model_dir),
463
+ "upload": upload,
464
+ }, indent=2, sort_keys=True))
465
+
466
+
467
+ if __name__ == "__main__":
468
+ main()
scripts/test_formula_split.py CHANGED
@@ -1,6 +1,6 @@
1
- from pino.upload_data import create_molecule_disjoint_split
2
 
3
- dd = create_molecule_disjoint_split('data/synthetic_dataset_v2.jsonl', train_ratio=0.8)
4
  print('train:', len(dd['train']))
5
  print('validation:', len(dd['validation']))
6
  train_cas = {
 
1
+ from pino.upload_data import DEFAULT_TRAIN_RATIO, create_molecule_disjoint_split
2
 
3
+ dd = create_molecule_disjoint_split('data/synthetic_dataset_v2.jsonl', train_ratio=DEFAULT_TRAIN_RATIO)
4
  print('train:', len(dd['train']))
5
  print('validation:', len(dd['validation']))
6
  train_cas = {
scripts/train_substantivity.py CHANGED
@@ -29,6 +29,8 @@ DATA = Path("data")
29
  ARTIFACTS = Path("artifacts")
30
  FEATURE_NAMES = ["log10_vapor_pressure_pa", "boiling_point_k", "molecular_weight", "logp"]
31
  STRUCTURAL_BITS = 256
 
 
32
  try:
33
  from pino.version import PIMT_VERSION
34
  except Exception:
@@ -39,6 +41,20 @@ def load_jsonl(path: Path) -> list[dict[str, Any]]:
39
  return [json.loads(line) for line in path.open(encoding="utf-8") if line.strip()]
40
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  def load_registry_rows() -> dict[str, dict[str, Any]]:
43
  rows: dict[str, dict[str, Any]] = {}
44
  for path in [DATA / "aroma_chemicals.jsonl"]:
@@ -291,7 +307,7 @@ def scaffold_key(smiles: str | None, cas: str) -> str:
291
 
292
 
293
  def enrich_rows(fetch_pubchem_missing: bool) -> list[dict[str, Any]]:
294
- poucher = load_jsonl(DATA / "poucher_substantivity.jsonl")
295
  registry = load_registry_rows()
296
  cache = pubchem_cache(poucher, DATA / "pubchem_substantivity_cache.json", fetch_pubchem_missing)
297
  enriched = []
 
29
  ARTIFACTS = Path("artifacts")
30
  FEATURE_NAMES = ["log10_vapor_pressure_pa", "boiling_point_k", "molecular_weight", "logp"]
31
  STRUCTURAL_BITS = 256
32
+ POUCHER_TARGET_PATH = DATA / "poucher_substantivity.jsonl"
33
+ EXPECTED_MODEL_READY_RANGE = (150, 190)
34
  try:
35
  from pino.version import PIMT_VERSION
36
  except Exception:
 
41
  return [json.loads(line) for line in path.open(encoding="utf-8") if line.strip()]
42
 
43
 
44
+ def load_poucher_targets(path: Path = POUCHER_TARGET_PATH) -> list[dict[str, Any]]:
45
+ resolved = path.resolve()
46
+ if not resolved.is_file():
47
+ raise FileNotFoundError(f"Poucher target file is missing: {resolved}")
48
+ rows = load_jsonl(resolved)
49
+ values = [safe_float(row.get("poucher_coefficient")) for row in rows]
50
+ measured = [value for value in values if value is not None and value > 0]
51
+ if not measured:
52
+ raise ValueError(f"Poucher target file has no positive measured coefficients: {resolved}")
53
+ if float(np.std(measured)) <= 0.0:
54
+ raise ValueError(f"Poucher target is constant in {resolved}")
55
+ return rows
56
+
57
+
58
  def load_registry_rows() -> dict[str, dict[str, Any]]:
59
  rows: dict[str, dict[str, Any]] = {}
60
  for path in [DATA / "aroma_chemicals.jsonl"]:
 
307
 
308
 
309
  def enrich_rows(fetch_pubchem_missing: bool) -> list[dict[str, Any]]:
310
+ poucher = load_poucher_targets()
311
  registry = load_registry_rows()
312
  cache = pubchem_cache(poucher, DATA / "pubchem_substantivity_cache.json", fetch_pubchem_missing)
313
  enriched = []
src/pino/train.py CHANGED
@@ -24,7 +24,7 @@ from pino.pimt_model import (
24
  objective_targets_to_pyramid,
25
  )
26
  from pino.thermo.losses import AdaptiveLossBalancer
27
- from pino.upload_data import create_molecule_disjoint_split_from_records
28
 
29
  logger = logging.getLogger("pino.train")
30
 
@@ -263,8 +263,8 @@ def main():
263
  parser.add_argument("--seed", type=int, default=2026)
264
  parser.add_argument("--output-dir", default="models")
265
  parser.add_argument("--log-dir", default="runs")
266
- parser.add_argument("--checkpoint-name", default="pimt_v6.pt", help="Filename for the best checkpoint")
267
- parser.add_argument("--train-ratio", type=float, default=0.6, help="Molecule-disjoint train molecule ratio")
268
  parser.add_argument("--smoke-test", action="store_true", help="Run lightweight CPU smoke test")
269
  args = parser.parse_args()
270
 
 
24
  objective_targets_to_pyramid,
25
  )
26
  from pino.thermo.losses import AdaptiveLossBalancer
27
+ from pino.upload_data import DEFAULT_TRAIN_RATIO, create_molecule_disjoint_split_from_records
28
 
29
  logger = logging.getLogger("pino.train")
30
 
 
263
  parser.add_argument("--seed", type=int, default=2026)
264
  parser.add_argument("--output-dir", default="models")
265
  parser.add_argument("--log-dir", default="runs")
266
+ parser.add_argument("--checkpoint-name", default="pimt_v9.pt", help="Filename for the best checkpoint")
267
+ parser.add_argument("--train-ratio", type=float, default=DEFAULT_TRAIN_RATIO, help="Molecule-disjoint train molecule ratio; default keeps a 15% molecule holdout")
268
  parser.add_argument("--smoke-test", action="store_true", help="Run lightweight CPU smoke test")
269
  args = parser.parse_args()
270
 
src/pino/upload_data.py CHANGED
@@ -15,6 +15,9 @@ from datasets import ClassLabel, Dataset, DatasetDict, load_dataset
15
 
16
  logger = logging.getLogger("pino.upload_data")
17
 
 
 
 
18
 
19
  def _validate_ratio(name: str, value: float) -> None:
20
  if not 0.0 < value < 1.0:
@@ -285,7 +288,7 @@ def analyze_molecule_graph(
285
 
286
  def create_hub_excluded_component_split_from_records(
287
  records: list[dict[str, Any]],
288
- train_ratio: float = 0.8,
289
  seed: int = 42,
290
  solvent_cas: str = "64-17-5",
291
  hub_threshold: float = 0.1,
@@ -458,7 +461,7 @@ def selection_bias_report(
458
  def diagnose_split_strategy(
459
  records: list[dict[str, Any]],
460
  *,
461
- train_ratio: float = 0.8,
462
  seed: int = 42,
463
  solvent_cas: str = "64-17-5",
464
  hub_thresholds: tuple[float, ...] = (0.2, 0.1, 0.05, 0.02, 0.01),
@@ -522,7 +525,7 @@ def diagnose_split_strategy(
522
 
523
  def create_formula_disjoint_split_from_dataset(
524
  dataset: Dataset,
525
- train_ratio: float = 0.8,
526
  ) -> DatasetDict:
527
  """
528
  Partition a Hugging Face Dataset of formula records at the formula level.
@@ -539,7 +542,7 @@ def create_formula_disjoint_split_from_dataset(
539
 
540
  def create_formula_disjoint_split_from_records(
541
  records: list[dict[str, Any]],
542
- train_ratio: float = 0.8,
543
  ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
544
  """
545
  Partition a list of formula records at the formula level.
@@ -569,7 +572,7 @@ def create_formula_disjoint_split_from_records(
569
 
570
  def create_formula_disjoint_split(
571
  jsonl_path: str | Path,
572
- train_ratio: float = 0.8,
573
  ) -> DatasetDict:
574
  """
575
  Partition a JSON-L formulation corpus at the formula level.
@@ -585,7 +588,7 @@ def create_formula_disjoint_split(
585
 
586
  def create_molecule_disjoint_split(
587
  jsonl_path: str | Path,
588
- train_ratio: float = 0.8,
589
  seed: int = 42,
590
  solvent_cas: str = "64-17-5",
591
  ) -> DatasetDict:
@@ -623,7 +626,7 @@ def create_molecule_disjoint_split(
623
 
624
  def create_molecule_disjoint_split_from_records(
625
  records: list[dict[str, Any]],
626
- train_ratio: float = 0.8,
627
  seed: int = 42,
628
  solvent_cas: str = "64-17-5",
629
  ) -> dict[str, Any]:
@@ -682,7 +685,7 @@ def create_molecule_disjoint_split_from_records(
682
 
683
  def molecule_disjoint_split(
684
  jsonl_path: str | Path,
685
- val_ratio: float = 0.2,
686
  seed: int = 42,
687
  solvent_cas: str = "64-17-5",
688
  ) -> dict[str, Any]:
@@ -769,7 +772,7 @@ def molecule_disjoint_split(
769
  def split_and_upload_dataset(
770
  jsonl_path: str,
771
  repo_id: str,
772
- val_ratio: float = 0.2,
773
  seed: int = 42,
774
  solvent_cas: str = "64-17-5",
775
  ) -> None:
@@ -800,7 +803,7 @@ if __name__ == "__main__":
800
  parser = argparse.ArgumentParser(description="Molecule-disjoint dataset split and upload for PINO")
801
  parser.add_argument("--jsonl", default="data/synthetic_dataset_v2_text.jsonl", help="Input JSON-L corpus")
802
  parser.add_argument("--repo-id", default="mattbitzesty/pino-synthetic-dataset", help="HF Hub dataset repo")
803
- parser.add_argument("--val-ratio", type=float, default=0.2, help="Fraction of compounds to hold out")
804
  parser.add_argument("--seed", type=int, default=42, help="Random seed for hold-out selection")
805
  parser.add_argument("--solvent-cas", default="64-17-5", help="CAS number of the universal solvent")
806
  parser.add_argument("--diagnose-only", action="store_true", help="Write split diagnostics without uploading")
 
15
 
16
  logger = logging.getLogger("pino.upload_data")
17
 
18
+ DEFAULT_TRAIN_RATIO = 0.85
19
+ DEFAULT_VAL_RATIO = 0.15
20
+
21
 
22
  def _validate_ratio(name: str, value: float) -> None:
23
  if not 0.0 < value < 1.0:
 
288
 
289
  def create_hub_excluded_component_split_from_records(
290
  records: list[dict[str, Any]],
291
+ train_ratio: float = DEFAULT_TRAIN_RATIO,
292
  seed: int = 42,
293
  solvent_cas: str = "64-17-5",
294
  hub_threshold: float = 0.1,
 
461
  def diagnose_split_strategy(
462
  records: list[dict[str, Any]],
463
  *,
464
+ train_ratio: float = DEFAULT_TRAIN_RATIO,
465
  seed: int = 42,
466
  solvent_cas: str = "64-17-5",
467
  hub_thresholds: tuple[float, ...] = (0.2, 0.1, 0.05, 0.02, 0.01),
 
525
 
526
  def create_formula_disjoint_split_from_dataset(
527
  dataset: Dataset,
528
+ train_ratio: float = DEFAULT_TRAIN_RATIO,
529
  ) -> DatasetDict:
530
  """
531
  Partition a Hugging Face Dataset of formula records at the formula level.
 
542
 
543
  def create_formula_disjoint_split_from_records(
544
  records: list[dict[str, Any]],
545
+ train_ratio: float = DEFAULT_TRAIN_RATIO,
546
  ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
547
  """
548
  Partition a list of formula records at the formula level.
 
572
 
573
  def create_formula_disjoint_split(
574
  jsonl_path: str | Path,
575
+ train_ratio: float = DEFAULT_TRAIN_RATIO,
576
  ) -> DatasetDict:
577
  """
578
  Partition a JSON-L formulation corpus at the formula level.
 
588
 
589
  def create_molecule_disjoint_split(
590
  jsonl_path: str | Path,
591
+ train_ratio: float = DEFAULT_TRAIN_RATIO,
592
  seed: int = 42,
593
  solvent_cas: str = "64-17-5",
594
  ) -> DatasetDict:
 
626
 
627
  def create_molecule_disjoint_split_from_records(
628
  records: list[dict[str, Any]],
629
+ train_ratio: float = DEFAULT_TRAIN_RATIO,
630
  seed: int = 42,
631
  solvent_cas: str = "64-17-5",
632
  ) -> dict[str, Any]:
 
685
 
686
  def molecule_disjoint_split(
687
  jsonl_path: str | Path,
688
+ val_ratio: float = DEFAULT_VAL_RATIO,
689
  seed: int = 42,
690
  solvent_cas: str = "64-17-5",
691
  ) -> dict[str, Any]:
 
772
  def split_and_upload_dataset(
773
  jsonl_path: str,
774
  repo_id: str,
775
+ val_ratio: float = DEFAULT_VAL_RATIO,
776
  seed: int = 42,
777
  solvent_cas: str = "64-17-5",
778
  ) -> None:
 
803
  parser = argparse.ArgumentParser(description="Molecule-disjoint dataset split and upload for PINO")
804
  parser.add_argument("--jsonl", default="data/synthetic_dataset_v2_text.jsonl", help="Input JSON-L corpus")
805
  parser.add_argument("--repo-id", default="mattbitzesty/pino-synthetic-dataset", help="HF Hub dataset repo")
806
+ parser.add_argument("--val-ratio", type=float, default=DEFAULT_VAL_RATIO, help="Fraction of compounds to hold out")
807
  parser.add_argument("--seed", type=int, default=42, help="Random seed for hold-out selection")
808
  parser.add_argument("--solvent-cas", default="64-17-5", help="CAS number of the universal solvent")
809
  parser.add_argument("--diagnose-only", action="store_true", help="Write split diagnostics without uploading")