File size: 14,629 Bytes
63ccb7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""Stacked out-of-fold (OOF) ensemble with nested cross-validation.

The base models are trained on exactly the same five folds (``--split_seed``
fixed), so every sample has one out-of-fold prediction per model.  A per-target
linear blend is then fitted *inside* the loop: for fold ``k`` the weights are
estimated on the other four folds and applied to fold ``k``.  No sample ever
contributes to the weights that predict it, so the reported score is an honest
out-of-sample estimate of the stacked model.

Why stacking: the architectures fail in different places (the physics-informed
Mamba is best at the absolute stress level, the attention hybrids at the curve
shape).  A fixed average cannot exploit that; a fitted blend can.

Usage::

    python -m pimamba.stack --prefix best --models hymba gdn llama pimamba \
        --seeds 0 1 2 --out stack_best
"""
from __future__ import annotations

import argparse
import json
import re
from pathlib import Path
from typing import Dict, Iterable, List, Sequence

import numpy as np
import pandas as pd

from .data import TARGETS, TARGET_KEYS
from .metrics import PRIMARY, _r2, regression_metrics
from .pooled import RUNS, TABLES

TAG_RE = re.compile(r"^(?P<prefix>[a-z0-9]+)_(?P<model>.+)_f(?P<fold>\d+)_s(?P<seed>\d+)$")


# ---------------------------------------------------------------------------
# data assembly
# ---------------------------------------------------------------------------
def collect(prefix: str, models: Sequence[str], seeds: Sequence[int],
            n_folds: int = 5, pmap: Dict[str, str] | None = None,
            smap: Dict[str, Sequence[int]] | None = None
            ) -> Dict[str, Dict[int, np.ndarray]]:
    """Read ``predictions.npz`` for every (model, fold, seed).

    Returns ``{model: {sid: (pred, true, mask)}}`` where each array is
    ``(T, 13)``.  Seeds are averaged *after* inverse normalisation (the stored
    predictions are already in physical units), which is the same operation as
    averaging the sampled curves.
    """
    pmap = pmap or {}
    smap = smap or {}
    acc: Dict[str, Dict[int, List[np.ndarray]]] = {m: {} for m in models}
    for m in models:
        pref = pmap.get(m, prefix)
        for f in range(n_folds):
            for s in smap.get(m, seeds):
                d = RUNS / f"{pref}_{m}_f{f}_s{s}" / "predictions.npz"
                if not d.exists():
                    continue
                z = np.load(d, allow_pickle=True)
                P, Y, M = z["pred"], z["true"], z["mask"]
                sids = np.asarray(z["sids"]).astype(int)
                for i, sid in enumerate(sids):
                    slot = acc[m].setdefault(int(sid), {"p": [], "y": None, "m": None})
                    slot["p"].append(P[i])
                    slot["y"] = Y[i]
                    slot["m"] = M[i]
    out: Dict[str, Dict[int, tuple]] = {}
    for m, per in acc.items():
        out[m] = {sid: (np.mean(v["p"], 0), v["y"], v["m"]) for sid, v in per.items()}
    return out


def fold_of(prefix: str, models: Sequence[str], seeds: Sequence[int],
            n_folds: int = 5, pmap: Dict[str, str] | None = None,
            smap: Dict[str, Sequence[int]] | None = None) -> Dict[int, int]:
    """Recover the fold membership of every sample from the run folders."""
    pmap = pmap or {}
    smap = smap or {}
    fmap: Dict[int, int] = {}
    m = models[0]
    pref = pmap.get(m, prefix)
    for f in range(n_folds):
        d = RUNS / f"{pref}_{m}_f{f}_s{smap.get(m, seeds)[0]}" / "predictions.npz"
        if not d.exists():
            continue
        z = np.load(d, allow_pickle=True)
        for sid in np.asarray(z["sids"]).astype(int):
            fmap[int(sid)] = f
    return fmap


# ---------------------------------------------------------------------------
# blending
# ---------------------------------------------------------------------------
def _fit_weights(X: np.ndarray, y: np.ndarray, ridge: float = 1e-3,
                 nonneg: bool = True) -> tuple:
    """Ridge regression with optional non-negativity on the model weights.

    Returns ``(w, b)`` such that ``pred = X @ w + b``.  Centring removes the
    intercept from the penalty; the solution is obtained with a small
    projected-gradient loop (``nonneg``) or a closed form.
    """
    mu_x, mu_y = X.mean(0), float(y.mean())
    Xc, yc = X - mu_x, y - mu_y
    A = Xc.T @ Xc + ridge * np.eye(X.shape[1])
    b_vec = Xc.T @ yc
    if not nonneg:
        w = np.linalg.solve(A, b_vec)
    else:
        w = np.clip(np.linalg.solve(A, b_vec), 0, None)
        # projected gradient refinement (a few hundred cheap iterations)
        step = 1.0 / (np.linalg.eigvalsh(A).max() + 1e-9)
        for _ in range(400):
            w = np.clip(w - step * (A @ w - b_vec), 0, None)
    b = mu_y - float(mu_x @ w)
    return w, b


def nested_stack(data: Dict[str, Dict[int, tuple]], fmap: Dict[int, int],
                 models: Sequence[str], n_folds: int = 5,
                 ridge: float = 1e-3, nonneg: bool = True):
    """Fit per-target blends in a leave-one-fold-out loop.

    Returns ``(P, Y, M, S, weights)`` with stacked predictions in the same
    (sample, time, target) layout as a single model, plus the per-fold weight
    matrix for inspection.
    """
    sids = sorted(fmap, key=lambda s: (fmap[s], s))
    keep = [s for s in sids if all(s in data[m] for m in models)]
    S = np.asarray(keep, dtype=int)
    shp = data[models[0]][keep[0]][0].shape
    P = np.zeros((len(keep),) + shp, np.float32)
    Y = np.zeros_like(P)
    M = np.zeros_like(P)
    weights = []
    fold_arr = np.array([fmap[s] for s in keep])
    for f in range(n_folds):
        te = fold_arr == f
        tr = ~te
        for i, s in enumerate(keep):
            Y[i] = data[models[0]][s][1]
            M[i] = data[models[0]][s][2]
        for j in range(shp[-1]):
            Xtr, ytr = [], []
            for i in np.where(tr)[0]:
                msk = M[i, :, j] > 0
                if not msk.any():
                    continue
                Xtr.append(np.stack([data[m][keep[i]][0][msk, j] for m in models], -1))
                ytr.append(Y[i, msk, j])
            if not Xtr:
                continue
            Xc = np.concatenate(Xtr, 0)
            yc = np.concatenate(ytr, 0)
            w, b = _fit_weights(Xc, yc, ridge=ridge, nonneg=nonneg)
            for i in np.where(te)[0]:
                msk = M[i, :, j] > 0
                if not msk.any():
                    continue
                Xte = np.stack([data[m][keep[i]][0][msk, j] for m in models], -1)
                P[i, msk, j] = Xte @ w + b
            weights.append({"fold": f, "target": TARGET_KEYS[j],
                            **{f"w_{m}": float(wi) for m, wi in zip(models, w)},
                            "b": float(b)})
    return P, Y, M, S, pd.DataFrame(weights)


def mean_ensemble(data: Dict[str, Dict[int, tuple]], fmap: Dict[int, int],
                  models: Sequence[str]):
    sids = sorted(fmap, key=lambda s: (fmap[s], s))
    keep = [s for s in sids if all(s in data[m] for m in models)]
    S = np.asarray(keep, dtype=int)
    P = np.mean([np.stack([data[m][s][0] for s in keep]) for m in models], 0)
    Y = np.stack([data[models[0]][s][1] for s in keep])
    M = np.stack([data[models[0]][s][2] for s in keep])
    return P, Y, M, S


def greedy_blend(data: Dict[str, Dict[int, tuple]], fmap: Dict[int, int],
                 models: Sequence[str], n_folds: int = 5, iters: int = 15):
    """Caruana-style forward selection with replacement, fitted per fold.

    For every target we start from an empty blend and repeatedly add the model
    that most reduces the squared error on the *training* folds; the final
    prediction on the held-out fold is the average of the selected models
    (a model can be picked several times, which gives it a larger weight).
    Selection uses only training folds, so the score stays out-of-sample.

    Why this instead of ridge: with 26 training trajectories the models are
    strongly correlated, and unconstrained least squares produces unstable,
    sometimes negative weights.  Greedy selection is a coarse but much more
    stable procedure on this sample size.
    """
    sids = sorted(fmap, key=lambda s: (fmap[s], s))
    keep = [s for s in sids if all(s in data[m] for m in models)]
    S = np.asarray(keep, dtype=int)
    shp = data[models[0]][keep[0]][0].shape
    P = np.zeros((len(keep),) + shp, np.float32)
    Y = np.zeros_like(P)
    M = np.zeros_like(P)
    fold_arr = np.array([fmap[s] for s in keep])
    for i, s in enumerate(keep):
        Y[i] = data[models[0]][s][1]
        M[i] = data[models[0]][s][2]
    picks = []
    for f in range(n_folds):
        te = np.where(fold_arr == f)[0]
        tr = np.where(fold_arr != f)[0]
        for j in range(shp[-1]):
            trn = [i for i in tr if (M[i, :, j] > 0).sum() >= 4]
            if not trn:
                continue
            ytr = np.concatenate([Y[i, M[i, :, j] > 0, j] for i in trn])
            Xtr = {m: np.concatenate([data[m][keep[i]][0][M[i, :, j] > 0, j]
                                      for i in trn]) for m in models}
            sel: List[str] = []
            cur = np.zeros_like(ytr)
            for _ in range(iters):
                best = None
                for m in models:
                    trial = (cur * len(sel) + Xtr[m]) / (len(sel) + 1)
                    err = float(np.mean((trial - ytr) ** 2))
                    if best is None or err < best[0]:
                        best = (err, m, trial)
                sel.append(best[1])
                cur = best[2]
            cnt = {m: sel.count(m) / float(len(sel)) for m in models}
            picks.append({"fold": f, "target": TARGET_KEYS[j], **cnt})
            for i in te:
                msk = M[i, :, j] > 0
                if not msk.any():
                    continue
                P[i, msk, j] = sum(cnt[m] * data[m][keep[i]][0][msk, j]
                                   for m in models if cnt[m] > 0)
    return P, Y, M, S, pd.DataFrame(picks)

# ---------------------------------------------------------------------------
# scoring
# ---------------------------------------------------------------------------
def score(P: np.ndarray, Y: np.ndarray, M: np.ndarray, S: np.ndarray) -> Dict:
    pt = regression_metrics(Y.reshape(-1, len(TARGETS)),
                            P.reshape(-1, len(TARGETS)),
                            M.reshape(-1, len(TARGETS)))
    row = {k: (round(pt[k]["r2"], 3) if np.isfinite(pt[k]["r2"]) else np.nan)
           for k in TARGET_KEYS}
    prim = [pt[k]["r2"] for k in PRIMARY if np.isfinite(pt[k]["r2"])]
    row["primary_mean"] = round(float(np.mean(prim)), 3) if prim else np.nan
    j = TARGET_KEYS.index("sigma")
    mm = M[:, :, j] > 0
    yv, pv = Y[:, :, j][mm], P[:, :, j][mm]
    row["sigma_r2"] = round(_r2(yv, pv), 3)
    ys, ps = [], []
    for i in range(len(S)):
        msk = M[i, :, j] > 0
        if msk.sum() < 4:
            continue
        ys.append(Y[i, msk, j] - Y[i, msk, j].mean())
        ps.append(P[i, msk, j] - P[i, msk, j].mean())
    row["shape_r2"] = round(_r2(np.concatenate(ys), np.concatenate(ps)), 3)
    row["n_samples"] = int(len(S))
    return row


def main():
    ap = argparse.ArgumentParser("pimamba.stack")
    ap.add_argument("--prefix", default="best")
    ap.add_argument("--models", nargs="+",
                    default=["hymba", "gdn", "llama", "pimamba"])
    ap.add_argument("--seeds", nargs="+", type=int, default=[0])
    ap.add_argument("--n_folds", type=int, default=5)
    ap.add_argument("--ridge", type=float, default=1e-3)
    ap.add_argument("--allow-negative", action="store_true")
    ap.add_argument("--method", default="greedy",
                    choices=["greedy", "ridge", "mean"],
                    help="greedy = forward selection with replacement "
                         "(stable on small samples); ridge = per-target "
                         "non-negative least squares; mean = equal weights")
    ap.add_argument("--iters", type=int, default=15)
    ap.add_argument("--out", default="stack")
    ap.add_argument("--prefixes", nargs="*", default=[],
                    help="per-model run prefix, e.g. mlp=main pimamba=main")
    ap.add_argument("--seeds_map", nargs="*", default=[],
                    help="per-model seeds, e.g. mlp=0 pimamba=0,1,2")
    a = ap.parse_args()

    pmap = {}
    for kv in a.prefixes:
        k, v = kv.split("=")
        pmap[k] = v
    smap = {}
    for kv in a.seeds_map:
        k, v = kv.split("=")
        smap[k] = [int(x) for x in v.split(",")]

    data = collect(a.prefix, a.models, a.seeds, a.n_folds, pmap, smap)
    fmap = fold_of(a.prefix, a.models, a.seeds, a.n_folds, pmap, smap)
    rows = []
    for m in a.models:
        if not data.get(m):
            continue
        sids = sorted(data[m])
        P = np.stack([data[m][s][0] for s in sids])
        Y = np.stack([data[m][s][1] for s in sids])
        M = np.stack([data[m][s][2] for s in sids])
        rows.append({"model": m, **score(P, Y, M, np.asarray(sids))})
    P, Y, M, S = mean_ensemble(data, fmap, a.models)
    rows.append({"model": "mean-ensemble", **score(P, Y, M, S)})
    if a.method == "mean":
        Ps, Ys, Ms, Ss, W = P, Y, M, S, None
    elif a.method == "greedy":
        Ps, Ys, Ms, Ss, W = greedy_blend(data, fmap, a.models, a.n_folds,
                                         iters=a.iters)
    else:
        Ps, Ys, Ms, Ss, W = nested_stack(data, fmap, a.models, a.n_folds,
                                         ridge=a.ridge,
                                         nonneg=not a.allow_negative)
    rows.append({"model": f"stacked-{a.method}", **score(Ps, Ys, Ms, Ss)})
    df = pd.DataFrame(rows)
    df.to_csv(TABLES / f"tab_{a.out}.csv", index=False)
    if W is not None:
        W.to_csv(TABLES / f"tab_{a.out}_weights.csv", index=False)
        print(df.to_string(index=False))
        print("\nmean weight per model (greedy: selection frequency):")
        wcols = [c for c in W.columns if c not in ("fold", "target")]
        print(W[wcols].mean().round(3).to_string())
    else:
        print(df.to_string(index=False))
    np.savez_compressed(TABLES / f"{a.out}_pred.npz", pred=Ps, true=Ys,
                        mask=Ms, sids=Ss)
    (TABLES / f"{a.out}_meta.json").write_text(json.dumps(
        {"models": a.models, "seeds": a.seeds, "prefixes": pmap,
         "seeds_map": smap, "method": a.method, "ridge": a.ridge,
         "nonneg": not a.allow_negative}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()