File size: 4,622 Bytes
f87a628 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | """External supervision as *features* rather than as pretraining.
A lipid-level model trained on LNP Atlas predicts four absolute properties
(size, PDI, zeta, encapsulation efficiency) for every LNPDB ionisable lipid.
Those predictions are appended to the 398-d identity-free chemistry block and a
random forest is refitted, exactly as in PhysChem-Tree. This separates
"external labels carry information" from "pretrained weights transfer", which
the pretraining experiments conflate.
python scripts/atlas_feature_probe.py --folds 0 --seeds 0
"""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from sklearn.ensemble import RandomForestRegressor
from scipy.stats import spearmanr
from lnpbench import data, paths
from lnpbench.models.backbone import ATOM_DIM, BOND_DIM
from lnpbench.models.blocks import GINEEncoder
from lnpbench.store import FeatureStore
from lnpbench.trainer import build_batch, compute_norm_stats
import torch.nn as nn
ROOT = Path(__file__).resolve().parents[1]
class LipidEncoder(nn.Module):
def __init__(self, desc_dim: int, d_model: int = 192, dual: bool = True, dropout: float = 0.1):
super().__init__()
self.gnn = GINEEncoder(ATOM_DIM, BOND_DIM, d_model, 3, dropout)
self.gnn_prot = GINEEncoder(ATOM_DIM, BOND_DIM, d_model, 3, dropout) if dual else None
self.desc_enc = nn.Sequential(
nn.Linear(desc_dim, 192), nn.SiLU(), nn.Dropout(dropout),
nn.Linear(192, 128), nn.SiLU(),
)
self.head = nn.Sequential(nn.Linear(d_model + 128, 256), nn.SiLU(), nn.Dropout(dropout), nn.Linear(256, 4))
def forward(self, batch):
g = self.gnn(batch["graph"])
if self.gnn_prot is not None:
g = 0.5 * (g + self.gnn_prot(batch["graph"]))
return self.head(torch.cat([g, self.desc_enc(batch["desc"])], dim=-1))
def predict_all(store: FeatureStore, ckpt: str, device, batch: int = 256) -> np.ndarray:
model = LipidEncoder(store.il_desc.shape[1]).to(device)
state = torch.load(ckpt, map_location=device)
own = model.state_dict()
model.load_state_dict({k: v for k, v in state.items() if k in own and own[k].shape == v.shape}, strict=False)
model.eval()
norm = compute_norm_stats(store, np.arange(len(store)))
# one representative row per unique ionisable lipid
first = np.zeros(len(store.il_smiles), dtype=np.int64)
for row, gid in enumerate(store.il_id):
if first[gid] == 0:
first[gid] = row
out = np.zeros((len(store.il_smiles), 4), dtype=np.float32)
with torch.no_grad():
for s in range(0, len(first), batch):
rows = first[s:s + batch]
b = build_batch(store, rows, ["graph", "desc", "cpp"], device, norm)
out[s:s + batch] = model(b).cpu().numpy()
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", default=str(ROOT / "cache" / "atlas_pretrain_lipid.pt"))
ap.add_argument("--folds", nargs="+", type=int, default=[0])
ap.add_argument("--out", default=str(ROOT / "results" / "atlas_feature_probe.csv"))
args = ap.parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
store = FeatureStore()
pred = predict_all(store, args.ckpt, device)
# attach the four predicted properties to every formulation through its lipid
extra = pred[store.il_id]
base = np.load(paths.CACHE_DIR / "schema_blocks.npz", allow_pickle=True)["base"].astype(np.float32)
print("base", base.shape, "extra", extra.shape)
tasks = [t for t in data.load_tasks(paths.CACHE_DIR / "tasks.pkl")
if t.protocol == "external" and int(t.name.split("fold")[-1]) in args.folds]
rows = []
for t in tasks:
for name, X in (("base", base), ("base+atlas", np.concatenate([base, extra], axis=1))):
rf = RandomForestRegressor(n_estimators=400, min_samples_leaf=2, n_jobs=-1, random_state=0)
rf.fit(X[t.train_idx], store.y[t.train_idx])
p = rf.predict(X[t.test_idx])
rows.append({"task": t.name, "study": t.meta.get("study"), "features": name,
"spearman": float(spearmanr(store.y[t.test_idx], p).statistic)})
print(f"{name:12s} {t.name:18s} {rows[-1]['spearman']:.3f}", flush=True)
df = pd.DataFrame(rows)
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
df.to_csv(args.out, index=False)
print(df.groupby("features").spearman.mean().round(4).to_string())
if __name__ == "__main__":
main() |