File size: 5,504 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
"""PReP — Perturbation-Robustness Probes (Phase 4, idx 10).

Run K=16 noisy forward passes per sample with Gaussian noise injected
on the input embeddings: e_k = e_0 + σ · N(0, I) where σ = SIGMA_REL ·
‖e_0‖ / √(numel(e_0)). Collect anchor-layer [CLS] hidden states
Z_l = {z_l^(k)}_{k=0}^{15} for l ∈ {0, 4, 8, 12} and summarise:

  per-anchor:
    effective rank of cov(Z_l)          (1)
    mean displacement from clean        (1)
  cross-anchor (4 layer pairs × 18 Ripser scalars):
    persistence on the 16×16 distance matrix between perturbations
    at each anchor pair                  (4 × 18 = 72)

Output dim = 4·2 + 4·18 = 80.

Memory: noise is shared across the batch, so the per-batch cost is
roughly 16 × (one forward). Disables ``torch.no_grad`` is unnecessary —
forwards are pure inference.
"""
from __future__ import annotations

import numpy as np
import torch

from .persistence_summary import ripser_summary_from_distance, column_names as pcol


ANCHORS = [0, 4, 8, 12]
K = 16
SIGMA_REL = 0.05


def _columns():
    cols = []
    for l in ANCHORS:
        cols.append(f"prep_L{l}_effrank")
        cols.append(f"prep_L{l}_displacement")
    for k in range(len(ANCHORS)):
        cols.extend(pcol(f"prep_anchor{ANCHORS[k]}"))
    return cols


COLUMNS = _columns()
DIM = len(COLUMNS)


def _input_embed_module(model):
    if hasattr(model, "roberta"):
        return model.roberta.embeddings
    if hasattr(model, "electra"):
        return model.electra.embeddings
    return model.embeddings


@torch.no_grad()
def _forward_with_embedding_noise(model, ids, att, noise, anchors_set):
    """Single forward with noise added on input embeddings; capture anchor outputs."""
    emb_mod = _input_embed_module(model)
    captured = {}
    handles = []

    def make_hook(l_idx, label):
        def fn(module, inputs, output):
            if isinstance(output, tuple): output = output[0]
            captured[label] = output.detach().clone()
        return fn

    # Intercept the embedding output and add noise
    def emb_post_hook(module, inputs, output):
        return output + noise

    handles.append(emb_mod.register_forward_hook(emb_post_hook))

    # Capture anchor layer outputs (using HF's hidden_states convention)
    # We use the encoder's per-layer hook (covers anchors > 0).
    if hasattr(model, "roberta"):
        encoder_layers = model.roberta.encoder.layer
    elif hasattr(model, "electra"):
        encoder_layers = model.electra.encoder.layer
    else:
        encoder_layers = model.encoder.layer
    for l in anchors_set:
        if l == 0:
            # anchor 0 == embedding output
            handles.append(emb_mod.register_forward_hook(make_hook(l, l)))
        else:
            handles.append(encoder_layers[l - 1].register_forward_hook(make_hook(l, l)))

    try:
        _ = model(input_ids=ids, attention_mask=att, return_dict=True)
    finally:
        for h in handles: h.remove()
    return captured


def extract_prep(model, input_ids, attention_mask, cache, pred_label=None):
    """Return (features (B, 80), columns)."""
    device = input_ids.device
    B = input_ids.shape[0]
    feats = np.zeros((B, DIM), dtype=np.float32)
    emb_mod = _input_embed_module(model)
    # Clean embedding to scale noise
    with torch.no_grad():
        e0 = emb_mod(input_ids)         # (B, T, D)
    sigma = SIGMA_REL * e0.norm() / float(np.sqrt(e0.numel()))

    # Anchors → list of (K+1) (B, T, D) tensors at each anchor
    anchors_set = set(ANCHORS)
    # Clean pass: anchor states
    clean = _forward_with_embedding_noise(model, input_ids, attention_mask,
                                           noise=torch.zeros_like(e0),
                                           anchors_set=anchors_set)

    # Noisy passes
    perturbed = {l: [] for l in ANCHORS}
    for k in range(K):
        noise = sigma * torch.randn_like(e0)
        cap = _forward_with_embedding_noise(model, input_ids, attention_mask,
                                              noise=noise, anchors_set=anchors_set)
        for l in ANCHORS:
            perturbed[l].append(cap[l][:, 0, :].cpu().numpy())   # (B, D)

    # Per-sample features
    for b in range(B):
        for ai, l in enumerate(ANCHORS):
            # Z_l: (K, D)  at sample b
            Z = np.stack([perturbed[l][k][b] for k in range(K)], axis=0)
            clean_b = clean[l][b, 0, :].cpu().numpy()
            # Effective rank of cov(Z)
            Zc = Z - Z.mean(axis=0, keepdims=True)
            cov = Zc.T @ Zc / max(K - 1, 1)
            try:
                sv = np.linalg.svd(cov, compute_uv=False)
                p = sv / (sv.sum() + 1e-12)
                eff_rank = float(np.exp(-(p * np.log(p + 1e-12)).sum()))
            except np.linalg.LinAlgError:
                eff_rank = 0.0
            displacement = float(np.linalg.norm(Z - clean_b[None, :], axis=1).mean())
            feats[b, ai * 2 + 0] = eff_rank
            feats[b, ai * 2 + 1] = displacement

            # Persistence on the K×K distance matrix of perturbations at anchor l
            Zn = Z / (np.linalg.norm(Z, axis=1, keepdims=True) + 1e-12)
            cos = Zn @ Zn.T
            D = 1.0 - cos
            np.fill_diagonal(D, 0.0)
            pers, _ = ripser_summary_from_distance(D, maxdim=1,
                                                      prefix=f"prep_anchor{l}")
            base = len(ANCHORS) * 2 + ai * 18
            feats[b, base : base + 18] = pers
    return feats, COLUMNS