paper_extraction / src /forward_cache.py
zaaabik's picture
Add files using upload-large-folder tool
2eb3475 verified
Raw
History Blame Contribute Delete
8.59 kB
"""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