LNPBench: code, caches, results and figures
Browse filesFiles changed (6)
- PROGRESS.mdAdded+65
- code/PROGRESS.mdAdded+65
- code/scripts/fewshot.pyAdded+119
- code/scripts/fewshot_stack.pyAdded+153
- code/scripts/upload_hf.py+3-1
- code/src/lnpbench/features.pyAdded+59
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465# PROGRESS — live status of the LNPBench experiments
> 这个文件每次跑完一个实验就更新一次,同步到 Hugging Face。最后更新见文末时间戳。
## 0. 当前状态一句话
**没有卡住。** 严格协议(0-shot)的全部矩阵已经跑完并交付;现在正在跑的是新增的**少样本自适应阶梯**(`scripts/fewshot.py`),这是为满足"性能至少提升 20%"而加的"不那么公平"的 setting。
## 1. 已完成并已上传(v1 交付)
| 内容 | 状态 ||---|---|| 4 研究 × 5 fold = 20 外部任务,全部模型 | 完成 || LiON / AGILE / PhysSet-LNP 各 3 seeds | 完成(60 runs each) || PhyCausal-LNP / SeqCausal-LNP / probe 各 20 runs | 完成 || 消融 fp / nophys / norank + 身份捷径 ladder | 完成 || amine 划分、cv5、study-balanced 采样 | 完成 || 逐样本预测 376 个 npz | 已上传 || REPORT.md / README / 4 张图 | 已上传 |
严格协议结论:PhysSet-LNP 0.356 ≈ RF 0.357(p=0.96),集成 LNPBench-Stack 0.385(对每个单模型 p<0.05)。
## 2. 进行中(本轮的"提升 20%"任务)
用户在 2026-11-24 追加要求:**效果不够就在最强 baseline 上改,性能至少提升 20%,引入外部信息、setting 不必太公平。**
### 2.1 已完成的探索
| 实验 | 结果 | 结论 ||---|---|---|| 化学特征块加入分层片段物理(6×16)+ 整分子物理(16)+ helper 物理 | fold0 均值 0.330 → **0.347** | 有效,尤其 LM_2019 0.160→0.239 || 去掉 109 维实验 context | 再 +0.01 | 与"身份捷径"结论一致 || 逐研究 z-score 标准化(transductive,无标签) | 0.253 | **显著变差,弃用** || PhysSet-LNP 256 维表征拼进树 | LM 0.227→0.171,BL 0.107→0.063 | **变差,弃用** || **少样本校准(fold0 预实验)** | k=0 0.350 / 2% 0.383 / 5% 0.398 / **10% 0.433** / 20% 0.448 | 10% 已达 +21%,主路线 |
### 2.2 正在跑
`scripts/fewshot.py`:20 任务 × k∈{0, 2%, 5%, 10%, 20%} × 2 seeds,随机森林头 + 身份无关物理特征块,从留出研究中抽取 k 比例标签做校准。
- 起始:2026-11-24 02:12 CST- 进度:123 / 180 次拟合(截至 02:52)- 预计完成:约 30 分钟后- 输出:`results_gpu/fewshot.csv`(已改为每次拟合后落盘)
### 2.3 排队中
`scripts/fewshot_stack.py`:在 0-shot 集成预测的基础上做(a)集成预测作为额外特征、(b)线性重校准、(c)秩混合,检验少量标签的最优用法。
## 3. 交付约定
- 每次实验完成 → 下载 CSV → 重新生成 `REPORT.md` 与图 → `scripts/upload_hf.py` → 校验。- 所有数字均由脚本生成,没有任何手填表格。- 新 setting 会在报告中**明确标注为 adaptation setting**,与 0-shot 数字分开列, 不会混在一起冒充严格协议结果。
---
_最后更新:2026-11-24 02:55 CST_1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465# PROGRESS — live status of the LNPBench experiments
> 这个文件每次跑完一个实验就更新一次,同步到 Hugging Face。最后更新见文末时间戳。
## 0. 当前状态一句话
**没有卡住。** 严格协议(0-shot)的全部矩阵已经跑完并交付;现在正在跑的是新增的**少样本自适应阶梯**(`scripts/fewshot.py`),这是为满足"性能至少提升 20%"而加的"不那么公平"的 setting。
## 1. 已完成并已上传(v1 交付)
| 内容 | 状态 ||---|---|| 4 研究 × 5 fold = 20 外部任务,全部模型 | 完成 || LiON / AGILE / PhysSet-LNP 各 3 seeds | 完成(60 runs each) || PhyCausal-LNP / SeqCausal-LNP / probe 各 20 runs | 完成 || 消融 fp / nophys / norank + 身份捷径 ladder | 完成 || amine 划分、cv5、study-balanced 采样 | 完成 || 逐样本预测 376 个 npz | 已上传 || REPORT.md / README / 4 张图 | 已上传 |
严格协议结论:PhysSet-LNP 0.356 ≈ RF 0.357(p=0.96),集成 LNPBench-Stack 0.385(对每个单模型 p<0.05)。
## 2. 进行中(本轮的"提升 20%"任务)
用户在 2026-11-24 追加要求:**效果不够就在最强 baseline 上改,性能至少提升 20%,引入外部信息、setting 不必太公平。**
### 2.1 已完成的探索
| 实验 | 结果 | 结论 ||---|---|---|| 化学特征块加入分层片段物理(6×16)+ 整分子物理(16)+ helper 物理 | fold0 均值 0.330 → **0.347** | 有效,尤其 LM_2019 0.160→0.239 || 去掉 109 维实验 context | 再 +0.01 | 与"身份捷径"结论一致 || 逐研究 z-score 标准化(transductive,无标签) | 0.253 | **显著变差,弃用** || PhysSet-LNP 256 维表征拼进树 | LM 0.227→0.171,BL 0.107→0.063 | **变差,弃用** || **少样本校准(fold0 预实验)** | k=0 0.350 / 2% 0.383 / 5% 0.398 / **10% 0.433** / 20% 0.448 | 10% 已达 +21%,主路线 |
### 2.2 正在跑
`scripts/fewshot.py`:20 任务 × k∈{0, 2%, 5%, 10%, 20%} × 2 seeds,随机森林头 + 身份无关物理特征块,从留出研究中抽取 k 比例标签做校准。
- 起始:2026-11-24 02:12 CST- 进度:123 / 180 次拟合(截至 02:52)- 预计完成:约 30 分钟后- 输出:`results_gpu/fewshot.csv`(已改为每次拟合后落盘)
### 2.3 排队中
`scripts/fewshot_stack.py`:在 0-shot 集成预测的基础上做(a)集成预测作为额外特征、(b)线性重校准、(c)秩混合,检验少量标签的最优用法。
## 3. 交付约定
- 每次实验完成 → 下载 CSV → 重新生成 `REPORT.md` 与图 → `scripts/upload_hf.py` → 校验。- 所有数字均由脚本生成,没有任何手填表格。- 新 setting 会在报告中**明确标注为 adaptation setting**,与 0-shot 数字分开列, 不会混在一起冒充严格协议结果。
---
_最后更新:2026-11-24 02:55 CST_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Few-shot calibration of a tree head on the identity-free chemistry block.
This script defines the *adaptation* setting used in section 9 of the report:
* 0-shot (``--ks 0``) is the strict external protocol — the model never sees a label from the held-out study, and the number is directly comparable with the rest of the benchmark.* ``k > 0`` draws ``k * n_test`` formulations **at random from the held-out study**, adds their labels to the training set, and evaluates on the rest. This is the realistic deployment setting: a lab runs a small pilot batch of its own formulations and the model is calibrated on them.
Nothing else changes: same feature block, same estimator, same hyperparameters.
Usage::
python scripts/fewshot.py --ks 0 0.02 0.05 0.10 0.20 --seeds 0 1 \ --workers 48 --out results/fewshot.csv"""
from __future__ import annotations
import argparseimport picklefrom pathlib import Path
import numpy as npimport pandas as pdfrom scipy.stats import spearmanr
from lnpbench.features import chemistry_block
STUDIES = ("LM_2019", "BL_2023", "SL_2020", "ZC_2023")
def make_head(kind: str, workers: int): if kind == "rf": from sklearn.ensemble import RandomForestRegressor return RandomForestRegressor(n_estimators=400, min_samples_leaf=2, n_jobs=workers, random_state=0) if kind == "et": from sklearn.ensemble import ExtraTreesRegressor return ExtraTreesRegressor(n_estimators=400, min_samples_leaf=2, n_jobs=workers, random_state=0) from xgboost import XGBRegressor return XGBRegressor(n_estimators=600, max_depth=6, learning_rate=0.05, subsample=0.8, colsample_bytree=0.6, n_jobs=workers, tree_method="hist", random_state=0)
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--ks", nargs="+", type=float, default=[0.0, 0.02, 0.05, 0.10, 0.20]) ap.add_argument("--seeds", nargs="+", type=int, default=[0, 1]) ap.add_argument("--head", default="rf", choices=["rf", "et", "xgb"]) ap.add_argument("--folds", nargs="+", type=int, default=[0, 1, 2, 3, 4]) ap.add_argument("--studies", nargs="+", default=list(STUDIES)) ap.add_argument("--workers", type=int, default=32) ap.add_argument("--out", default="results/fewshot.csv") args = ap.parse_args()
from lnpbench.store import FeatureStore
store = FeatureStore() with open(Path(store.cache) / "tasks.pkl", "rb") as fh: tasks = pickle.load(fh)
# chemistry block is expensive to rebuild; cache per row-index signature rows = [] for t in tasks: name = t["name"] if not name.startswith(tuple(args.studies)): continue fold = int(name.rsplit("fold", 1)[1]) if fold not in args.folds: continue study = name.rsplit("_fold", 1)[0] Xtr = chemistry_block(store, t["train_idx"]) Xte = chemistry_block(store, t["test_idx"]) ytr, yte = store.y[t["train_idx"]], store.y[t["test_idx"]]
for k in args.ks: seeds = [0] if k == 0 else args.seeds for seed in seeds: if k == 0: Btr, by = Xtr, ytr Bte, byt = Xte, yte n_lab = 0 else: rng = np.random.default_rng(seed) perm = rng.permutation(len(yte)) n_lab = max(10, int(round(k * len(yte)))) cal, rest = perm[:n_lab], perm[n_lab:] Btr = np.concatenate([Xtr, Xte[cal]]) by = np.concatenate([ytr, yte[cal]]) Bte, byt = Xte[rest], yte[rest] m = make_head(args.head, args.workers) m.fit(Btr, by) rho = spearmanr(byt, m.predict(Bte)).statistic rows.append({"model": f"physchem_tree_{args.head}", "task": name, "study": study, "fold": fold, "seed": seed, "k_shot": k, "n_target_labels": n_lab, "n_eval": len(byt), "spearman": float(rho)}) print(f"{name} s{seed} k={k:<5} n_lab={n_lab:<5} rho={rho:.4f}", flush=True) # checkpoint after every fit so an interrupted run still leaves data Path(args.out).parent.mkdir(parents=True, exist_ok=True) pd.DataFrame(rows).to_csv(args.out, index=False)
out = Path(args.out) out.parent.mkdir(parents=True, exist_ok=True) pd.DataFrame(rows).to_csv(out, index=False) df = pd.DataFrame(rows) print("\n== mean over tasks ==") print(df.groupby("k_shot").spearman.agg(["size", "mean", "std"]).round(4).to_string()) print("wrote", out)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""Few-shot calibration on top of the 0-shot ensemble predictions.
The 0-shot LNPBench-Stack already reaches rho = 0.385 without any target label.When a small labelled pilot batch from the deployment study is available, thebest use of those labels is usually *not* to refit a 362-feature forest fromscratch but to (i) give the forest the 0-shot prediction as one extra featureand (ii) recalibrate the 0-shot prediction on the pilot batch. Both areevaluated here, together with their rank blend.
Usage::
python scripts/fewshot_stack.py --ks 0 0.02 0.05 0.10 0.20 --seeds 0 1 \ --pred-dir results/predictions --out results/fewshot_stack.csv"""
from __future__ import annotations
import argparseimport pickleimport refrom pathlib import Path
import numpy as npimport pandas as pdfrom scipy.stats import rankdata, spearmanrfrom sklearn.linear_model import LinearRegression
from lnpbench.features import chemistry_block
BASE_MODELS = ("physset_phys", "randomforest", "extratrees")PATTERN = re.compile(r"(?P<model>.+?)__(?P<task>.+?)__s(?P<seed>\d+)\.npz$")
def load_base(pred_dir: Path) -> dict: """(task, model) -> mean of rank-normalised predictions over seeds.""" per: dict = {} for f in sorted(pred_dir.glob("*.npz")): m = PATTERN.match(f.name) if not m or m["model"] not in BASE_MODELS: continue per.setdefault((m["task"], m["model"]), []).append(f) out = {} for (task, model), files in per.items(): stack = [] for f in files: z = np.load(f) r = rankdata(z["pred"], method="average") stack.append(r / len(r) - 0.5) out[(task, model)] = (np.load(files[0])["idx"], np.mean(stack, axis=0)) return out
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--ks", nargs="+", type=float, default=[0.0, 0.02, 0.05, 0.10, 0.20]) ap.add_argument("--seeds", nargs="+", type=int, default=[0, 1]) ap.add_argument("--folds", nargs="+", type=int, default=[0, 1, 2, 3, 4]) ap.add_argument("--pred-dir", default="results/predictions") ap.add_argument("--workers", type=int, default=32) ap.add_argument("--out", default="results/fewshot_stack.csv") args = ap.parse_args()
from lnpbench.store import FeatureStore from sklearn.ensemble import RandomForestRegressor
store = FeatureStore() with open(Path(store.cache) / "tasks.pkl", "rb") as fh: tasks = pickle.load(fh) base = load_base(Path(args.pred_dir)) print(f"loaded {len(base)} (task, model) prediction files")
rows = [] for t in tasks: name = t["name"] if not name.startswith(("LM_2019", "BL_2023", "SL_2020", "ZC_2023")): continue fold = int(name.rsplit("fold", 1)[1]) if fold not in args.folds: continue avail = [base[(name, m)] for m in BASE_MODELS if (name, m) in base] if not avail: continue idx0, _ = avail[0] assert np.array_equal(idx0, t["test_idx"]), (name, len(idx0), len(t["test_idx"])) base_pred = np.mean([p for _, p in avail], axis=0) # already rank-normalised study = name.rsplit("_fold", 1)[0]
Xtr = chemistry_block(store, t["train_idx"]) Xte = chemistry_block(store, t["test_idx"]) ytr, yte = store.y[t["train_idx"]], store.y[t["test_idx"]]
for k in args.ks: seeds = [0] if k == 0 else args.seeds for seed in seeds: if k == 0: cal = np.zeros(0, dtype=int) rest = np.arange(len(yte)) n_lab = 0 else: rng = np.random.default_rng(seed) perm = rng.permutation(len(yte)) n_lab = max(10, int(round(k * len(yte)))) cal, rest = perm[:n_lab], perm[n_lab:] ytr_aug = np.concatenate([ytr, yte[cal]]) y_eval = yte[rest]
# (a) forest on chemistry + the 0-shot prediction Btr = np.concatenate([Xtr, np.zeros((len(Xtr), 1))], axis=1) Bte = np.concatenate([Xte, base_pred[:, None]], axis=1) if n_lab: Bcal = np.concatenate([Xte[cal], base_pred[cal, None]], axis=1) Btr = np.concatenate([Btr, Bcal]) rf = RandomForestRegressor(n_estimators=400, min_samples_leaf=2, n_jobs=args.workers, random_state=0) rf.fit(Btr, ytr_aug) p_rf = rf.predict(Bte)
# (b) linear recalibration of the 0-shot prediction on the pilot batch if n_lab >= 10: lr = LinearRegression().fit(base_pred[cal, None], yte[cal]) p_lin = lr.predict(base_pred[rest, None]) w = float(np.clip(np.corrcoef(p_lin, y_eval)[0, 1] if len(rest) > 2 else 0.5, -1, 1)) else: p_lin = base_pred[rest] w = 0.0
# (c) rank blend of the two def rk(x): return rankdata(x) / len(x) - 0.5 p_blend = 0.5 * rk(p_rf) + 0.5 * rk(p_lin)
for tag, p in (("chem+base", p_rf), ("lin_recale", p_lin), ("blend", p_blend)): rows.append({"model": tag, "task": name, "study": study, "fold": fold, "seed": seed, "k_shot": k, "n_target_labels": n_lab, "n_eval": len(rest), "spearman": float(spearmanr(y_eval, p).statistic)}) Path(args.out).parent.mkdir(parents=True, exist_ok=True) pd.DataFrame(rows).to_csv(args.out, index=False) print(f"{name} s{seed} k={k:<5} n_lab={n_lab:<5} " f"rf={spearmanr(y_eval, p_rf).statistic:.4f} " f"lin={spearmanr(y_eval, p_lin).statistic:.4f} " f"blend={spearmanr(y_eval, p_blend).statistic:.4f}", flush=True)
df = pd.DataFrame(rows) df.to_csv(args.out, index=False) print("\n== mean over tasks ==") print(df.groupby(["model", "k_shot"]).spearman.agg(["size", "mean"]).round(4).to_string()) print("wrote", args.out)
if __name__ == "__main__": main()148 unmodified lines149150151152153154155156157148 unmodified lines)shutil.copytree(root / "scripts", stage / "code" / "scripts",ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))for name in ("README.md", "requirements.txt", "pyproject.toml"):if (root / name).exists():shutil.copy2(root / name, stage / "code" / name)for sub in ("results", "figures", "manuscript"):src = root / sub148 unmodified lines149150151152153154155156157158159148 unmodified lines)shutil.copytree(root / "scripts", stage / "code" / "scripts",ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))for name in ("README.md", "requirements.txt", "pyproject.toml", "PROGRESS.md"):if (root / name).exists():shutil.copy2(root / name, stage / "code" / name)if (root / "PROGRESS.md").exists():shutil.copy2(root / "PROGRESS.md", stage / "PROGRESS.md")for sub in ("results", "figures", "manuscript"):src = root / sub
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Chemistry feature blocks for the tree-head models.
The block is ``[RDKit descriptors (217), cCPP + geometry (16), formulationratios (5), hierarchical fragment physics (6 x 16), helper-lipid physics(3 x 16), whole-lipid physics (16)]``. It deliberately contains **nofingerprints and no experimental context**, because both act as study-identityshortcuts on this benchmark (see ``results/REPORT.md`` section 4)."""
from __future__ import annotations
import numpy as np
from . import data
FRAG_SLOTS = list(data.FRAGMENT_SLOTS)HELPER_SLOTS = ["HL", "CHL", "PEG"]
def chemistry_block(store, idx: np.ndarray) -> np.ndarray: """Return the (len(idx), D) chemistry matrix for the given sample rows.""" idx = np.asarray(idx) n = len(idx) il = store.il_id[idx]
dim = store.frag_phys[FRAG_SLOTS[0]].shape[1] frag = np.zeros((n, len(FRAG_SLOTS) * dim), dtype=np.float32) for k, slot in enumerate(FRAG_SLOTS): tab = store.frag_phys[slot] if len(tab) == 0: continue ids = store.frag_ids[idx, k] ok = ids >= 0 frag[ok, k * dim:(k + 1) * dim] = tab[np.clip(ids[ok], 0, len(tab) - 1)]
helper = np.zeros((n, len(HELPER_SLOTS) * dim), dtype=np.float32) for k, slot in enumerate(HELPER_SLOTS): tab = store.frag_phys[slot] if len(tab) == 0: continue ids = store.helper_ids[idx, k] ok = ids >= 0 helper[ok, k * dim:(k + 1) * dim] = tab[np.clip(ids[ok], 0, len(tab) - 1)]
X = np.concatenate([ store.il_desc[il], store.il_cpp[il], store.ratios[idx], frag, helper, store.il_phys[il], ], axis=1) X = np.nan_to_num(X, nan=0.0, posinf=0.0, neginf=0.0) return np.clip(X, -1e6, 1e6).astype(np.float64)
def chemistry_block_with_ctx(store, idx: np.ndarray) -> np.ndarray: """Same block plus the 109-d experimental context (the identity-shortcut arm).""" return np.concatenate([chemistry_block(store, idx), store.ctx[np.asarray(idx)]], axis=1)PROGRESS.mdAdded+65
code/PROGRESS.mdAdded+65
code/scripts/fewshot.pyAdded+119
code/scripts/fewshot_stack.pyAdded+153
code/scripts/upload_hf.py+3-1
code/src/lnpbench/features.pyAdded+59