eduzrh's picture
sync code
566a5d5 verified
Raw History Blame Contribute Delete
5.27 kB
"""Inference / deployment: run a trained checkpoint on new alloy conditions.
Two use cases
-------------
1. *Re-score* held-out samples with a published checkpoint::
python -m pimamba.predict --run results/runs/main_pimamba_f2_s0
2. *What-if* on new compositions / conditions: give a CSV with the same columns
as ``data/processed/samples_meta.csv`` (one row per condition)::
python -m pimamba.predict --run results/runs/main_pimamba_f0_s0 \
--meta my_alloys.csv --out my_preds.csv
Only the *static* columns are used for a new sample; the strain grid is
synthesised (0 -> eps_max), because the dynamic input channels depend only on
strain, strain rate, T0 and load mode. Every column of ``samples_meta.csv``
must be present (missing optional ones may be left empty / NaN).
Output: long-format CSV with ``sample_id, strain, <13 targets>``.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import numpy as np
import pandas as pd
from .data import (PROC, TARGETS, Normalizer, PackedDataset, build_static_frame,
collate)
from .models import build_model
ROOT = Path(__file__).resolve().parents[2]
def synth_traj(sids, n_points: int = 401, eps_max: float = 0.2) -> pd.DataFrame:
"""Strain grid with all targets missing -> the loss mask is all-zero."""
eps = np.linspace(0.0, eps_max, n_points)
frames = []
for s in sids:
d = {"sample_id": int(s), "strain": eps}
for t in TARGETS:
d[t.name] = np.nan
frames.append(pd.DataFrame(d))
return pd.concat(frames, ignore_index=True)
def load_run(run_dir: Path, device="cpu"):
import torch
ck = torch.load(run_dir / "model.pt", map_location=device, weights_only=False)
meta = json.loads((run_dir / "metrics.json").read_text())
cfg = ck["cfg"]
model = build_model(cfg["model"], n_static=int(np.sum(ck["keep_mask"])),
n_out=len(TARGETS), d_model=cfg["d_model"],
n_layers=cfg["n_layers"], d_state=cfg["d_state"],
dropout=cfg["dropout"], coupling=cfg["coupling"]).to(device)
model.load_state_dict(ck["state"])
model.eval()
return model, cfg, meta, ck
def predict(run_dir: Path, meta: pd.DataFrame, sids, n_points: int = 401,
eps_max: float = 0.2, device="cpu") -> pd.DataFrame:
import torch
model, cfg, run_meta, ck = load_run(run_dir, device)
names = ck["names"]
km = np.asarray(ck["keep_mask"], dtype=bool)
kinds = build_static_frame(meta)[2]
norm = Normalizer.from_json(run_meta["normalizer"])
mtab = meta.reset_index(drop=True)
traj = synth_traj(sids, n_points, eps_max)
ds = PackedDataset(sids, mtab, traj, norm, names, kinds, km)
dl = torch.utils.data.DataLoader(ds, batch_size=8, shuffle=False,
collate_fn=collate)
preds, used = [], []
with torch.no_grad():
for st, x, _Y, _M, sid in dl:
out = model(st.to(device), x.to(device))
preds.append(out["pred"].cpu().numpy())
used.extend([int(v) for v in sid])
raw = norm.inverse_targets(np.concatenate(preds, 0)) # (N, T, 13)
eps = np.linspace(0.0, eps_max, n_points)
frames = []
for i, s in enumerate(used):
d = {"sample_id": s, "strain": eps}
for k, t in enumerate(TARGETS):
d[t.name] = raw[i, :, k]
frames.append(pd.DataFrame(d))
return pd.concat(frames, ignore_index=True)
def main():
ap = argparse.ArgumentParser("pimamba.predict")
ap.add_argument("--run", default="results/runs/main_pimamba_f2_s0",
help="run directory containing model.pt + metrics.json")
ap.add_argument("--meta", default=None,
help="CSV of new samples (same columns as samples_meta.csv)")
ap.add_argument("--sids", default=None,
help="comma separated sample_ids of data/processed/samples_meta.csv")
ap.add_argument("--n-points", type=int, default=401)
ap.add_argument("--eps-max", type=float, default=0.2)
ap.add_argument("--out", default="predictions.csv")
ap.add_argument("--device", default="cpu")
a = ap.parse_args()
run_dir = Path(a.run)
if not run_dir.is_absolute():
run_dir = ROOT / run_dir
run_meta = json.loads((run_dir / "metrics.json").read_text())
if a.meta:
meta = pd.read_csv(a.meta)
else:
meta = pd.read_csv(PROC / "samples_meta.csv")
if a.sids:
sids = [int(s) for s in a.sids.split(",") if s.strip()]
elif a.meta:
# a new alloy table: predict every row it contains
sids = [int(s) for s in meta.sample_id]
else:
sids = [int(s) for s in run_meta["test_ids"]]
missing = set(sids) - set(meta.sample_id.astype(int))
if missing:
raise SystemExit(f"sample_id not found in meta table: {sorted(missing)}")
df = predict(run_dir, meta, sids, a.n_points, a.eps_max, a.device)
df.to_csv(a.out, index=False)
print(f"wrote {a.out}: {df.shape[0]} rows x {df.shape[1]} cols "
f"({len(sids)} samples, {a.n_points} strain points)")
print(df.head(3).to_string(index=False))
if __name__ == "__main__":
main()