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

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +299 -151
app.py CHANGED
@@ -13,7 +13,9 @@ import re
13
  import io
14
  import sys
15
  import json
 
16
  import unicodedata
 
17
  from datetime import datetime
18
 
19
  import torch
@@ -168,6 +170,18 @@ def _resolve_o_proj(layer):
168
  return None
169
 
170
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  # ── The Probe (lifted from cartographer3, ANSI removed) ───────────────────
172
  class InteractiveProbe:
173
  def __init__(self, model_id: str = None):
@@ -252,6 +266,7 @@ class InteractiveProbe:
252
  self.full_log = []
253
  self.muted_heads = set()
254
  self._mute_handles = []
 
255
 
256
  # ── architecture accessors ──
257
  def _lm_head_out_features(self):
@@ -274,6 +289,51 @@ class InteractiveProbe:
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
 
@@ -290,25 +350,28 @@ class InteractiveProbe:
290
  full_prompt = prompt
291
  self.history_ids = self.tokenizer(full_prompt, return_tensors="pt").to(DEVICE).input_ids
292
 
293
- def perform_xray(self):
294
- if self.history_ids is None: return []
 
 
 
 
 
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}"
305
- out.append((label, tok))
306
  return out
307
 
308
- def generate_previews(self, width: int, length: int):
309
- with torch.no_grad():
310
- outputs = self.model(self.history_ids)
311
- next_logits = outputs.logits[0, -1, :]
 
 
 
312
  probs = F.softmax(next_logits, dim=-1)
313
  top_probs, top_ids = torch.topk(probs, width)
314
 
@@ -356,74 +419,51 @@ class InteractiveProbe:
356
  self.history_ids = torch.cat([self.history_ids, ids], dim=1)
357
  self.full_log.append({"type": "inject", "text": text})
358
 
359
- def scan_heads(self, target_layers=None, target_heads=None):
360
- if self.history_ids is None: return None
 
 
 
 
 
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
411
- multi = inp.view(b, s, self.num_heads, head_dim)
412
- wv = wo.view(hidden, self.num_heads, head_dim)
413
-
414
- for hi in target_heads:
415
- if not (0 <= hi < self.num_heads): continue
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):
@@ -475,10 +515,14 @@ class InteractiveProbe:
475
  self.full_log.append({"type": "unmute_all"})
476
  return f"UNMUTED ALL ({n} heads)"
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:
@@ -487,40 +531,26 @@ class InteractiveProbe:
487
  tid = ids[0]; name = token_str
488
  if rank_hi is None: rank_hi = self.vocab_size
489
 
490
- captured = {}
491
- def get_hook(li):
492
- def fn(module, args, output):
493
- captured[li] = args[0].detach()
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)
512
- wv = wo.view(hidden, self.num_heads, head_dim)
513
  for hi in range(self.num_heads):
514
- ho = multi[:, -1, hi, :]
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
523
- ranks[(hi, li)] = rank
524
  return {"name": name, "tid": tid, "rank_lo": rank_lo, "rank_hi": rank_hi, "ranks": ranks}
525
 
526
 
@@ -604,18 +634,26 @@ def render_headmap(probe: InteractiveProbe, data: dict, xray: list) -> str:
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:
609
- return "<div class='pane-body'><i>No futures yet.</i></div>"
610
- rows = ["<tr><th>#</th><th>Prob</th><th>Token</th><th>Preview</th></tr>"]
611
  for o in options:
 
612
  prob = f"{o['prob']:.1%}"
613
  col = heat_color(o["prob"])
 
 
 
 
614
  rows.append(
615
- f"<tr><td class='idx'>[{o['index']+1}]</td>"
 
616
  f"<td style='color:{col}'>{prob}</td>"
617
  f"<td class='tok'>{html_escape(fmt_tok(o['root_token'], 16))}</td>"
618
- f"<td class='preview'>{html_escape(o['future_text'][:120])}…</td></tr>"
 
 
619
  )
620
  return f"<div class='pane-body scroll'><table class='futures'>{''.join(rows)}</table></div>"
621
 
@@ -677,6 +715,35 @@ def render_muted(probe: InteractiveProbe) -> str:
677
  items = ", ".join(f"L{l}H{h}" for l, h in sorted(probe.muted_heads))
678
  return f"<span class='muted-tag'>MUTED: {items}</span>"
679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
680
 
681
  # ── State container ──────────────────────────────────────────────────────
682
  class Session:
@@ -689,19 +756,50 @@ class Session:
689
  self.width = DEFAULT_WIDTH
690
  self.preview_len = DEFAULT_PREVIEW
691
  self.transcript: list = [] # [(cmd, status), ...]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
692
 
693
  def ensure(self, model_id: str, system_prompt: str = None, user_prompt: str = ""):
 
694
  if self.probe is None:
695
- self.probe = InteractiveProbe(model_id=model_id)
696
- self.probe.set_seed()
697
- self.probe.load_start(user_prompt or "", system_prompt or None)
698
 
