jspace-reproduction-qwen2.5-0.5b / jspace_advanced.py
KikoCis's picture
J-space reproduction on Qwen2.5-0.5B: measurements + method + card
3646c00 verified
Raw
History Blame Contribute Delete
7.33 kB
#!/usr/bin/env python3
"""J-SPACE analyzer — advanced (after Anthropic 'A global workspace in language models', Jul 2026).
Beyond the logit-lens primitive. Implements the real machinery to identify & score a model's reasoning
'global workspace', as a DATA-FREE genetic-merge fitness:
1. FUTURE-INFLUENCE JACOBIAN (the actual J-lens signal, not next-token logit-lens):
G_l = d(total future NLL)/d(hidden_l) [seq,hid]. Row i = the direction in which position i's
activation steers ALL future outputs (causal). This is "the pattern that makes the model likely to
say things later" — the workspace read/write signal.
2. J-SPACE SUBSPACE via SVD of G_l per layer:
- energy_conc : fraction of future-influence energy in the top-k singular directions.
- eff_rank : exp(entropy of normalized singular values) — a LOW effective rank = a small,
coherent workspace (<10% signature). Reported as frac = eff_rank/hidden.
- The top singular vectors ARE the J-space directions at that layer.
3. PLANNING via the lens: how EARLY the model resolves future tokens (front-loaded competence),
base=layer1 (skip embeddings). A rich workspace reasons in mid layers, not just at the end.
4. CAUSAL INTERVENTION: project the J-space subspace OUT at a mid layer (hook) and measure the
reasoning-NLL increase vs a random-subspace-of-equal-rank control. If ablating the workspace hurts
reasoning MORE than a random subspace, the identified subspace is causally the reasoning substrate.
5. Composite FITNESS = f(front_load, workspace concentration, causal necessity). All data-free
(fixed reasoning probe set). CPU / float32.
"""
import sys, math, torch
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL = "/Users/kikocisneros/coco_ppl/attn_longctx/model"; DEV = "cpu"
tok = AutoTokenizer.from_pretrained(MODEL)
def load(): return AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32).to(DEV).eval()
PROBES = [
"Q: If a train goes 60 km in 1 hour, how far in 3 hours? 60 times 3 equals",
"Q: Ana has 5 apples, buys 7 more, gives 3 away. 5 plus 7 is 12, minus 3 is",
"Q: A spider has 8 legs. How many legs do 3 spiders have? 8 times 3 is",
"The opposite of hot is cold. The opposite of up is down. The opposite of fast is",
"Paris is to France as Rome is to",
]
# ── hooks to capture per-layer hidden states with grad, and to intervene ──
class Tap:
def __init__(self, model):
self.model = model; self.L = model.config.num_hidden_layers
self.h = {}; self.handles = []; self.intervene = None
def __enter__(self):
for l, lyr in enumerate(self.model.model.layers):
self.handles.append(lyr.register_forward_hook(self._mk(l)))
return self
def _mk(self, l):
def hook(m, i, o):
hs = o[0] if isinstance(o, tuple) else o
if self.intervene and self.intervene[0] == l: # project OUT a subspace at this layer
Q = self.intervene[1] # [hid,k] orthonormal
hs2 = hs - (hs @ Q) @ Q.transpose(-1, -2)
hs = hs2
return (hs2,) + o[1:] if isinstance(o, tuple) else hs2
if hs.requires_grad: # skip under torch.no_grad (reasoning_nll)
hs.retain_grad(); self.h[l] = hs
return hook
def __exit__(self, *a):
for h in self.handles: h.remove()
def influence_jacobian(model, ids):
"""G_l = d(total next-token NLL)/d(hidden_l) for each layer -> {l: [seq,hid]} (future-influence dirs)."""
with Tap(model) as tap:
out = model(ids)
loss = torch.nn.functional.cross_entropy(out.logits[0, :-1], ids[0, 1:], reduction="sum")
loss.backward()
G = {l: tap.h[l].grad[0].detach().clone() for l in range(tap.L) if tap.h[l].grad is not None}
model.zero_grad(set_to_none=True)
return G
def subspace_stats(G_l, k=8):
"""SVD of the future-influence matrix [seq,hid] -> workspace concentration + effective rank + top dirs."""
U, S, Vh = torch.linalg.svd(G_l.float(), full_matrices=False) # V rows = influence directions
s = S / (S.sum() + 1e-9)
energy_topk = s[:k].sum().item()
ent = -(s * (s + 1e-12).log()).sum().item()
eff_rank = math.exp(ent)
return {"energy_topk": energy_topk, "eff_rank_frac": eff_rank / G_l.shape[1],
"dirs": Vh[:k].transpose(0, 1)} # [hid,k] top-k directions
def frontload_and_final(model, ids):
L = model.config.num_hidden_layers; norm, head = model.model.norm, model.lm_head
with torch.no_grad():
hs = model(ids, output_hidden_states=True).hidden_states
tgt = ids[0, 1:]; lp = []
for l in range(L+1):
ll = head(norm(hs[l][0][:-1])).float()
lp.append(torch.log_softmax(ll, -1).gather(1, tgt.unsqueeze(1)).squeeze(1).mean().item())
base, final = lp[1], lp[-1]
c = [max(0., min(1.2, (v - base) / (final - base + 1e-6))) for v in lp]
return sum(c[1:]) / L, final # frontload AUC, final competence
@torch.no_grad()
def reasoning_nll(model, ids, intervene=None):
with Tap(model) as tap:
tap.intervene = intervene
out = model(ids)
return torch.nn.functional.cross_entropy(out.logits[0, :-1], ids[0, 1:]).item()
def causal_necessity(model, ids, layer, k=8):
"""Ablate the J-space subspace at `layer` vs a random subspace of equal rank -> reasoning-NLL delta."""
G = influence_jacobian(model, ids)
if layer not in G: return 0.0
Q = subspace_stats(G[layer], k)["dirs"] # [hid,k] workspace dirs
Qr, _ = torch.linalg.qr(torch.randn_like(Q)) # random orthonormal control
base = reasoning_nll(model, ids)
js = reasoning_nll(model, ids, intervene=(layer, Q))
rnd = reasoning_nll(model, ids, intervene=(layer, Qr))
return (js - base) - (rnd - base) # extra damage from ablating the workspace
def fitness(model, verbose=False):
L = model.config.num_hidden_layers; mid = L // 2
fl, fc, et, er, cn = [], [], [], [], []
for p in PROBES:
ids = tok(p, return_tensors="pt").input_ids.to(DEV)
a, b = frontload_and_final(model, ids); fl.append(a); fc.append(b)
G = influence_jacobian(model, ids)
st = subspace_stats(G[mid]); et.append(st["energy_topk"]); er.append(st["eff_rank_frac"])
cn.append(causal_necessity(model, ids, mid))
r = {"frontload": sum(fl)/len(fl), "final_comp": sum(fc)/len(fc),
"ws_energy_topk": sum(et)/len(et), "ws_effrank_frac": sum(er)/len(er),
"causal_necessity": sum(cn)/len(cn)}
# composite: reward front-loading + a concentrated workspace (high top-k energy, low eff-rank) + causal necessity
r["JSPACE_FITNESS"] = (r["frontload"] + r["ws_energy_topk"] - r["ws_effrank_frac"]
+ 0.1 * r["causal_necessity"] + 0.1 * r["final_comp"])
if verbose:
for k, v in r.items(): print(f" {k:18s} = {v:+.4f}")
return r
if __name__ == "__main__":
print("=== J-SPACE (advanced) on clean 0.5B ==="); fitness(load(), verbose=True)
print("JSPACE_ADV_DONE")