File size: 10,469 Bytes
773c429
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4a865e
773c429
a4a865e
 
 
 
773c429
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""Physical interpretability of the next-generation backbones.

Every architecture is probed on the same held-out trajectories, and each probe
is chosen to expose the *physics* the model claims to represent:

koopman   eigen-spectrum of the linear latent operator -> memory time constants
gdn       norm of the delta-rule fast-weight matrix  -> "memory written at yield"
xlstm     forget-gate value                          -> memory horizon vs strain
node      ||dz/dt|| of the learned vector field       -> where the dynamics change
rssm      prior std of the stochastic latent         -> model uncertainty vs strain
flow      spread of K sampled curves                 -> predictive interval quality

Outputs land in ``results/tables/interpret_*.csv`` and
``results/figures/fig_interpret_*.png``.
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Dict, List

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]
RUNS = ROOT / "results" / "runs"
TABLES = ROOT / "results" / "tables"
FIGS = ROOT / "results" / "figures"
EPS = np.linspace(0.0, 0.2, 401)


def _plt():
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    return plt


def load(tag: str, device="cpu"):
    import torch
    d = RUNS / tag
    ck = torch.load(d / "model.pt", map_location=device, weights_only=False)
    meta = json.loads((d / "metrics.json").read_text())
    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()
    return m, cfg, meta, ck


def _loader(tag, meta, ck, device="cpu", batch=2):
    import torch
    mtab = pd.read_csv(PROC / "samples_meta.csv")
    traj = pd.read_csv(PROC / "trajectories.csv")
    names = ck["names"]
    km = np.asarray(ck["keep_mask"], dtype=bool)
    kinds = build_static_frame(mtab)[2]
    norm = Normalizer.from_json(meta["normalizer"])
    ids = [int(s) for s in meta["test_ids"]]
    ds = PackedDataset(ids, mtab, traj, norm, names, kinds, km)
    dl = torch.utils.data.DataLoader(ds, batch_size=batch, shuffle=False,
                                     collate_fn=collate)
    return dl, norm, ids


def _collect_trace(model, dl, device="cpu", per_sample=False) -> np.ndarray:
    """Run the model with recording enabled; returns (T,) or (T, C) mean trace.

    Each block appends one entry per timestep (a scalar or a tuple of scalars),
    already averaged over the batch.  Entries of the same block therefore stack
    to ``(T, C)``; blocks of one architecture share ``C``.
    """
    import torch
    blocks = list(getattr(model, "blocks", []))
    for b in blocks:
        if hasattr(b, "record"):
            b.record = True
            b.trace = []
    if hasattr(model, "record"):
        model.record = True
        model.trace = []
    rows = []
    with torch.no_grad():
        for st, x, _Y, _M, _s in dl:
            model(st.to(device), x.to(device))
            per = [np.asarray(getattr(b, "trace", [])) for b in blocks
                   if len(getattr(b, "trace", []))]
            if not per and len(getattr(model, "trace", [])):
                # single trace on the model itself (NODE / RSSM)
                per = [np.asarray(model.trace)]
            if per:
                ps = [p if p.ndim >= 2 else p[:, None] for p in per]  # (T, C)
                L = min(p.shape[0] for p in ps)
                rows.append(np.mean(np.stack([p[:L] for p in ps], 0), 0))
            for b in blocks:
                if hasattr(b, "trace"):
                    b.trace = []
            if hasattr(model, "trace"):
                model.trace = []
    for b in blocks:
        if hasattr(b, "record"):
            b.record = False
    if not rows:
        return np.zeros((0, 401))
    return np.mean(np.stack(rows, 0), 0)   # average over batches -> (T,) / (T, C)


# ---------------------------------------------------------------------------
# individual probes
# ---------------------------------------------------------------------------
def koopman_spectrum(tag: str) -> pd.DataFrame:
    m, cfg, meta, ck = load(tag)
    r, th = m.spectrum()
    r = r.detach().numpy()
    th = th.detach().numpy()
    d_eps = 0.2 / 400.0
    tau = -d_eps / np.log(np.clip(r, 1e-6, 1 - 1e-9))     # strain units
    df = pd.DataFrame({"mode": np.arange(len(r)), "radius": r,
                       "angle": th, "tau_strain": tau,
                       "period_strain": 2 * np.pi * d_eps / np.maximum(th, 1e-6)})
    TABLES.mkdir(parents=True, exist_ok=True)
    df.to_csv(TABLES / "interpret_koopman.csv", index=False)
    return df


def trace_probe(tag: str, kind: str) -> pd.DataFrame:
    m, cfg, meta, ck = load(tag)
    dl, norm, ids = _loader(tag, meta, ck)
    tr = _collect_trace(m, dl)
    if tr.size == 0:
        return pd.DataFrame()
    if tr.ndim == 1:
        tr = tr[:, None]
    if kind == "gdn":
        names = ["mem_norm", "decay_alpha", "write_beta"]
    elif kind == "xlstm":
        names = ["mem_norm", "forget_gate"]
    elif kind == "node":
        names = ["dz_dt_norm"]
    elif kind == "rssm":
        names = ["prior_std"]
    else:
        names = [f"c{i}" for i in range(tr.shape[1])]
    names = names[:tr.shape[1]]
    T = tr.shape[0]
    df = pd.DataFrame(tr, columns=names)
    df.insert(0, "strain", np.linspace(0, 0.2, T))
    df.to_csv(TABLES / f"interpret_{kind}.csv", index=False)
    return df


