anotheruserishere commited on
Commit
3c92965
·
verified ·
1 Parent(s): ad477eb

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. README.md +27 -12
  2. app.py +253 -80
README.md CHANGED
@@ -14,24 +14,39 @@ short_description: Mechanistic probe on Gemma-3-1B-IT
14
 
15
  # Cartogemma
16
 
17
- A faithful Gradio port of `cartographer3.py` / `cartographer_tui.py` against
18
- the Gemma-3 family. Default: **`google/gemma-3-270m-it`** (tiny enough that
19
- full head-scans are near-instant). Swap to `google/gemma-3-1b-it` or
20
- `google/functiongemma-270m-it` via the Model ID box. Four panes:
 
 
 
 
21
 
22
  - **Context** — running token tail.
23
- - **Head Map** — for each layer: per-head pre-stream projection · logit-lens xray ·
24
- per-head delta-v · full-layer delta-v (`L_full`). The layer projection sits as
25
- another column rather than a separate view, as requested.
26
- - **Futures** — top-k next-token branches with deterministic continuations.
27
- - **Sparkline** — rank-of-token scatter across (head × layer).
28
 
29
  REPL-style command bar: `1-N`, `i`, `h * | h L | h L H`, `top`, `rew`, `spark`,
30
  `w`, `l`, `mute`/`unmute`, `muted`, `r`, `s`.
31
 
 
 
 
 
 
 
 
 
 
 
 
32
  ## Setup
33
 
34
- Gemma-3-1B-IT is gated. Set a Space secret named `HF_TOKEN` with a token that
35
- has accepted the model license.
36
 
37
- CPU works for `1B`; GPU (e.g. ZeroGPU / T4) is much snappier for head-scans.
 
 
14
 
15
  # Cartogemma
16
 
17
+ A faithful Gradio port of `cartographer3.py` / `cartographer_tui.py`.
18
+ Default: **`google/gemma-3-270m-it`** (tiny — full head×layer scans are
19
+ near-instant). The architecture is **auto-discovered**, so the Model ID box
20
+ also accepts other decoder LMs: `google/gemma-3-1b-it`, multimodal
21
+ `google/gemma-3-4b-it`, the Gemma-4 family (`google/gemma-4-E2B-it`, …),
22
+ `Qwen/Qwen3-0.6B`, Llama, etc.
23
+
24
+ Four panes:
25
 
26
  - **Context** — running token tail.
27
+ - **Head Map** — for each layer: per-head pre-projection · logit-lens xray ·
28
+ per-head Δ-residual · full-layer Δ-residual (`L_full`).
29
+ - **Branches** — top-k next-token continuations (deterministic rollouts).
30
+ - **Token Rank Trace** — rank of a chosen token across (head × layer).
 
31
 
32
  REPL-style command bar: `1-N`, `i`, `h * | h L | h L H`, `top`, `rew`, `spark`,
33
  `w`, `l`, `mute`/`unmute`, `muted`, `r`, `s`.
34
 
35
+ ## Two tiers of capability
36
+
37
+ - **Tier 1 (any HF decoder LM):** logit-lens, per-layer Δ-residual, branches,
38
+ rank-pick, inject, rewind. Needs only `output_hidden_states` + a final norm +
39
+ an lm_head (or tied embeddings).
40
+ - **Tier 2 (standard MHA/GQA attention):** per-head pre-projection, per-head
41
+ Δ-residual, head muting, token rank trace. Needs an attention `o_proj` whose
42
+ input decomposes as `num_heads × head_dim`. When a model doesn't satisfy this
43
+ (fused QKV, MLA, exotic attention), the UI **degrades to Tier 1** rather than
44
+ crashing.
45
+
46
  ## Setup
47
 
48
+ Most Gemma checkpoints are gated. Set a Space secret named `HF_TOKEN` with a
49
+ token that has accepted the relevant model licenses.
50
 
51
+ Tiny models (270m / E2B) are comfortable on CPU; ZeroGPU / a GPU is much
52
+ snappier, and required in practice for 4B+ and the Gemma-4 family.
app.py CHANGED
@@ -17,9 +17,14 @@ import unicodedata
17
  from datetime import datetime
18
 
19
  import torch
 
20
  import torch.nn.functional as F
21
  import gradio as gr
22
  from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed
 
 
 
 
23
 
24
  # ── Config ────────────────────────────────────────────────────────────────
25
  DEFAULT_MODEL_ID = os.environ.get("CARTOGEMMA_MODEL", "google/gemma-3-270m-it")
