File size: 6,429 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
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
"""EAPT — Edge-Attribution-Patching Topology (Phase 4, idx 11).

Simplified port of EAP-IG (Hanna et al. COLM 2024). Instead of patching
arbitrary edges between MLPs/attention heads at activation-tensor
granularity (which requires a full circuit tracer), we treat each
attention head ``(l, h)`` as a node and score its causal contribution
to the predicted class via integrated-gradients on the attention output:

  score(l, h) = ∫_0^1  (clean − corrupt)_{l,h} · ∂L/∂(activation)_{l,h}  dα

where ``corrupt`` is a per-token-mean baseline. We approximate the
integral with K_STEPS = 4 Riemann steps. Top-TOP_EDGES = 144 head-scores
define a similarity graph; we run Ripser persistence on it plus a small
set of spectral / SCC scalars.

Output dim = 18 + 5 = 23.
"""
from __future__ import annotations

import numpy as np
import torch
import torch.nn.functional as F

from .persistence_summary import ripser_summary_from_distance, column_names as pcol


K_STEPS = 4
L = 12
H = 12


def _columns():
    cols = list(pcol("eapt_pers"))
    cols.extend(["eapt_spec_rad", "eapt_lap_eig1", "eapt_scc_n",
                  "eapt_top10_sum", "eapt_top10_std"])
    return cols


COLUMNS = _columns()
DIM = len(COLUMNS)


def _attention_modules(model):
    if hasattr(model, "roberta"):
        return [l.attention.output.dense for l in model.roberta.encoder.layer]
    if hasattr(model, "electra"):
        return [l.attention.output.dense for l in model.electra.encoder.layer]
    return [l.attention.output.dense for l in model.encoder.layer]


def extract_eapt(model, input_ids, attention_mask, cache, pred_label=None):
    """Return (features (B, 23), columns)."""
    B = input_ids.shape[0]
    feats = np.zeros((B, DIM), dtype=np.float32)
    if pred_label is None:
        with torch.no_grad():
            pred_label = model(input_ids=input_ids, attention_mask=attention_mask).logits.argmax(dim=-1)

    attn_dense_modules = _attention_modules(model)

    for b in range(B):
        ids = input_ids[b:b + 1]
        att = attention_mask[b:b + 1]
        tgt = pred_label[b:b + 1]
        # Clean activation outputs of attention.output.dense (per layer)
        clean_acts = {}
        handles = []
        def make_clean_hook(idx):
            def fn(mod, inputs, output):
                clean_acts[idx] = output.detach().clone()
            return fn
        for l, m in enumerate(attn_dense_modules):
            handles.append(m.register_forward_hook(make_clean_hook(l)))
        with torch.no_grad():
            model(input_ids=ids, attention_mask=att)
        for h in handles: h.remove()

        # Corrupt activation: per-token mean across batch position (here B=1 so just mean across tokens)
        corrupt_acts = {l: clean_acts[l].mean(dim=1, keepdim=True).expand_as(clean_acts[l])
                          for l in clean_acts}

        # IG: K_STEPS Riemann steps, accumulate (clean - corrupt) * grad
        edge_score = np.zeros((L, H), dtype=np.float32)
        head_dim = model.config.hidden_size // H
        for step in range(K_STEPS):
            alpha = (step + 0.5) / K_STEPS
            mix = {l: alpha * clean_acts[l] + (1.0 - alpha) * corrupt_acts[l]
                    for l in clean_acts}
            # Replace each layer's attention.output.dense output with mix via hooks
            patch_handles = []
            def make_patch_hook(idx):
                def fn(mod, inputs, output):
                    return mix[idx]
                return fn
            for l, m in enumerate(attn_dense_modules):
                # Make the hook leaf require grad by replacing the output
                mix[l].requires_grad_(True)
                patch_handles.append(m.register_forward_hook(make_patch_hook(l)))
            model.zero_grad(set_to_none=True)
            out = model(input_ids=ids, attention_mask=att)
            loss = F.cross_entropy(out.logits, tgt)
            grads = torch.autograd.grad(loss, [mix[l] for l in range(L)], allow_unused=True)
            for h in patch_handles: h.remove()
            # score(l, h) = sum over tokens, hidden_dim of head h, of (clean - corrupt) * grad
            for l in range(L):
                if grads[l] is None: continue
                delta = clean_acts[l] - corrupt_acts[l]            # (1, T, D)
                contrib = (delta * grads[l]).sum(dim=1)            # (1, D)
                # Project per head
                contrib_h = contrib.view(1, H, head_dim).sum(dim=-1).cpu().numpy()
                edge_score[l] += contrib_h[0] / K_STEPS

        # Top edges → graph
        # Build (L*H) × (L*H) similarity from outer product of head scores
        scores_flat = edge_score.flatten()
        S = np.outer(np.abs(scores_flat), np.abs(scores_flat))
        N = S.shape[0]
        # Persistence on (1 - normalised S) as a distance
        S_n = S / (S.max() + 1e-12)
        Dmat = 1.0 - S_n
        np.fill_diagonal(Dmat, 0.0)
        pers, _ = ripser_summary_from_distance(Dmat, maxdim=1, prefix="eapt_pers")
        feats[b, 0:18] = pers

        # Spectral radius of S
        try:
            ev = np.linalg.eigvalsh(0.5 * (S + S.T))
            spec_rad = float(np.max(np.abs(ev)))
        except np.linalg.LinAlgError:
            spec_rad = 0.0
        feats[b, 18] = spec_rad

        # Top eigenvalue of normalised Laplacian
        Aabs = np.abs(S_n); np.fill_diagonal(Aabs, 0.0)
        d = Aabs.sum(axis=1); d = np.where(d > 0, d, 1.0)
        Dinv = 1.0 / np.sqrt(d)
        Lap = np.eye(N) - (Dinv[:, None] * Aabs * Dinv[None, :])
        try:
            le = np.linalg.eigvalsh(0.5 * (Lap + Lap.T))
            feats[b, 19] = float(np.sort(le)[::-1][0])
        except np.linalg.LinAlgError:
            pass

        # Number of strongly-connected components of |S| > 0.1 quantile threshold
        thr = np.quantile(Aabs[Aabs > 0], 0.5) if (Aabs > 0).any() else 0.0
        Adj = (Aabs > thr).astype(np.int8)
        # SCC via SciPy
        try:
            from scipy.sparse.csgraph import connected_components
            n_scc, _ = connected_components(Adj, directed=False, connection="strong")
            feats[b, 20] = float(n_scc)
        except Exception:
            feats[b, 20] = 0.0

        # Top-10 statistics of |scores_flat|
        top10 = np.sort(np.abs(scores_flat))[::-1][:10]
        feats[b, 21] = float(top10.sum())
        feats[b, 22] = float(top10.std())
    return feats, COLUMNS