def flow_uncertainty(tag: str, k: int = 16) -> Dict[str, float]:
    import torch
    m, cfg, meta, ck = load(tag)
    dl, norm, ids = _loader(tag, meta, ck, batch=8)
    S, Y, M = [], [], []
    with torch.no_grad():
        for st, x, y, msk, _ in dl:
            z = m.sample(st, x, k=k)          # (k, b, T, 13)
            S.append(z.numpy())
            Y.append(y.numpy())
            M.append(msk.numpy())
    S = np.concatenate(S, 1)                  # (k, N, T, 13)
    Y = np.concatenate(Y, 0)
    M = np.concatenate(M, 0)
    raw = norm.inverse_targets(S)             # (k, N, T, 13)
    raww = norm.inverse_targets(Y)
    mu = raw.mean(0)
    sd = raw.std(0)
    j = 0
    mask = M[..., j] > 0
    if mask.sum() < 10:
        return {}
    lo, hi = mu[..., j] - 1.645 * sd[..., j], mu[..., j] + 1.645 * sd[..., j]
    cov = float(((raww[..., j] >= lo) & (raww[..., j] <= hi))[mask].mean())
    err = np.abs(mu[..., j] - raww[..., j])[mask]
    width = (hi - lo)[mask]
    out = {"coverage90": cov, "mean_width": float(width.mean()),
           "mean_abs_err": float(err.mean()),
           "sharpness_ratio": float(err.mean() / max(width.mean(), 1e-9)),
           "n_samples": int(mask.sum())}
    pd.DataFrame([out]).to_csv(TABLES / "interpret_flow.csv", index=False)
    return out


# ---------------------------------------------------------------------------
# figures
# ---------------------------------------------------------------------------
def fig_memory(traces: Dict[str, pd.DataFrame], fname="fig_interpret_memory.png"):
    plt = _plt()
    panels = [("xlstm", "forget_gate", "xLSTM forget gate $f_t$"),
              ("gdn", "mem_norm", r"Gated DeltaNet $\|S_t\|_F$"),
              ("node", "dz_dt_norm", r"Neural ODE $\|dz/dt\|$"),
              ("rssm", "prior_std", r"RSSM prior std $\sigma_t$")]
    fig, axes = plt.subplots(2, 2, figsize=(7.2, 4.4), sharex=True)
    for ax, (k, col, title) in zip(axes.ravel(), panels):
        df = traces.get(k)
        if df is None or col not in df:
            ax.axis("off")
            continue
        v = df[col].to_numpy(dtype=float)
        eps = df["strain"].to_numpy(dtype=float)
        # plot the raw quantity (each panel has its own units); the title states
        # the elastic (eps<0.02) -> plastic (eps>0.15) means, the same windows
        # used in the text, so figure and table never disagree.
        ax.plot(eps, v, lw=1.2, color="C0")
        ax.set_title(f"{title}\n{v[eps < 0.02].mean():.4g} → {v[eps > 0.15].mean():.4g}",
                     fontsize=7.5)
        ax.axvline(0.02, color="0.6", ls=":", lw=0.8)
        ax.grid(alpha=0.2)
    for ax in axes[-1]:
        ax.set_xlabel("true strain")
    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_koopman(df: pd.DataFrame, fname="fig_interpret_koopman.png"):
    plt = _plt()
    fig, ax = plt.subplots(1, 2, figsize=(6.4, 2.6))
    th = np.linspace(0, 2 * np.pi, 200)
    ax[0].plot(np.cos(th), np.sin(th), color="0.8", lw=0.8)
    ax[0].scatter(df.radius * np.cos(df.angle), df.radius * np.sin(df.angle),
                  c=df.tau_strain, cmap="viridis", s=18)
    ax[0].set_aspect("equal")
    ax[0].set_title("Koopman eigenvalues", fontsize=8)
    ax[1].bar(np.arange(len(df)), df.tau_strain, color="C0")
    ax[1].set_yscale("log")
    ax[1].set_xlabel("mode")
    ax[1].set_ylabel(r"memory time $\tau_\varepsilon$")
    ax[1].set_title("decay time per mode", fontsize=8)
    fig.tight_layout()
    fig.savefig(FIGS / fname, bbox_inches="tight")
    plt.close(fig)
    return FIGS / fname


def main():
    ap = argparse.ArgumentParser("pimamba.interpret")
    ap.add_argument("--koopman", default=None)
    ap.add_argument("--gdn", default=None)
    ap.add_argument("--xlstm", default=None)
    ap.add_argument("--node", default=None)
    ap.add_argument("--rssm", default=None)
    ap.add_argument("--flow", default=None)
    ap.add_argument("--device", default="cpu")
    a = ap.parse_args()

    traces: Dict[str, pd.DataFrame] = {}
    if a.koopman:
        df = koopman_spectrum(a.koopman)
        print(fig_koopman(df))
        print(df.describe().to_string())
    for kind, tag in [("gdn", a.gdn), ("xlstm", a.xlstm), ("node", a.node),
                      ("rssm", a.rssm)]:
        if tag:
            df = trace_probe(tag, kind)
            traces[kind] = df
            print(f"{kind}: {df.shape}")
    if traces:
        print(fig_memory(traces))
    if a.flow:
        print(flow_uncertainty(a.flow))


if __name__ == "__main__":
    main()