@@ -64,6 +69,105 @@ ANSI_RE = re.compile(r"\033\[[0-9;]*m")
64
  def strip_ansi(s: str) -> str:
65
  return ANSI_RE.sub("", s)
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  # ── The Probe (lifted from cartographer3, ANSI removed) ───────────────────
68
  class InteractiveProbe:
69
  def __init__(self, model_id: str = None):
@@ -77,47 +181,99 @@ class InteractiveProbe:
77
  self.tokenizer.pad_token = self.tokenizer.eos_token
78
 
79
  dtype = torch.bfloat16 if DEVICE == "cuda" else torch.float32
80
- self.model = AutoModelForCausalLM.from_pretrained(
81
- model_id,
82
- device_map="auto" if DEVICE == "cuda" else None,
83
- torch_dtype=dtype,
84
- **kw,
85
- )
 
 
 
 
 
 
 
 
 
 
 
 
86
  if DEVICE == "cpu":
87
  self.model = self.model.to(DEVICE)
88
  self.model.eval()
89
 
90
- # Resolve inner stack (Gemma3 text-only: model.model.layers)
91
- inner = self.model.model
92
- # Gemma3ForCausalLM may wrap a language_model; handle both.
93
- if not hasattr(inner, "layers") and hasattr(inner, "language_model"):
94
- inner = inner.language_model
95
- self._inner_model = inner
96
-
97
- cfg = self.model.config
98
- # Gemma3 text-config nests under cfg.text_config sometimes
99
- text_cfg = getattr(cfg, "text_config", cfg)
100
- self.num_layers = getattr(text_cfg, "num_hidden_layers", cfg.num_hidden_layers)
101
- self.num_heads = getattr(text_cfg, "num_attention_heads", cfg.num_attention_heads)
102
- self.num_kv_heads = getattr(text_cfg, "num_key_value_heads", self.num_heads)
103
- hidden_size = getattr(text_cfg, "hidden_size", cfg.hidden_size)
104
- vocab_size = getattr(text_cfg, "vocab_size", cfg.vocab_size)
105
-
106
- if hasattr(text_cfg, "head_dim") and text_cfg.head_dim:
107
- self.head_dim = text_cfg.head_dim
108
  else:
109
- o_proj_in = self._inner_model.layers[0].self_attn.o_proj.weight.shape[1]
110
- self.head_dim = o_proj_in // self.num_heads
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  self.hidden_size = hidden_size
112
- self.vocab_size = vocab_size
113
- print(f"[*] Arch: {self.num_layers}L x {self.num_heads}H (kv={self.num_kv_heads}), "
114
- f"head_dim={self.head_dim}, hidden={hidden_size}, vocab={vocab_size}")
 
 
 
 
 
 
 
 
 
 
115
 
116
  self.history_ids = None
117
  self.full_log = []
118
  self.muted_heads = set()
119
  self._mute_handles = []
120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  def set_seed(self):
122
  set_seed(SEED)
123
 
@@ -139,11 +295,10 @@ class InteractiveProbe:
139
  with torch.no_grad():
140
  outputs = self.model(self.history_ids, output_hidden_states=True)
141
  out = []
142
- final_norm = self._inner_model.norm
143
  for i, layer_state in enumerate(outputs.hidden_states):
144
  last = layer_state[:, -1, :]
145
- normed = final_norm(last)
146
- logits = self.model.lm_head(normed)
147
  tid = torch.argmax(logits, dim=-1).item()
148
  tok = self.tokenizer.decode(tid)
149
  label = "Emb" if i == 0 else f"L{i}"
@@ -206,31 +361,50 @@ class InteractiveProbe:
206
  if target_layers is None: target_layers = list(range(self.num_layers))
207
  if target_heads is None: target_heads = list(range(self.num_heads))
208
 
 
209
  captured = {}
210
  def get_hook(li):
211
  def fn(module, args, output):
212
  captured[li] = args[0].detach()
213
  return fn
214
  handles = []
215
- for li in target_layers:
216
- if 0 <= li < self.num_layers:
217
- h = self._inner_model.layers[li].self_attn.o_proj.register_forward_hook(get_hook(li))
218
- handles.append(h)
 
 
219
  try:
220
  with torch.no_grad():
221
  outputs = self.model(self.history_ids, output_hidden_states=True)
222
  finally:
223
  for h in handles: h.remove()
224
  hs = outputs.hidden_states
225
- final_norm = self._inner_model.norm
226
- lm = self.model.lm_head
 
 
 
 
 
 
227
 