699
 
700
  def panes_html(s: Session):
701
  return (
 
702
  render_context(s.probe),
703
  render_headmap(s.probe, s.scan_data, s.xray),
704
- render_futures(s.options),
705
  render_sparkline(s.probe, s.spark),
706
  render_muted(s.probe),
707
  )
@@ -735,8 +833,9 @@ def handle_command(cmd: str, s: Session, model_id: str, system_prompt: str):
735
  if 0 <= idx < len(s.options):
736
  keep_len = int(parts[1]) if len(parts) > 1 else None
737
  s.probe.commit(s.options[idx], keep_len)
 
738
  _refresh_after_step(s)
739
- status = f"committed [{idx+1}]"
740
  else:
741
  status = f"invalid index {idx+1}"
742
 
@@ -751,7 +850,9 @@ def handle_command(cmd: str, s: Session, model_id: str, system_prompt: str):
751
  target_heads = None
752
  if len(parts) > 2:
753
  target_heads = None if parts[2] == "*" else [int(parts[2])]
754
- s.scan_data = s.probe.scan_heads(target_layers, target_heads)
 
 
755
  s.xray = s.probe.perform_xray()
756
  status = f"head-scan: layers={parts[1]} heads={parts[2] if len(parts)>2 else '*'}"
757
 
@@ -847,26 +948,28 @@ def handle_command(cmd: str, s: Session, model_id: str, system_prompt: str):
847
 
848
 
849
  def _refresh_futures(s: Session):
 
850
  if s.probe is None or s.probe.history_ids is None: return
 
 
851
  s.options = s.probe.generate_previews(s.width, s.preview_len)
852
 
853
- def _refresh_headmap(s: Session):
854
- """Always run full h * scan + xray after any step that mutates context."""
855
  if s.probe is None or s.probe.history_ids is None: return
856
- s.scan_data = s.probe.scan_heads(None, None)
 
 
857
  s.xray = s.probe.perform_xray()
858
 
859
- def _refresh_after_step(s: Session):
860
- _refresh_futures(s)
861
- _refresh_headmap(s)
862
-
863
 
864
  def initial_load(model_id: str, system_prompt: str, user_prompt: str, s: Session):
865
- s.ensure(model_id=model_id, system_prompt=system_prompt or None, user_prompt=user_prompt or "")
866
- _refresh_futures(s)
867
- _refresh_headmap(s)
868
- s.transcript.append(("(load)", f"loaded {s.probe.model_id} "
869
- f"({s.probe.num_layers}L×{s.probe.num_heads}H)"))
 
870
  return panes_html(s) + (status_html(s),)
871
 
872
 
