Matthew Ford commited on
Commit ·
456264c
1
Parent(s): c020b8e
feat: add leakage-resistant genre baseline benchmark
Browse filesFormer-commit-id: 3c1e178cde8eaebf9dcc14c2e94001fcc88f87e7
Former-commit-id: 8746b6066d564519290be224361793b7a79919a3
- GENRE_BENCHMARK_CHECKLIST.md +51 -0
- scripts/genre_baseline_benchmark.py +44 -0
- src/pino/genre_benchmark.py +159 -0
- tests/test_genre_benchmark.py +36 -0
GENRE_BENCHMARK_CHECKLIST.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Genre-representation benchmark checklist
|
| 2 |
+
|
| 3 |
+
This checklist preregisters the test of whether a redesigned learned representation captures more than elementary formula-composition statistics. Complete it for every reported run; do not tune the rule after viewing held-out results.
|
| 4 |
+
|
| 5 |
+
## Freeze before evaluation
|
| 6 |
+
|
| 7 |
+
- [ ] Freeze the dataset version, genre labels, model checkpoint, random seeds, and split manifest.
|
| 8 |
+
- [ ] Use at least three independently seeded held-out splits.
|
| 9 |
+
- [ ] Keep all active molecule identities disjoint between train and held-out records.
|
| 10 |
+
- [ ] Keep exact formulas disjoint between train and held-out records.
|
| 11 |
+
- [ ] Fit normalization, centroids, and any other learned preprocessing on training records only.
|
| 12 |
+
- [ ] Store learned train/test representations in manifest-aligned `.npy` files without genre labels as inputs.
|
| 13 |
+
|
| 14 |
+
## Run the controlled comparison
|
| 15 |
+
|
| 16 |
+
- [ ] Run `scripts/genre_baseline_benchmark.py` on the frozen manifest.
|
| 17 |
+
- [ ] Confirm every `leakage_audit.passed` value is `true`; a failure invalidates the split rather than becoming an exclusion after results are seen.
|
| 18 |
+
- [ ] Compare both representations with the identical nearest-centroid probe and identical held-out rows.
|
| 19 |
+
- [ ] Report held-out accuracy for the learned representation and composition baseline.
|
| 20 |
+
- [ ] Report the paired bootstrap accuracy delta and 95% confidence interval for every split.
|
| 21 |
+
- [ ] Archive the manifest, output JSON, checkpoint identifier, and commit hash.
|
| 22 |
+
|
| 23 |
+
## Decision and reporting
|
| 24 |
+
|
| 25 |
+
- [ ] Claim support only if the lower 95% bound for learned-minus-baseline accuracy is above the preregistered margin on every valid split and at least three splits are valid.
|
| 26 |
+
- [ ] If that criterion fails, report the result as negative; do not substitute a favorable in-sample or leaky split.
|
| 27 |
+
- [ ] In a negative report, state the supported interpretation: the benchmark's genre structure may be explained by elementary compositional statistics, and the experiment does not establish deeper formula semantics.
|
| 28 |
+
- [ ] Report all split results, including weak or adverse ones, and document any invalid split with its leakage audit.
|
| 29 |
+
|
| 30 |
+
Manifest format:
|
| 31 |
+
|
| 32 |
+
```json
|
| 33 |
+
[
|
| 34 |
+
{
|
| 35 |
+
"name": "seed_1",
|
| 36 |
+
"train_records": "data/splits/seed_1_train.jsonl",
|
| 37 |
+
"test_records": "data/splits/seed_1_test.jsonl",
|
| 38 |
+
"learned_train": "artifacts/seed_1_train_embeddings.npy",
|
| 39 |
+
"learned_test": "artifacts/seed_1_test_embeddings.npy"
|
| 40 |
+
}
|
| 41 |
+
]
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
Example:
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
python scripts/genre_baseline_benchmark.py \
|
| 48 |
+
--manifest artifacts/genre_split_manifest.json \
|
| 49 |
+
--output artifacts/genre_baseline_report.json \
|
| 50 |
+
--minimum-splits 3 --margin 0
|
| 51 |
+
```
|
scripts/genre_baseline_benchmark.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run learned-vs-composition genre benchmarks from a split manifest."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
from pino.genre_benchmark import benchmark_split, decide, load_jsonl
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def main() -> None:
|
| 16 |
+
parser = argparse.ArgumentParser()
|
| 17 |
+
parser.add_argument("--manifest", required=True, help="JSON list of train/test JSONL and learned .npy paths")
|
| 18 |
+
parser.add_argument("--output", required=True)
|
| 19 |
+
parser.add_argument("--minimum-splits", type=int, default=3)
|
| 20 |
+
parser.add_argument("--margin", type=float, default=0.0)
|
| 21 |
+
parser.add_argument("--bootstrap-samples", type=int, default=10_000)
|
| 22 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 23 |
+
args = parser.parse_args()
|
| 24 |
+
|
| 25 |
+
manifest = json.loads(Path(args.manifest).read_text(encoding="utf-8"))
|
| 26 |
+
results = []
|
| 27 |
+
for index, split in enumerate(manifest):
|
| 28 |
+
result = benchmark_split(
|
| 29 |
+
load_jsonl(split["train_records"]),
|
| 30 |
+
load_jsonl(split["test_records"]),
|
| 31 |
+
np.load(split["learned_train"]),
|
| 32 |
+
np.load(split["learned_test"]),
|
| 33 |
+
seed=args.seed + index,
|
| 34 |
+
bootstrap_samples=args.bootstrap_samples,
|
| 35 |
+
)
|
| 36 |
+
result["name"] = split.get("name", f"split_{index}")
|
| 37 |
+
results.append(result)
|
| 38 |
+
report = {"splits": results, "verdict": decide(results, minimum_splits=args.minimum_splits, margin=args.margin)}
|
| 39 |
+
Path(args.output).write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
| 40 |
+
print(json.dumps(report, indent=2))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__ == "__main__":
|
| 44 |
+
main()
|
src/pino/genre_benchmark.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Leakage-resistant genre benchmark with an elementary composition baseline."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
from collections.abc import Sequence
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
SOLVENTS = {"64-17-5", "ethanol", "water", "7732-18-5"}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _identity(component: dict[str, Any]) -> str:
|
| 17 |
+
return str(component.get("cas") or component.get("smiles") or component.get("name") or "").strip().lower()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def active_compounds(record: dict[str, Any]) -> set[str]:
|
| 21 |
+
"""Return non-solvent component identities used for leakage accounting."""
|
| 22 |
+
return {identity for component in record.get("formula", []) if (identity := _identity(component)) and identity not in SOLVENTS}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def formula_fingerprint(record: dict[str, Any], precision: int = 6) -> str:
|
| 26 |
+
"""Stable, order-invariant identity for exact/near-exact formula duplicates."""
|
| 27 |
+
parts = sorted(
|
| 28 |
+
(_identity(component), round(float(component.get("weight_fraction", 0.0)), precision))
|
| 29 |
+
for component in record.get("formula", [])
|
| 30 |
+
)
|
| 31 |
+
return hashlib.sha256(json.dumps(parts, separators=(",", ":")).encode()).hexdigest()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def audit_split(train: Sequence[dict[str, Any]], test: Sequence[dict[str, Any]]) -> dict[str, Any]:
|
| 35 |
+
"""Fail closed on molecule or formula leakage between train and test."""
|
| 36 |
+
train_compounds = set().union(*(active_compounds(row) for row in train)) if train else set()
|
| 37 |
+
test_compounds = set().union(*(active_compounds(row) for row in test)) if test else set()
|
| 38 |
+
train_formulas = {formula_fingerprint(row) for row in train}
|
| 39 |
+
test_formulas = {formula_fingerprint(row) for row in test}
|
| 40 |
+
compound_overlap = sorted(train_compounds & test_compounds)
|
| 41 |
+
formula_overlap = sorted(train_formulas & test_formulas)
|
| 42 |
+
result = {
|
| 43 |
+
"passed": not compound_overlap and not formula_overlap,
|
| 44 |
+
"train_records": len(train),
|
| 45 |
+
"test_records": len(test),
|
| 46 |
+
"compound_overlap": compound_overlap,
|
| 47 |
+
"formula_overlap": formula_overlap,
|
| 48 |
+
}
|
| 49 |
+
if not result["passed"]:
|
| 50 |
+
raise ValueError(
|
| 51 |
+
f"leaky split: {len(compound_overlap)} shared compounds, "
|
| 52 |
+
f"{len(formula_overlap)} shared formulas"
|
| 53 |
+
)
|
| 54 |
+
return result
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def composition_features(records: Sequence[dict[str, Any]]) -> np.ndarray:
|
| 58 |
+
"""Compute label-free mass-distribution statistics; no identities are encoded."""
|
| 59 |
+
features: list[list[float]] = []
|
| 60 |
+
for row in records:
|
| 61 |
+
formula = row.get("formula", [])
|
| 62 |
+
solvent_mass = sum(float(c.get("weight_fraction", 0.0)) for c in formula if _identity(c) in SOLVENTS)
|
| 63 |
+
weights = np.asarray(
|
| 64 |
+
[float(c.get("weight_fraction", 0.0)) for c in formula if _identity(c) not in SOLVENTS], dtype=float
|
| 65 |
+
)
|
| 66 |
+
weights = weights[weights > 0]
|
| 67 |
+
if not len(weights):
|
| 68 |
+
weights = np.zeros(1)
|
| 69 |
+
total = float(weights.sum())
|
| 70 |
+
proportions = weights / total if total else weights
|
| 71 |
+
sorted_weights = np.sort(weights)[::-1]
|
| 72 |
+
top = np.pad(sorted_weights, (0, max(0, 3 - len(sorted_weights))))[:3]
|
| 73 |
+
entropy = float(-(proportions[proportions > 0] * np.log(proportions[proportions > 0])).sum())
|
| 74 |
+
hhi = float(np.square(proportions).sum())
|
| 75 |
+
q25, median, q75 = np.quantile(weights, [0.25, 0.5, 0.75])
|
| 76 |
+
features.append([
|
| 77 |
+
len(weights), solvent_mass, total, float(weights.mean()), float(weights.std()),
|
| 78 |
+
float(q25), float(median), float(q75), float(weights.max()), entropy, hhi,
|
| 79 |
+
1.0 / hhi if hhi else 0.0, *top.tolist(),
|
| 80 |
+
])
|
| 81 |
+
return np.asarray(features, dtype=float)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def nearest_centroid_predict(train_x: np.ndarray, train_y: np.ndarray, test_x: np.ndarray) -> np.ndarray:
|
| 85 |
+
"""Standardized nearest-centroid classifier with training-only statistics."""
|
| 86 |
+
mean = train_x.mean(axis=0)
|
| 87 |
+
scale = train_x.std(axis=0)
|
| 88 |
+
scale[scale == 0] = 1.0
|
| 89 |
+
train_z, test_z = (train_x - mean) / scale, (test_x - mean) / scale
|
| 90 |
+
labels = np.unique(train_y)
|
| 91 |
+
centroids = np.vstack([train_z[train_y == label].mean(axis=0) for label in labels])
|
| 92 |
+
distances = np.square(test_z[:, None, :] - centroids[None, :, :]).sum(axis=2)
|
| 93 |
+
return labels[np.argmin(distances, axis=1)]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def paired_bootstrap_delta(
|
| 97 |
+
learned_correct: np.ndarray,
|
| 98 |
+
baseline_correct: np.ndarray,
|
| 99 |
+
*,
|
| 100 |
+
seed: int = 0,
|
| 101 |
+
samples: int = 10_000,
|
| 102 |
+
) -> dict[str, float]:
|
| 103 |
+
"""Bootstrap the paired accuracy advantage on the identical held-out rows."""
|
| 104 |
+
if learned_correct.shape != baseline_correct.shape or not learned_correct.size:
|
| 105 |
+
raise ValueError("paired non-empty correctness arrays are required")
|
| 106 |
+
differences = learned_correct.astype(float) - baseline_correct.astype(float)
|
| 107 |
+
rng = np.random.default_rng(seed)
|
| 108 |
+
draws = rng.choice(differences, size=(samples, len(differences)), replace=True).mean(axis=1)
|
| 109 |
+
low, high = np.quantile(draws, [0.025, 0.975])
|
| 110 |
+
return {"delta": float(differences.mean()), "ci95_low": float(low), "ci95_high": float(high)}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def benchmark_split(
|
| 114 |
+
train: Sequence[dict[str, Any]],
|
| 115 |
+
test: Sequence[dict[str, Any]],
|
| 116 |
+
learned_train: np.ndarray,
|
| 117 |
+
learned_test: np.ndarray,
|
| 118 |
+
*,
|
| 119 |
+
seed: int = 0,
|
| 120 |
+
bootstrap_samples: int = 10_000,
|
| 121 |
+
) -> dict[str, Any]:
|
| 122 |
+
"""Compare learned representations with the composition baseline on one split."""
|
| 123 |
+
leakage = audit_split(train, test)
|
| 124 |
+
train_y = np.asarray([row["genre"] for row in train])
|
| 125 |
+
test_y = np.asarray([row["genre"] for row in test])
|
| 126 |
+
baseline_pred = nearest_centroid_predict(composition_features(train), train_y, composition_features(test))
|
| 127 |
+
learned_pred = nearest_centroid_predict(np.asarray(learned_train), train_y, np.asarray(learned_test))
|
| 128 |
+
baseline_correct = baseline_pred == test_y
|
| 129 |
+
learned_correct = learned_pred == test_y
|
| 130 |
+
return {
|
| 131 |
+
"leakage_audit": leakage,
|
| 132 |
+
"n_test": len(test),
|
| 133 |
+
"baseline_accuracy": float(baseline_correct.mean()),
|
| 134 |
+
"learned_accuracy": float(learned_correct.mean()),
|
| 135 |
+
"paired_advantage": paired_bootstrap_delta(
|
| 136 |
+
learned_correct, baseline_correct, seed=seed, samples=bootstrap_samples
|
| 137 |
+
),
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def decide(results: Sequence[dict[str, Any]], *, minimum_splits: int = 3, margin: float = 0.0) -> dict[str, Any]:
|
| 142 |
+
"""Apply the preregistered rule: every split CI must clear the margin."""
|
| 143 |
+
valid = [r for r in results if r.get("leakage_audit", {}).get("passed")]
|
| 144 |
+
beats = len(valid) >= minimum_splits and all(r["paired_advantage"]["ci95_low"] > margin for r in valid)
|
| 145 |
+
return {
|
| 146 |
+
"decision": "learned_representation_supported" if beats else "negative_result",
|
| 147 |
+
"reason": (
|
| 148 |
+
"learned representation reliably beats composition baseline"
|
| 149 |
+
if beats else "learned representation did not reliably beat composition baseline"
|
| 150 |
+
),
|
| 151 |
+
"valid_splits": len(valid),
|
| 152 |
+
"minimum_splits": minimum_splits,
|
| 153 |
+
"required_margin": margin,
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def load_jsonl(path: str | Path) -> list[dict[str, Any]]:
|
| 158 |
+
with Path(path).open(encoding="utf-8") as handle:
|
| 159 |
+
return [json.loads(line) for line in handle if line.strip()]
|
tests/test_genre_benchmark.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pino.genre_benchmark import audit_split, benchmark_split, composition_features, decide
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def row(genre, *components):
|
| 8 |
+
return {"genre": genre, "formula": [{"cas": cas, "weight_fraction": weight} for cas, weight in components]}
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_composition_features_ignore_identity_and_order():
|
| 12 |
+
a = row("a", ("64-17-5", .8), ("x", .15), ("y", .05))
|
| 13 |
+
b = row("b", ("z", .05), ("q", .15), ("64-17-5", .8))
|
| 14 |
+
np.testing.assert_allclose(composition_features([a]), composition_features([b]))
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_audit_rejects_shared_active_compounds():
|
| 18 |
+
with pytest.raises(ValueError, match="shared compounds"):
|
| 19 |
+
audit_split([row("a", ("x", 1))], [row("b", ("x", 1))])
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_benchmark_and_negative_decision():
|
| 23 |
+
train = [row("a", ("a1", .1)), row("a", ("a2", .12)), row("b", ("b1", .8)), row("b", ("b2", .82))]
|
| 24 |
+
test = [row("a", ("a3", .11)), row("a", ("a4", .13)), row("b", ("b3", .79)), row("b", ("b4", .81))]
|
| 25 |
+
learned_train = np.zeros((4, 2))
|
| 26 |
+
learned_test = np.zeros((4, 2))
|
| 27 |
+
result = benchmark_split(train, test, learned_train, learned_test, bootstrap_samples=200, seed=4)
|
| 28 |
+
assert result["baseline_accuracy"] == 1.0
|
| 29 |
+
assert decide([result], minimum_splits=1)["decision"] == "negative_result"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_decision_requires_every_leakage_free_split_to_clear_ci():
|
| 33 |
+
good = {"leakage_audit": {"passed": True}, "paired_advantage": {"ci95_low": .01}}
|
| 34 |
+
weak = {"leakage_audit": {"passed": True}, "paired_advantage": {"ci95_low": 0.0}}
|
| 35 |
+
assert decide([good, good, good])["decision"] == "learned_representation_supported"
|
| 36 |
+
assert decide([good, good, weak])["decision"] == "negative_result"
|