228
  pre_stream, delta_v = {}, {}
 
 
 
 
 
 
 
 
 
 
 
229
  for li in sorted(captured.keys()):
230
  inp = captured[li]
231
- pre_stream[li], delta_v[li] = {}, {}
232
- layer = self._inner_model.layers[li]
233
- wo = layer.self_attn.o_proj.weight
234
  hidden = wo.shape[0]; attn_out = wo.shape[1]
235
  head_dim = attn_out // self.num_heads
236
  b, s, _ = inp.shape
@@ -242,34 +416,14 @@ class InteractiveProbe:
242
  ho = multi[:, :, hi, :]
243
  hw = wv[:, hi, :]
244
  proj = torch.matmul(ho, hw.t())
245
- last = proj[:, -1, :]
246
- with torch.no_grad():
247
- normed = final_norm(last)
248
- logits = lm(normed)
249
- probs = F.softmax(logits, dim=-1)
250
- tp, ti = torch.topk(probs, 3)
251
- pre_stream[li][hi] = [(self.tokenizer.decode(ti[0, k].item()), tp[0, k].item()) for k in range(3)]
252
-
253
- before = hs[li][:, -1, :]; after = hs[li + 1][:, -1, :]
254
- ld = after - before
255
- with torch.no_grad():
256
- normed = final_norm(ld)
257
- logits = lm(normed)
258
- probs = F.softmax(logits, dim=-1)
259
- tp, ti = torch.topk(probs, 3)
260
- delta_v[li]["full"] = [(self.tokenizer.decode(ti[0, k].item()), tp[0, k].item()) for k in range(3)]
261
 
262
  for hi in target_heads:
263
  if not (0 <= hi < self.num_heads): continue
264
  ho = multi[:, :, hi, :]
265
  hw = wv[:, hi, :]
266
  contrib = torch.matmul(ho[:, -1:, :], hw.t())
267
- with torch.no_grad():
268
- normed = final_norm(contrib.squeeze(1))
269
- logits = lm(normed)
270
- probs = F.softmax(logits, dim=-1)
271
- tp, ti = torch.topk(probs, 3)
272
- delta_v[li][hi] = [(self.tokenizer.decode(ti[0, k].item()), tp[0, k].item()) for k in range(3)]
273
  return {"pre_stream": pre_stream, "delta_v": delta_v}
274
 
275
  def _install_mute_hooks(self):
@@ -289,10 +443,13 @@ class InteractiveProbe:
289
  xv[:, :, h, :] = 0.0
290
  return (xv.reshape(x.shape),)
291
  return fn
292
- o_proj = self._inner_model.layers[li].self_attn.o_proj
293
- self._mute_handles.append(o_proj.register_forward_pre_hook(make_hook(heads, hd, nh)))
 
294
 
295
  def mute_head(self, layer, head):
 
 
296
  if not (0 <= layer < self.num_layers): return f"Layer {layer} OOR"
297
  if not (0 <= head < self.num_heads): return f"Head {head} OOR"
298
  key = (layer, head)
@@ -320,6 +477,8 @@ class InteractiveProbe:
320
 
321
  def sparkline_data(self, token_str: str, rank_lo: int = 0, rank_hi: int = None):
322
  if self.history_ids is None: return None
 
 
323
  if token_str.isdigit():
324
  tid = int(token_str); name = self.tokenizer.decode(tid)
325
  else:
@@ -335,18 +494,18 @@ class InteractiveProbe:
335
  return fn
336
  handles = []
337
  for li in range(self.num_layers):
338
- handles.append(self._inner_model.layers[li].self_attn.o_proj.register_forward_hook(get_hook(li)))
 
 
339
  try:
340
  with torch.no_grad():
341
  self.model(self.history_ids)
342
  finally:
343
  for h in handles: h.remove()
344
 
345
- final_norm = self._inner_model.norm
346
  ranks = {}
347
  for li, inp in captured.items():
348
- layer_mod = self._inner_model.layers[li]
349
- wo = layer_mod.self_attn.o_proj.weight
350
  hidden = wo.shape[0]; attn_out = wo.shape[1]
351
  head_dim = attn_out // self.num_heads
352
  multi = inp.view(1, -1, self.num_heads, head_dim)
@@ -356,8 +515,8 @@ class InteractiveProbe:
356
  hw = wv[:, hi, :]
357
  proj = torch.matmul(ho, hw.t())
358
  with torch.no_grad():
359
- normed = final_norm(proj)
360
- logits = self.model.lm_head(normed)
361
  probs = F.softmax(logits, dim=-1).squeeze()
