File size: 8,591 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 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 | """Forward-pass cache shared by all cross-interaction features.
A single forward pass populates ``ForwardCache``; subsequent features read
from it without re-running the model. Captures:
- hidden_states[l] for l in 0..L (L+1 tensors, pre-LN residual)
- ln_inputs[l] for l in 0..L-1 (input to attention LayerNorm at layer l)
- attn_weights[l] for l in 0..L-1 (B, H, T, T)
- attn_outputs[l] for l in 0..L-1 (B, T, H*Dh) raw before W_O
- mlp_pre_act[l] for l in 0..L-1 (B, T, 4*D) W_up @ LN(h)
- mlp_post_act[l] for l in 0..L-1 (B, T, 4*D) activation
- mlp_out[l] for l in 0..L-1 (B, T, D) W_down @ post_act
- head_writes[l] for l in 0..L-1 (B, H, T, D) per-head contribution after W_O
- logits (B, C)
Compatible with HuggingFace RoBERTa / ELECTRA encoder layouts:
model.encoder.layer[l].attention.self
model.encoder.layer[l].attention.output.dense (W_O)
model.encoder.layer[l].attention.output.LayerNorm (post-attn LN)
model.encoder.layer[l].intermediate.dense (W_up)
model.encoder.layer[l].intermediate.intermediate_act_fn
model.encoder.layer[l].output.dense (W_down)
model.encoder.layer[l].output.LayerNorm (post-MLP LN)
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Optional
import torch
import torch.nn as nn
@dataclass
class ForwardCache:
"""Container for activations captured during a single forward pass."""
hidden_states: List[torch.Tensor] = field(default_factory=list)
ln_inputs: List[torch.Tensor] = field(default_factory=list)
attn_weights: List[torch.Tensor] = field(default_factory=list)
attn_outputs: List[torch.Tensor] = field(default_factory=list)
mlp_pre_act: List[torch.Tensor] = field(default_factory=list)
mlp_post_act: List[torch.Tensor] = field(default_factory=list)
mlp_out: List[torch.Tensor] = field(default_factory=list)
head_writes: List[torch.Tensor] = field(default_factory=list)
logits: Optional[torch.Tensor] = None
# Per-layer LN params (gain/bias) — useful for LN-decomposition (LGAP)
ln_gain: List[torch.Tensor] = field(default_factory=list)
ln_bias: List[torch.Tensor] = field(default_factory=list)
def _find_encoder_layers(model: nn.Module) -> List[nn.Module]:
"""Locate the transformer encoder layer list for RoBERTa / ELECTRA."""
if hasattr(model, "roberta"):
return model.roberta.encoder.layer
if hasattr(model, "electra"):
return model.electra.encoder.layer
if hasattr(model, "encoder") and hasattr(model.encoder, "layer"):
return model.encoder.layer
raise ValueError(f"Could not locate encoder layers in {type(model).__name__}")
def _attn_layout(layer: nn.Module):
"""Return (attention_self, attention_output_dense, attention_output_LN)."""
return (layer.attention.self,
layer.attention.output.dense,
layer.attention.output.LayerNorm)
def _mlp_layout(layer: nn.Module):
"""Return (intermediate.dense, intermediate.intermediate_act_fn,
output.dense, output.LayerNorm)."""
return (layer.intermediate.dense,
layer.intermediate.intermediate_act_fn,
layer.output.dense,
layer.output.LayerNorm)
@torch.no_grad()
def run_with_hooks(model: nn.Module,
input_ids: torch.Tensor,
attention_mask: torch.Tensor) -> ForwardCache:
"""Run a single forward pass, capturing activations into ForwardCache.
The model is put in eval mode; gradients are disabled.
"""
cache = ForwardCache()
layers = _find_encoder_layers(model)
L = len(layers)
H = layers[0].attention.self.num_attention_heads
Dh = layers[0].attention.self.attention_head_size
handles = []
# ---- Per-layer hooks --------------------------------------------------
def make_attn_inp_hook(idx):
def hook(module, inputs, output):
# input[0] to attention.self is the post-LN normalised hidden state
x = inputs[0].detach()
while len(cache.ln_inputs) <= idx: cache.ln_inputs.append(None)
cache.ln_inputs[idx] = x
return hook
def make_attn_self_hook(idx):
def hook(module, inputs, output):
# output: (context_layer, [attention_probs]) or context_layer
if isinstance(output, tuple):
ctx = output[0]
# attention_probs are returned when output_attentions=True
if len(output) > 1 and isinstance(output[1], torch.Tensor):
while len(cache.attn_weights) <= idx: cache.attn_weights.append(None)
cache.attn_weights[idx] = output[1].detach()
else:
ctx = output
# ctx shape: (B, T, H*Dh)
while len(cache.attn_outputs) <= idx: cache.attn_outputs.append(None)
cache.attn_outputs[idx] = ctx.detach()
return hook
def make_int_hook(idx):
def hook(module, inputs, output):
# intermediate.dense output = W_up @ LN(h); pre activation
while len(cache.mlp_pre_act) <= idx: cache.mlp_pre_act.append(None)
cache.mlp_pre_act[idx] = output.detach()
return hook
def make_act_hook(idx):
def hook(module, inputs, output):
while len(cache.mlp_post_act) <= idx: cache.mlp_post_act.append(None)
cache.mlp_post_act[idx] = output.detach()
return hook
def make_outdense_hook(idx):
def hook(module, inputs, output):
# output.dense projects post_act -> D
while len(cache.mlp_out) <= idx: cache.mlp_out.append(None)
cache.mlp_out[idx] = output.detach()
return hook
def make_post_attn_ln_hook(idx):
def hook(module, inputs, output):
# Capture the LayerNorm gain/bias and the input
gain = module.weight.detach()
bias = module.bias.detach()
while len(cache.ln_gain) <= idx: cache.ln_gain.append(None)
while len(cache.ln_bias) <= idx: cache.ln_bias.append(None)
cache.ln_gain[idx] = gain
cache.ln_bias[idx] = bias
return hook
for l, layer in enumerate(layers):
attn_self, attn_dense, attn_LN = _attn_layout(layer)
int_dense, act_fn, out_dense, out_LN = _mlp_layout(layer)
handles.append(attn_self.register_forward_hook(make_attn_inp_hook(l)))
handles.append(attn_self.register_forward_hook(make_attn_self_hook(l)))
handles.append(int_dense.register_forward_hook(make_int_hook(l)))
handles.append(act_fn.register_forward_hook(make_act_hook(l)))
handles.append(out_dense.register_forward_hook(make_outdense_hook(l)))
handles.append(attn_LN.register_forward_hook(make_post_attn_ln_hook(l)))
try:
model.eval()
out = model(input_ids=input_ids,
attention_mask=attention_mask,
output_hidden_states=True,
output_attentions=True,
return_dict=True)
cache.hidden_states = [h.detach() for h in out.hidden_states]
# Some HF heads return attentions even when not hooked
if hasattr(out, "attentions") and out.attentions is not None and not cache.attn_weights:
cache.attn_weights = [a.detach() for a in out.attentions]
cache.logits = out.logits.detach()
finally:
for h in handles:
h.remove()
# ---- Derived: head_writes -------------------------------------------
# head_writes[l][b, h, t, :] = W_O_slice_h @ attn_outputs[l][b, t, h*Dh:(h+1)*Dh]
for l, layer in enumerate(layers):
attn_out = cache.attn_outputs[l] # (B, T, H*Dh)
_, attn_dense, _ = _attn_layout(layer)
W_O = attn_dense.weight.detach() # (D, H*Dh)
b_O = attn_dense.bias.detach() if attn_dense.bias is not None else None
B, T, _ = attn_out.shape
D = W_O.shape[0]
attn_h = attn_out.view(B, T, H, Dh) # (B, T, H, Dh)
W_h = W_O.view(D, H, Dh).permute(1, 0, 2) # (H, D, Dh)
# head_writes[b, h, t, :] = sum_d (attn_h[b, t, h, d] * W_h[h, :, d])
# = einsum("bthd, hpd -> bhtp", attn_h, W_h)
hw = torch.einsum("bthd, hpd -> bhtp", attn_h, W_h) # (B, H, T, D)
cache.head_writes.append(hw)
return cache
|