senku21x's picture
Dory forward pass, J-lens / R-lens / J++ code, fit records
498b9c9 verified
Raw History Blame Contribute Delete
7.9 kB
"""Jacobian lens (J-lens) for Dory.
The lens of Gurnee et al. 2026 ("Verbalizable Representations Form a Global Workspace in Language Models"):
for a source node v, one d x d matrix
J_v = mean over prompts, mean over source positions s, sum over target positions t >= s of
d final[t] / d h_v[s]
and the readout logits = unembed( N( J_v h ) ). The estimator is the paper's pseudocode: one backward pass
per output dimension with a one-hot injected at every target position, the gradient averaged over source
positions, then over prompts. Here the backward passes are batched (`is_grads_batched`).
Dory specifics.
* The graph is the unrolled one: every firing of a recurrent sublayer is its own source node, for a fixed
number of loops k. A lens is therefore fitted for one k.
* The target is the final residual state (after output sublayer 71), which is what the LM head reads.
Dory has no final norm layer; the state is already unit norm, and `N` above is that same L2 norm.
* Source nodes, in forward order: emb; in.00..in.14; x (the input block's output, i.e. after sublayer 15);
for each loop t: u.t (the loop input N(s_{t-1} + x)), rec.t.16..rec.t.54, s.t (the loop output, i.e.
after sublayer 55); out.56..out.70. Every sublayer output has exactly one node.
"""
from __future__ import annotations
import json
from pathlib import Path
import torch
from safetensors.torch import load_file, save_file
from .model import Dory, justnorm
BINS = ((0, 4), (4, 16), (16, None)) # source-position bins kept separately during the fit
def source_nodes(model: Dory, k: int) -> list[tuple]:
n_in, n_rec, n_out = model.n_in, model.n_rec, model.n_out
nodes = [("emb",)] + [("in", i) for i in range(n_in - 1)] + [("x",)]
for t in range(1, k + 1):
nodes += [("u", t)] + [("rec", t, i) for i in range(n_in, n_in + n_rec - 1)] + [("s", t)]
nodes += [("out", i) for i in range(n_in + n_rec, n_in + n_rec + n_out - 1)]
return nodes
def node_key(node: tuple) -> str:
return ".".join([node[0]] + [f"{v:02d}" if node[0] in ("in", "rec", "out") and j == len(node) - 2 else str(v)
for j, v in enumerate(node[1:])])
def key_node(key: str) -> tuple:
p = key.split(".")
return (p[0], *[int(v) for v in p[1:]])
def run_with_graph(model: Dory, ids: torch.Tensor, k: int, nodes: list[tuple]):
"""Forward pass that keeps the autograd graph from every source node to the final state."""
want, got = set(nodes), {}
def tap(name, h):
if name == ("emb",):
h = h.detach().requires_grad_(True)
got[name] = h
return h
if name in want:
got[name] = h
final = model.forward(ids, n_loops=k, tap=tap)
return final, [got[n] for n in nodes]
def prompt_jacobians(model: Dory, ids: torch.Tensor, k: int, nodes: list[tuple], chunk: int = 256,
bins=BINS, rows: torch.Tensor | None = None):
"""Per-prompt Jacobian sums for one prompt of shape [1, T].
Returns
jsum [n_nodes, n_bins, R, d] sum over source positions in the bin of d(sum_t final[t, r]) / d h[s]
sq [n_nodes, T] squared Frobenius norm of the per-source-position Jacobian (over the R rows)
hsum [n_nodes, n_bins, d] sum of the source states over positions in the bin
`rows` restricts the output dimensions (default: all d).
"""
assert ids.shape[0] == 1
T, d = ids.shape[1], model.cfg["hidden_size"]
rows = torch.arange(d, device=ids.device) if rows is None else rows
bins = [(lo, T if hi is None else hi) for lo, hi in bins]
with torch.enable_grad():
final, srcs = run_with_graph(model, ids, k, nodes)
z = final[0].sum(0) # [d]: summed over target positions
jsum = torch.zeros(len(nodes), len(bins), len(rows), d, device=ids.device)
sq = torch.zeros(len(nodes), T, device=ids.device)
for c0 in range(0, len(rows), chunk):
r = rows[c0 : c0 + chunk]
cot = torch.zeros(len(r), d, device=ids.device)
cot[torch.arange(len(r)), r] = 1.0
grads = torch.autograd.grad(z, srcs, grad_outputs=cot, is_grads_batched=True, retain_graph=True)
for j, g in enumerate(grads): # g: [C, 1, T, d]
g = g[:, 0]
sq[j] += g.pow(2).sum(dim=(0, 2))
for b, (lo, hi) in enumerate(bins):
jsum[j, b, c0 : c0 + len(r)] = g[:, lo:hi].sum(1)
del grads
hsum = torch.stack([torch.stack([h.detach()[0, lo:hi].sum(0) for lo, hi in bins]) for h in srcs])
return jsum, sq, hsum
class JLens:
"""A fitted lens: one d x d matrix per source node, for one loop count."""
def __init__(self, J: dict[str, torch.Tensor], meta: dict, mean_state: dict[str, torch.Tensor] | None = None):
self.J, self.meta, self.mean_state = J, meta, mean_state or {}
@property
def k(self) -> int:
return int(self.meta["n_loops"])
def nodes(self) -> list[tuple]:
return [key_node(k) for k in self.J]
def transport(self, h: torch.Tensor, node: tuple) -> torch.Tensor:
J = self.J[node_key(node)]
return h.float() @ J.to(h.device).float().T
def logits(self, model: Dory, h: torch.Tensor, node: tuple) -> torch.Tensor:
"""Readout: unembed(N(J h)). h: [..., d] state at `node`."""
return model.unembed(justnorm(self.transport(h, node)).to(model.lm_head.weight.dtype))
def save(self, path: str | Path):
tensors = {f"J/{k}": v.contiguous().cpu() for k, v in self.J.items()}
tensors.update({f"mean/{k}": v.contiguous().cpu() for k, v in self.mean_state.items()})
save_file(tensors, str(path), metadata={"meta": json.dumps(self.meta)})
@classmethod
def load(cls, path: str | Path, device="cpu") -> "JLens":
from safetensors import safe_open
with safe_open(str(path), framework="pt") as f:
meta = json.loads(f.metadata()["meta"])
t = load_file(str(path), device=device)
return cls({k[2:]: v for k, v in t.items() if k.startswith("J/")}, meta,
{k[5:]: v for k, v in t.items() if k.startswith("mean/")})
def logit_lens(model: Dory, h: torch.Tensor) -> torch.Tensor:
"""Baseline: the unembedding applied to the state directly (J = identity)."""
return model.unembed(justnorm(h.float()).to(model.lm_head.weight.dtype))
def accumulate_grouped(model: Dory, ids: torch.Tensor, k: int, nodes: list[tuple], group_ids: torch.Tensor,
out: torch.Tensor, chunk: int = 256) -> list[torch.Tensor]:
"""Add one prompt's Jacobian sums into `out` [n_nodes, n_groups, d, d], source positions grouped.
group_ids: [T] long, the group of each source position (-1 = leave the position out). For group g,
out[node, g] += sum over positions s in g of d(sum_t final[t]) / d h_node[s] (rows = output dims).
Returns the source states [T, d] of every node."""
assert ids.shape[0] == 1
d, G = model.cfg["hidden_size"], out.shape[1]
onehot = torch.nn.functional.one_hot(group_ids.clamp(min=0), G).float() * (group_ids >= 0).float()[:, None] # [T, G]
with torch.enable_grad():
final, srcs = run_with_graph(model, ids, k, nodes)
z = final[0].sum(0)
for c0 in range(0, d, chunk):
C = min(chunk, d - c0)
cot = torch.zeros(C, d, device=ids.device)
cot[torch.arange(C), c0 + torch.arange(C)] = 1.0
grads = torch.autograd.grad(z, srcs, grad_outputs=cot, is_grads_batched=True, retain_graph=True)
for j, g in enumerate(grads):
out[j, :, c0 : c0 + C] += torch.einsum("tg,ctd->gcd", onehot, g[:, 0])
del grads
return [h.detach()[0] for h in srcs]