File size: 4,540 Bytes
2eb3475
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""MWP — MLP-Write Topology (admissible cross-layer on MLP substrate).

HalluZig lists "blind to MLP layer failures" as an explicit limitation
of attention-only methods. MWP addresses this. For each layer:
  m_ell^t in R^D  is the MLP block's write to the residual stream at
                  token t (read from ForwardCache.mlp_out).

Per layer we build a sparse top-k cosine-similarity graph among the T
MLP-write vectors, then apply ZAP-style zigzag (#CC, #cycles,
shared-edge, Jaccard, cumulative) over the depth sequence.

Per-sample features: same 21-scalar structure as ZAP, computed on the
MLP-write graph sequence instead of the attention graph sequence.

Admissible: pure MLP-output geometry, no W_cls, no softmax outputs.
Different substrate from ZAP (MLP writes vs attention edges).
"""
from __future__ import annotations
import numpy as np


def _columns():
    cols = []
    for name in ("cc", "cyc"):
        for stat in ("mean", "std", "max", "argmax", "late", "early"):
            cols.append(f"mwp_{name}_{stat}")
    for name in ("shared", "jacc"):
        for stat in ("mean", "std", "min", "argmin"):
            cols.append(f"mwp_{name}_{stat}")
    cols.append("mwp_cum_shared_ratio")
    return cols


COLUMNS = _columns()
DIM = len(COLUMNS)


def _connected_components(edges_set, V):
    parent = list(range(V))
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    def union(x, y):
        rx, ry = find(x), find(y)
        if rx != ry: parent[rx] = ry
    for (u, v) in edges_set: union(u, v)
    return len({find(i) for i in range(V)})


def extract_mwp(model, input_ids, attention_mask, cache, pred_label=None):
    """Return (features (B, DIM), columns).

    Reads cache.mlp_out: list of L tensors of shape (B, T, D).
    """
    B = input_ids.shape[0]
    if not getattr(cache, "mlp_out", None):
        return np.zeros((B, DIM), dtype=np.float32), COLUMNS
    L = len(cache.mlp_out)
    feats = np.zeros((B, DIM), dtype=np.float32)

    for b in range(B):
        T_b = int(attention_mask[b].sum().item())
        T_max = cache.mlp_out[0].shape[1]
        T = max(min(T_b, T_max), 3)

        cc = np.zeros(L, dtype=np.float32)
        cyc = np.zeros(L, dtype=np.float32)
        edges_per_layer = []
        for l in range(L):
            M = cache.mlp_out[l][b, :T].detach().float().cpu().numpy()  # (T, D)
            norms = np.linalg.norm(M, axis=-1, keepdims=True)
            U = M / np.maximum(norms, 1e-9)
            sim = U @ U.T
            np.fill_diagonal(sim, 0.0)
            iu = np.triu_indices(T, k=1)
            w = sim[iu]
            if w.size == 0:
                edges_per_layer.append(set())
                cc[l] = T; cyc[l] = 0.0; continue
            k = max(int(0.10 * w.size), 1)
            thr = np.partition(w, -k)[-k]
            mask = w >= thr
            us = iu[0][mask].tolist()
            vs = iu[1][mask].tolist()
            es = {(min(u, v), max(u, v)) for u, v in zip(us, vs)}
            cc_l = _connected_components(es, T)
            cc[l] = cc_l; cyc[l] = len(es) - T + cc_l
            edges_per_layer.append(es)

        shared = np.zeros(max(L - 1, 1), dtype=np.float32)
        jacc = np.zeros(max(L - 1, 1), dtype=np.float32)
        for l in range(L - 1):
            a = edges_per_layer[l]; b_ = edges_per_layer[l + 1]
            inter = len(a & b_); union = len(a | b_)
            shared[l] = inter / max(union, 1); jacc[l] = inter / max(union, 1)
        cum_inter = set.intersection(*edges_per_layer) if all(edges_per_layer) else set()
        cum_union = set.union(*edges_per_layer) if any(edges_per_layer) else set()
        cum_ratio = len(cum_inter) / max(len(cum_union), 1)

        half = L // 2
        idx = 0
        for arr in (cc, cyc):
            feats[b, idx + 0] = float(arr.mean())
            feats[b, idx + 1] = float(arr.std())
            feats[b, idx + 2] = float(arr.max())
            feats[b, idx + 3] = float(np.argmax(arr))
            feats[b, idx + 4] = float(arr[half:].mean())
            feats[b, idx + 5] = float(arr[:half].mean())
            idx += 6
        for arr in (shared, jacc):
            if arr.size == 0: idx += 4; continue
            feats[b, idx + 0] = float(arr.mean())
            feats[b, idx + 1] = float(arr.std())
            feats[b, idx + 2] = float(arr.min())
            feats[b, idx + 3] = float(np.argmin(arr))
            idx += 4
        feats[b, idx] = float(cum_ratio)
    return feats, COLUMNS