@@ -940,11 +1043,43 @@ table.headmap td.xr { color: #ECA60F; background: #15110a; }
940
  table.headmap td.full { background: #0a1410; }
941
  table.headmap tr.subhdr th { background: #161b22; color: #8b949e; font-weight: normal; font-size: 10px; }
942
  table.futures { width: 100%; border-collapse: collapse; }
943
- table.futures th { background: #161b22; padding: 3px 6px; text-align: left; color: #8b949e; font-size: 10px; }
944
- table.futures td { padding: 3px 6px; border-bottom: 1px solid #21262d; }
 
 
 
945
  table.futures td.idx { color: #6e7681; }
 
 
 
946
  table.futures td.tok { color: #c9d1d9; font-weight: bold; white-space: pre; }
947
- table.futures td.preview { color: #8b949e; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
948
  pre.spark { margin: 0; font-size: 11px; line-height: 1.1; }
949
  .muted-tag { color: #ff6b6b; font-weight: bold; padding: 2px 6px; }
950
  .prompt { color: #64D32A; }
@@ -967,10 +1102,21 @@ def build_ui():
967
  session = gr.State(Session())
968
 
969
  # ── Compact top bar: model | system | user | load ──
 
 
 
 
 
 
 
 
 
 
970
  with gr.Row(elem_id="topbar"):
971
- model_id = gr.Textbox(value=DEFAULT_MODEL_ID, label="Model",
972
- lines=1, max_lines=1, scale=3, container=True,
973
- show_label=True)
 
974
  system_prompt = gr.Textbox(label="System", value="",
975
  lines=1, max_lines=3, scale=4, container=True)
976
  user_prompt = gr.Textbox(
@@ -982,6 +1128,8 @@ def build_ui():
982
  )
983
  load_btn = gr.Button("Load", variant="primary", scale=1, min_width=80)
984
 
 
 
985
  muted_html = gr.HTML(elem_id="muted-row")
986
 
987
  # ── Context: full width ──
@@ -1001,27 +1149,26 @@ def build_ui():
1001
  )
1002
  run_btn = gr.Button("Run", scale=1, variant="primary", min_width=70)
1003
 
1004
- # ── Branches + Head Map: side by side ──
1005
- with gr.Row():
1006
- with gr.Column(scale=3, min_width=280):
 
1007
  fut_pane = gr.HTML(value="<div class='pane'><h3>Branches (next-token top-k)</h3>"
1008
- "<div class='pane-body'><i>Top-k continuations appear here after Load.</i></div></div>")
1009
- with gr.Column(scale=7):
1010
  hm_pane = gr.HTML(value="<div class='pane'><h3>Head Map "
1011
  "— per-head pre-projection · logit-lens · per-head Δ-residual · L<sub>full</sub></h3>"
1012
  "<div class='pane-body'><i>Auto-runs after every step.</i></div></div>")
1013
-
1014
- # ── Token Rank Trace: full width below ──
1015
  spark_pane = gr.HTML(value="<div class='pane'><h3>Token Rank Trace "
1016
  "(per-(head,layer) rank of a chosen token)</h3>"
1017
  "<div class='pane-body'><i>Run <code>spark &lt;token&gt;</code>.</i></div></div>")
1018
-
1019
  status = gr.HTML(value="<div class='pane'><h3>Transcript</h3>"
1020
  "<div class='pane-body dim'>Ready.</div></div>")
1021
 
1022
  # Wrap renderers so each output is its own pane (with title)
1023
- def _wrap(ctx, hm, fut, sp, mute, st):
1024
  return (
 
1025
  f"<div class='pane'><h3>Context</h3>{ctx}</div>",
1026
  f"<div class='pane'><h3>Head Map "
1027
  f"— per-head pre-projection · logit-lens · per-head Δ-residual · L<sub>full</sub></h3>{hm}</div>",
@@ -1033,27 +1180,28 @@ def build_ui():
1033
  )
1034
 
1035
  def on_load(mid, sp, up, s):
1036
- ctx, hm, fut, spk, mute, st = initial_load(mid, sp, up, s)
1037
- return _wrap(ctx, hm, fut, spk, mute, st) + (s,)
1038
 
1039
  def on_cmd(c, s, mid, sp):
1040
- ctx, hm, fut, spk, mute, st = handle_command(c, s, mid, sp)
1041
- return _wrap(ctx, hm, fut, spk, mute, st) + ("", s)
1042
 
 
1043
  load_btn.click(
1044
  on_load,
1045
  inputs=[model_id, system_prompt, user_prompt, session],
1046
- outputs=[ctx_pane, hm_pane, fut_pane, spark_pane, muted_html, status, session],
1047
  )
1048
  run_btn.click(
1049
  on_cmd,
1050
  inputs=[cmd, session, model_id, system_prompt],
1051
- outputs=[ctx_pane, hm_pane, fut_pane, spark_pane, muted_html, status, cmd, session],
1052
  )
1053
  cmd.submit(
1054
  on_cmd,
1055
  inputs=[cmd, session, model_id, system_prompt],
1056
- outputs=[ctx_pane, hm_pane, fut_pane, spark_pane, muted_html, status, cmd, session],
1057
  )
1058
  return demo
1059
 
 
13
  import io
14
  import sys
15
  import json
16
+ import math
17
  import unicodedata
18
+ from dataclasses import dataclass, field
19
  from datetime import datetime
20
 
21
  import torch
 
170
  return None
171
 
172
 
173
+ @dataclass
174
+ class Snapshot:
175
+ """One forward pass over the current context, shared by every pane.
176
+ Avoids the old pattern of xray / scan / branches each doing their own
177
+ forward. head_inputs is populated only when head_scan is supported."""
178
+ logits: torch.Tensor # [vocab] last-token logits (float)
179
+ hidden_states: tuple # len L+1, each [1, seq, hidden]
180
+ head_inputs: dict = field(default_factory=dict) # layer_idx -> o_proj input [1, seq, H*hd]
181
+ entropy: float = 0.0 # next-token entropy (nats)
182
+ top1: float = 0.0 # next-token top-1 probability
183
+
184
+
185
  # ── The Probe (lifted from cartographer3, ANSI removed) ───────────────────
186
  class InteractiveProbe:
187
  def __init__(self, model_id: str = None):
 
266
  self.full_log = []
267
  self.muted_heads = set()
268
  self._mute_handles = []
269
+ self.snapshot = None
270
 
271
  # ── architecture accessors ──
272
  def _lm_head_out_features(self):
 
289
  def o_proj(self, layer_idx):
290
  return _resolve_o_proj(self.layers[layer_idx])
291
 
292
+ # ── single shared forward pass ──
293
+ def forward_snapshot(self):
294
+ """Run ONE forward over the current context, capturing logits, hidden
295
+ states, and (Tier-2) per-layer o_proj inputs. All panes read from this."""
296
+ if self.history_ids is None:
297
+ self.snapshot = None
298
+ return None
299
+ captured = {}
300
+ handles = []
301
+ if self.head_scan_supported:
302
+ def mk(li):
303
+ def fn(module, args, output):
304
+ captured[li] = args[0].detach()
305
+ return fn
306
+ for li in range(self.num_layers):
307
+ op = self.o_proj(li)
308
+ if op is not None:
309
+ handles.append(op.register_forward_hook(mk(li)))
310
+ try:
311
+ with torch.no_grad():
312
+ out = self.model(self.history_ids, output_hidden_states=True)
313
+ finally:
314
+ for h in handles: h.remove()
315
+ last_logits = out.logits[0, -1, :].float()
316
+ probs = F.softmax(last_logits, dim=-1)
317
+ ent = float(-(probs * torch.log(probs + 1e-12)).sum().item())
318
+ top1 = float(probs.max().item())
319
+ self.snapshot = Snapshot(
320
+ logits=last_logits, hidden_states=out.hidden_states,
321
+ head_inputs=captured, entropy=ent, top1=top1,
322
+ )
323
+ return self.snapshot
324
+
325
+ def _batch_top3(self, mat: torch.Tensor, k: int = 3):
326
+ """mat: [N, hidden] → list of N rows, each [(token, prob) * k].
327
+ One norm + one lm_head + one top-k over the whole batch."""
328
+ with torch.no_grad():
329
+ normed = self.norm(mat)
330
+ logits = self.lm_head(normed) # [N, vocab]
331
+ probs = F.softmax(logits, dim=-1)
332
+ tp, ti = torch.topk(probs, k, dim=-1) # [N, k]
333
+ tp = tp.tolist(); ti = ti.tolist()
334
+ return [[(self.tokenizer.decode(ti[n][j]), tp[n][j]) for j in range(k)]
335
+ for n in range(mat.shape[0])]
336
+
337
  def set_seed(self):
338
  set_seed(SEED)
339
 
 
350
  full_prompt = prompt
351
  self.history_ids = self.tokenizer(full_prompt, return_tensors="pt").to(DEVICE).input_ids
352
 
353
+ def perform_xray(self, snap: "Snapshot" = None):
354
+ """Logit lens per layer, batched: stack all last-token hidden states,
355
+ one norm + lm_head + argmax."""
356
+ snap = snap or self.snapshot
357
+ if snap is None: return []
358
+ hs = snap.hidden_states
359
+ stacked = torch.cat([h[:, -1, :] for h in hs], dim=0) # [L+1, hidden]
360
  with torch.no_grad():
361
+ tids = self.lm_head(self.norm(stacked)).argmax(dim=-1).tolist()
362
  out = []
363
+ for i, tid in enumerate(tids):
 
 
 
 
 
364
  label = "Emb" if i == 0 else f"L{i}"
365
+ out.append((label, self.tokenizer.decode(tid)))
366
  return out
367
 
368
+ def generate_previews(self, width: int, length: int, snap: "Snapshot" = None):
369
+ snap = snap or self.snapshot
370
+ if snap is not None:
371
+ next_logits = snap.logits
372
+ else:
373
+ with torch.no_grad():
374
+ next_logits = self.model(self.history_ids).logits[0, -1, :]
375
  probs = F.softmax(next_logits, dim=-1)
376
  top_probs, top_ids = torch.topk(probs, width)
377
 
 
419
  self.history_ids = torch.cat([self.history_ids, ids], dim=1)
420
  self.full_log.append({"type": "inject", "text": text})
421
 
422
+ def scan_heads(self, snap: "Snapshot" = None, target_layers=None, target_heads=None):
423
+ """Decode the head map from a precomputed snapshot. No model call here.
424
+ Note: the per-head 'pre-projection' and per-head 'Δ-residual' are the
425
+ same quantity (a head's last-token write into the residual via o_proj);
426
+ the original tool computed them twice. We compute once and fill both."""
427
+ snap = snap or self.snapshot
428
+ if snap is None: return None
429
  if target_layers is None: target_layers = list(range(self.num_layers))
430
  if target_heads is None: target_heads = list(range(self.num_heads))
431
+ target_layers = [li for li in target_layers if 0 <= li < self.num_layers]
432
+ target_heads = [hi for hi in target_heads if 0 <= hi < self.num_heads]
433
+ hs = snap.hidden_states
434
 
435
+ pre_stream = {li: {} for li in target_layers}
436
+ delta_v = {li: {} for li in target_layers}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
 
438
+ # ── Tier-1: per-layer full Δ-residual (always available) — batched ──
439
+ full_vecs = torch.cat([hs[li + 1][:, -1, :] - hs[li][:, -1, :] for li in target_layers], dim=0)
440
+ full_top = self._batch_top3(full_vecs)
441
+ for row, li in enumerate(target_layers):
442
+ delta_v[li]["full"] = full_top[row]
 
 
443
 
444
+ do_heads = self.head_scan_supported and snap.head_inputs
445
  if not do_heads:
446
  return {"pre_stream": pre_stream, "delta_v": delta_v}
447
 
448
+ # ── Tier-2: per-head residual writes — one batched lm_head over all ──
449
+ rows = []
450
+ index = [] # (li, hi) aligned with rows
451
+ for li in target_layers:
452
+ inp = snap.head_inputs.get(li)
453
+ if inp is None: continue
454
+ wo = self.o_proj(li).weight
455
+ wv = wo.view(wo.shape[0], self.num_heads, self.head_dim)
456
+ x_last = inp[0, -1, :].view(self.num_heads, self.head_dim) # [H, hd]
457
+ # proj[h] = Wo[:, h, :] @ x_last[h] → [H, hidden]
458
+ proj_all = torch.einsum("khd,hd->hk", wv.to(x_last.dtype), x_last)
 
 
 
 
 
 
 
459
  for hi in target_heads:
460
+ rows.append(proj_all[hi])
461
+ index.append((li, hi))
462
+ if rows:
463
+ head_top = self._batch_top3(torch.stack(rows, dim=0))
464
+ for (li, hi), res in zip(index, head_top):
465
+ pre_stream[li][hi] = res
466
+ delta_v[li][hi] = res # identical quantity (see docstring)
467
  return {"pre_stream": pre_stream, "delta_v": delta_v}
468
 
469
  def _install_mute_hooks(self):
 
515
  self.full_log.append({"type": "unmute_all"})
516
  return f"UNMUTED ALL ({n} heads)"
517
 
518
+ def sparkline_data(self, token_str: str, rank_lo: int = 0, rank_hi: int = None,
519
+ snap: "Snapshot" = None):
520
  if self.history_ids is None: return None
521
  if not self.head_scan_supported:
522
  return "unsupported"
523
+ snap = snap or self.snapshot
524
+ if snap is None or not snap.head_inputs:
525
+ return None
526
  if token_str.isdigit():
527
  tid = int(token_str); name = self.tokenizer.decode(tid)
528
  else:
 
531
  tid = ids[0]; name = token_str
532
  if rank_hi is None: rank_hi = self.vocab_size
533
 
534
+ # Build [N, hidden] of every (head, layer) last-token projection, then a
535
+ # single lm_head, then rank by COMPARISON (count of logits above target)
536
+ # rather than a full argsort — O(vocab) vs O(vocab·log vocab) per row.
537
+ rows, index = [], []
538
+ for li in sorted(snap.head_inputs.keys()):
539
+ inp = snap.head_inputs[li]
 
 
 
 
 
 
 
 
 
 
 
 
540
  wo = self.o_proj(li).weight
541
+ wv = wo.view(wo.shape[0], self.num_heads, self.head_dim)
542
+ x_last = inp[0, -1, :].view(self.num_heads, self.head_dim)
543
+ proj_all = torch.einsum("khd,hd->hk", wv.to(x_last.dtype), x_last) # [H, hidden]
 
544
  for hi in range(self.num_heads):
545
+ rows.append(proj_all[hi]); index.append((hi, li))
546
+ ranks = {}
547
+ if rows:
548
+ with torch.no_grad():
549
+ logits = self.lm_head(self.norm(torch.stack(rows, dim=0))) # [N, vocab]
550
+ target = logits[:, tid].unsqueeze(1) # [N, 1]
551
+ rk = (logits > target).sum(dim=1).add(1).tolist() # [N]
552
+ for (hi, li), r in zip(index, rk):
553
+ ranks[(hi, li)] = int(r)
 
554
  return {"name": name, "tid": tid, "rank_lo": rank_lo, "rank_hi": rank_hi, "ranks": ranks}
555
 
556
 
 
634
  "architecture — showing logit-lens + full-layer Δ-residual only (Tier-1)</div>")
635
  return f"<div class='pane-body scroll'>{note}<table class='headmap'>{''.join(rows)}</table></div>"
636
 
637
+ def render_futures(options: list, selected: int = None) -> str:
638
  if not options:
639
+ return "<div class='pane-body'><i>No branches yet — click Load.</i></div>"
640
+ rows = ["<tr><th>cmd</th><th>prob</th><th>token</th><th>preview</th><th>hints</th></tr>"]
641
  for o in options:
642
+ n = o["index"] + 1
643
  prob = f"{o['prob']:.1%}"
644
  col = heat_color(o["prob"])
645
+ root_clean = o["root_token"].strip()[:12] or o["root_token"][:12]
646
+ hints = (f"<code>{n},5</code>·<code>{n},20</code>·"
647
+ f"<code>spark {html_escape(root_clean)}</code>" if root_clean else f"<code>{n},5</code>")
648
+ cls = "selected" if selected == n else ""
649
  rows.append(
650
+ f"<tr class='{cls}'>"
651
+ f"<td class='idx'><code class='cmd-pill'>{n}</code></td>"
652
  f"<td style='color:{col}'>{prob}</td>"
653
  f"<td class='tok'>{html_escape(fmt_tok(o['root_token'], 16))}</td>"
654
+ f"<td class='preview'>{html_escape(o['future_text'][:120])}…</td>"
655
+ f"<td class='cmd-hints dim'>{hints}</td>"
656
+ f"</tr>"
657
  )
658
  return f"<div class='pane-body scroll'><table class='futures'>{''.join(rows)}</table></div>"
659
 
 
715
  items = ", ".join(f"L{l}H{h}" for l, h in sorted(probe.muted_heads))
716
  return f"<span class='muted-tag'>MUTED: {items}</span>"
717
 
718
+ def render_summary(s) -> str:
719
+ """Compact run-summary strip: arch · tokens · entropy · top1 · selected · mode · muted."""
720
+ if s.probe is None:
721
+ return "<div class='summary dim'>no model loaded</div>"
722
+ p = s.probe
723
+ n_tok = p.history_ids.shape[1] if p.history_ids is not None else 0
724
+ snap = p.snapshot
725
+ ent = f"{snap.entropy:.2f}" if snap else "—"
726
+ top1 = f"{snap.top1*100:.1f}%" if snap else "—"
727
+ tier = "T2" if p.head_scan_supported else "T1"
728
+ sel = getattr(s, "last_selected", None)
729
+ sel_str = f"branch [{sel}]" if sel is not None else "—"
730
+ muted = (f"<span style='color:#ff6b6b'>muted {len(p.muted_heads)}</span>"
731
+ if p.muted_heads else "muted 0")
732
+ arch = html_escape(p.arch_name)
733
+ mid = html_escape(p.model_id)
734
+ items = [
735
+ f"<b>{arch}</b> <span class='dim'>{mid}</span>",
736
+ f"<span class='dim'>tier</span> {tier}",
737
+ f"<span class='dim'>L</span>{p.num_layers} <span class='dim'>×H</span>{p.num_heads}",
738
+ f"<span class='dim'>tok</span> {n_tok}",
739
+ f"<span class='dim'>H</span>=<b>{ent}</b>",
740
+ f"<span class='dim'>top1</span>=<b>{top1}</b>",
741
+ f"<span class='dim'>last</span> {sel_str}",
742
+ f"<span class='dim'>w</span>={s.width} <span class='dim'>len</span>={s.preview_len}",
743
+ muted,
744
+ ]
745
+ return "<div class='summary'>" + " <span class='sep'>·</span> ".join(items) + "</div>"
746
+
747
 
748
  # ── State container ──────────────────────────────────────────────────────
749
  class Session:
 
756
  self.width = DEFAULT_WIDTH
757
  self.preview_len = DEFAULT_PREVIEW
758
  self.transcript: list = [] # [(cmd, status), ...]
759
+ self.loaded_model = None
760
+ self.loaded_system = None
761
+ self.loaded_user = None
762
+ self.last_selected = None # which branch index was last committed
763
+
764
+ def _reset_panes(self):
765
+ self.options = []
766
+ self.scan_data = None
767
+ self.xray = []
768
+ self.spark = None
769
+ self.transcript = []
770
+ self.last_selected = None
771
+
772
+ def load(self, model_id, system_prompt, user_prompt, force=False):
773
+ """(Re)build the probe when model/prompt changed. Returns True if rebuilt.
774
+ Fixes the stale-session bug: clicking Load with a new model/prompt now
775
+ actually resets state instead of silently keeping the old probe."""
776
+ changed = (
777
+ force or self.probe is None
778
+ or self.loaded_model != model_id
779
+ or self.loaded_system != system_prompt
780
+ or self.loaded_user != user_prompt
781
+ )
782
+ if not changed:
783
+ return False
784
+ self.probe = InteractiveProbe(model_id=model_id)
785
+ self.probe.set_seed()
786
+ self.probe.load_start(user_prompt or "", system_prompt or None)
787
+ self._reset_panes()
788
+ self.loaded_model, self.loaded_system, self.loaded_user = model_id, system_prompt, user_prompt
789
+ return True
790
 
791
  def ensure(self, model_id: str, system_prompt: str = None, user_prompt: str = ""):
792
+ """Lazy load for the first command if the user typed before clicking Load."""
793
  if self.probe is None:
794
+ self.load(model_id, system_prompt, user_prompt or "")
 
 
795
 
796
 
797
  def panes_html(s: Session):
798
  return (
799
+ render_summary(s),
800
  render_context(s.probe),
801
  render_headmap(s.probe, s.scan_data, s.xray),
802
+ render_futures(s.options, s.last_selected),
803
  render_sparkline(s.probe, s.spark),
804
  render_muted(s.probe),
805
  )
 
833
  if 0 <= idx < len(s.options):
834
  keep_len = int(parts[1]) if len(parts) > 1 else None
835
  s.probe.commit(s.options[idx], keep_len)
836
+ s.last_selected = idx + 1
837
  _refresh_after_step(s)
838
+ status = f"selected branch [{idx+1}]"
839
  else:
840
  status = f"invalid index {idx+1}"
841
 
 
850
  target_heads = None
851
  if len(parts) > 2:
852
  target_heads = None if parts[2] == "*" else [int(parts[2])]
853
+ if s.probe.snapshot is None:
854
+ s.probe.forward_snapshot()
855
+ s.scan_data = s.probe.scan_heads(target_layers=target_layers, target_heads=target_heads)
856
  s.xray = s.probe.perform_xray()
857
  status = f"head-scan: layers={parts[1]} heads={parts[2] if len(parts)>2 else '*'}"
858
 
 
948
 
949
 
950
  def _refresh_futures(s: Session):
951
+ """Re-derive branches from the existing snapshot (context unchanged)."""
952
  if s.probe is None or s.probe.history_ids is None: return
953
+ if s.probe.snapshot is None:
954
+ s.probe.forward_snapshot()
955
  s.options = s.probe.generate_previews(s.width, s.preview_len)
956
 
957
+ def _refresh_after_step(s: Session):
958
+ """Context changed: ONE forward, then every pane reads that snapshot."""
959
  if s.probe is None or s.probe.history_ids is None: return
960
+ s.probe.forward_snapshot()
961
+ s.options = s.probe.generate_previews(s.width, s.preview_len)
962
+ s.scan_data = s.probe.scan_heads()
963
  s.xray = s.probe.perform_xray()
964
 
 
 
 
 
965
 
966
  def initial_load(model_id: str, system_prompt: str, user_prompt: str, s: Session):
967
+ rebuilt = s.load(model_id, system_prompt or None, user_prompt or "")
968
+ _refresh_after_step(s)
969
+ tier = "Tier-2 (per-head)" if s.probe.head_scan_supported else "Tier-1 only"
970
+ verb = "loaded" if rebuilt else "ready"
971
+ s.transcript.append(("(load)", f"{verb} {s.probe.arch_name} {s.probe.model_id} "
972
+ f"— {s.probe.num_layers}L×{s.probe.num_heads}H, {tier}"))
973
  return panes_html(s) + (status_html(s),)
974
 
975
 
 
1043
  table.headmap td.full { background: #0a1410; }
1044
  table.headmap tr.subhdr th { background: #161b22; color: #8b949e; font-weight: normal; font-size: 10px; }
1045
  table.futures { width: 100%; border-collapse: collapse; }
1046
+ table.futures th { background: #161b22; padding: 3px 6px; text-align: left; color: #8b949e;
1047
+ font-size: 10px; text-transform: uppercase; letter-spacing: 0.4px; }
1048
+ table.futures td { padding: 5px 6px; border-bottom: 1px solid #21262d; vertical-align: top; }
1049
+ table.futures tr:hover { background: #11161c; }
1050
+ table.futures tr.selected { background: #0f2418; outline: 1px solid #64D32A; }
1051
  table.futures td.idx { color: #6e7681; }
1052
+ .cmd-pill { background: #21262d; color: #c9d1d9; padding: 1px 7px; border-radius: 3px;
1053
+ font-weight: bold; font-size: 11px; border: 1px solid #30363d; }
1054
+ table.futures tr.selected .cmd-pill { background: #1a4022; border-color: #64D32A; color: #b8f0c4; }
1055
  table.futures td.tok { color: #c9d1d9; font-weight: bold; white-space: pre; }
1056
+ table.futures td.preview { color: #8b949e; max-width: 320px; }
1057
+ table.futures td.cmd-hints code { background: transparent; padding: 0 1px; color: #8b949e; font-size: 10.5px; }
1058
+
1059
+ /* ── Run-summary strip ── */
1060
+ #summary-strip { padding: 0 !important; margin: 0 !important; }
1061
+ .summary { font-family: 'JetBrains Mono', Consolas, monospace; font-size: 11px;
1062
+ padding: 4px 8px; background: #0d1117; border: 1px solid #30363d; border-radius: 4px;
1063
+ color: #c9d1d9; line-height: 1.5; }
1064
+ .summary .sep { color: #30363d; padding: 0 4px; }
1065
+ .summary .dim { color: #6e7681; }
1066
+
1067
+ /* ── Locked-height instrument row: widening branches does not reflow head map ── */
1068
+ #dual-row { align-items: stretch !important; }
1069
+ #dual-row > div { display: flex; flex-direction: column; }
1070
+ #dual-row #col-branch, #dual-row #col-head { height: 55vh; min-height: 360px; max-height: 640px; }
1071
+ #dual-row .pane { height: 100%; display: flex; flex-direction: column; overflow: hidden; }
1072
+ #dual-row .pane h3 { flex: 0 0 auto; }
1073
+ #dual-row .pane .pane-body { flex: 1 1 auto; max-height: none !important; overflow: auto; }
1074
+
1075
+ /* ── Placeholder legibility (was being swallowed by the dark theme) ── */
1076
+ .gradio-container textarea::placeholder,
1077
+ .gradio-container input[type="text"]::placeholder {
1078
+ color: #6e7681 !important; opacity: 1 !important;
1079
+ }
1080
+ #cmdbar textarea::placeholder, #cmdbar input[type="text"]::placeholder {
1081
+ color: #8b949e !important; opacity: 1 !important;
1082
+ }
1083
  pre.spark { margin: 0; font-size: 11px; line-height: 1.1; }
1084
  .muted-tag { color: #ff6b6b; font-weight: bold; padding: 2px 6px; }
1085
  .prompt { color: #64D32A; }
 
1102
  session = gr.State(Session())
1103
 
1104
  # ── Compact top bar: model | system | user | load ──
1105
+ MODEL_PRESETS = [
1106
+ "google/gemma-3-270m-it",
1107
+ "google/gemma-3-1b-it",
1108
+ "google/gemma-3-4b-it",
1109
+ "google/gemma-3n-E2B-it",
1110
+ "google/gemma-4-E2B-it",
1111
+ "google/gemma-4-E4B-it",
1112
+ "Qwen/Qwen3-0.6B",
1113
+ "meta-llama/Llama-3.2-1B-Instruct",
1114
+ ]
1115
  with gr.Row(elem_id="topbar"):
1116
+ model_id = gr.Dropdown(
1117
+ choices=MODEL_PRESETS, value=DEFAULT_MODEL_ID, label="Model",
1118
+ allow_custom_value=True, filterable=True, scale=3, container=True,
1119
+ )
1120
  system_prompt = gr.Textbox(label="System", value="",
1121
  lines=1, max_lines=3, scale=4, container=True)
1122
  user_prompt = gr.Textbox(
 
1128
  )
1129
  load_btn = gr.Button("Load", variant="primary", scale=1, min_width=80)
1130
 
1131
+ # ── Run-summary strip: arch · tier · L×H · tokens · entropy · top1 · selected · mode · muted ──
1132
+ summary_pane = gr.HTML(value="<div class='summary dim'>no model loaded</div>", elem_id="summary-strip")
1133
  muted_html = gr.HTML(elem_id="muted-row")
1134
 
1135
  # ── Context: full width ──
 
1149
  )
1150
  run_btn = gr.Button("Run", scale=1, variant="primary", min_width=70)
1151
 
1152
+ # ── Instrument grid: Branches | Head Map on one row, Spark + Transcript below.
1153
+ # Row heights locked so widening branches (w 30) doesn't reflow neighbors. ──
1154
+ with gr.Row(elem_id="dual-row"):
1155
+ with gr.Column(scale=3, min_width=280, elem_id="col-branch"):
1156
  fut_pane = gr.HTML(value="<div class='pane'><h3>Branches (next-token top-k)</h3>"
1157
+ "<div class='pane-body'><i>Top-k continuations appear after Load.</i></div></div>")
1158
+ with gr.Column(scale=7, elem_id="col-head"):
1159
  hm_pane = gr.HTML(value="<div class='pane'><h3>Head Map "
1160
  "— per-head pre-projection · logit-lens · per-head Δ-residual · L<sub>full</sub></h3>"
1161
  "<div class='pane-body'><i>Auto-runs after every step.</i></div></div>")
 
 
1162
  spark_pane = gr.HTML(value="<div class='pane'><h3>Token Rank Trace "
1163
  "(per-(head,layer) rank of a chosen token)</h3>"
1164
  "<div class='pane-body'><i>Run <code>spark &lt;token&gt;</code>.</i></div></div>")
 
1165
  status = gr.HTML(value="<div class='pane'><h3>Transcript</h3>"
1166
  "<div class='pane-body dim'>Ready.</div></div>")
1167
 
1168
  # Wrap renderers so each output is its own pane (with title)
1169
+ def _wrap(summary, ctx, hm, fut, sp, mute, st):
1170
  return (
1171
+ summary,
1172
  f"<div class='pane'><h3>Context</h3>{ctx}</div>",
1173
  f"<div class='pane'><h3>Head Map "
1174
  f"— per-head pre-projection · logit-lens · per-head Δ-residual · L<sub>full</sub></h3>{hm}</div>",
 
1180
  )
1181
 
1182
  def on_load(mid, sp, up, s):
1183
+ summary, ctx, hm, fut, spk, mute, st = initial_load(mid, sp, up, s)
1184
+ return _wrap(summary, ctx, hm, fut, spk, mute, st) + (s,)
1185
 
1186
  def on_cmd(c, s, mid, sp):
1187
+ summary, ctx, hm, fut, spk, mute, st = handle_command(c, s, mid, sp)
1188
+ return _wrap(summary, ctx, hm, fut, spk, mute, st) + ("", s)
1189
 
1190
+ OUT_BASE = [summary_pane, ctx_pane, hm_pane, fut_pane, spark_pane, muted_html, status]
1191
  load_btn.click(
1192
  on_load,
1193
  inputs=[model_id, system_prompt, user_prompt, session],
1194
+ outputs=OUT_BASE + [session],
1195
  )
1196
  run_btn.click(
1197
  on_cmd,
1198
  inputs=[cmd, session, model_id, system_prompt],
1199
+ outputs=OUT_BASE + [cmd, session],
1200
  )
1201
  cmd.submit(
1202
  on_cmd,
1203
  inputs=[cmd, session, model_id, system_prompt],
1204
+ outputs=OUT_BASE + [cmd, session],
1205
  )
1206
  return demo
1207