362
  sorted_ids = torch.argsort(probs, descending=True)
363
  rank = (sorted_ids == tid).nonzero(as_tuple=True)[0].item() + 1
@@ -386,7 +545,7 @@ def render_headmap(probe: InteractiveProbe, data: dict, xray: list) -> str:
386
  layers = sorted(pre.keys())
387
  if not layers:
388
  return "<div class='pane-body'><i>Empty scan.</i></div>"
389
- heads = sorted(h for h in pre[layers[0]].keys() if isinstance(h, int))
390
  xray_map = {label: tok for label, tok in xray} if xray else {}
391
 
392
  def cell(tok, prob):
@@ -395,7 +554,7 @@ def render_headmap(probe: InteractiveProbe, data: dict, xray: list) -> str:
395
  return f"<td class='hm-cell' style='color:{c}'>{clean}</td>"
396
 
397
  rows = []
398
- # Header with two banner sections: pre-stream | xray | delta-v
399
  hdr = ["<tr><th class='lay'>Lay</th>"]
400
  for h in heads: hdr.append(f"<th class='ps'>H{h}</th>")
401
  hdr.append("<th class='xr'>Xray</th>")
@@ -405,9 +564,11 @@ def render_headmap(probe: InteractiveProbe, data: dict, xray: list) -> str:
405
  rows.append("".join(hdr))
406
 
407
  sub = ["<tr class='subhdr'><th></th>"]
408
- sub.append(f"<th class='ps' colspan='{len(heads)}'>per-head pre-projection (raw head → norm → lm_head)</th>")
 
409
  sub.append("<th class='xr'>logit lens</th>")
410
- sub.append(f"<th class='dv' colspan='{len(heads)+1}'>Δ-residual (attn+MLP+skip), per head + full layer</th>")
 
411
  sub.append("</tr>")
412
  rows.insert(0, "".join(sub))
413
 
@@ -437,7 +598,11 @@ def render_headmap(probe: InteractiveProbe, data: dict, xray: list) -> str:
437
  r.append("<td class='hm-cell full'>--</td>")
438
  r.append("</tr>")
439
  rows.append("".join(r))
440
- return f"<div class='pane-body scroll'><table class='headmap'>{''.join(rows)}</table></div>"
 
 
 
 
441
 
442
  def render_futures(options: list) -> str:
443
  if not options:
@@ -633,8 +798,14 @@ def handle_command(cmd: str, s: Session, model_id: str, system_prompt: str):
633
  if len(parts) > 1 and ":" in parts[1]:
634
  a, b = parts[1].split(":")
635
  rl, rh = int(a), int(b)
636
- s.spark = s.probe.sparkline_data(tok, rl, rh)
637
- status = f"spark '{tok}' [{rl}:{rh if rh else 'vocab'}]"
 
 
 
 
 
 
638
 
639
  elif lc.startswith("mute ") and not lc.startswith("muted"):
640
  parts = cmd.split()
