eduzrh's picture
sync code
773c429 verified
Raw History Blame Contribute Delete
22.3 kB
"""Post-hoc analysis: aggregation tables, figures, and micro->macro sensitivity.
Everything here is CPU-only and reads ``results/runs/<tag>/`` produced by
``pimamba.train``. Used to generate the tables and figures of the report.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Dict, Iterable, List, Optional
import numpy as np
import pandas as pd
ROOT = Path(os.environ.get("PIMAMBA_ROOT")
or Path(__file__).resolve().parents[2])
RUNS = ROOT / "results" / "runs"
FIGS = ROOT / "results" / "figures"
TABLES = ROOT / "results" / "tables"
MODEL_LABEL = {
"mlp": "MLP", "gru": "GRU", "lstm": "LSTM", "transformer": "Transformer",
"mamba": "Mamba (S6)", "mamba2": "Mamba-2", "pimamba": "PI-Mamba",
"pimamba_nocouple": "PI-Mamba w/o coupling",
"pimamba_phys": "PI-Mamba + physics loss",
"pimamba_nogeom": "PI-Mamba w/o geometry",
"pimamba_noflags": "PI-Mamba w/o shape flags",
"pimamba_noensemble": "PI-Mamba w/o ensemble",
"pimamba_noinit": "PI-Mamba w/o initial state",
"pimamba_nonorm": "PI-Mamba w/o normalisation",
"pimamba_phys005": "PI-Mamba + physics loss (0.05)",
# ---- next generation (2024-2026) ----
"llama": "LLaMA-style Transformer",
"xlstm": "xLSTM (mLSTM)",
"gdn": "Gated DeltaNet",
"hymba": "Mamba+Attention hybrid",
"koopman": "Deep Koopman",
"node": "Neural ODE",
"rssm": "RSSM world model",
"flow": "Flow matching (generative)",
"pimamba2": "PI-Mamba v2 (Taylor)",
}
PRIMARY_COLS = ["sigma_r2", "sigma_shape_r2", "macro_r2_primary",
"rho_total_r2", "twin_r2", "xi_FCC_r2", "peak_rel_err"]
def load_summary() -> pd.DataFrame:
df = pd.read_csv(ROOT / "results" / "summary.csv")
return df
def agg(df: pd.DataFrame, by: str, cols: Optional[Iterable[str]] = None) -> pd.DataFrame:
cols = list(cols or PRIMARY_COLS)
g = df.groupby(by)
mean = g[cols].mean()
sd = g[cols].std()
n = g.size().rename("n")
out = mean.copy()
for c in cols:
out[c + "_sd"] = sd[c]
out[c] = out[c].map(lambda v: round(float(v), 3))
out[c + "_sd"] = out[c + "_sd"].map(lambda v: round(float(v), 3))
return out.join(n).reset_index()
def markdown_table(df: pd.DataFrame, cols: List[str], rename: Dict[str, str] = None) -> str:
rename = rename or {}
head = "| " + " | ".join(rename.get(c, c) for c in cols) + " |"
sep = "|" + "|".join(["---"] * len(cols)) + "|"
lines = [head, sep]
for _, r in df.iterrows():
cells = []
for c in cols:
v = r[c]
if isinstance(v, float):
cells.append("nan" if not np.isfinite(v) else f"{v:.3f}")
else:
cells.append(str(v))
lines.append("| " + " | ".join(cells) + " |")
return "\n".join(lines)
def fmt_pm(mean: float, sd: float, nd: int = 3) -> str:
if not np.isfinite(mean):
return "n/a"
if not np.isfinite(sd):
return f"{mean:.{nd}f}"
return f"{mean:.{nd}f} ± {sd:.{nd}f}"
# ---------------------------------------------------------------------------
# figures
# ---------------------------------------------------------------------------
def _plt():
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams.update({"figure.dpi": 150, "font.size": 8,
"axes.spines.top": False, "axes.spines.right": False})
return plt
def fig_model_comparison(df: pd.DataFrame, fname="fig1_model_comparison.png"):
plt = _plt()
sub = df[df.suite == "main"]
order = ["mlp", "gru", "lstm", "transformer", "mamba", "mamba2", "pimamba"]
metrics = [("sigma_r2", "Stress $R^2$"), ("sigma_shape_r2", "Curve-shape $R^2$"),
("rho_total_r2", "Dislocation $R^2$"),
("peak_rel_err", "Peak-stress rel. err. (lower better)")]
fig, axes = plt.subplots(1, 4, figsize=(10, 2.6), sharey=False)
for ax, (col, title) in zip(axes, metrics):
m = [sub[sub.model == k][col].mean() for k in order]
s = [sub[sub.model == k][col].std() for k in order]
colr = ["#b0b0b0"] * 6 + ["#c0392b"]
ax.bar(range(len(order)), m, yerr=s, color=colr, capsize=2,
error_kw={"lw": 0.8})
ax.set_xticks(range(len(order)))
ax.set_xticklabels([MODEL_LABEL[k].replace(" ", "\n") for k in order],
rotation=90, fontsize=6)
ax.set_title(title, fontsize=8)
ax.axhline(0, color="k", lw=0.5)
fig.tight_layout()
FIGS.mkdir(parents=True, exist_ok=True)
fig.savefig(FIGS / fname, bbox_inches="tight")
plt.close(fig)
return FIGS / fname
def fig_curves(tag: str, fname=None, max_samples=6):
"""Predicted vs reference stress-strain and microstructural evolution."""
plt = _plt()
d = np.load(RUNS / tag / "predictions.npz", allow_pickle=True)
pred, true, mask, sids = d["pred"], d["true"], d["mask"], d["sids"]
m = json.loads((RUNS / tag / "metrics.json").read_text())
from .data import TARGET_KEYS
js = TARGET_KEYS.index("sigma")
n = min(max_samples, len(sids))
sel = np.argsort([-np.nanmax(np.abs(true[i, :, js])) for i in range(len(sids))])[:n]
fig, axes = plt.subplots(1, 3, figsize=(9, 2.6))
eps = np.linspace(0, 0.2, true.shape[1])
for i in sel:
mm = mask[i, :, js] > 0
axes[0].plot(eps[mm], true[i, mm, js], color="k", lw=0.8, alpha=0.55)
axes[0].plot(eps[mm], pred[i, mm, js], color="#c0392b", lw=0.8,
ls="--", alpha=0.75)
axes[0].set_xlabel("true strain"); axes[0].set_ylabel("stress (GPa)")
axes[0].set_title("stress-strain", fontsize=7)
from matplotlib.lines import Line2D
axes[0].legend(handles=[Line2D([], [], color="k", lw=0.9, label="MD reference"),
Line2D([], [], color="#c0392b", lw=0.9, ls="--",
label="PI-Mamba")], fontsize=6, frameon=False)
for j, lab, col in ((TARGET_KEYS.index("rho_total"), "dislocation density", "#2c7fb8"),
(TARGET_KEYS.index("twin"), "twin density", "#31a354")):
for i in sel:
mm = mask[i, :, j] > 0
if mm.sum() < 2:
continue
axes[1 if j == TARGET_KEYS.index("rho_total") else 2].plot(
eps[mm], true[i, mm, j], color="k", lw=0.7, alpha=0.45)
axes[1 if j == TARGET_KEYS.index("rho_total") else 2].plot(
eps[mm], pred[i, mm, j], color=col, lw=0.7, ls="--", alpha=0.8)
axes[1].set_xlabel("true strain"); axes[1].set_ylabel(r"$\rho$ ($10^{19}$ m$^{-2}$)")
axes[1].set_title("total dislocation density", fontsize=7)
axes[2].set_xlabel("true strain"); axes[2].set_ylabel(r"$\rho_{twin}$ (nm$^{-1}$)")
axes[2].set_title("twin density", fontsize=7)
fig.tight_layout()
FIGS.mkdir(parents=True, exist_ok=True)
fname = fname or f"fig_curves_{tag}.png"
fig.savefig(FIGS / fname, bbox_inches="tight")
plt.close(fig)
return FIGS / fname# ---------------------------------------------------------------------------
# micro -> macro coupling analysis (step 2, question 2)
# ---------------------------------------------------------------------------
def _load_model(tag: str, device="cpu"):
"""Rebuild a trained model from ``results/runs/<tag>``."""
import torch
from .data import TARGETS
from .models import build_model
d = RUNS / tag
ck = torch.load(d / "model.pt", map_location=device, weights_only=False)
cfg = ck["cfg"]
m = 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)
m.load_state_dict(ck["state"])
m.eval()
meta = json.loads((d / "metrics.json").read_text())
return m, cfg, meta, ck
def coupling_sensitivity(tag: str, channel: str = "rho_total", delta: float = 0.05,
device="cpu") -> Dict[str, float]:
"""Finite-difference counterfactual on the micro -> macro coupling path.
The stress head sees ``[h, W * micro]``; we perturb one micro channel by
``delta`` (in its normalised units) and measure the relative change of the
predicted flow stress, averaged over all evaluated trajectories and strains.
"""
import torch
from .data import PROC
m, cfg, meta, ck = _load_model(tag, device)
if m.micro_proj is None:
return {"error": "model has no coupling path"}
# micro vector layout = [4 phase fractions, 7 dislocation types, twin]
# i.e. the full 13-dim output minus the leading stress channel
from .data import TARGETS as _TG
idx = {t.key: i - 1 for i, t in enumerate(_TG) if i > 0}
ch = idx[channel]
rec = []
def pre_hook(module, args):
x = args[0].clone()
x[..., ch] = x[..., ch] + delta
rec.append(1)
return (x,)
d = np.load(RUNS / tag / "predictions.npz", allow_pickle=True)
# re-run the model on the same test samples
from .data import PackedDataset, Normalizer, build_static_frame, collate
mtab = pd.read_csv(PROC / "samples_meta.csv")
traj = pd.read_csv(PROC / "trajectories.csv")
Xraw, names, kinds = build_static_frame(mtab)
km = np.asarray(ck["keep_mask"], dtype=bool)
keep = [n for n, k in zip(names, km) if k]
norm = Normalizer.from_json(meta["normalizer"])
test_ids = [int(s) for s in meta["test_ids"]]
ds = PackedDataset(test_ids, mtab, traj, norm, names, kinds, km)
dl = torch.utils.data.DataLoader(ds, batch_size=8, shuffle=False, collate_fn=collate)
base, pert = [], []
with torch.no_grad():
for st, x, Y, M, _ in dl:
base.append(m(st, x)["pred"][..., 0].numpy())
h = m.micro_proj.register_forward_pre_hook(pre_hook)
pert.append(m(st, x)["pred"][..., 0].numpy())
h.remove()
b = np.concatenate(base, 0)
p = np.concatenate(pert, 0)
# stress is z-scored (no asinh), so the inverse is a plain affine map
rb = b * norm.tgt_sd[0] + norm.tgt_mu[0]
rp = p * norm.tgt_sd[0] + norm.tgt_mu[0]
rel = (rp - rb) / np.maximum(np.abs(rb), 1e-6)
return {
"tag": tag, "channel": channel, "delta_norm": delta,
"mean_rel_change": float(np.mean(rel)),
"median_abs_rel_change": float(np.median(np.abs(rel))),
"p95_abs_rel_change": float(np.percentile(np.abs(rel), 95)),
"sign_consistency": float(np.mean(np.sign(rel) == np.sign(np.mean(rel)))),
}
def autograd_sensitivity(tag: str, device="cpu") -> pd.DataFrame:
"""d sigma / d (normalised micro channel) via autograd, per strain point."""
import torch
from .data import PROC, PackedDataset, Normalizer, build_static_frame, collate
m, cfg, meta, ck = _load_model(tag, device)
if m.micro_proj is None:
return pd.DataFrame()
mtab = pd.read_csv(PROC / "samples_meta.csv")
traj = pd.read_csv(PROC / "trajectories.csv")
Xraw, names, kinds = build_static_frame(mtab)
km = np.asarray(ck["keep_mask"], dtype=bool)
norm = Normalizer.from_json(meta["normalizer"])
test_ids = [int(s) for s in meta["test_ids"]]
ds = PackedDataset(test_ids, mtab, traj, norm, names, kinds, km)
dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=False, collate_fn=collate)
labels = ["xi_BCC", "xi_FCC", "xi_HCP", "xi_other"] + \
[f"rho_{i}" for i in range(7)] + ["twin"]
rows = []
for st, x, Y, M, sid in dl:
m.zero_grad(set_to_none=True)
# capture the micro vector by hooking micro_proj input
cache = {}
def pre(module, args):
a = args[0].clone().requires_grad_(True)
cache["micro"] = a
return (a,)
h = m.micro_proj.register_forward_pre_hook(pre)
out = m(st, x)
h.remove()
sig = out["pred"][..., 0]
g = torch.autograd.grad(sig.sum(), cache["micro"])[0][0] # (T, n_micro)
arr = g.detach().numpy()
eps = np.linspace(0, 0.2, arr.shape[0])
for k, lab in enumerate(labels):
rows.append(pd.DataFrame({"strain": eps, "channel": lab,
"grad": arr[:, k], "sid": int(sid[0])}))
return pd.concat(rows, ignore_index=True)
def fig_sensitivity(df: pd.DataFrame, fname="fig_coupling_sensitivity.png"):
plt = _plt()
chans = ["xi_BCC", "xi_FCC", "xi_HCP", "rho_total", "twin"]
fig, ax = plt.subplots(figsize=(4.2, 2.6))
for c in chans:
if c not in set(df.channel):
continue
g = df[df.channel == c].groupby("strain").grad
mu, sd = g.mean(), g.std()
ax.plot(mu.index, mu.values, lw=1.0, label=c)
ax.fill_between(mu.index, mu - sd, mu + sd, alpha=0.15, lw=0)
ax.set_xlabel("true strain"); ax.set_ylabel(r"$\partial \sigma/\partial z_{micro}$")
ax.set_title("micro -> macro coupling sensitivity", fontsize=8)
ax.legend(fontsize=6, frameon=False)
ax.axhline(0, color="k", lw=0.4)
fig.tight_layout()
FIGS.mkdir(parents=True, exist_ok=True)
fig.savefig(FIGS / fname, bbox_inches="tight")
plt.close(fig)
return FIGS / fname
def fig_ablation(df: pd.DataFrame, fname="fig4_ablation.png"):
plt = _plt()
sub = df[df.suite == "ablation"]
names = [n for n in sub.variant.unique()]
names.sort(key=lambda n: -sub[sub.variant == n].sigma_r2.mean())
fig, ax = plt.subplots(figsize=(5.2, 2.4))
m = [sub[sub.variant == n]["sigma_r2"].mean() for n in names]
s = [sub[sub.variant == n]["sigma_r2"].std() for n in names]
s = [0.0 if not np.isfinite(v) else v for v in s]
ax.bar(range(len(names)), m, yerr=s, color="#2c7fb8", capsize=2,
error_kw={"lw": 0.8})
ax.set_xticks(range(len(names)))
ax.set_xticklabels([MODEL_LABEL.get(n, n) for n in names], rotation=30,
ha="right", fontsize=6)
ax.set_ylabel("stress $R^2$")
fig.tight_layout()
FIGS.mkdir(parents=True, exist_ok=True)
fig.savefig(FIGS / fname, bbox_inches="tight")
plt.close(fig)
return FIGS / fname
def fig_dataeff(df: pd.DataFrame, fname="fig5_data_efficiency.png"):
plt = _plt()
sub = df[df.suite == "dataeff"].copy()
if not len(sub):
return None
sub["frac"] = sub.variant.str.split("@").str[-1].astype(float)
fig, ax = plt.subplots(figsize=(3.4, 2.4))
for mdl, g in sub.groupby("model"):
a = g.groupby("frac").sigma_r2
ax.errorbar(a.mean().index, a.mean().values, yerr=a.std().values,
marker="o", ms=3, lw=1, capsize=2,
label=MODEL_LABEL.get(mdl, mdl))
ax.set_xlabel("fraction of training set"); ax.set_ylabel("stress $R^2$")
ax.legend(fontsize=6, frameon=False)
fig.tight_layout()
FIGS.mkdir(parents=True, exist_ok=True)
fig.savefig(FIGS / fname, bbox_inches="tight")
plt.close(fig)
return FIGS / fname
def fig_selectivity(tag: str, fname="fig6_selectivity.png", device="cpu"):
"""Visualise the input-dependent step size Delta_t of the S6 blocks.
Delta_t is what makes the SSM *selective*: small Delta -> long memory (elastic
regime), large Delta -> fast forgetting (yielding / dislocation multiplication).
"""
import torch
import torch.nn.functional as F
from .data import PROC, PackedDataset, Normalizer, build_static_frame, collate
plt = _plt()
m, cfg, meta, ck = _load_model(tag, device)
mtab = pd.read_csv(PROC / "samples_meta.csv")
traj = pd.read_csv(PROC / "trajectories.csv")
Xraw, names, kinds = build_static_frame(mtab)
km = np.asarray(ck["keep_mask"], dtype=bool)
norm = Normalizer.from_json(meta["normalizer"])
test_ids = [int(s) for s in meta["test_ids"]]
ds = PackedDataset(test_ids, mtab, traj, norm, names, kinds, km)
dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=False, collate_fn=collate)
blocks = list(getattr(m, "blocks", []))
if not blocks:
return None
caps: Dict[int, List[np.ndarray]] = {i: [] for i in range(len(blocks))}
handles = []
for i, blk in enumerate(blocks):
def mk(i):
def hook(module, inp, out):
caps[i].append(F.softplus(out).detach().mean(-1)[0].numpy())
return hook
handles.append(blk.dt_proj.register_forward_hook(mk(i)))
sig, eps = [], []
with torch.no_grad():
for st, x, Y, M, sid in dl:
m(st, x)
sig.append(Y[0, :, 0].numpy())
eps.append(x[0, :, 0].numpy() * 0.2)
for h in handles:
h.remove()
fig, axes = plt.subplots(1, 2, figsize=(6.4, 2.3))
ax = axes[0]
for i in range(len(blocks)):
d = np.stack(caps[i]) # (N, T)
ax.plot(eps[0], d.mean(0), lw=1.0, label=f"layer {i+1}")
ax.fill_between(eps[0], d.mean(0) - d.std(0), d.mean(0) + d.std(0),
alpha=0.15, lw=0)
ax.set_xlabel("true strain"); ax.set_ylabel(r"$\bar\Delta_t$ (softplus)")
ax.set_title(r"learned step size $\Delta_t$", fontsize=8)
ax.legend(fontsize=6, frameon=False)
ax = axes[1]
D = np.stack(caps[0]) # (N, T) first-layer Delta_t
S_ = np.stack(sig) # (N, T) reference stress
d0 = D.mean(0)
s = S_.mean(0)
dsde = np.abs(np.gradient(s, eps[0]))
ax.scatter(dsde, d0, s=3, alpha=0.4)
ax.set_xlabel(r"$|d\sigma/d\varepsilon|$ (GPa)"); ax.set_ylabel(r"$\bar\Delta_t$")
ax.set_title("selectivity vs. hardening rate", fontsize=8)
r = float(np.corrcoef(dsde, d0)[0, 1])
# per-sample detrending removes the shared strain trend, which would
# otherwise create a spurious correlation between two decaying curves
dw, sw = [], []
for i in range(D.shape[0]):
di = np.gradient(S_[i], eps[0])
dw.append(D[i] - D[i].mean())
sw.append(np.abs(di) - np.abs(di).mean())
r_detr = float(np.corrcoef(np.concatenate(dw), np.concatenate(sw))[0, 1])
ax.text(0.05, 0.88, f"r={r:.2f} (within-sample r={r_detr:.2f})",
transform=ax.transAxes, fontsize=6)
fig.tight_layout()
FIGS.mkdir(parents=True, exist_ok=True)
fig.savefig(FIGS / fname, bbox_inches="tight")
plt.close(fig)
return FIGS / fname, {"r_pooled": float(r), "r_detrended": r_detr}
# ---------------------------------------------------------------------------
# CLI: python -m pimamba.analysis --coupling <tag> [--autograd <tag>] [--selectivity <tag>]
# ---------------------------------------------------------------------------
def main(argv=None):
import argparse
ap = argparse.ArgumentParser("pimamba.analysis")
ap.add_argument("--coupling", metavar="TAG",
help="counterfactual sensitivity on the micro->macro path")
ap.add_argument("--autograd", metavar="TAG",
help="d sigma / d z_micro per strain point (dumps sens.csv)")
ap.add_argument("--selectivity", metavar="TAG",
help="figure of the input-dependent step size Delta_t")
ap.add_argument("--device", default="cpu")
args = ap.parse_args(argv)
if args.coupling:
rows = []
for ch in ["rho_total", "twin", "xi_FCC", "xi_BCC", "xi_HCP"]:
for dv in [0.05, 0.1, 0.2]:
r = coupling_sensitivity(args.coupling, ch, dv, device=args.device)
rows.append(r)
print(r)
df = pd.DataFrame(rows)
TABLES.mkdir(parents=True, exist_ok=True)
df.to_csv(TABLES / "coupling_elasticity.csv", index=False)
print("wrote", TABLES / "coupling_elasticity.csv")
if args.autograd:
df = autograd_sensitivity(args.autograd, device=args.device)
if len(df):
TABLES.mkdir(parents=True, exist_ok=True)
df.to_csv(TABLES / "sens.csv", index=False)
print("wrote", TABLES / "sens.csv", "->", fig_sensitivity(df))
if args.selectivity:
print("wrote", fig_selectivity(args.selectivity, device=args.device))
if __name__ == "__main__":
main()
def fig_next(df: pd.DataFrame, fname: str = "fig_next_comparison.png"):
"""Next-generation backbones vs the best of the first wave."""
plt = _plt()
order = ["pimamba", "mamba", "transformer", "llama", "xlstm", "gdn",
"hymba", "koopman", "node", "rssm", "flow", "pimamba2"]
sub = df[df.suite.isin(["main", "next", "v2"])].copy()
rows = []
for m in order:
suite = "main" if m in ("pimamba", "mamba", "mamba2", "transformer") else None
g = sub[(sub.model == m) & ((sub.suite == suite) if suite else True)]
if m == "pimamba2" and "variant" in g:
# the v2 suite shares the "pimamba2" backbone between three variants
# (plain / peak-loss / no-coupling) -- plot only the plain one.
g = g[g.variant == "pimamba2"]
if not len(g):
continue
rows.append({"model": m, "mu": g.sigma_r2.mean(), "sd": g.sigma_r2.std(),
"shape": g.sigma_shape_r2.mean(),
"params": g.n_params.mean()})
if not rows:
return None
t = pd.DataFrame(rows).sort_values("mu")
fig, ax = plt.subplots(figsize=(4.6, 3.4))
colors = ["C1" if m in ("pimamba", "pimamba2") else
("C2" if m in ("mamba", "mamba2", "transformer") else "C0")
for m in t.model]
ax.barh(np.arange(len(t)), t.mu, xerr=t.sd, color=colors, alpha=0.85,
error_kw=dict(lw=0.8, capsize=2))
ax.scatter(t["shape"], np.arange(len(t)), marker="|", color="k", s=40,
label="shape $R^2$")
ax.set_yticks(np.arange(len(t)))
ax.set_yticklabels([MODEL_LABEL.get(m, m) for m in t.model], fontsize=7)
ax.axvline(0, color="k", lw=0.6)
ax.set_xlabel(r"stress $R^2$ (mean over runs)")
ax.legend(fontsize=6, frameon=False, loc="lower right")
ax.set_title("next-generation backbones", fontsize=8)
fig.tight_layout()
FIGS.mkdir(parents=True, exist_ok=True)
fig.savefig(FIGS / fname, bbox_inches="tight")
plt.close(fig)
return FIGS / fname