Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse files- README.md +26 -4
- app.py +817 -0
- requirements.txt +6 -0
README.md
CHANGED
|
@@ -1,12 +1,34 @@
|
|
| 1 |
---
|
| 2 |
title: Cartogemma
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: indigo
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
|
|
|
|
|
|
| 10 |
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: Cartogemma
|
| 3 |
+
emoji: πΊοΈ
|
| 4 |
colorFrom: indigo
|
| 5 |
+
colorTo: green
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 4.44.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
license: apache-2.0
|
| 11 |
+
short_description: Mechanistic probe on Gemma-3-1B-IT
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# Cartogemma
|
| 15 |
+
|
| 16 |
+
A faithful Gradio port of `cartographer3.py` / `cartographer_tui.py` against
|
| 17 |
+
**`google/gemma-3-1b-it`**. Four panes:
|
| 18 |
+
|
| 19 |
+
- **Context** β running token tail.
|
| 20 |
+
- **Head Map** β for each layer: per-head pre-stream projection Β· logit-lens xray Β·
|
| 21 |
+
per-head delta-v Β· full-layer delta-v (`L_full`). The layer projection sits as
|
| 22 |
+
another column rather than a separate view, as requested.
|
| 23 |
+
- **Futures** β top-k next-token branches with deterministic continuations.
|
| 24 |
+
- **Sparkline** β rank-of-token scatter across (head Γ layer).
|
| 25 |
+
|
| 26 |
+
REPL-style command bar: `1-N`, `i`, `h * | h L | h L H`, `top`, `rew`, `spark`,
|
| 27 |
+
`w`, `l`, `mute`/`unmute`, `muted`, `r`, `s`.
|
| 28 |
+
|
| 29 |
+
## Setup
|
| 30 |
+
|
| 31 |
+
Gemma-3-1B-IT is gated. Set a Space secret named `HF_TOKEN` with a token that
|
| 32 |
+
has accepted the model license.
|
| 33 |
+
|
| 34 |
+
CPU works for `1B`; GPU (e.g. ZeroGPU / T4) is much snappier for head-scans.
|
app.py
ADDED
|
@@ -0,0 +1,817 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cartogemma β Gradio Space wrapping InteractiveProbe against google/gemma-3-1b-it.
|
| 2 |
+
|
| 3 |
+
Faithful to the cartographer3.py / cartographer_tui.py presentation:
|
| 4 |
+
- Context tail pane
|
| 5 |
+
- Head Map: Layer | H0..Hn (pre-stream) | Xray | H0..Hn dv | Full dv
|
| 6 |
+
- Futures pane (top-k branches with probs + previews)
|
| 7 |
+
- Sparkline pane (token rank scatter across heads x layers, rendered as <pre>)
|
| 8 |
+
- REPL command bar (1-N, h, top, rew, i, spark, mute, unmute, w, l, s, q)
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import re
|
| 13 |
+
import io
|
| 14 |
+
import sys
|
| 15 |
+
import json
|
| 16 |
+
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-1b-it")
|
| 26 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
| 27 |
+
SEED = 42
|
| 28 |
+
DEFAULT_WIDTH = 5
|
| 29 |
+
DEFAULT_PREVIEW = 20
|
| 30 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 31 |
+
|
| 32 |
+
# ββ HEAT palette (mirrors cartographer3) ββββββββββββββββββββββββββββββββββ
|
| 33 |
+
HEAT_HEX = ["#59749C", "#948863", "#ECA60F", "#FFCF67", "#219C7F", "#E0D05B", "#64D32A"]
|
| 34 |
+
|
| 35 |
+
def heat_color(p: float) -> str:
|
| 36 |
+
if p >= 0.85: return HEAT_HEX[6]
|
| 37 |
+
if p >= 0.70: return HEAT_HEX[5]
|
| 38 |
+
if p >= 0.50: return HEAT_HEX[4]
|
| 39 |
+
if p >= 0.30: return HEAT_HEX[3]
|
| 40 |
+
if p >= 0.15: return HEAT_HEX[2]
|
| 41 |
+
if p >= 0.05: return HEAT_HEX[1]
|
| 42 |
+
return HEAT_HEX[0]
|
| 43 |
+
|
| 44 |
+
def char_width(ch: str) -> int:
|
| 45 |
+
cat = unicodedata.category(ch)
|
| 46 |
+
if cat in ("Mn", "Me"): return 0
|
| 47 |
+
eaw = unicodedata.east_asian_width(ch)
|
| 48 |
+
if eaw in ("W", "F"): return 2
|
| 49 |
+
return 1
|
| 50 |
+
|
| 51 |
+
def fmt_tok(tok: str, max_w: int = 10) -> str:
|
| 52 |
+
tok = tok.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t")
|
| 53 |
+
w, out = 0, []
|
| 54 |
+
for ch in tok:
|
| 55 |
+
cw = char_width(ch)
|
| 56 |
+
if w + cw > max_w: break
|
| 57 |
+
out.append(ch); w += cw
|
| 58 |
+
return "".join(out)
|
| 59 |
+
|
| 60 |
+
def html_escape(s: str) -> str:
|
| 61 |
+
return s.replace("&", "&").replace("<", "<").replace(">", ">")
|
| 62 |
+
|
| 63 |
+
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):
|
| 70 |
+
model_id = model_id or DEFAULT_MODEL_ID
|
| 71 |
+
self.model_id = model_id
|
| 72 |
+
print(f"[*] Loading {model_id} on {DEVICE}...")
|
| 73 |
+
kw = {"token": HF_TOKEN} if HF_TOKEN else {}
|
| 74 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_id, **kw)
|
| 75 |
+
self.tokenizer.padding_side = "left"
|
| 76 |
+
if self.tokenizer.pad_token is None:
|
| 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 |
+
|
| 124 |
+
def load_start(self, prompt: str, system_prompt: str = None):
|
| 125 |
+
messages = []
|
| 126 |
+
if system_prompt:
|
| 127 |
+
messages.append({"role": "system", "content": system_prompt})
|
| 128 |
+
messages.append({"role": "user", "content": prompt})
|
| 129 |
+
try:
|
| 130 |
+
full_prompt = self.tokenizer.apply_chat_template(
|
| 131 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 132 |
+
)
|
| 133 |
+
except Exception:
|
| 134 |
+
full_prompt = prompt
|
| 135 |
+
self.history_ids = self.tokenizer(full_prompt, return_tensors="pt").to(DEVICE).input_ids
|
| 136 |
+
|
| 137 |
+
def perform_xray(self):
|
| 138 |
+
if self.history_ids is None: return []
|
| 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}"
|
| 150 |
+
out.append((label, tok))
|
| 151 |
+
return out
|
| 152 |
+
|
| 153 |
+
def generate_previews(self, width: int, length: int):
|
| 154 |
+
with torch.no_grad():
|
| 155 |
+
outputs = self.model(self.history_ids)
|
| 156 |
+
next_logits = outputs.logits[0, -1, :]
|
| 157 |
+
probs = F.softmax(next_logits, dim=-1)
|
| 158 |
+
top_probs, top_ids = torch.topk(probs, width)
|
| 159 |
+
|
| 160 |
+
batch_inputs = []
|
| 161 |
+
for i in range(width):
|
| 162 |
+
tid = top_ids[i].item()
|
| 163 |
+
nxt = torch.cat([self.history_ids, torch.tensor([[tid]], device=DEVICE)], dim=1)
|
| 164 |
+
batch_inputs.append(nxt)
|
| 165 |
+
batch = torch.cat(batch_inputs, dim=0)
|
| 166 |
+
|
| 167 |
+
with torch.no_grad():
|
| 168 |
+
outs = self.model.generate(
|
| 169 |
+
batch, max_new_tokens=length, do_sample=False, temperature=0.0,
|
| 170 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 171 |
+
)
|
| 172 |
+
previews = []
|
| 173 |
+
for i in range(width):
|
| 174 |
+
tid = top_ids[i].item()
|
| 175 |
+
p = top_probs[i].item()
|
| 176 |
+
full_seq = outs[i]
|
| 177 |
+
trunk_len = self.history_ids.shape[1]
|
| 178 |
+
root = self.tokenizer.decode(full_seq[trunk_len])
|
| 179 |
+
future = self.tokenizer.decode(full_seq[trunk_len + 1:], skip_special_tokens=False)
|
| 180 |
+
previews.append({
|
| 181 |
+
"index": i, "token_id": tid, "root_token": root, "prob": p,
|
| 182 |
+
"future_text": future.replace("\n", "\\n"),
|
| 183 |
+
"full_ids": full_seq.unsqueeze(0),
|
| 184 |
+
})
|
| 185 |
+
return previews
|
| 186 |
+
|
| 187 |
+
def commit(self, preview_obj, tokens_to_keep=None):
|
| 188 |
+
full_seq = preview_obj["full_ids"]
|
| 189 |
+
trunk_len = self.history_ids.shape[1]
|
| 190 |
+
if tokens_to_keep is None:
|
| 191 |
+
cut = full_seq.shape[1]
|
| 192 |
+
else:
|
| 193 |
+
cut = min(trunk_len + 1 + tokens_to_keep, full_seq.shape[1])
|
| 194 |
+
self.history_ids = full_seq[:, :cut]
|
| 195 |
+
committed = self.tokenizer.decode(self.history_ids[0, trunk_len:], skip_special_tokens=True)
|
| 196 |
+
self.full_log.append({"type": "commit", "token": preview_obj["root_token"],
|
| 197 |
+
"full_text": committed, "kept_len": tokens_to_keep})
|
| 198 |
+
|
| 199 |
+
def inject(self, text: str):
|
| 200 |
+
ids = self.tokenizer(text, return_tensors="pt", add_special_tokens=False).to(DEVICE).input_ids
|
| 201 |
+
self.history_ids = torch.cat([self.history_ids, ids], dim=1)
|
| 202 |
+
self.full_log.append({"type": "inject", "text": text})
|
| 203 |
+
|
| 204 |
+
def scan_heads(self, target_layers=None, target_heads=None):
|
| 205 |
+
if self.history_ids is None: return None
|
| 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
|
| 237 |
+
multi = inp.view(b, s, self.num_heads, head_dim)
|
| 238 |
+
wv = wo.view(hidden, self.num_heads, head_dim)
|
| 239 |
+
|
| 240 |
+
for hi in target_heads:
|
| 241 |
+
if not (0 <= hi < self.num_heads): continue
|
| 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):
|
| 276 |
+
for h in self._mute_handles: h.remove()
|
| 277 |
+
self._mute_handles = []
|
| 278 |
+
if not self.muted_heads: return
|
| 279 |
+
muted_by_layer = {}
|
| 280 |
+
for (l, h) in self.muted_heads:
|
| 281 |
+
muted_by_layer.setdefault(l, set()).add(h)
|
| 282 |
+
hd, nh = self.head_dim, self.num_heads
|
| 283 |
+
for li, heads in muted_by_layer.items():
|
| 284 |
+
def make_hook(muted_set, head_dim, num_heads):
|
| 285 |
+
def fn(module, args):
|
| 286 |
+
x = args[0]
|
| 287 |
+
xv = x.view(x.shape[0], x.shape[1], num_heads, head_dim)
|
| 288 |
+
for h in muted_set:
|
| 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)
|
| 299 |
+
if key in self.muted_heads: return f"L{layer}H{head} already muted"
|
| 300 |
+
self.muted_heads.add(key)
|
| 301 |
+
self._install_mute_hooks()
|
| 302 |
+
self.full_log.append({"type": "mute", "layer": layer, "head": head})
|
| 303 |
+
return f"MUTED L{layer}H{head}"
|
| 304 |
+
|
| 305 |
+
def unmute_head(self, layer, head):
|
| 306 |
+
key = (layer, head)
|
| 307 |
+
if key not in self.muted_heads: return f"L{layer}H{head} not muted"
|
| 308 |
+
self.muted_heads.discard(key)
|
| 309 |
+
self._install_mute_hooks()
|
| 310 |
+
self.full_log.append({"type": "unmute", "layer": layer, "head": head})
|
| 311 |
+
return f"UNMUTED L{layer}H{head}"
|
| 312 |
+
|
| 313 |
+
def unmute_all(self):
|
| 314 |
+
for h in self._mute_handles: h.remove()
|
| 315 |
+
self._mute_handles = []
|
| 316 |
+
n = len(self.muted_heads)
|
| 317 |
+
self.muted_heads.clear()
|
| 318 |
+
self.full_log.append({"type": "unmute_all"})
|
| 319 |
+
return f"UNMUTED ALL ({n} heads)"
|
| 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:
|
| 326 |
+
ids = self.tokenizer.encode(token_str, add_special_tokens=False)
|
| 327 |
+
if not ids: return None
|
| 328 |
+
tid = ids[0]; name = token_str
|
| 329 |
+
if rank_hi is None: rank_hi = self.vocab_size
|
| 330 |
+
|
| 331 |
+
captured = {}
|
| 332 |
+
def get_hook(li):
|
| 333 |
+
def fn(module, args, output):
|
| 334 |
+
captured[li] = args[0].detach()
|
| 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)
|
| 353 |
+
wv = wo.view(hidden, self.num_heads, head_dim)
|
| 354 |
+
for hi in range(self.num_heads):
|
| 355 |
+
ho = multi[:, -1, hi, :]
|
| 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
|
| 364 |
+
ranks[(hi, li)] = rank
|
| 365 |
+
return {"name": name, "tid": tid, "rank_lo": rank_lo, "rank_hi": rank_hi, "ranks": ranks}
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
# ββ HTML renderers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 369 |
+
CELL_W = 10 # display chars per token cell
|
| 370 |
+
|
| 371 |
+
def render_context(probe: InteractiveProbe) -> str:
|
| 372 |
+
if probe is None or probe.history_ids is None:
|
| 373 |
+
return "<div class='pane-body'><i>No context loaded.</i></div>"
|
| 374 |
+
full = probe.tokenizer.decode(probe.history_ids[0], skip_special_tokens=False)
|
| 375 |
+
tail = full[-800:].replace("\n", " ")
|
| 376 |
+
if len(full) > 800: tail = "..." + tail
|
| 377 |
+
n = probe.history_ids.shape[1]
|
| 378 |
+
return (f"<div class='pane-body'>"
|
| 379 |
+
f"<div class='dim'>[{n} tokens]</div>"
|
| 380 |
+
f"<div class='context-text'>{html_escape(tail)}</div></div>")
|
| 381 |
+
|
| 382 |
+
def render_headmap(probe: InteractiveProbe, data: dict, xray: list) -> str:
|
| 383 |
+
if not data:
|
| 384 |
+
return "<div class='pane-body'><i>No head-scan run yet. Try <code>h *</code> for all layers.</i></div>"
|
| 385 |
+
pre, dv = data.get("pre_stream", {}), data.get("delta_v", {})
|
| 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):
|
| 393 |
+
clean = html_escape(fmt_tok(tok, CELL_W))
|
| 394 |
+
c = heat_color(prob)
|
| 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>")
|
| 402 |
+
for h in heads: hdr.append(f"<th class='dv'>H{h}<sub>dv</sub></th>")
|
| 403 |
+
hdr.append("<th class='dv full'>L<sub>full</sub></th>")
|
| 404 |
+
hdr.append("</tr>")
|
| 405 |
+
rows.append("".join(hdr))
|
| 406 |
+
|
| 407 |
+
sub = ["<tr class='subhdr'><th></th>"]
|
| 408 |
+
sub.append(f"<th class='ps' colspan='{len(heads)}'>pre-stream (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}'>delta-v (attn+MLP+skip), incl. full layer</th>")
|
| 411 |
+
sub.append("</tr>")
|
| 412 |
+
rows.insert(0, "".join(sub))
|
| 413 |
+
|
| 414 |
+
for l in layers:
|
| 415 |
+
r = [f"<tr><td class='lay'>L{l}</td>"]
|
| 416 |
+
for h in heads:
|
| 417 |
+
if h in pre.get(l, {}):
|
| 418 |
+
tok, p = pre[l][h][0]; r.append(cell(tok, p))
|
| 419 |
+
else:
|
| 420 |
+
r.append("<td class='hm-cell'>--</td>")
|
| 421 |
+
# Xray (logit lens at this layer)
|
| 422 |
+
label = "Emb" if l == 0 else f"L{l}"
|
| 423 |
+
xt = xray_map.get(label, "--")
|
| 424 |
+
r.append(f"<td class='hm-cell xr'>{html_escape(fmt_tok(xt, CELL_W))}</td>")
|
| 425 |
+
# delta-v per head
|
| 426 |
+
dvl = dv.get(l, {})
|
| 427 |
+
for h in heads:
|
| 428 |
+
if h in dvl:
|
| 429 |
+
tok, p = dvl[h][0]; r.append(cell(tok, p))
|
| 430 |
+
else:
|
| 431 |
+
r.append("<td class='hm-cell'>--</td>")
|
| 432 |
+
# full layer dv
|
| 433 |
+
if "full" in dvl:
|
| 434 |
+
tok, p = dvl["full"][0]
|
| 435 |
+
r.append(f"<td class='hm-cell full' style='color:{heat_color(p)}'>{html_escape(fmt_tok(tok, CELL_W))}</td>")
|
| 436 |
+
else:
|
| 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:
|
| 444 |
+
return "<div class='pane-body'><i>No futures yet.</i></div>"
|
| 445 |
+
rows = ["<tr><th>#</th><th>Prob</th><th>Token</th><th>Preview</th></tr>"]
|
| 446 |
+
for o in options:
|
| 447 |
+
prob = f"{o['prob']:.1%}"
|
| 448 |
+
col = heat_color(o["prob"])
|
| 449 |
+
rows.append(
|
| 450 |
+
f"<tr><td class='idx'>[{o['index']+1}]</td>"
|
| 451 |
+
f"<td style='color:{col}'>{prob}</td>"
|
| 452 |
+
f"<td class='tok'>{html_escape(fmt_tok(o['root_token'], 16))}</td>"
|
| 453 |
+
f"<td class='preview'>{html_escape(o['future_text'][:120])}β¦</td></tr>"
|
| 454 |
+
)
|
| 455 |
+
return f"<div class='pane-body scroll'><table class='futures'>{''.join(rows)}</table></div>"
|
| 456 |
+
|
| 457 |
+
def render_sparkline(probe: InteractiveProbe, sd: dict) -> str:
|
| 458 |
+
if not sd:
|
| 459 |
+
return "<div class='pane-body'><i>No sparkline. Try <code>spark <token> [lo:hi]</code>.</i></div>"
|
| 460 |
+
n_layers = probe.num_layers
|
| 461 |
+
n_heads = probe.num_heads
|
| 462 |
+
rank_lo, rank_hi = sd["rank_lo"], sd["rank_hi"]
|
| 463 |
+
span = max(rank_hi - rank_lo, 1)
|
| 464 |
+
ranks = sd["ranks"]
|
| 465 |
+
band_h = 8
|
| 466 |
+
head_colors = ["#64D32A", "#FFCF67", "#21C5C5", "#E78BFF"]
|
| 467 |
+
lines = []
|
| 468 |
+
name = sd["name"].replace("\n", "\\n")[:15]
|
| 469 |
+
lines.append(f"Scatter: '{html_escape(name)}' (id={sd['tid']}) rank {rank_lo:,} (top) β {rank_hi:,} (bottom)")
|
| 470 |
+
hdr = " " + "".join(f"{l:>3}" for l in range(n_layers))
|
| 471 |
+
lines.append(f"<span class='dim'>{html_escape(hdr)}</span>")
|
| 472 |
+
lines.append(f" {'β' * (n_layers * 3)}")
|
| 473 |
+
for hi in range(n_heads):
|
| 474 |
+
color = head_colors[hi % len(head_colors)]
|
| 475 |
+
grid = [[" "] * n_layers for _ in range(band_h)]
|
| 476 |
+
for li in range(n_layers):
|
| 477 |
+
r = ranks.get((hi, li), rank_hi + 1)
|
| 478 |
+
if r < rank_lo:
|
| 479 |
+
grid[0][li] = "β²"
|
| 480 |
+
elif r > rank_hi:
|
| 481 |
+
grid[band_h - 1][li] = "βΌ"
|
| 482 |
+
else:
|
| 483 |
+
frac = (r - rank_lo) / span
|
| 484 |
+
row = int(frac * (band_h - 1))
|
| 485 |
+
grid[max(0, min(band_h - 1, row))][li] = "β"
|
| 486 |
+
for ri in range(band_h):
|
| 487 |
+
if ri == 0:
|
| 488 |
+
label = f"H{hi} {rank_lo:>6}β"
|
| 489 |
+
elif ri == band_h - 1:
|
| 490 |
+
label = f" {rank_hi:>6}β"
|
| 491 |
+
elif ri == band_h // 2:
|
| 492 |
+
mid = rank_lo + span // 2
|
| 493 |
+
label = f" {mid:>6}β"
|
| 494 |
+
else:
|
| 495 |
+
label = f" β"
|
| 496 |
+
cells = []
|
| 497 |
+
for li in range(n_layers):
|
| 498 |
+
ch = grid[ri][li]
|
| 499 |
+
if ch in ("β", "β²", "βΌ"):
|
| 500 |
+
cells.append(f"<span style='color:{color}'> {ch} </span>")
|
| 501 |
+
else:
|
| 502 |
+
cells.append(f" {ch} ")
|
| 503 |
+
lines.append(html_escape(label) + "".join(cells))
|
| 504 |
+
if hi < n_heads - 1:
|
| 505 |
+
lines.append(f" {'β' * (n_layers * 3)}")
|
| 506 |
+
lines.append(f" {'β' * (n_layers * 3)}")
|
| 507 |
+
return f"<div class='pane-body scroll'><pre class='spark'>{chr(10).join(lines)}</pre></div>"
|
| 508 |
+
|
| 509 |
+
def render_muted(probe: InteractiveProbe) -> str:
|
| 510 |
+
if probe is None or not probe.muted_heads:
|
| 511 |
+
return ""
|
| 512 |
+
items = ", ".join(f"L{l}H{h}" for l, h in sorted(probe.muted_heads))
|
| 513 |
+
return f"<span class='muted-tag'>MUTED: {items}</span>"
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
# ββ State container ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 517 |
+
class Session:
|
| 518 |
+
def __init__(self):
|
| 519 |
+
self.probe: InteractiveProbe = None
|
| 520 |
+
self.options: list = []
|
| 521 |
+
self.scan_data: dict = None
|
| 522 |
+
self.xray: list = []
|
| 523 |
+
self.spark: dict = None
|
| 524 |
+
self.width = DEFAULT_WIDTH
|
| 525 |
+
self.preview_len = DEFAULT_PREVIEW
|
| 526 |
+
self.transcript: list = [] # [(cmd, status), ...]
|
| 527 |
+
|
| 528 |
+
def ensure(self, model_id: str, system_prompt: str = None, user_prompt: str = ""):
|
| 529 |
+
if self.probe is None:
|
| 530 |
+
self.probe = InteractiveProbe(model_id=model_id)
|
| 531 |
+
self.probe.set_seed()
|
| 532 |
+
self.probe.load_start(user_prompt or "", system_prompt or None)
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def panes_html(s: Session):
|
| 536 |
+
return (
|
| 537 |
+
render_context(s.probe),
|
| 538 |
+
render_headmap(s.probe, s.scan_data, s.xray),
|
| 539 |
+
render_futures(s.options),
|
| 540 |
+
render_sparkline(s.probe, s.spark),
|
| 541 |
+
render_muted(s.probe),
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def status_html(s: Session) -> str:
|
| 546 |
+
if not s.transcript:
|
| 547 |
+
return "<div class='pane-body dim'>Ready.</div>"
|
| 548 |
+
rows = []
|
| 549 |
+
for cmd, status in s.transcript[-20:]:
|
| 550 |
+
rows.append(f"<div><span class='prompt'>βΊ</span> <code>{html_escape(cmd)}</code> "
|
| 551 |
+
f"<span class='dim'>β {html_escape(status)}</span></div>")
|
| 552 |
+
return f"<div class='pane-body scroll'>{''.join(rows)}</div>"
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def handle_command(cmd: str, s: Session, model_id: str, system_prompt: str):
|
| 556 |
+
cmd = (cmd or "").strip()
|
| 557 |
+
if not cmd:
|
| 558 |
+
return panes_html(s) + (status_html(s),)
|
| 559 |
+
|
| 560 |
+
# Lazy load model on first command (so UI renders fast)
|
| 561 |
+
s.ensure(model_id=model_id, system_prompt=system_prompt)
|
| 562 |
+
|
| 563 |
+
status = "ok"
|
| 564 |
+
try:
|
| 565 |
+
lc = cmd.lower()
|
| 566 |
+
|
| 567 |
+
if cmd[0].isdigit():
|
| 568 |
+
parts = cmd.split(",")
|
| 569 |
+
idx = int(parts[0]) - 1
|
| 570 |
+
if 0 <= idx < len(s.options):
|
| 571 |
+
keep_len = int(parts[1]) if len(parts) > 1 else None
|
| 572 |
+
s.probe.commit(s.options[idx], keep_len)
|
| 573 |
+
_refresh_after_step(s)
|
| 574 |
+
status = f"committed [{idx+1}]"
|
| 575 |
+
else:
|
| 576 |
+
status = f"invalid index {idx+1}"
|
| 577 |
+
|
| 578 |
+
elif lc.startswith("i "):
|
| 579 |
+
s.probe.inject(cmd[2:])
|
| 580 |
+
_refresh_after_step(s)
|
| 581 |
+
status = f"injected '{cmd[2:][:30]}'"
|
| 582 |
+
|
| 583 |
+
elif lc.startswith("h "):
|
| 584 |
+
parts = cmd.split()
|
| 585 |
+
target_layers = None if parts[1] == "*" else [int(parts[1])]
|
| 586 |
+
target_heads = None
|
| 587 |
+
if len(parts) > 2:
|
| 588 |
+
target_heads = None if parts[2] == "*" else [int(parts[2])]
|
| 589 |
+
s.scan_data = s.probe.scan_heads(target_layers, target_heads)
|
| 590 |
+
s.xray = s.probe.perform_xray()
|
| 591 |
+
status = f"head-scan: layers={parts[1]} heads={parts[2] if len(parts)>2 else '*'}"
|
| 592 |
+
|
| 593 |
+
elif lc.startswith("top "):
|
| 594 |
+
ranks = [int(r.strip()) for r in cmd[4:].split(",")]
|
| 595 |
+
for rank in ranks:
|
| 596 |
+
with torch.no_grad():
|
| 597 |
+
out = s.probe.model(s.probe.history_ids)
|
| 598 |
+
logits = out.logits[0, -1, :]
|
| 599 |
+
probs = F.softmax(logits, dim=-1)
|
| 600 |
+
sp, si = torch.sort(probs, descending=True)
|
| 601 |
+
if rank < 1 or rank > len(si): continue
|
| 602 |
+
tid = si[rank - 1].item()
|
| 603 |
+
s.probe.history_ids = torch.cat(
|
| 604 |
+
[s.probe.history_ids, torch.tensor([[tid]], device=DEVICE)], dim=1
|
| 605 |
+
)
|
| 606 |
+
s.probe.full_log.append({"type": "top_select", "rank": rank,
|
| 607 |
+
"token": s.probe.tokenizer.decode([tid]),
|
| 608 |
+
"token_id": tid, "prob": sp[rank-1].item()})
|
| 609 |
+
_refresh_after_step(s)
|
| 610 |
+
status = f"top-selected {len(ranks)} tokens"
|
| 611 |
+
|
| 612 |
+
elif lc.startswith("rew "):
|
| 613 |
+
n = int(cmd[4:].strip())
|
| 614 |
+
cur = s.probe.history_ids.shape[1]
|
| 615 |
+
new = max(1, cur - n)
|
| 616 |
+
s.probe.history_ids = s.probe.history_ids[:, :new]
|
| 617 |
+
s.probe.full_log.append({"type": "rewind", "tokens_removed": cur - new})
|
| 618 |
+
_refresh_after_step(s)
|
| 619 |
+
status = f"rewound {cur - new} tokens"
|
| 620 |
+
|
| 621 |
+
elif lc.startswith("w "):
|
| 622 |
+
s.width = int(cmd[2:]); status = f"width={s.width}"
|
| 623 |
+
_refresh_futures(s)
|
| 624 |
+
|
| 625 |
+
elif lc.startswith("l "):
|
| 626 |
+
s.preview_len = int(cmd[2:]); status = f"preview_len={s.preview_len}"
|
| 627 |
+
_refresh_futures(s)
|
| 628 |
+
|
| 629 |
+
elif lc.startswith("spark "):
|
| 630 |
+
parts = cmd[6:].strip().split()
|
| 631 |
+
tok = parts[0]
|
| 632 |
+
rl, rh = 0, None
|
| 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()
|
| 641 |
+
status = s.probe.mute_head(int(parts[1]), int(parts[2]))
|
| 642 |
+
_refresh_after_step(s)
|
| 643 |
+
|
| 644 |
+
elif lc == "unmute all":
|
| 645 |
+
status = s.probe.unmute_all()
|
| 646 |
+
_refresh_after_step(s)
|
| 647 |
+
|
| 648 |
+
elif lc.startswith("unmute "):
|
| 649 |
+
parts = cmd.split()
|
| 650 |
+
status = s.probe.unmute_head(int(parts[1]), int(parts[2]))
|
| 651 |
+
_refresh_after_step(s)
|
| 652 |
+
|
| 653 |
+
elif lc == "muted":
|
| 654 |
+
status = f"muted: {sorted(s.probe.muted_heads)}"
|
| 655 |
+
|
| 656 |
+
elif lc == "s":
|
| 657 |
+
ts = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 658 |
+
fname = f"/tmp/session_{ts}.json"
|
| 659 |
+
with open(fname, "w") as f: json.dump(s.probe.full_log, f, indent=2)
|
| 660 |
+
status = f"saved {fname}"
|
| 661 |
+
|
| 662 |
+
elif lc == "refresh" or lc == "r":
|
| 663 |
+
_refresh_after_step(s)
|
| 664 |
+
status = "refreshed"
|
| 665 |
+
|
| 666 |
+
elif lc == "q":
|
| 667 |
+
status = "(q is a no-op in the web UI β close the tab)"
|
| 668 |
+
|
| 669 |
+
else:
|
| 670 |
+
status = f"unknown: {cmd}"
|
| 671 |
+
except Exception as e:
|
| 672 |
+
status = f"error: {type(e).__name__}: {e}"
|
| 673 |
+
|
| 674 |
+
s.transcript.append((cmd, status))
|
| 675 |
+
return panes_html(s) + (status_html(s),)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def _refresh_futures(s: Session):
|
| 679 |
+
if s.probe is None or s.probe.history_ids is None: return
|
| 680 |
+
s.options = s.probe.generate_previews(s.width, s.preview_len)
|
| 681 |
+
|
| 682 |
+
def _refresh_after_step(s: Session):
|
| 683 |
+
_refresh_futures(s)
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def initial_load(model_id: str, system_prompt: str, user_prompt: str, s: Session):
|
| 687 |
+
s.ensure(model_id=model_id, system_prompt=system_prompt or None, user_prompt=user_prompt or "")
|
| 688 |
+
_refresh_futures(s)
|
| 689 |
+
s.transcript.append(("(load)", f"loaded {s.probe.model_id} "
|
| 690 |
+
f"({s.probe.num_layers}LΓ{s.probe.num_heads}H)"))
|
| 691 |
+
return panes_html(s) + (status_html(s),)
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 695 |
+
CSS = """
|
| 696 |
+
.gradio-container { max-width: 100% !important; }
|
| 697 |
+
#cartogemma-grid { display: grid; grid-template-columns: 1fr 2fr; grid-template-rows: auto auto auto; gap: 8px; }
|
| 698 |
+
.pane { border: 1px solid #444; border-radius: 4px; background: #0d1117; color: #c9d1d9;
|
| 699 |
+
font-family: 'JetBrains Mono', 'Fira Code', Consolas, monospace; font-size: 12px; }
|
| 700 |
+
.pane h3 { margin: 0; padding: 4px 8px; background: #161b22; border-bottom: 1px solid #30363d;
|
| 701 |
+
font-size: 11px; letter-spacing: 0.5px; text-transform: uppercase; color: #8b949e; }
|
| 702 |
+
.pane-body { padding: 6px 8px; max-height: 360px; overflow: auto; }
|
| 703 |
+
.pane-body.scroll { overflow: auto; }
|
| 704 |
+
.dim { color: #6e7681; }
|
| 705 |
+
.context-text { white-space: pre-wrap; word-break: break-word; margin-top: 4px; }
|
| 706 |
+
table.headmap { border-collapse: collapse; font-size: 11px; }
|
| 707 |
+
table.headmap th, table.headmap td { padding: 1px 4px; border: 1px solid #21262d; text-align: center; white-space: pre; }
|
| 708 |
+
table.headmap th.ps { background: #112; }
|
| 709 |
+
table.headmap th.xr { background: #221; color: #ECA60F; }
|
| 710 |
+
table.headmap th.dv { background: #122; }
|
| 711 |
+
table.headmap th.full { background: #133; color: #64D32A; }
|
| 712 |
+
table.headmap td.lay { color: #8b949e; }
|
| 713 |
+
table.headmap td.xr { color: #ECA60F; background: #15110a; }
|
| 714 |
+
table.headmap td.full { background: #0a1410; }
|
| 715 |
+
table.headmap tr.subhdr th { background: #161b22; color: #8b949e; font-weight: normal; font-size: 10px; }
|
| 716 |
+
table.futures { width: 100%; border-collapse: collapse; }
|
| 717 |
+
table.futures th { background: #161b22; padding: 3px 6px; text-align: left; color: #8b949e; font-size: 10px; }
|
| 718 |
+
table.futures td { padding: 3px 6px; border-bottom: 1px solid #21262d; }
|
| 719 |
+
table.futures td.idx { color: #6e7681; }
|
| 720 |
+
table.futures td.tok { color: #c9d1d9; font-weight: bold; white-space: pre; }
|
| 721 |
+
table.futures td.preview { color: #8b949e; }
|
| 722 |
+
pre.spark { margin: 0; font-size: 11px; line-height: 1.1; }
|
| 723 |
+
.muted-tag { color: #ff6b6b; font-weight: bold; padding: 2px 6px; }
|
| 724 |
+
.prompt { color: #64D32A; }
|
| 725 |
+
"""
|
| 726 |
+
|
| 727 |
+
HELP = """\
|
| 728 |
+
**Commands** (REPL-style):
|
| 729 |
+
`1`β`N` commit future Β· `1,5` commit + keep 5 tokens Β· `i <text>` inject Β·
|
| 730 |
+
`h * | h L | h L H` head-scan Β· `top R1,R2,...` rank-pick tokens Β·
|
| 731 |
+
`rew N` rewind Β· `spark <tok> [lo:hi]` rank scatter Β· `w N` width Β· `l N` length Β·
|
| 732 |
+
`mute L H` / `unmute L H` / `unmute all` / `muted` Β·
|
| 733 |
+
`r` refresh futures Β· `s` save log Β· `q` (no-op)
|
| 734 |
+
"""
|
| 735 |
+
|
| 736 |
+
def build_ui():
|
| 737 |
+
with gr.Blocks(title="Cartogemma", css=CSS, theme=gr.themes.Base()) as demo:
|
| 738 |
+
gr.Markdown("# Cartogemma \n*Mechanistic probe (logit lens Β· head map Β· futures Β· rank sparkline) "
|
| 739 |
+
"wrapping `google/gemma-3-1b-it`. Layout faithful to `cartographer3.py`.*")
|
| 740 |
+
|
| 741 |
+
session = gr.State(Session())
|
| 742 |
+
|
| 743 |
+
with gr.Row():
|
| 744 |
+
with gr.Column(scale=2):
|
| 745 |
+
model_id = gr.Textbox(value=DEFAULT_MODEL_ID, label="Model ID",
|
| 746 |
+
info="Gated model β set HF_TOKEN as a Space secret.")
|
| 747 |
+
with gr.Column(scale=3):
|
| 748 |
+
system_prompt = gr.Textbox(label="System prompt", value="", lines=1)
|
| 749 |
+
with gr.Column(scale=3):
|
| 750 |
+
user_prompt = gr.Textbox(label="Initial user prompt", value="", lines=1)
|
| 751 |
+
with gr.Column(scale=1, min_width=120):
|
| 752 |
+
load_btn = gr.Button("Load model", variant="primary")
|
| 753 |
+
|
| 754 |
+
muted_html = gr.HTML()
|
| 755 |
+
|
| 756 |
+
with gr.Row():
|
| 757 |
+
ctx_pane = gr.HTML(label="Context", value="<div class='pane'><h3>Context</h3>"
|
| 758 |
+
"<div class='pane-body'><i>Click <b>Load model</b> to begin.</i></div></div>")
|
| 759 |
+
hm_pane = gr.HTML(label="Head Map", value="<div class='pane'><h3>Head Map "
|
| 760 |
+
"(pre-stream | xray | delta-v | L<sub>full</sub>)</h3>"
|
| 761 |
+
"<div class='pane-body'><i>Run <code>h *</code> after loading.</i></div></div>")
|
| 762 |
+
|
| 763 |
+
with gr.Row():
|
| 764 |
+
fut_pane = gr.HTML(label="Futures", value="<div class='pane'><h3>Futures</h3>"
|
| 765 |
+
"<div class='pane-body'><i>Top-k branches will appear here.</i></div></div>")
|
| 766 |
+
spark_pane = gr.HTML(label="Sparkline", value="<div class='pane'><h3>Sparkline</h3>"
|
| 767 |
+
"<div class='pane-body'><i>Run <code>spark <token></code>.</i></div></div>")
|
| 768 |
+
|
| 769 |
+
gr.Markdown(HELP)
|
| 770 |
+
|
| 771 |
+
with gr.Row():
|
| 772 |
+
cmd = gr.Textbox(label="CMD", placeholder="1-N | h * | top 1000,3,1 | spark the | mute 5 2 | β¦",
|
| 773 |
+
scale=8, autofocus=True)
|
| 774 |
+
run_btn = gr.Button("Run", scale=1, variant="primary")
|
| 775 |
+
|
| 776 |
+
status = gr.HTML(value="<div class='pane'><h3>Transcript</h3>"
|
| 777 |
+
"<div class='pane-body dim'>Ready.</div></div>")
|
| 778 |
+
|
| 779 |
+
# Wrap renderers so each output is its own pane (with title)
|
| 780 |
+
def _wrap(ctx, hm, fut, sp, mute, st):
|
| 781 |
+
return (
|
| 782 |
+
f"<div class='pane'><h3>Context</h3>{ctx}</div>",
|
| 783 |
+
f"<div class='pane'><h3>Head Map (pre-stream | xray | delta-v | L<sub>full</sub>)</h3>{hm}</div>",
|
| 784 |
+
f"<div class='pane'><h3>Futures</h3>{fut}</div>",
|
| 785 |
+
f"<div class='pane'><h3>Sparkline</h3>{sp}</div>",
|
| 786 |
+
mute,
|
| 787 |
+
f"<div class='pane'><h3>Transcript</h3>{st}</div>",
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
def on_load(mid, sp, up, s):
|
| 791 |
+
ctx, hm, fut, spk, mute, st = initial_load(mid, sp, up, s)
|
| 792 |
+
return _wrap(ctx, hm, fut, spk, mute, st) + (s,)
|
| 793 |
+
|
| 794 |
+
def on_cmd(c, s, mid, sp):
|
| 795 |
+
ctx, hm, fut, spk, mute, st = handle_command(c, s, mid, sp)
|
| 796 |
+
return _wrap(ctx, hm, fut, spk, mute, st) + ("", s)
|
| 797 |
+
|
| 798 |
+
load_btn.click(
|
| 799 |
+
on_load,
|
| 800 |
+
inputs=[model_id, system_prompt, user_prompt, session],
|
| 801 |
+
outputs=[ctx_pane, hm_pane, fut_pane, spark_pane, muted_html, status, session],
|
| 802 |
+
)
|
| 803 |
+
run_btn.click(
|
| 804 |
+
on_cmd,
|
| 805 |
+
inputs=[cmd, session, model_id, system_prompt],
|
| 806 |
+
outputs=[ctx_pane, hm_pane, fut_pane, spark_pane, muted_html, status, cmd, session],
|
| 807 |
+
)
|
| 808 |
+
cmd.submit(
|
| 809 |
+
on_cmd,
|
| 810 |
+
inputs=[cmd, session, model_id, system_prompt],
|
| 811 |
+
outputs=[ctx_pane, hm_pane, fut_pane, spark_pane, muted_html, status, cmd, session],
|
| 812 |
+
)
|
| 813 |
+
return demo
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
if __name__ == "__main__":
|
| 817 |
+
build_ui().launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.44.0
|
| 2 |
+
torch>=2.4.0
|
| 3 |
+
transformers>=4.50.0
|
| 4 |
+
accelerate>=0.30.0
|
| 5 |
+
sentencepiece
|
| 6 |
+
protobuf
|