@@ -788,8 +959,10 @@ HELP = (
788
 
789
  def build_ui():
790
  with gr.Blocks(title="Cartogemma", css=CSS, theme=gr.themes.Base()) as demo:
791
- gr.Markdown("# Cartogemma \n*Mechanistic probe — logit lens · head map · futures · rank sparkline — "
792
- "on the Gemma-3 family.*", elem_id="hdr")
 
 
793
 
794
  session = gr.State(Session())
795
 
 
17
  from datetime import datetime
18
 
19
  import torch
20
+ import torch.nn as nn
21
  import torch.nn.functional as F
22
  import gradio as gr
23
  from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed
24
+ try:
25
+ from transformers import AutoModelForImageTextToText
26
+ except Exception: # older transformers
27
+ AutoModelForImageTextToText = None
28
 
29
  # ── Config ────────────────────────────────────────────────────────────────
30
  DEFAULT_MODEL_ID = os.environ.get("CARTOGEMMA_MODEL", "google/gemma-3-270m-it")
 
69
  def strip_ansi(s: str) -> str:
70
  return ANSI_RE.sub("", s)
71
 
72
+ # ── Architecture resolver ─────────────────────────────────────────────────
73
+ # The probe makes two tiers of assumption about a model:
74
+ # TIER 1 (generic): output_hidden_states + a final norm + an lm_head/tied
75
+ # embedding. Gives logit-lens (xray), per-layer Δ-residual, branches,
76
+ # top-by-rank, inject, rewind. Works on essentially any HF decoder LM.
77
+ # TIER 2 (architecture-specific): attention writes the residual through an
78
+ # o_proj whose INPUT is the concatenation of contiguous per-head blocks
79
+ # (standard MHA/GQA: in_features == num_heads * head_dim). Gives per-head
80
+ # pre-projection, per-head Δ-residual, head muting, token rank trace.
81
+ # We auto-discover both tiers and flip `head_scan_supported` off (degrading to
82
+ # Tier 1) when the Tier-2 assumption doesn't hold (fused QKV, MLA, exotic attn).
83
+
84
+ def _resolve_text_config(cfg):
85
+ """Find the sub-config that actually holds num_hidden_layers, etc.
86
+ Multimodal configs (Gemma3/4, gemma3n) nest the LM under .text_config."""
87
+ if hasattr(cfg, "get_text_config"):
88
+ try:
89
+ tc = cfg.get_text_config()
90
+ if tc is not None and hasattr(tc, "num_hidden_layers"):
91
+ return tc
92
+ except Exception:
93
+ pass
94
+ tc = getattr(cfg, "text_config", None)
95
+ if tc is not None and hasattr(tc, "num_hidden_layers"):
96
+ return tc
97
+ return cfg
98
+
99
+ def _is_decoder(mod):
100
+ layers = getattr(mod, "layers", None)
101
+ if not isinstance(layers, nn.ModuleList) or len(layers) == 0:
102
+ return False
103
+ first = layers[0]
104
+ return any(hasattr(first, a) for a in ("self_attn", "attn", "attention"))
105
+
106
+ _DECODER_PATHS = [
107
+ ("model",), ("model", "language_model"), ("language_model",),
108
+ ("model", "model"), ("model", "language_model", "model"),
109
+ ("transformer",), ("model", "decoder"), ("decoder",),
110
+ ]
111
+
112
+ def _resolve_decoder(model):
113
+ """Locate the module that owns the decoder-block ModuleList (.layers)."""
114
+ for path in _DECODER_PATHS:
115
+ obj = model
116
+ ok = True
117
+ for a in path:
118
+ if hasattr(obj, a):
119
+ obj = getattr(obj, a)
120
+ else:
121
+ ok = False
122
+ break
123
+ if ok and _is_decoder(obj):
124
+ return obj
125
+ # Generic fallback: longest attention-bearing ModuleList in the tree.
126
+ best = None
127
+ for _, mod in model.named_modules():
128
+ if _is_decoder(mod) and (best is None or len(mod.layers) > len(best.layers)):
129
+ best = mod
130
+ if best is not None:
131
+ return best
132
+ raise RuntimeError("Could not locate a decoder layer stack for this model.")
133
+
134
+ def _resolve_final_norm(decoder):
135
+ for a in ("norm", "final_layernorm", "ln_f", "final_norm"):
136
+ n = getattr(decoder, a, None)
137
+ if n is not None:
138
+ return n
139
+ return None
140
+
141
+ def _resolve_lm_head(model):
142
+ for path in (("lm_head",), ("language_model", "lm_head"), ("model", "lm_head")):
143
+ obj = model
144
+ ok = True
145
+ for a in path:
146
+ if hasattr(obj, a):
147
+ obj = getattr(obj, a)
148
+ else:
149
+ ok = False
150
+ break
151
+ if ok and obj is not None and hasattr(obj, "weight"):
152
+ return obj
153
+ return None # caller falls back to tied input embeddings
154
+
155
+ def _resolve_o_proj(layer):
156
+ """The attention output projection whose input is per-head-concatenated."""
157
+ attn = None
158
+ for a in ("self_attn", "attn", "attention"):
159
+ attn = getattr(layer, a, None)
160
+ if attn is not None:
161
+ break
162
+ if attn is None:
163
+ return None
164
+ for a in ("o_proj", "out_proj", "wo", "dense", "c_proj"):
165
+ p = getattr(attn, a, None)
166
+ if p is not None and hasattr(p, "weight"):
167
+ return p
168
+ return None
169
+
170
+
171
  # ── The Probe (lifted from cartographer3, ANSI removed) ───────────────────
172
  class InteractiveProbe:
173
  def __init__(self, model_id: str = None):
 
181
  self.tokenizer.pad_token = self.tokenizer.eos_token
182
 
183
  dtype = torch.bfloat16 if DEVICE == "cuda" else torch.float32
184
+ load_kw = dict(torch_dtype=dtype, **kw)
185
+ if DEVICE == "cuda":
186
+ load_kw["device_map"] = "auto"
187
+ # Try text CausalLM first; fall back to the multimodal head (gemma-3-4b,
188
+ # gemma-4, gemma3n are all image-text-to-text wrappers around a text LM).
189
+ self.model = None
190
+ errs = []
191
+ loaders = [AutoModelForCausalLM]
192
+ if AutoModelForImageTextToText is not None:
193
+ loaders.append(AutoModelForImageTextToText)
194
+ for loader in loaders:
195
+ try:
196
+ self.model = loader.from_pretrained(model_id, **load_kw)
197
+ break
198
+ except Exception as e:
199
+ errs.append(f"{loader.__name__}: {type(e).__name__}: {e}")
200
+ if self.model is None:
201
+ raise RuntimeError("Could not load model with any auto-class:\n" + "\n".join(errs))
202
  if DEVICE == "cpu":
203
  self.model = self.model.to(DEVICE)
204
  self.model.eval()
205
 
206
+ # ── Auto-discover the architecture (see resolver notes above) ──
207
+ self._decoder = _resolve_decoder(self.model)
208
+ self.layers = self._decoder.layers
209
+ self.final_norm = _resolve_final_norm(self._decoder)
210
+ self._lm_head_mod = _resolve_lm_head(self.model)
211
+ if self._lm_head_mod is None:
212
+ emb = self.model.get_input_embeddings()
213
+ self._tied_emb_weight = emb.weight
 
 
 
 
 
 
 
 
 
 
214
  else:
215
+ self._tied_emb_weight = None
216
+
217
+ text_cfg = _resolve_text_config(self.model.config)
218
+ # Trust the actual stack length over config (resolver may pick a sub-stack).
219
+ self.num_layers = len(self.layers)
220
+ self.num_heads = int(getattr(text_cfg, "num_attention_heads", 0)) or 1
221
+ self.num_kv_heads = int(getattr(text_cfg, "num_key_value_heads", self.num_heads))
222
+ hidden_size = int(getattr(text_cfg, "hidden_size", 0)) or 0
223
+ vocab_size = int(getattr(text_cfg, "vocab_size", 0)) or int(getattr(self.model.config, "vocab_size", 0))
224
+ self.vocab_size = vocab_size or self._lm_head_out_features()
225
+
226
+ o0 = _resolve_o_proj(self.layers[0])
227
+ cfg_head_dim = getattr(text_cfg, "head_dim", None)
228
+ if cfg_head_dim:
229
+ self.head_dim = int(cfg_head_dim)
230
+ elif o0 is not None:
231
+ self.head_dim = o0.weight.shape[1] // self.num_heads
232
+ elif hidden_size:
233
+ self.head_dim = hidden_size // self.num_heads
234
+ else:
235
+ self.head_dim = 0
236
  self.hidden_size = hidden_size
237
+
238
+ # Tier-2 (per-head) support: o_proj input must decompose as heads*head_dim.
239
+ self.head_scan_supported = bool(
240
+ o0 is not None
241
+ and self.final_norm is not None
242
+ and self.head_dim
243
+ and o0.weight.shape[1] == self.num_heads * self.head_dim
244
+ )
245
+ self.arch_name = type(self.model).__name__
246
+
247
+ print(f"[*] {self.arch_name}: {self.num_layers}L x {self.num_heads}H "
248
+ f"(kv={self.num_kv_heads}), head_dim={self.head_dim}, hidden={hidden_size}, "
249
+ f"vocab={self.vocab_size}, head_scan={'yes' if self.head_scan_supported else 'NO (Tier-1 only)'}")
250
 
251
  self.history_ids = None
252
  self.full_log = []
253
  self.muted_heads = set()
254
  self._mute_handles = []
255
 
256
+ # ── architecture accessors ──
257
+ def _lm_head_out_features(self):
258
+ if self._lm_head_mod is not None and hasattr(self._lm_head_mod, "weight"):
259
+ return self._lm_head_mod.weight.shape[0]
260
+ if self._tied_emb_weight is not None:
261
+ return self._tied_emb_weight.shape[0]
262
+ return 0
263
+
264
+ def lm_head(self, x):
265
+ """Project hidden state to vocab logits (handles tied embeddings)."""
266
+ if self._lm_head_mod is not None:
267
+ return self._lm_head_mod(x)
268
+ return F.linear(x, self._tied_emb_weight)
269
+
270
+ def norm(self, x):
271
+ """Apply final norm if the model has one, else identity."""
272
+ return self.final_norm(x) if self.final_norm is not None else x
273
+
274
+ def o_proj(self, layer_idx):
275
+ return _resolve_o_proj(self.layers[layer_idx])
276
+
277
  def set_seed(self):
278
  set_seed(SEED)
279
 
 
295
  with torch.no_grad():
296
  outputs = self.model(self.history_ids, output_hidden_states=True)
297
  out = []
 
298
  for i, layer_state in enumerate(outputs.hidden_states):
299
  last = layer_state[:, -1, :]
300
+ normed = self.norm(last)
301
+ logits = self.lm_head(normed)
302
  tid = torch.argmax(logits, dim=-1).item()
303
  tok = self.tokenizer.decode(tid)
304
  label = "Emb" if i == 0 else f"L{i}"
 
361
  if target_layers is None: target_layers = list(range(self.num_layers))
362
  if target_heads is None: target_heads = list(range(self.num_heads))
363
 
364
+ do_heads = self.head_scan_supported # Tier-2 per-head decomposition
365
  captured = {}
366
  def get_hook(li):
367
  def fn(module, args, output):
368
  captured[li] = args[0].detach()
369
  return fn
370
  handles = []
371
+ if do_heads:
372
+ for li in target_layers:
373
+ if 0 <= li < self.num_layers:
374
+ op = self.o_proj(li)
375
+ if op is not None:
376
+ handles.append(op.register_forward_hook(get_hook(li)))
377
  try:
378
  with torch.no_grad():
379
  outputs = self.model(self.history_ids, output_hidden_states=True)
380
  finally:
381
  for h in handles: h.remove()
382
  hs = outputs.hidden_states
383
+
384
+ def top3(vec):
385
+ with torch.no_grad():
386
+ normed = self.norm(vec)
387
+ logits = self.lm_head(normed)
388
+ probs = F.softmax(logits, dim=-1)
389
+ tp, ti = torch.topk(probs, 3)
390
+ return [(self.tokenizer.decode(ti[0, k].item()), tp[0, k].item()) for k in range(3)]
391
 
392
  pre_stream, delta_v = {}, {}
393
+ # Tier-1: per-layer Δ-residual ("full") is always available from hidden states.
394
+ for li in target_layers:
395
+ if not (0 <= li < self.num_layers): continue
396
+ pre_stream[li], delta_v[li] = {}, {}
397
+ before = hs[li][:, -1, :]; after = hs[li + 1][:, -1, :]
398
+ delta_v[li]["full"] = top3(after - before)
399
+
400
+ if not do_heads:
401
+ return {"pre_stream": pre_stream, "delta_v": delta_v}
402
+
403
+ # Tier-2: decompose each head's contribution through o_proj.
404
  for li in sorted(captured.keys()):
405
  inp = captured[li]
406
+ op = self.o_proj(li)
407
+ wo = op.weight
 
408
  hidden = wo.shape[0]; attn_out = wo.shape[1]
409
  head_dim = attn_out // self.num_heads
410
  b, s, _ = inp.shape
 
416
  ho = multi[:, :, hi, :]
417
  hw = wv[:, hi, :]
418
  proj = torch.matmul(ho, hw.t())
419
+ pre_stream[li][hi] = top3(proj[:, -1, :])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
 
421
  for hi in target_heads:
422
  if not (0 <= hi < self.num_heads): continue
423
  ho = multi[:, :, hi, :]
424
  hw = wv[:, hi, :]
425
  contrib = torch.matmul(ho[:, -1:, :], hw.t())
426
+ delta_v[li][hi] = top3(contrib.squeeze(1))
 
 
 
 
 
427
  return {"pre_stream": pre_stream, "delta_v": delta_v}
428
 
429
  def _install_mute_hooks(self):
 
443
  xv[:, :, h, :] = 0.0
444
  return (xv.reshape(x.shape),)
445
  return fn
446
+ op = self.o_proj(li)
447
+ if op is not None:
448
+ self._mute_handles.append(op.register_forward_pre_hook(make_hook(heads, hd, nh)))
449
 
450
  def mute_head(self, layer, head):
451
+ if not self.head_scan_supported:
452
+ return f"head muting unsupported for {self.arch_name} (no per-head o_proj decomposition)"
453
  if not (0 <= layer < self.num_layers): return f"Layer {layer} OOR"
454
  if not (0 <= head < self.num_heads): return f"Head {head} OOR"
455
  key = (layer, head)
 
477
 
478
  def sparkline_data(self, token_str: str, rank_lo: int = 0, rank_hi: int = None):
479
  if self.history_ids is None: return None
480
+ if not self.head_scan_supported:
481
+ return "unsupported"
482
  if token_str.isdigit():
483
  tid = int(token_str); name = self.tokenizer.decode(tid)
484
  else:
 
494
  return fn
495
  handles = []
496
  for li in range(self.num_layers):
497
+ op = self.o_proj(li)
498
+ if op is not None:
499
+ handles.append(op.register_forward_hook(get_hook(li)))
500
  try:
501
  with torch.no_grad():
502
  self.model(self.history_ids)
503
  finally:
504
  for h in handles: h.remove()
505
 
 
506
  ranks = {}
507
  for li, inp in captured.items():
508
+ wo = self.o_proj(li).weight
 
509
  hidden = wo.shape[0]; attn_out = wo.shape[1]
510
  head_dim = attn_out // self.num_heads
511
  multi = inp.view(1, -1, self.num_heads, head_dim)
 
515
  hw = wv[:, hi, :]
516
  proj = torch.matmul(ho, hw.t())
517
  with torch.no_grad():
518
+ normed = self.norm(proj)
519
+ logits = self.lm_head(normed)
520
  probs = F.softmax(logits, dim=-1).squeeze()
521
  sorted_ids = torch.argsort(probs, descending=True)
522
  rank = (sorted_ids == tid).nonzero(as_tuple=True)[0].item() + 1
 
545
  layers = sorted(pre.keys())
546
  if not layers:
547
  return "<div class='pane-body'><i>Empty scan.</i></div>"
548
+ heads = sorted(h for h in pre.get(layers[0], {}).keys() if isinstance(h, int))
549
  xray_map = {label: tok for label, tok in xray} if xray else {}
550
 
551
  def cell(tok, prob):
 
554
  return f"<td class='hm-cell' style='color:{c}'>{clean}</td>"
555
 
556
  rows = []
557
+ # Header: [pre-stream heads] | Xray | [Δ-residual heads] | L_full
558
  hdr = ["<tr><th class='lay'>Lay</th>"]
559
  for h in heads: hdr.append(f"<th class='ps'>H{h}</th>")
560
  hdr.append("<th class='xr'>Xray</th>")
 
564
  rows.append("".join(hdr))
565
 
566
  sub = ["<tr class='subhdr'><th></th>"]
567
+ if heads:
568
+ sub.append(f"<th class='ps' colspan='{len(heads)}'>per-head pre-projection (raw head → norm → lm_head)</th>")
569
  sub.append("<th class='xr'>logit lens</th>")
570
+ sub.append(f"<th class='dv' colspan='{len(heads)+1}'>Δ-residual (attn+MLP+skip), "
571
+ f"{'per head + ' if heads else ''}full layer</th>")
572
  sub.append("</tr>")
573
  rows.insert(0, "".join(sub))
574
 
 
598
  r.append("<td class='hm-cell full'>--</td>")
599
  r.append("</tr>")
600
  rows.append("".join(r))
601
+ note = ""
602
+ if not heads:
603
+ note = ("<div class='dim' style='padding:2px 0'>per-head decomposition unavailable for this "
604
+ "architecture — showing logit-lens + full-layer Δ-residual only (Tier-1)</div>")
605
+ return f"<div class='pane-body scroll'>{note}<table class='headmap'>{''.join(rows)}</table></div>"
606
 
607
  def render_futures(options: list) -> str:
608
  if not options:
 
798
  if len(parts) > 1 and ":" in parts[1]:
799
  a, b = parts[1].split(":")
800
  rl, rh = int(a), int(b)
801
+ sd = s.probe.sparkline_data(tok, rl, rh)
802
+ if sd == "unsupported":
803
+ status = f"token rank trace unsupported for {s.probe.arch_name} (Tier-1 only)"
804
+ elif sd is None:
805
+ status = f"token '{tok}' not found in vocab"
806
+ else:
807
+ s.spark = sd
808
+ status = f"spark '{tok}' [{rl}:{rh if rh else 'vocab'}]"
809
 
810
  elif lc.startswith("mute ") and not lc.startswith("muted"):
811
  parts = cmd.split()
 
959
 
960
  def build_ui():
961
  with gr.Blocks(title="Cartogemma", css=CSS, theme=gr.themes.Base()) as demo:
962
+ gr.Markdown("# Cartogemma \n*Mechanistic probe — logit lens · head map · branches · token rank trace — "
963
+ "on the Gemma family (3 / 3n / 4) and most HF decoder LMs (Qwen, Llama, …). "
964
+ "Architecture is auto-discovered; per-head views degrade gracefully when unavailable.*",
965
+ elem_id="hdr")
966
 
967
  session = gr.State(Session())
968