anotheruserishere commited on
Commit
23d9781
·
verified ·
1 Parent(s): 442f33e
README.md CHANGED
@@ -1,13 +1,31 @@
1
- ---
2
- title: Tokescope
3
- emoji: 🐨
4
- colorFrom: green
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 6.16.0
8
- python_version: '3.13'
9
- app_file: app.py
10
- pinned: false
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Tokescope (full)
3
+ emoji: 🔬
4
+ colorFrom: indigo
5
+ colorTo: pink
6
+ sdk: gradio
7
+ app_file: gradio_app.py
8
+ pinned: false
9
+ license: mit
10
+ short_description: Interactive observability for transformer internals
11
+ ---
12
+
13
+ # Tokescope — full build (private)
14
+
15
+ Interactive observability for transformer internals: pick a focus word and a
16
+ control, and watch where the model ranks each — layer by layer — as it writes,
17
+ with rank‑band heatmaps, a per‑layer trace, a latency/closest‑cells log, and
18
+ threshold **suppress / stop** interventions on `google/gemma-3-1b-it`.
19
+
20
+ This **private/gated** build carries both projection methods side by side:
21
+
22
+ - **lm** — the standard logit‑lens (final_norm + lm_head).
23
+ - **interp** — an experimental, lm_head‑free projection. Held out of the public
24
+ build (a cheap way to explore the rank neighborhood of arbitrary tokens is a
25
+ mild dual‑use surface); kept here, behind access control, for research.
26
+
27
+ Where the two disagree is the interesting part.
28
+
29
+ ---
30
+
31
+ Built by **James J. Davison**, with Claude (Anthropic) as coding collaborator. **Responsibility for the code and its design choices rests with the human author.** MIT licensed. © 2026 James J. Davison.
__pycache__/gradio_app.cpython-312.pyc ADDED
Binary file (25.9 kB). View file
 
__pycache__/mri_live.cpython-312.pyc ADDED
Binary file (21.2 kB). View file
 
__pycache__/projection_map.cpython-312.pyc ADDED
Binary file (23.4 kB). View file
 
gradio_app.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gradiographer — live MRI viewer for Gemma-3-1B (and siblings).
3
+
4
+ Watches tracked words' ranks through each layer/head cell as tokens generate,
5
+ with threshold-based suppress/stop interventions. Two projection methods:
6
+ - lm : standard logit-lens (final_norm + lm_head); residual-only by default.
7
+ - interp : projection-free readout (no lm_head); every head + Layer by default.
8
+
9
+ Presentation follows small-multiples discipline: every tracked word × method is a
10
+ panel on ONE shared color scale, so target-vs-control and lm-vs-interp are honest
11
+ visual comparisons rather than separately-autoscaled images.
12
+
13
+ Local-first, Spaces-compatible. Defaults to google/gemma-3-1b-it.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import sys
20
+ from dataclasses import dataclass
21
+
22
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
+
24
+ import gradio as gr
25
+ import numpy as np
26
+ import plotly.graph_objects as go
27
+ from plotly.subplots import make_subplots
28
+
29
+ from projection_map import load_model, build_col_specs
30
+ from mri_live import (
31
+ TrackedWord,
32
+ InterventionConfig,
33
+ MethodTrace,
34
+ stream_trace,
35
+ tokenize_word,
36
+ word_preview,
37
+ make_rank_threshold_trigger,
38
+ )
39
+
40
+ DEFAULT_MODEL = os.environ.get("GRADIOGRAPHER_MODEL", "google/gemma-3-1b-it")
41
+
42
+ _METHOD_COLOR = {"lm": "#4cc9f0", "interp": "#ffb703"} # vivid on dark
43
+
44
+ # Discrete rank bands — finer near the surface, coarse for the buried tail.
45
+ # Color: Magma sampled bright(top) -> dark; 'buried' sits near the dark canvas.
46
+ BAND_LABELS = ["top", "top-10", "top-100", "top-1k", "top-2.5k", "buried"]
47
+ BAND_COLORS = ["#fcfdbf", "#fe9f6d", "#de4968", "#8c2981", "#3b0f70", "#1a1a22"]
48
+ BAND_EDGES = [1, 10, 100, 1000, 2500] # upper bound of bands 0..4; >1000 = buried
49
+
50
+
51
+ def _bands(rank2d):
52
+ """Map a 2D rank array to band indices 0(top)..5(buried)."""
53
+ b = np.full(rank2d.shape, 5.0)
54
+ b[rank2d <= 2500] = 4
55
+ b[rank2d <= 1000] = 3
56
+ b[rank2d <= 100] = 2
57
+ b[rank2d <= 10] = 1
58
+ b[rank2d <= 1] = 0
59
+ return b
60
+
61
+
62
+ def _discrete_scale(colors):
63
+ """Stepped colorscale so each integer band index renders a flat color."""
64
+ n = len(colors)
65
+ cs = []
66
+ for i, c in enumerate(colors):
67
+ cs.append([i / n, c])
68
+ cs.append([(i + 1) / n, c])
69
+ return cs
70
+
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # Lazy model state
74
+ # ---------------------------------------------------------------------------
75
+
76
+ @dataclass
77
+ class ModelBundle:
78
+ model: object
79
+ tokenizer: object
80
+ device: str
81
+ num_layers: int
82
+ num_heads: int
83
+ num_vocab: int
84
+ col_labels_default: list[str]
85
+
86
+
87
+ _bundle: ModelBundle | None = None
88
+
89
+
90
+ def get_bundle() -> ModelBundle:
91
+ global _bundle
92
+ if _bundle is None:
93
+ model, tokenizer, device, num_layers, num_heads = load_model(DEFAULT_MODEL)
94
+ col_specs, _, _, _ = build_col_specs(num_heads)
95
+ default_cols = [c[2] for c in col_specs if c[0] in ("single", "layer")]
96
+ num_vocab = int(model.lm_head.weight.shape[0])
97
+ _bundle = ModelBundle(model, tokenizer, device, num_layers, num_heads,
98
+ num_vocab, default_cols)
99
+ return _bundle
100
+
101
+
102
+ # ---------------------------------------------------------------------------
103
+ # UI helpers
104
+ # ---------------------------------------------------------------------------
105
+
106
+ def render_word_preview(words_raw: str) -> str:
107
+ if not words_raw.strip():
108
+ return "_(enter one or more comma-separated words — first is the focus, others read as controls)_"
109
+ b = get_bundle()
110
+ tok = b.tokenizer
111
+ lines = []
112
+ for w in [x.strip() for x in words_raw.split(",") if x.strip()]:
113
+ prev = word_preview(tok, w)
114
+ ws = " | ".join(f"`{repr(s)}`(id {tid})" for tid, s in prev["with_leading_space"])
115
+ ns = " | ".join(f"`{repr(s)}`(id {tid})" for tid, s in prev["no_leading_space"])
116
+ lines.append(f"**{w}**")
117
+ lines.append(f"- with leading space: {ws}")
118
+ lines.append(f"- no leading space: {ns}")
119
+ return "\n".join(lines)
120
+
121
+
122
+ def _empty_fig(title: str = "") -> go.Figure:
123
+ f = go.Figure()
124
+ f.update_layout(template="plotly_dark", height=320, title=title,
125
+ margin=dict(l=40, r=20, t=40, b=40))
126
+ return f
127
+
128
+
129
+ def build_heatmap_grid(hist_by_wm, words, methods, layer_axis) -> go.Figure:
130
+ """Small multiples (rows = tracked words, cols = methods) on ONE shared
131
+ discrete rank-band scale. Bands are absolute categories (top / top-5 / ... /
132
+ buried), so a single legend is both honest and comparable across methods —
133
+ no log decoding, no per-panel autoscale. Crisp tiles on a dark field: a
134
+ surfaced concept glows like structure on a scan. Each panel collapses cols
135
+ to min-rank per layer (best visibility of the tracked word); hover = exact rank."""
136
+ rows, cols = len(words), len(methods)
137
+ titles = [f"{w.label} · {m}" for w in words for m in methods]
138
+ fig = make_subplots(rows=rows, cols=cols, subplot_titles=titles,
139
+ shared_xaxes=True, shared_yaxes=True,
140
+ horizontal_spacing=0.09, vertical_spacing=0.14)
141
+ ylabels = [f"L{l:02d}" for l in layer_axis]
142
+ any_data = False
143
+ for r, _w in enumerate(words):
144
+ for c, m in enumerate(methods):
145
+ hist = hist_by_wm.get((r, m))
146
+ if not hist:
147
+ continue
148
+ rankmin = np.stack([rm.min(axis=1) for rm in hist], axis=0).T # (layers, steps)
149
+ fig.add_trace(go.Heatmap(
150
+ z=_bands(rankmin), customdata=rankmin,
151
+ y=ylabels, x=[f"t{i}" for i in range(len(hist))],
152
+ coloraxis="coloraxis", xgap=1.5, ygap=1.5, zsmooth=False,
153
+ hovertemplate="L%{y} · %{x}<br>rank %{customdata}<extra></extra>",
154
+ ), row=r + 1, col=c + 1)
155
+ any_data = True
156
+ if not any_data:
157
+ return _empty_fig("rank heatmaps")
158
+ fig.update_layout(
159
+ template="plotly_dark",
160
+ coloraxis=dict(
161
+ colorscale=_discrete_scale(BAND_COLORS), cmin=-0.5, cmax=5.5,
162
+ colorbar=dict(title="rank<br>band", tickvals=list(range(6)),
163
+ ticktext=BAND_LABELS, thickness=16, len=0.92, outlinewidth=0),
164
+ ),
165
+ height=max(320, 250 * rows),
166
+ margin=dict(l=55, r=95, t=56, b=40),
167
+ title="MRI — where each word surfaces across layers (x = generation step) · bright = nearer the surface",
168
+ )
169
+ fig.update_annotations(font_size=12)
170
+ return fig
171
+
172
+
173
+ def build_trace_grid(step_methods, words, methods, layer_axis) -> go.Figure:
174
+ """Rows = tracked words; lm vs interp overlaid as two lines per word so the
175
+ divergence is read within-panel. Log-rank y, REVERSED so the surface (rank 1)
176
+ is at the top; faint dotted band-edges echo the heatmap legend."""
177
+ rows = len(words)
178
+ titles = [w.label for w in words]
179
+ fig = make_subplots(rows=rows, cols=1, subplot_titles=titles, shared_xaxes=True,
180
+ vertical_spacing=0.13)
181
+ for r, _w in enumerate(words):
182
+ for m in methods:
183
+ mt = step_methods.get(m)
184
+ if mt is None:
185
+ continue
186
+ per_layer = mt.rank_matrix(r).min(axis=1)
187
+ fig.add_trace(go.Scatter(
188
+ x=mt.layers_used, y=per_layer, mode="lines+markers",
189
+ name=m, legendgroup=m, showlegend=(r == 0),
190
+ line=dict(color=_METHOD_COLOR.get(m), width=2), marker=dict(size=5),
191
+ ), row=r + 1, col=1)
192
+ for e in BAND_EDGES:
193
+ fig.add_hline(y=e, line=dict(color="rgba(255,255,255,0.10)", width=1, dash="dot"),
194
+ row=r + 1, col=1)
195
+ fig.update_yaxes(type="log", autorange="reversed", title_text="rank",
196
+ row=r + 1, col=1)
197
+ fig.update_xaxes(title_text="layer", row=rows, col=1)
198
+ fig.update_layout(template="plotly_dark", height=max(320, 240 * rows),
199
+ margin=dict(l=55, r=20, t=50, b=40),
200
+ title="per-layer rank at this step — lm vs interp (higher = nearer the surface)")
201
+ fig.update_annotations(font_size=12)
202
+ return fig
203
+
204
+
205
+ def _fmt_rank(r: int) -> str:
206
+ return f"{round(r/1000)}k" if r >= 1000 else str(r)
207
+
208
+
209
+ def _five_closest(mt: MethodTrace, tracked_idx: int = 0) -> str:
210
+ if not mt or not mt.cells:
211
+ return ""
212
+ cells = sorted(mt.cells, key=lambda c: c.ranks[tracked_idx])[:5]
213
+ parts = []
214
+ for c in cells:
215
+ loc = f"L{c.layer:02d}·R" if c.col == "Layer" else f"L{c.layer:02d}{c.col}"
216
+ parts.append(f"{loc} {_fmt_rank(c.ranks[tracked_idx])}")
217
+ return "|".join(parts)
218
+
219
+
220
+ def _log_line(step) -> str:
221
+ bits = [f"t{step.step:>2}"]
222
+ if step.fwd_ms >= 0:
223
+ bits.append(f"fwd {step.fwd_ms:.0f}ms")
224
+ for m in ("lm", "interp"):
225
+ if m in step.methods:
226
+ mt = step.methods[m]
227
+ lat = f" {mt.proj_ms:.1f}ms" if mt.proj_ms >= 0 else ""
228
+ bits.append(f"{m}{lat} |{_five_closest(mt)}|")
229
+ if step.intervened:
230
+ bits.append(f"⚠ INTERVENED→{step.intervention_action.upper()} ({','.join(step.intervention_methods)})")
231
+ return " ".join(bits)
232
+
233
+
234
+ # ---------------------------------------------------------------------------
235
+ # Main run generator
236
+ # ---------------------------------------------------------------------------
237
+
238
+ def run_session(
239
+ prompt, words_raw, scan_mode, max_new_tokens, scale_mode, layers_str, cols_str,
240
+ precise_timing,
241
+ threshold_enabled, threshold_word_idx, threshold_layers_str, threshold_cols_str,
242
+ threshold_rank_below, threshold_rank_above, intervention_action,
243
+ ):
244
+ b = get_bundle()
245
+ tok = b.tokenizer
246
+
247
+ words = [w.strip() for w in words_raw.split(",") if w.strip()]
248
+ if not words:
249
+ yield ("no tracked words provided", _empty_fig(), _empty_fig(), "", {}, "—")
250
+ return
251
+ tracked = [TrackedWord(text=w, token_ids=tokenize_word(tok, w, True), anchor_idx=0) for w in words]
252
+
253
+ def _parse_ints(s, default):
254
+ s = s.strip()
255
+ if not s:
256
+ return default
257
+ out = []
258
+ for part in s.split(","):
259
+ part = part.strip()
260
+ step = 1
261
+ if ":" in part:
262
+ part, step_s = part.split(":")
263
+ step = max(1, int(step_s))
264
+ if "-" in part:
265
+ a, z = part.split("-")
266
+ out.extend(range(int(a), int(z) + 1, step))
267
+ else:
268
+ out.append(int(part))
269
+ return sorted(set(out))
270
+
271
+ layer_mask = _parse_ints(layers_str, list(range(b.num_layers)))
272
+ methods = {"lm": ("lm",), "interp": ("interp",), "both": ("lm", "interp")}[scan_mode]
273
+ method_list = list(methods)
274
+
275
+ cols_parsed = [c.strip() for c in cols_str.split(",") if c.strip()]
276
+ if cols_parsed:
277
+ lm_cols = interp_cols = cols_parsed
278
+ else:
279
+ lm_cols = ["Layer"] # lm_head is expensive -> residual only
280
+ interp_cols = None # interp is cheap -> everything
281
+
282
+ intervention = None
283
+ if threshold_enabled:
284
+ th_layers = _parse_ints(threshold_layers_str, layer_mask)
285
+ th_cols = [c.strip() for c in threshold_cols_str.split(",") if c.strip()] or ["Layer"]
286
+ rb = int(threshold_rank_below) if int(threshold_rank_below) > 0 else None
287
+ ra = int(threshold_rank_above) if int(threshold_rank_above) > 0 else None
288
+ trigger = make_rank_threshold_trigger(int(threshold_word_idx), th_layers, th_cols, rb, ra)
289
+ intervention = InterventionConfig(trigger_fn=trigger, action=intervention_action)
290
+
291
+ hist_by_wm: dict = {} # (word_idx, method) -> list of (layers, cols) matrices
292
+ trace_snaps: list = [] # per-step step.methods dict (lightweight; trace figs built lazily)
293
+ log_lines: list = []
294
+ generated = ""
295
+
296
+ # Rebuilding a make_subplots figure costs ~hundreds of ms; doing it every
297
+ # token dwarfs the model. So render the heavy figures ~12 times across the
298
+ # run (+ a final full render), and stream only log/text on the steps between.
299
+ total = int(max_new_tokens)
300
+ render_every = max(1, total // 12)
301
+ last_hm = _empty_fig("rank heatmaps")
302
+ last_tg = _empty_fig("per-layer trace")
303
+ layer_axis = layer_mask
304
+
305
+ def _state(idx):
306
+ return {"snaps": trace_snaps, "words": tracked, "methods": method_list,
307
+ "layer_axis": layer_axis, "idx": idx}
308
+
309
+ for i, step in enumerate(stream_trace(
310
+ model=b.model, tokenizer=tok, device=b.device,
311
+ num_layers=b.num_layers, num_heads=b.num_heads,
312
+ prompt=prompt, tracked_words=tracked, max_new_tokens=total,
313
+ layer_mask=layer_mask, lm_cols=lm_cols, interp_cols=interp_cols,
314
+ methods=methods, scale_mode=scale_mode, intervention=intervention,
315
+ precise_timing=bool(precise_timing),
316
+ )):
317
+ generated += step.token_str
318
+ for m, mt in step.methods.items():
319
+ for wi in range(len(tracked)):
320
+ hist_by_wm.setdefault((wi, m), []).append(mt.rank_matrix(wi))
321
+ trace_snaps.append(step.methods)
322
+ log_lines.append(_log_line(step))
323
+ layer_axis = step.methods[method_list[0]].layers_used
324
+
325
+ if i % render_every == 0: # throttled live frame
326
+ last_hm = build_heatmap_grid(hist_by_wm, tracked, method_list, layer_axis)
327
+ last_tg = build_trace_grid(step.methods, tracked, method_list, layer_axis)
328
+
329
+ idx = len(trace_snaps) - 1
330
+ yield ("\n".join(log_lines), last_hm, last_tg, generated, _state(idx), f"step {idx} / {idx}")
331
+
332
+ # final full render so the finished state is complete
333
+ if trace_snaps:
334
+ last_hm = build_heatmap_grid(hist_by_wm, tracked, method_list, layer_axis)
335
+ last_tg = build_trace_grid(trace_snaps[-1], tracked, method_list, layer_axis)
336
+ idx = len(trace_snaps) - 1
337
+ yield ("\n".join(log_lines), last_hm, last_tg, generated, _state(idx), f"step {idx} / {idx}")
338
+
339
+
340
+ # ---------------------------------------------------------------------------
341
+ # Paging — rebuild the per-step trace grid lazily from stored snapshots
342
+ # ---------------------------------------------------------------------------
343
+
344
+ def _page(state, delta):
345
+ if not state or not state.get("snaps"):
346
+ return _empty_fig(), "—", state
347
+ snaps = state["snaps"]
348
+ n = len(snaps)
349
+ idx = max(0, min(n - 1, state.get("idx", n - 1) + delta))
350
+ state["idx"] = idx
351
+ fig = build_trace_grid(snaps[idx], state["words"], state["methods"], state["layer_axis"])
352
+ return fig, f"step {idx} / {n - 1}", state
353
+
354
+
355
+ def page_prev(state):
356
+ return _page(state, -1)
357
+
358
+
359
+ def page_next(state):
360
+ return _page(state, +1)
361
+
362
+
363
+ # ---------------------------------------------------------------------------
364
+ # UI
365
+ # ---------------------------------------------------------------------------
366
+
367
+ def build_ui():
368
+ with gr.Blocks(title="Tokescope — interactive observability for transformer internals") as demo:
369
+ gr.Markdown(
370
+ "# Tokescope\n"
371
+ "### Interactive observability for transformer internals\n"
372
+ "Pick a word and watch where the model ranks it as it writes, at every layer. "
373
+ "Tokescope surfaces these intermediate signals and lets them be inspected, "
374
+ "suppressed, or stopped in real time. An alternative, experimental lightweight "
375
+ "vocabulary-projection technique (`interp`) supports real-time exploration with "
376
+ "significantly lower overhead than a repeated full-vocabulary decode at every layer."
377
+ )
378
+
379
+ with gr.Row():
380
+ with gr.Column(scale=1):
381
+ prompt = gr.Textbox(label="prompt", lines=3,
382
+ value="Give a brief biography of Kurt Cobain and his life, no more than 50 words please.")
383
+ words = gr.Textbox(label="tracked words (focus first, then controls)",
384
+ value="suicide,elephant")
385
+ preview = gr.Markdown()
386
+ words.change(render_word_preview, inputs=words, outputs=preview)
387
+
388
+ with gr.Accordion("generation & scan", open=True):
389
+ scan_mode = gr.Radio(
390
+ ["lm", "interp", "both"], value="lm", label="projection method",
391
+ info="lm = logit-lens (residual only by default); interp = no lm_head (every head + Layer)",
392
+ )
393
+ max_new = gr.Slider(1, 80, value=20, step=1, label="max new tokens")
394
+ scale_mode = gr.Radio(["raw", "full", "mean"], value="full", label="head scale mode")
395
+ layers_str = gr.Textbox(
396
+ label="layers", value="0-25:2",
397
+ placeholder="blank = all; 'a-z:n' = every nth (default every other, for speed)")
398
+ cols_str = gr.Textbox(
399
+ label="cols (override)", value="",
400
+ placeholder="blank = smart defaults (lm:Layer, interp:all heads+Layer); else forces both")
401
+ precise_timing = gr.Checkbox(
402
+ label="precise per-method timing (slower — adds GPU syncs)", value=False)
403
+
404
+ with gr.Accordion("intervention", open=False):
405
+ th_enabled = gr.Checkbox(label="enable threshold", value=False)
406
+ th_word_idx = gr.Number(label="tracked-word index (0-based)", value=0, precision=0)
407
+ th_layers = gr.Textbox(label="layers to watch", value="", placeholder="blank = all")
408
+ th_cols = gr.Textbox(label="cols to watch", value="Layer", placeholder="e.g. Layer")
409
+ th_below = gr.Number(label="fire if rank <= (0 disables)", value=10, precision=0)
410
+ th_above = gr.Number(label="fire if rank >= (0 disables)", value=0, precision=0)
411
+ th_action = gr.Radio(["log", "suppress", "stop"], value="log", label="action on trigger")
412
+
413
+ run_btn = gr.Button("run", variant="primary")
414
+
415
+ with gr.Column(scale=2):
416
+ heatmap_grid = gr.Plot(label="rank heatmaps — small multiples, shared scale")
417
+ with gr.Row():
418
+ prev_btn = gr.Button("◀ prev step", size="sm")
419
+ page_label = gr.Markdown("_(run to populate)_")
420
+ next_btn = gr.Button("next step ▶", size="sm")
421
+ trace_grid = gr.Plot(label="per-layer rank at selected step")
422
+ page_state = gr.State({})
423
+
424
+ generated = gr.Textbox(label="generated", lines=3, interactive=False)
425
+ log = gr.Textbox(label="trace log — fwd + per-method proj latency + 5 closest cells",
426
+ lines=12, interactive=False, max_lines=40)
427
+
428
+ run_btn.click(
429
+ run_session,
430
+ inputs=[prompt, words, scan_mode, max_new, scale_mode, layers_str, cols_str,
431
+ precise_timing,
432
+ th_enabled, th_word_idx, th_layers, th_cols, th_below, th_above, th_action],
433
+ outputs=[log, heatmap_grid, trace_grid, generated, page_state, page_label],
434
+ )
435
+ prev_btn.click(page_prev, inputs=page_state, outputs=[trace_grid, page_label, page_state])
436
+ next_btn.click(page_next, inputs=page_state, outputs=[trace_grid, page_label, page_state])
437
+
438
+ demo.load(render_word_preview, inputs=words, outputs=preview)
439
+
440
+ return demo
441
+
442
+
443
+ if __name__ == "__main__":
444
+ demo = build_ui()
445
+ demo.queue()
446
+ demo.launch()
mri_live.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MRI Live — streaming rank-capture for mid-inference monitoring.
3
+
4
+ Two projection methods, side by side:
5
+ - lm : residual / per-head vectors -> final_norm -> lm_head (the standard
6
+ logit-lens readout; expensive, so by default I only project the
7
+ 'Layer' residual column).
8
+ - interp : the same vectors linearly interpolated up to vocab length and
9
+ softmaxed — a projection-free readout that needs NO lm_head. Cheap
10
+ enough that by default I project EVERY head + Layer.
11
+
12
+ For each generated token it yields a TraceStep carrying, per active method, the
13
+ rank of each tracked token at each (layer, col) cell, plus the projection
14
+ latency for that method (so the cost difference is visible).
15
+
16
+ Interventions: pass an InterventionConfig. The trigger is screened against each
17
+ active method; if any fires I suppress/stop the (single, real) generation and
18
+ record which method(s) tripped.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import os
24
+ import sys
25
+ import time
26
+ from dataclasses import dataclass, field
27
+ from typing import Callable, Iterator, Optional
28
+
29
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
30
+
31
+ import numpy as np
32
+ import torch
33
+ import torch.nn.functional as F
34
+
35
+ from projection_map import load_model, build_col_specs
36
+
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Configs
40
+ # ---------------------------------------------------------------------------
41
+
42
+ @dataclass
43
+ class TrackedWord:
44
+ """A word to track. Tokenizes to 1..N tokens; anchor picks which one."""
45
+ text: str
46
+ token_ids: list[int]
47
+ anchor_idx: int = 0
48
+
49
+ @property
50
+ def anchor_id(self) -> int:
51
+ return self.token_ids[self.anchor_idx]
52
+
53
+ @property
54
+ def label(self) -> str:
55
+ if len(self.token_ids) == 1:
56
+ return self.text
57
+ return f"{self.text} [tok{self.anchor_idx}]"
58
+
59
+
60
+ @dataclass
61
+ class InterventionConfig:
62
+ """When to intervene, and how.
63
+
64
+ trigger_fn: given a MethodTrace, returns True if intervention fires.
65
+ action: 'log' | 'suppress' | 'stop'
66
+ """
67
+ trigger_fn: Callable[["MethodTrace"], bool]
68
+ action: str = "log"
69
+
70
+
71
+ @dataclass
72
+ class CellTrace:
73
+ """Per-cell trace data for a single (layer, col)."""
74
+ layer: int
75
+ col: str
76
+ ranks: list[int] # rank per tracked word, 1-indexed
77
+ probs: list[float] # prob per tracked word
78
+ top30_ids: list[int] = field(default_factory=list)
79
+ top30_probs: list[float] = field(default_factory=list)
80
+
81
+
82
+ @dataclass
83
+ class MethodTrace:
84
+ """One projection method's view of a single generated token."""
85
+ method: str # 'lm' | 'interp'
86
+ cells: list[CellTrace]
87
+ layers_used: list[int]
88
+ cols_used: list[str]
89
+ proj_ms: float = 0.0
90
+
91
+ def rank_matrix(self, tracked_idx: int) -> np.ndarray:
92
+ n_layers, n_cols = len(self.layers_used), len(self.cols_used)
93
+ m = np.full((n_layers, n_cols), 1, dtype=np.int32)
94
+ lr = {l: i for i, l in enumerate(self.layers_used)}
95
+ cc = {c: j for j, c in enumerate(self.cols_used)}
96
+ for cell in self.cells:
97
+ if cell.layer in lr and cell.col in cc:
98
+ m[lr[cell.layer], cc[cell.col]] = cell.ranks[tracked_idx]
99
+ return m
100
+
101
+ def prob_matrix(self, tracked_idx: int) -> np.ndarray:
102
+ n_layers, n_cols = len(self.layers_used), len(self.cols_used)
103
+ m = np.zeros((n_layers, n_cols), dtype=np.float32)
104
+ lr = {l: i for i, l in enumerate(self.layers_used)}
105
+ cc = {c: j for j, c in enumerate(self.cols_used)}
106
+ for cell in self.cells:
107
+ if cell.layer in lr and cell.col in cc:
108
+ m[lr[cell.layer], cc[cell.col]] = cell.probs[tracked_idx]
109
+ return m
110
+
111
+
112
+ @dataclass
113
+ class TraceStep:
114
+ """One generated token's full trace across the active method(s)."""
115
+ step: int
116
+ token_id: int
117
+ token_str: str
118
+ token_prob: float
119
+ fwd_ms: float
120
+ methods: dict # 'lm'/'interp' -> MethodTrace
121
+ intervened: bool = False
122
+ intervention_action: str = ""
123
+ intervention_methods: list = field(default_factory=list)
124
+
125
+
126
+ # ---------------------------------------------------------------------------
127
+ # Helpers
128
+ # ---------------------------------------------------------------------------
129
+
130
+ def tokenize_word(tokenizer, word: str, with_leading_space: bool = True) -> list[int]:
131
+ text = (" " + word) if with_leading_space else word
132
+ return tokenizer.encode(text, add_special_tokens=False)
133
+
134
+
135
+ def word_preview(tokenizer, word: str) -> dict:
136
+ with_space = tokenize_word(tokenizer, word, with_leading_space=True)
137
+ no_space = tokenize_word(tokenizer, word, with_leading_space=False)
138
+ return {
139
+ "with_leading_space": [(tid, tokenizer.decode([tid])) for tid in with_space],
140
+ "no_leading_space": [(tid, tokenizer.decode([tid])) for tid in no_space],
141
+ }
142
+
143
+
144
+ def _is_cuda(device) -> bool:
145
+ if isinstance(device, str):
146
+ return device.startswith("cuda")
147
+ return getattr(device, "type", "") == "cuda"
148
+
149
+
150
+ # ---------------------------------------------------------------------------
151
+ # Streaming trace
152
+ # ---------------------------------------------------------------------------
153
+
154
+ def stream_trace(
155
+ model,
156
+ tokenizer,
157
+ device,
158
+ num_layers: int,
159
+ num_heads: int,
160
+ prompt: str,
161
+ tracked_words: list[TrackedWord],
162
+ max_new_tokens: int = 30,
163
+ layer_mask: Optional[list[int]] = None,
164
+ lm_cols: Optional[list[str]] = None,
165
+ interp_cols: Optional[list[str]] = None,
166
+ methods: tuple = ("lm",),
167
+ scale_mode: str = "full",
168
+ intervention: Optional[InterventionConfig] = None,
169
+ apply_chat_template: bool = True,
170
+ precise_timing: bool = False,
171
+ ) -> Iterator[TraceStep]:
172
+ """Generate tokens one-by-one, yielding a TraceStep after each.
173
+
174
+ methods: any of ('lm',), ('interp',), ('lm','interp').
175
+ lm_cols / interp_cols: column labels each method projects. Defaults:
176
+ lm -> ['Layer'] (residual only; lm_head is expensive)
177
+ interp -> all cols (every head + Layer; interp is cheap)
178
+ """
179
+ col_specs, head_indices, _, _ = build_col_specs(num_heads)
180
+ default_cols = [c for c in col_specs if c[0] in ("single", "layer")]
181
+ all_labels = [c[2] for c in default_cols]
182
+
183
+ if lm_cols is None:
184
+ lm_cols = ["Layer"]
185
+ if interp_cols is None:
186
+ interp_cols = all_labels # everything
187
+
188
+ def _resolve(wanted):
189
+ return [c for c in default_cols if c[2] in set(wanted)]
190
+
191
+ method_cols = {}
192
+ if "lm" in methods:
193
+ method_cols["lm"] = _resolve(lm_cols)
194
+ if "interp" in methods:
195
+ method_cols["interp"] = _resolve(interp_cols)
196
+
197
+ if layer_mask is None:
198
+ layer_mask = list(range(num_layers))
199
+
200
+ # Do I need per-head decomposition at all? (only if some active col is a head)
201
+ need_heads = any(
202
+ ct != "layer"
203
+ for cols in method_cols.values()
204
+ for (ct, _, _) in cols
205
+ )
206
+
207
+ final_norm = model.model.norm
208
+ lm_head = model.lm_head
209
+ vocab_size = lm_head.weight.shape[0]
210
+ tracked_ids = [tw.anchor_id for tw in tracked_words]
211
+ tids_t = torch.tensor(tracked_ids, device=device)
212
+
213
+ # Hook o_proj inputs (per-head pre-projection) — only used if need_heads.
214
+ captured: dict[int, torch.Tensor] = {}
215
+
216
+ def make_hook(layer_idx):
217
+ def hook_fn(module, args, output):
218
+ captured[layer_idx] = args[0].detach()
219
+ return hook_fn
220
+
221
+ handles = []
222
+ if need_heads:
223
+ for l in range(num_layers):
224
+ handles.append(
225
+ model.model.layers[l].self_attn.o_proj.register_forward_hook(make_hook(l))
226
+ )
227
+
228
+ # ---- project a list of (layer, col_label, vec[hidden]) through a method ----
229
+ def project_method(entries, method):
230
+ if not entries:
231
+ return [], -1.0
232
+ if precise_timing and _is_cuda(device):
233
+ torch.cuda.synchronize()
234
+ t0 = time.time()
235
+ stack = torch.stack([v for (_, _, v) in entries], dim=0) # [N, hidden], model dtype
236
+ with torch.no_grad():
237
+ if method == "lm":
238
+ dist = lm_head(final_norm(stack)).float() # [N, vocab] logits
239
+ else: # interp — linear upsample to vocab; align_corners=True == np.interp(linspace)
240
+ dist = F.interpolate(
241
+ stack.float().unsqueeze(1), size=vocab_size, mode="linear", align_corners=True
242
+ ).squeeze(1) # [N, vocab]
243
+ sel = dist.index_select(1, tids_t) # [N, T]
244
+ ranks = torch.empty((dist.shape[0], len(tracked_ids)), dtype=torch.long, device=dist.device)
245
+ for ti in range(len(tracked_ids)):
246
+ ranks[:, ti] = (dist > sel[:, ti:ti + 1]).sum(dim=1) + 1
247
+ # prob of the tracked tokens without materializing the full [N,vocab] softmax
248
+ lse = torch.logsumexp(dist, dim=1, keepdim=True) # [N, 1]
249
+ probs = torch.exp(sel - lse) # [N, T]
250
+ if precise_timing and _is_cuda(device):
251
+ torch.cuda.synchronize()
252
+ proj_ms = (time.time() - t0) * 1000.0 if precise_timing else -1.0
253
+ ranks = ranks.cpu().numpy()
254
+ probs = probs.float().cpu().numpy()
255
+ cells = []
256
+ for i, (layer, col_label, _) in enumerate(entries):
257
+ cells.append(CellTrace(
258
+ layer=layer, col=col_label,
259
+ ranks=[int(x) for x in ranks[i]],
260
+ probs=[float(x) for x in probs[i]],
261
+ ))
262
+ return cells, proj_ms
263
+
264
+ # ---- build input ----
265
+ if prompt and apply_chat_template:
266
+ try:
267
+ full_prompt = tokenizer.apply_chat_template(
268
+ [{"role": "user", "content": prompt}], tokenize=False, add_generation_prompt=True
269
+ )
270
+ except Exception:
271
+ full_prompt = prompt
272
+ else:
273
+ full_prompt = prompt or ""
274
+ if full_prompt:
275
+ step_input = tokenizer(full_prompt, return_tensors="pt").input_ids.to(device)
276
+ else:
277
+ step_input = torch.tensor([[tokenizer.bos_token_id]], device=device)
278
+
279
+ # KV cache: first pass processes the whole prompt; every later pass feeds
280
+ # ONLY the new token with past_key_values, so generation is O(n) not O(n^2).
281
+ # The projection code only ever reads the last position, so it is unchanged.
282
+ past = None
283
+
284
+ try:
285
+ for step_idx in range(max_new_tokens):
286
+ captured.clear()
287
+ if precise_timing and _is_cuda(device):
288
+ torch.cuda.synchronize()
289
+ t_fwd = time.time()
290
+ with torch.no_grad():
291
+ outputs = model(step_input, past_key_values=past, use_cache=True,
292
+ output_hidden_states=True)
293
+ past = outputs.past_key_values
294
+ if precise_timing and _is_cuda(device):
295
+ torch.cuda.synchronize()
296
+ fwd_ms = (time.time() - t_fwd) * 1000.0 if precise_timing else -1.0
297
+
298
+ logits = outputs.logits[0, -1, :]
299
+ probs_final = F.softmax(logits.float(), dim=-1)
300
+
301
+ # Gather per-layer residual + (if needed) per-head vectors at last pos.
302
+ residual_by_layer = {}
303
+ head_by_layer = {}
304
+ for l_idx in layer_mask:
305
+ residual_by_layer[l_idx] = outputs.hidden_states[l_idx + 1][:, -1, :][0]
306
+ if need_heads and l_idx in captured:
307
+ inp = captured[l_idx]
308
+ ow = model.model.layers[l_idx].self_attn.o_proj.weight
309
+ hidden_size, attn_out_dim = ow.shape
310
+ per_head_dim = attn_out_dim // num_heads
311
+ # all heads at the last position in one shot, then slice:
312
+ # proj[h, o] = sum_d o_proj_weight[o, h, d] * head_out[h, d]
313
+ mh_last = inp[0, -1].view(num_heads, per_head_dim) # [H, d]
314
+ wv = ow.view(hidden_size, num_heads, per_head_dim) # [O, H, d]
315
+ proj = torch.einsum("ohd,hd->ho", wv, mh_last) # [H, O]
316
+ head_by_layer[l_idx] = {h: proj[h] for h in head_indices}
317
+
318
+ # Build entries + project, per method.
319
+ step_methods = {}
320
+ for m, cols in method_cols.items():
321
+ entries = []
322
+ for l_idx in layer_mask:
323
+ hv = head_by_layer.get(l_idx, {})
324
+ for (col_type, col_heads, col_label) in cols:
325
+ if col_type == "layer":
326
+ entries.append((l_idx, col_label, residual_by_layer[l_idx]))
327
+ else:
328
+ if not hv:
329
+ continue
330
+ combined = sum(hv[h] for h in col_heads)
331
+ if scale_mode == "full":
332
+ combined = combined * (num_heads / len(col_heads))
333
+ elif scale_mode == "mean":
334
+ combined = combined / len(col_heads)
335
+ entries.append((l_idx, col_label, combined))
336
+ cells, proj_ms = project_method(entries, m)
337
+ cols_used = [lbl for (_, _, lbl) in
338
+ ([(0, 0, c[2]) for c in cols])]
339
+ step_methods[m] = MethodTrace(
340
+ method=m, cells=cells,
341
+ layers_used=list(layer_mask),
342
+ cols_used=[c[2] for c in cols],
343
+ proj_ms=proj_ms,
344
+ )
345
+
346
+ # Pick next token (greedy, from the real logits).
347
+ top_prob, top_id = torch.max(probs_final, dim=-1)
348
+ chosen_id = int(top_id.item())
349
+ chosen_str = tokenizer.decode(chosen_id)
350
+ chosen_prob = float(top_prob.item())
351
+
352
+ step = TraceStep(
353
+ step=step_idx, token_id=chosen_id, token_str=chosen_str,
354
+ token_prob=chosen_prob, fwd_ms=fwd_ms, methods=step_methods,
355
+ )
356
+
357
+ # Intervention — screen each active method.
358
+ if intervention is not None:
359
+ fired = [m for m, mt in step_methods.items() if intervention.trigger_fn(mt)]
360
+ if fired:
361
+ step.intervened = True
362
+ step.intervention_action = intervention.action
363
+ step.intervention_methods = fired
364
+ if intervention.action == "suppress":
365
+ masked = logits.clone()
366
+ masked[chosen_id] = float("-inf")
367
+ np2 = F.softmax(masked.float(), dim=-1)
368
+ p2, i2 = torch.max(np2, dim=-1)
369
+ chosen_id = int(i2.item())
370
+ chosen_str = tokenizer.decode(chosen_id)
371
+ chosen_prob = float(p2.item())
372
+ step.token_id, step.token_str, step.token_prob = chosen_id, chosen_str, chosen_prob
373
+
374
+ yield step
375
+
376
+ if step.intervened and intervention.action == "stop":
377
+ break
378
+
379
+ # Next pass: feed ONLY the new token (the cache holds the rest).
380
+ step_input = torch.tensor([[chosen_id]], device=device)
381
+ if chosen_id == tokenizer.eos_token_id:
382
+ break
383
+ finally:
384
+ for h in handles:
385
+ h.remove()
386
+
387
+
388
+ # ---------------------------------------------------------------------------
389
+ # Threshold-based trigger (screened per method)
390
+ # ---------------------------------------------------------------------------
391
+
392
+ def make_rank_threshold_trigger(
393
+ tracked_idx: int,
394
+ layers: list[int],
395
+ cols: list[str],
396
+ rank_below: Optional[int] = None,
397
+ rank_above: Optional[int] = None,
398
+ ) -> Callable[["MethodTrace"], bool]:
399
+ """Fire if the tracked token's rank at any matching cell crosses a
400
+ threshold. `rank_below=10` -> fires when rank <= 10 (token surfaced)."""
401
+ layers_s = set(layers)
402
+ cols_s = set(cols)
403
+
404
+ def trigger(mt: "MethodTrace") -> bool:
405
+ for cell in mt.cells:
406
+ if cell.layer not in layers_s or cell.col not in cols_s:
407
+ continue
408
+ r = cell.ranks[tracked_idx]
409
+ if rank_below is not None and r <= rank_below:
410
+ return True
411
+ if rank_above is not None and r >= rank_above:
412
+ return True
413
+ return False
414
+ return trigger
projection_map.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Projection Map — Condensed view of layer, head, and head-combination projections.
3
+
4
+ One table: 26 rows (one per layer).
5
+ Columns: H0-H3 (individual heads), all pairs, all triples, full layer projection.
6
+ Format: #LL|tok PP%|tok PP%|...|laytok PP%|
7
+ """
8
+
9
+ import argparse
10
+ import unicodedata
11
+ from itertools import combinations
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from transformers import AutoModelForCausalLM, AutoTokenizer
15
+
16
+ DEFAULT_MODEL_ID = "google/gemma-3-1b-it"
17
+
18
+ C_H = '\033[95m'
19
+ C_B = '\033[94m'
20
+ C_G = '\033[92m'
21
+ C_Y = '\033[93m'
22
+ C_C = '\033[96m'
23
+ C_E = '\033[0m'
24
+ C_BLD = '\033[1m'
25
+ C_DIM = '\033[2m'
26
+
27
+
28
+ def safe_print(text):
29
+ try:
30
+ print(text)
31
+ except UnicodeEncodeError:
32
+ print(text.encode('ascii', 'replace').decode('ascii'))
33
+
34
+
35
+ def char_width(ch):
36
+ """Terminal column width of a single character."""
37
+ cat = unicodedata.category(ch)
38
+ if cat in ('Mn', 'Me'):
39
+ return 0
40
+ if ord(ch) in (0x200B, 0x200C, 0x200D, 0xFEFF):
41
+ return 0
42
+ eaw = unicodedata.east_asian_width(ch)
43
+ if eaw in ('W', 'F'):
44
+ return 2
45
+ return 1
46
+
47
+
48
+ def display_width(s):
49
+ return sum(char_width(ch) for ch in s)
50
+
51
+
52
+ def fmt_tok(s, width=9):
53
+ """Format token to exactly `width` terminal columns."""
54
+ s = s.replace('\n', '\\n').replace('\r', '\\r').replace('\t', '\\t')
55
+ s = s.lstrip('\u2581')
56
+ s = s.lstrip(' ')
57
+ if not s:
58
+ s = '·'
59
+ if display_width(s) <= width:
60
+ pad = width - display_width(s)
61
+ return s + ' ' * pad
62
+ result = []
63
+ used = 0
64
+ for ch in s:
65
+ ch_w = char_width(ch)
66
+ if ch_w > 0 and used + ch_w > width - 1:
67
+ break
68
+ result.append(ch)
69
+ used += ch_w
70
+ result.append('.')
71
+ used += 1
72
+ while used < width:
73
+ result.append(' ')
74
+ used += 1
75
+ return ''.join(result)
76
+
77
+
78
+ def fmt_pct(p):
79
+ pct = int(p * 100)
80
+ if pct > 99:
81
+ return "99"
82
+ return f"{pct:02d}"
83
+
84
+
85
+ def prob_color(p):
86
+ if p > 0.5: return C_G
87
+ if p > 0.1: return C_Y
88
+ return C_DIM
89
+
90
+
91
+ def combo_label(indices):
92
+ """Short label for a head combination."""
93
+ return ''.join(str(i) for i in indices)
94
+
95
+
96
+ def load_model(model_id):
97
+ device = "cuda" if torch.cuda.is_available() else "cpu"
98
+ print(f"{C_H}Loading {model_id}...{C_E}")
99
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
100
+ tokenizer.padding_side = "left"
101
+ if tokenizer.pad_token is None:
102
+ tokenizer.pad_token = tokenizer.eos_token
103
+
104
+ # Use bfloat16 — Gemma 3's RMSNorm breaks with float16 (NaN logits).
105
+ # bfloat16 works on RTX 30+ / A100 / H100. Fall back to float32 if unavailable.
106
+ if torch.cuda.is_available() and torch.cuda.is_bf16_supported():
107
+ dtype = torch.bfloat16
108
+ else:
109
+ dtype = torch.float32
110
+ model = AutoModelForCausalLM.from_pretrained(
111
+ model_id, device_map="auto", torch_dtype=dtype
112
+ )
113
+ model.eval()
114
+
115
+ num_layers = model.config.num_hidden_layers
116
+ num_heads = model.config.num_attention_heads
117
+ print(f"{C_C}Architecture: {num_layers} layers, {num_heads} heads{C_E}")
118
+
119
+ return model, tokenizer, device, num_layers, num_heads
120
+
121
+
122
+ def project_to_token(projected_hidden, final_norm, lm_head, tokenizer):
123
+ """Take a projected hidden state, norm -> lm_head -> argmax, return (token_str, prob)."""
124
+ normed = final_norm(projected_hidden)
125
+ logits = lm_head(normed)
126
+ probs = F.softmax(logits, dim=-1)
127
+ p, tid = torch.max(probs, dim=-1)
128
+ tok = tokenizer.decode(tid.item())
129
+ return tok, p.item()
130
+
131
+
132
+ def project_to_token_rich(projected_hidden, final_norm, lm_head, tokenizer, top_k=5):
133
+ """Rich projection: top-k tokens, entropy, full distribution shape.
134
+ Returns dict with:
135
+ 'top_k': list of (token_str, prob) for top k
136
+ 'entropy': Shannon entropy of the distribution (bits)
137
+ 'argmax': (token_str, prob) — same as project_to_token
138
+ 'mass_top5': total probability mass in top 5
139
+ 'mass_top50': total probability mass in top 50
140
+ """
141
+ normed = final_norm(projected_hidden)
142
+ logits = lm_head(normed)
143
+ probs = F.softmax(logits, dim=-1)
144
+
145
+ # Entropy in bits
146
+ log_probs = torch.log2(probs + 1e-10)
147
+ entropy = -(probs * log_probs).sum().item()
148
+
149
+ # Top-k
150
+ topk_probs, topk_ids = torch.topk(probs.squeeze(), top_k)
151
+ top_k_list = []
152
+ for i in range(top_k):
153
+ tok = tokenizer.decode(topk_ids[i].item())
154
+ top_k_list.append((tok, topk_probs[i].item()))
155
+
156
+ # Mass in top-50
157
+ top50_probs, _ = torch.topk(probs.squeeze(), min(50, probs.shape[-1]))
158
+ mass_top50 = top50_probs.sum().item()
159
+
160
+ return {
161
+ 'top_k': top_k_list,
162
+ 'entropy': entropy,
163
+ 'argmax': top_k_list[0],
164
+ 'mass_top5': sum(p for _, p in top_k_list),
165
+ 'mass_top50': mass_top50,
166
+ }
167
+
168
+
169
+ def project_to_softmax(projected_hidden, final_norm, lm_head):
170
+ """Project hidden state to full softmax distribution.
171
+ Returns the raw probability tensor (vocab_size,) on CPU as float16.
172
+ This is the complete recording — every possible analysis is a post-hoc query.
173
+ """
174
+ normed = final_norm(projected_hidden)
175
+ logits = lm_head(normed)
176
+ probs = F.softmax(logits, dim=-1)
177
+ return probs.squeeze().detach().cpu().half()
178
+
179
+
180
+ def project_full(projected_hidden, final_norm, lm_head):
181
+ """Project hidden state and return BOTH the projected vector and softmax.
182
+ Returns: (projected_vector, softmax_probs)
183
+ - projected_vector: (hidden_dim,) float32 on CPU — the normed hidden state,
184
+ directly comparable to lm_head weight vectors (i.e. token embeddings).
185
+ This is what you search against the Lance token index.
186
+ - softmax_probs: (vocab_size,) float16 on CPU — the full distribution.
187
+ """
188
+ normed = final_norm(projected_hidden)
189
+ logits = lm_head(normed)
190
+ probs = F.softmax(logits, dim=-1)
191
+ return (
192
+ normed.squeeze().detach().cpu().float(),
193
+ probs.squeeze().detach().cpu().half(),
194
+ )
195
+
196
+
197
+ def make_cell(tok, prob):
198
+ """Format a single table cell."""
199
+ pc = prob_color(prob)
200
+ return f"{pc}{fmt_tok(tok)}{fmt_pct(prob)}%{C_E}"
201
+
202
+
203
+ def build_col_specs(num_heads):
204
+ """Build column specifications for the projection table."""
205
+ head_indices = list(range(num_heads))
206
+ pairs = list(combinations(head_indices, 2))
207
+ triples = list(combinations(head_indices, 3))
208
+
209
+ col_specs = []
210
+ for i in head_indices:
211
+ col_specs.append(('single', (i,), f"H{i}"))
212
+ for combo in pairs:
213
+ col_specs.append(('combo', combo, f"H{''.join(str(i) for i in combo)}"))
214
+ for combo in triples:
215
+ col_specs.append(('combo', combo, f"H{''.join(str(i) for i in combo)}"))
216
+ col_specs.append(('layer', None, 'Layer'))
217
+
218
+ return col_specs, head_indices, pairs, triples
219
+
220
+
221
+ def capture_projection_map(model, tokenizer, input_ids, device, num_layers, num_heads,
222
+ scale_mode='full', rich=False, top_k=5, full_softmax=False):
223
+ """
224
+ Run forward pass and return structured projection data.
225
+ If rich=False: list of dicts, one per layer, each containing {col_label: (token, prob)}
226
+ If rich=True: list of dicts, one per layer, each containing {col_label: rich_dict}
227
+ where rich_dict has top_k, entropy, argmax, mass_top5, mass_top50
228
+ If full_softmax=True: also returns softmax_data — list of dicts per layer,
229
+ each {col_label: tensor(vocab_size)} as float16 on CPU.
230
+ This is the complete MRI — every query is post-hoc.
231
+ Returns: (layer_data, col_specs) or (layer_data, col_specs, softmax_data) if full_softmax
232
+ """
233
+ final_norm = model.model.norm
234
+ lm_head = model.lm_head
235
+
236
+ captured = {}
237
+
238
+ def make_hook(layer_idx):
239
+ def hook_fn(module, args, output):
240
+ captured[layer_idx] = args[0].detach()
241
+ return hook_fn
242
+
243
+ handles = []
244
+ for l in range(num_layers):
245
+ layer = model.model.layers[l]
246
+ h = layer.self_attn.o_proj.register_forward_hook(make_hook(l))
247
+ handles.append(h)
248
+
249
+ try:
250
+ with torch.no_grad():
251
+ outputs = model(input_ids, output_hidden_states=True)
252
+ finally:
253
+ for h in handles:
254
+ h.remove()
255
+
256
+ col_specs, head_indices, _, _ = build_col_specs(num_heads)
257
+
258
+ layer_data = []
259
+ softmax_data = [] if full_softmax else None
260
+ for l_idx in range(num_layers):
261
+ layer_state = outputs.hidden_states[l_idx + 1]
262
+ last_token = layer_state[:, -1, :]
263
+ if rich:
264
+ lay_rich = project_to_token_rich(last_token, final_norm, lm_head, tokenizer, top_k)
265
+ else:
266
+ lay_tok, lay_prob = project_to_token(last_token, final_norm, lm_head, tokenizer)
267
+
268
+ row = {}
269
+
270
+ if l_idx in captured:
271
+ input_tensor = captured[l_idx]
272
+ layer = model.model.layers[l_idx]
273
+ o_proj_weight = layer.self_attn.o_proj.weight
274
+ hidden_size = o_proj_weight.shape[0]
275
+ attn_out_dim = o_proj_weight.shape[1]
276
+ head_dim = attn_out_dim // num_heads
277
+
278
+ batch, seq, _ = input_tensor.shape
279
+ multi_head = input_tensor.view(batch, seq, num_heads, head_dim)
280
+ weight_view = o_proj_weight.view(hidden_size, num_heads, head_dim)
281
+
282
+ head_projected = {}
283
+ for h_idx in head_indices:
284
+ head_output = multi_head[:, :, h_idx, :]
285
+ head_weights = weight_view[:, h_idx, :]
286
+ projected = torch.matmul(head_output, head_weights.t())
287
+ head_projected[h_idx] = projected[:, -1, :]
288
+
289
+ for col_type, col_heads, col_label in col_specs:
290
+ if col_type == 'layer':
291
+ if rich:
292
+ row[col_label] = lay_rich
293
+ else:
294
+ row[col_label] = (lay_tok, lay_prob)
295
+ else:
296
+ combined = sum(head_projected[h] for h in col_heads)
297
+ if scale_mode == 'full':
298
+ combined = combined * (num_heads / len(col_heads))
299
+ elif scale_mode == 'mean':
300
+ combined = combined / len(col_heads)
301
+ if rich:
302
+ row[col_label] = project_to_token_rich(combined, final_norm, lm_head, tokenizer, top_k)
303
+ else:
304
+ tok, prob = project_to_token(combined, final_norm, lm_head, tokenizer)
305
+ row[col_label] = (tok, prob)
306
+
307
+ # If full softmax capture requested, store raw distributions
308
+ if full_softmax:
309
+ softmax_row = {}
310
+ for col_type, col_heads, col_label in col_specs:
311
+ if col_type == 'layer':
312
+ softmax_row[col_label] = project_to_softmax(last_token, final_norm, lm_head)
313
+ else:
314
+ combined = sum(head_projected[h] for h in col_heads)
315
+ if scale_mode == 'full':
316
+ combined = combined * (num_heads / len(col_heads))
317
+ elif scale_mode == 'mean':
318
+ combined = combined / len(col_heads)
319
+ softmax_row[col_label] = project_to_softmax(combined, final_norm, lm_head)
320
+ softmax_data.append(softmax_row)
321
+ else:
322
+ for _, _, col_label in col_specs:
323
+ if rich:
324
+ row[col_label] = {'top_k': [('--', 0.0)]*top_k, 'entropy': 0.0,
325
+ 'argmax': ('--', 0.0), 'mass_top5': 0.0, 'mass_top50': 0.0}
326
+ else:
327
+ row[col_label] = ('--', 0.0)
328
+ if full_softmax:
329
+ softmax_data.append({})
330
+
331
+ layer_data.append(row)
332
+
333
+ if full_softmax:
334
+ return layer_data, col_specs, softmax_data
335
+ return layer_data, col_specs
336
+
337
+
338
+ def print_projection_map(layer_data, col_specs):
339
+ """Print the projection map table from structured data."""
340
+ header_cells = [f"{C_BLD}{C_C}# {C_E}"]
341
+ for _, _, label in col_specs:
342
+ header_cells.append(f"{C_BLD}{C_C}{label:^12}{C_E}")
343
+ header = '|'.join(header_cells) + '|'
344
+
345
+ sep_width = 4 + len(col_specs) * 13
346
+ sep = f"{C_DIM}{'─' * sep_width}{C_E}"
347
+
348
+ print()
349
+ safe_print(header)
350
+ safe_print(sep)
351
+
352
+ for l_idx, row in enumerate(layer_data):
353
+ cells = []
354
+ for _, _, col_label in col_specs:
355
+ tok, prob = row[col_label]
356
+ cells.append(make_cell(tok, prob))
357
+ row_num = f"{C_BLD}#{l_idx:02d}{C_E}"
358
+ safe_print(f"{row_num}|{'|'.join(cells)}|")
359
+
360
+ safe_print(sep)
361
+
362
+
363
+ def format_map_plain(layer_data, col_specs):
364
+ """Format projection map as plain text (no ANSI) for LLM consumption."""
365
+ labels = [label for _, _, label in col_specs]
366
+ header = f"# |{'|'.join(f'{l:^12}' for l in labels)}|"
367
+ sep = '─' * len(header)
368
+
369
+ lines = [header, sep]
370
+ for l_idx, row in enumerate(layer_data):
371
+ cells = []
372
+ for _, _, col_label in col_specs:
373
+ tok, prob = row[col_label]
374
+ tok_clean = tok.replace('\n', '\\n').replace('\r', '\\r')
375
+ if len(tok_clean) > 9:
376
+ tok_clean = tok_clean[:8] + '.'
377
+ cell = f"{tok_clean:<9}{int(prob*100):02d}%"
378
+ cells.append(cell)
379
+ lines.append(f"#{l_idx:02d}|{'|'.join(cells)}|")
380
+ lines.append(sep)
381
+ return '\n'.join(lines)
382
+
383
+
384
+ def run(model, tokenizer, input_ids, device, num_layers, num_heads, scale_mode='full'):
385
+ """Capture and print the projection map. Returns structured data."""
386
+ layer_data, col_specs = capture_projection_map(
387
+ model, tokenizer, input_ids, device, num_layers, num_heads, scale_mode
388
+ )
389
+ print_projection_map(layer_data, col_specs)
390
+
391
+ # Legend
392
+ _, head_indices, pairs, triples = build_col_specs(num_heads)
393
+ print()
394
+ safe_print(f"{C_DIM}Singles: {', '.join(f'H{i}' for i in head_indices)}{C_E}")
395
+ safe_print(f"{C_DIM}Pairs: {', '.join('H' + ''.join(str(i) for i in c) for c in pairs)}{C_E}")
396
+ safe_print(f"{C_DIM}Triples: {', '.join('H' + ''.join(str(i) for i in c) for c in triples)}{C_E}")
397
+
398
+ return layer_data, col_specs
399
+
400
+
401
+ def main():
402
+ parser = argparse.ArgumentParser(description="Projection map — layer × head × combos")
403
+ parser.add_argument("--model", "-m", default=DEFAULT_MODEL_ID,
404
+ help=f"Model ID (default: {DEFAULT_MODEL_ID})")
405
+ parser.add_argument("--prompt", "-p", default="",
406
+ help="Prompt text (default: empty, just BOS)")
407
+ parser.add_argument("--scale", "-s", default="full",
408
+ choices=["raw", "full", "mean"],
409
+ help="Head scaling: raw (no scaling), full (scale to full-head magnitude), mean (average). Default: full")
410
+ args = parser.parse_args()
411
+
412
+ model, tokenizer, device, num_layers, num_heads = load_model(args.model)
413
+
414
+ if args.prompt:
415
+ input_ids = tokenizer(args.prompt, return_tensors="pt").input_ids.to(device)
416
+ safe_print(f"\n{C_Y}Prompt: \"{args.prompt}\"{C_E}")
417
+ safe_print(f"{C_DIM}Tokens: {input_ids.shape[1]}{C_E}")
418
+ else:
419
+ bos_id = tokenizer.bos_token_id
420
+ if bos_id is None:
421
+ input_ids = tokenizer("", return_tensors="pt").input_ids.to(device)
422
+ else:
423
+ input_ids = torch.tensor([[bos_id]], device=device)
424
+ safe_print(f"\n{C_Y}No prompt — raw BOS token only{C_E}")
425
+
426
+ safe_print(f"{C_DIM}Scale mode: {args.scale}{C_E}")
427
+
428
+ run(model, tokenizer, input_ids, device, num_layers, num_heads, scale_mode=args.scale)
429
+
430
+ print(f"\n{C_G}Done.{C_E}")
431
+
432
+
433
+ if __name__ == "__main__":
434
+ main()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio>=4.44
2
+ torch>=2.2
3
+ transformers>=4.45
4
+ numpy
5
+ plotly
6
+ accelerate