jejunepixels commited on
Commit
3e4c0fe
·
verified ·
1 Parent(s): 0dae3e0

Capture all attention layers and add coloured curved overlays with layer controls

Browse files
Files changed (7) hide show
  1. README.md +6 -0
  2. app.py +5 -3
  3. attention_view.py +92 -45
  4. engine.py +13 -2
  5. style.css +16 -0
  6. token_space.js +151 -40
  7. token_space.py +25 -0
README.md CHANGED
@@ -262,3 +262,9 @@ Sign in with Hugging Face to use your personal ZeroGPU quota. Curated models are
262
  ## English-biased sampling
263
 
264
  English bias (default 2; 0 disables it) adds a soft token prior before temperature and top-p filtering. The prior uses wordfreq English word frequencies compared with eight other Latin-script languages, English subword fragments, and Unicode script information. Punctuation, digits, special tokens, and incomplete byte tokens remain neutral. No prompt or chat template is added. Shared words, names, and subword ambiguity mean English is not guaranteed. The next-token inspector displays the actual distribution after this adjustment. The slider applies live and persists across GPU chunks. wordfreq data attribution and licensing: https://github.com/rspeer/wordfreq/blob/master/NOTICE.md
 
 
 
 
 
 
 
262
  ## English-biased sampling
263
 
264
  English bias (default 2; 0 disables it) adds a soft token prior before temperature and top-p filtering. The prior uses wordfreq English word frequencies compared with eight other Latin-script languages, English subword fragments, and Unicode script information. Punctuation, digits, special tokens, and incomplete byte tokens remain neutral. No prompt or chat template is added. Shared words, names, and subword ambiguity mean English is not guaranteed. The next-token inspector displays the actual distribution after this adjustment. The slider applies live and persists across GPU chunks. wordfreq data attribution and licensing: https://github.com/rspeer/wordfreq/blob/master/NOTICE.md
265
+
266
+ ## Coloured layer overlays
267
+
268
+ The attention panel defaults to early, middle and final layers. All layers uses a continuous cyan/violet/amber palette; Selected layer/head preserves the original inspection controls. Each layer overlay averages its attention heads. Curves separate overlapping connections; thickness encodes raw attention weight. Hover a curve for its layer, target and weight. Legend buttons hide/show layers, Shift-click isolates one, and hover highlights one. The links-per-layer selector and minimum-weight filter affect the display only.
269
+
270
+ During generation, all layer means are captured, keeping the eight strongest targets for each query in a compact 512-slot CPU tensor ring. Full attention matrices are not retained. Live transport sends the latest query; pausing sends retained layer records for token-by-token replay. Positions stay in the same embedding projection. Layer comparisons are measurements of attention, not explanations of all model computations. The chosen layer/head is also saved separately.
app.py CHANGED
@@ -55,6 +55,8 @@ def clear(flow):
55
  flow.tokens.clear()
56
  flow.space_history.clear()
57
  flow.attention_history.clear()
 
 
58
  flow.text_snapshot_cache = None
59
  flow.continue_automatically = False
60
  flow.pass_remaining = None
@@ -292,10 +294,10 @@ def build_app():
292
  info="Favour English without a prompt. 0 = off. Applies live; languages can still mix.")
293
  with gr.Row():
294
  attention = gr.Checkbox(label="Capture attention", value=True,
295
- info="Use Attention weights in Connections. Capture can slow generation.")
296
- attention_layer = gr.Number(value=-1, precision=0, label="Attention layer",
297
  info="-1 = last layer; otherwise a zero-based index.")
298
- attention_head = gr.Number(value=-1, precision=0, label="Attention head",
299
  info="-1 = average heads; otherwise a zero-based index.")
300
  auto_continue = gr.Checkbox(label="Automatically continue", value=True,
301
  info="Flow until Pause, Stop, an end token, or 16,384 tokens.")
 
55
  flow.tokens.clear()
56
  flow.space_history.clear()
57
  flow.attention_history.clear()
58
+ flow.layer_rows = flow.layer_keys = None
59
+ flow.layer_queries = [-1] * 512
60
  flow.text_snapshot_cache = None
61
  flow.continue_automatically = False
62
  flow.pass_remaining = None
 
294
  info="Favour English without a prompt. 0 = off. Applies live; languages can still mix.")
295
  with gr.Row():
296
  attention = gr.Checkbox(label="Capture attention", value=True,
297
+ info="Record layer averages for the coloured overlay, plus the selected layer/head.")
298
+ attention_layer = gr.Number(value=-1, precision=0, label="Selected attention layer",
299
  info="-1 = last layer; otherwise a zero-based index.")
300
+ attention_head = gr.Number(value=-1, precision=0, label="Selected attention head",
301
  info="-1 = average heads; otherwise a zero-based index.")
302
  auto_continue = gr.Checkbox(label="Automatically continue", value=True,
303
  info="Flow until Pause, Stop, an end token, or 16,384 tokens.")
attention_view.py CHANGED
@@ -1,45 +1,92 @@
1
- """Capture one real attention row without retaining every layer's attention matrix."""
2
- import torch
3
-
4
-
5
- def attention_modules(model):
6
- return [(name, module) for name, module in model.named_modules()
7
- if name.endswith((".self_attn", ".attn")) and not getattr(module, "is_cross_attention", False)]
8
-
9
-
10
- class AttentionProbe:
11
- def __init__(self, modules, layer=-1, head=-1):
12
- self.layer = len(modules) - 1 if layer == -1 else int(layer)
13
- if not 0 <= self.layer < len(modules):
14
- raise ValueError(f"Attention layer must be 0–{len(modules)-1}, or -1 for the last layer.")
15
- self.module = modules[self.layer][1]
16
- self.head = int(head)
17
- self.row = None
18
-
19
- def __enter__(self):
20
- def capture(module, inputs, output):
21
- weights = output[1] if isinstance(output, tuple) and len(output) > 1 else None
22
- if not isinstance(weights, torch.Tensor) or weights.ndim != 4:
23
- raise ValueError("This model does not expose supported attention weights.")
24
- row = weights[0, :, -1, :].detach().float()
25
- if self.head == -1:
26
- row = row.mean(0)
27
- elif 0 <= self.head < len(row):
28
- row = row[self.head]
29
- else:
30
- raise ValueError(f"Attention head must be 0–{len(row)-1}, or -1 to average heads.")
31
- self.row = row.cpu()
32
- self.handle = self.module.register_forward_hook(capture)
33
- return self
34
-
35
- def __exit__(self, *args):
36
- self.handle.remove()
37
-
38
- def record(self, key_start, query):
39
- if self.row is None:
40
- raise ValueError("The selected attention module did not return attention weights.")
41
- values, indices = torch.topk(self.row, min(8, len(self.row)))
42
- return {"query": query, "layer": self.layer, "head": self.head,
43
- "links": [{"n": key_start + int(i) - 1, "score": float(v)}
44
- for v, i in zip(values, indices)],
45
- "shown_mass": float(values.sum()), "keys": len(self.row)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture one real attention row without retaining every layer's attention matrix."""
2
+ import torch
3
+
4
+
5
+ def attention_modules(model):
6
+ return [(name, module) for name, module in model.named_modules()
7
+ if name.endswith((".self_attn", ".attn")) and not getattr(module, "is_cross_attention", False)]
8
+
9
+
10
+ class AttentionProbe:
11
+ def __init__(self, modules, layer=-1, head=-1):
12
+ self.layer = len(modules) - 1 if layer == -1 else int(layer)
13
+ if not 0 <= self.layer < len(modules):
14
+ raise ValueError(f"Attention layer must be 0–{len(modules)-1}, or -1 for the last layer.")
15
+ self.module = modules[self.layer][1]
16
+ self.head = int(head)
17
+ self.row = None
18
+
19
+ def __enter__(self):
20
+ def capture(module, inputs, output):
21
+ weights = output[1] if isinstance(output, tuple) and len(output) > 1 else None
22
+ if not isinstance(weights, torch.Tensor) or weights.ndim != 4:
23
+ raise ValueError("This model does not expose supported attention weights.")
24
+ row = weights[0, :, -1, :].detach().float()
25
+ if self.head == -1:
26
+ row = row.mean(0)
27
+ elif 0 <= self.head < len(row):
28
+ row = row[self.head]
29
+ else:
30
+ raise ValueError(f"Attention head must be 0–{len(row)-1}, or -1 to average heads.")
31
+ self.row = row.cpu()
32
+ self.handle = self.module.register_forward_hook(capture)
33
+ return self
34
+
35
+ def __exit__(self, *args):
36
+ self.handle.remove()
37
+
38
+ def record(self, key_start, query):
39
+ if self.row is None:
40
+ raise ValueError("The selected attention module did not return attention weights.")
41
+ values, indices = torch.topk(self.row, min(8, len(self.row)))
42
+ return {"query": query, "layer": self.layer, "head": self.head,
43
+ "links": [{"n": key_start + int(i) - 1, "score": float(v)}
44
+ for v, i in zip(values, indices)],
45
+ "shown_mass": float(values.sum()), "keys": len(self.row)}
46
+
47
+
48
+ class LayerAttentionProbe:
49
+ """Capture head means for all layers, plus the chosen layer/head for inspection."""
50
+ def __init__(self, modules, layer=-1, head=-1):
51
+ self.probes = [AttentionProbe(modules, index, -1) for index in range(len(modules))]
52
+ selected = len(modules) - 1 if layer == -1 else int(layer)
53
+ if not 0 <= selected < len(modules):
54
+ raise ValueError("Attention layer is outside this model's range.")
55
+ self.primary = self.probes[selected] if head == -1 else AttentionProbe(modules, selected, head)
56
+
57
+ def __enter__(self):
58
+ from contextlib import ExitStack
59
+ self.stack = ExitStack()
60
+ try:
61
+ for probe in self.probes:
62
+ self.stack.enter_context(probe)
63
+ if self.primary not in self.probes:
64
+ self.stack.enter_context(self.primary)
65
+ except BaseException:
66
+ self.stack.close()
67
+ raise
68
+ return self
69
+
70
+ def __exit__(self, *args):
71
+ return self.stack.__exit__(*args)
72
+
73
+ @property
74
+ def row(self):
75
+ return self.primary.row
76
+
77
+ def record(self, key_start, query):
78
+ return self.primary.record(key_start, query)
79
+
80
+ def layer_record(self, key_end):
81
+ # A fixed-size CPU tensor avoids thousands of dictionaries in GPU session snapshots.
82
+ packed = torch.zeros((len(self.probes), 8, 2), dtype=torch.float32)
83
+ packed[:, :, 0] = -2 # padding, distinct from boundary token index -1
84
+ keys = torch.zeros(len(self.probes), dtype=torch.int32)
85
+ for layer, probe in enumerate(self.probes):
86
+ if probe.row is None:
87
+ raise ValueError("A layer did not expose its attention weights.")
88
+ values, indices = torch.topk(probe.row, min(8, len(probe.row)))
89
+ packed[layer, :len(values), 0] = indices + key_end - len(probe.row) - 1
90
+ packed[layer, :len(values), 1] = values
91
+ keys[layer] = len(probe.row)
92
+ return packed, keys
engine.py CHANGED
@@ -19,6 +19,8 @@ class Flow:
19
  self.stream_id = uuid.uuid4().hex
20
  self.space_history = []
21
  self.attention_history = {}
 
 
22
  self.paused = False
23
  self.running = False
24
  self.reset_requested = False
@@ -201,14 +203,23 @@ def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, se
201
  consumed += 1
202
  probe = None
203
  if settings.get("attention", False):
204
- from attention_view import AttentionProbe
205
- probe = AttentionProbe(attention_modules or [], settings.get("attention_layer", -1),
206
  settings.get("attention_head", -1))
207
  with probe if probe is not None else nullcontext():
208
  result = model(input_ids=input_ids, past_key_values=cache, use_cache=True)
209
  if probe is not None and flow.tokens:
210
  query = len(flow.tokens) - 1
211
  flow.attention_history[query] = probe.record(len(all_ids) - len(probe.row), query)
 
 
 
 
 
 
 
 
 
212
  for link in flow.attention_history[query]["links"]:
213
  link["id"] = all_ids[link["n"] + 1]
214
  flow.attention_history = {i: row for i, row in flow.attention_history.items() if i >= query - 511}
 
19
  self.stream_id = uuid.uuid4().hex
20
  self.space_history = []
21
  self.attention_history = {}
22
+ self.layer_rows = self.layer_keys = None
23
+ self.layer_queries = [-1] * 512
24
  self.paused = False
25
  self.running = False
26
  self.reset_requested = False
 
203
  consumed += 1
204
  probe = None
205
  if settings.get("attention", False):
206
+ from attention_view import LayerAttentionProbe
207
+ probe = LayerAttentionProbe(attention_modules or [], settings.get("attention_layer", -1),
208
  settings.get("attention_head", -1))
209
  with probe if probe is not None else nullcontext():
210
  result = model(input_ids=input_ids, past_key_values=cache, use_cache=True)
211
  if probe is not None and flow.tokens:
212
  query = len(flow.tokens) - 1
213
  flow.attention_history[query] = probe.record(len(all_ids) - len(probe.row), query)
214
+ packed, keys = probe.layer_record(len(all_ids))
215
+ if flow.layer_rows is None or flow.layer_rows.shape[1] != len(packed):
216
+ flow.layer_rows = torch.zeros((512, *packed.shape), dtype=torch.float32)
217
+ flow.layer_keys = torch.zeros((512, len(packed)), dtype=torch.int32)
218
+ flow.layer_queries = [-1] * 512
219
+ slot = query % 512
220
+ flow.layer_rows[slot].copy_(packed)
221
+ flow.layer_keys[slot].copy_(keys)
222
+ flow.layer_queries[slot] = query
223
  for link in flow.attention_history[query]["links"]:
224
  link["id"] = all_ids[link["n"] + 1]
225
  flow.attention_history = {i: row for i, row in flow.attention_history.items() if i >= query - 511}
style.css CHANGED
@@ -122,3 +122,19 @@ header p { font: 18px/1.6 Georgia, serif; color: #777; }
122
  .attention-help summary { cursor:pointer; color:#f4bf67; }
123
  .attention-help p { margin:9px 0 0; color:#b8cbd1 !important; }
124
  @media(max-width:640px) { .space-detail { bottom:228px; width:calc(100vw - 24px); max-width:calc(100vw - 24px); max-height:30dvh; padding:14px; font-size:13px; box-sizing:border-box; } .attention-title { font-size:16px; } .attention-item { grid-template-columns:minmax(65px,1fr) minmax(50px,1fr) 43px; gap:8px; } }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  .attention-help summary { cursor:pointer; color:#f4bf67; }
123
  .attention-help p { margin:9px 0 0; color:#b8cbd1 !important; }
124
  @media(max-width:640px) { .space-detail { bottom:228px; width:calc(100vw - 24px); max-width:calc(100vw - 24px); max-height:30dvh; padding:14px; font-size:13px; box-sizing:border-box; } .attention-title { font-size:16px; } .attention-item { grid-template-columns:minmax(65px,1fr) minmax(50px,1fr) 43px; gap:8px; } }
125
+
126
+ .layer-controls { display:flex; flex-wrap:wrap; gap:10px; margin:12px 0; }
127
+ .layer-controls label { display:flex; flex-direction:column; gap:4px; color:#bacdd4; font:12px/1.4 system-ui,sans-serif; }
128
+ .layer-controls select { padding:6px 8px; border:1px solid #6b8796; border-radius:6px; background:#112530; color:#e0ebed; font:inherit; }
129
+ .layer-filter { flex:1 1 100%; }
130
+ .layer-filter input { width:100%; accent-color:#f4bf67; }
131
+ .layer-caption { margin:10px 0; color:#a8bdc4 !important; font:12px/1.5 system-ui,sans-serif; }
132
+ .layer-legend { display:flex; flex-wrap:wrap; gap:6px; margin-bottom:15px; }
133
+ .layer-chip,.layer-restore { padding:4px 8px; border:1px solid; border-radius:6px; background:#ffffff08; font:600 12px/1.5 system-ui,sans-serif; cursor:pointer; }
134
+ .layer-chip[aria-pressed="false"] { opacity:.35; text-decoration:line-through; }
135
+ .layer-chip:focus-visible,.layer-restore:focus-visible { outline:2px solid #f4bf67; outline-offset:2px; }
136
+ .layer-restore { border-color:#78949d; color:#d5e3e6; }
137
+ .attention-layer + .attention-layer { margin-top:16px; padding-top:12px; border-top:1px solid #ffffff18; }
138
+ .attention-layer > .attention-meta { border-left:3px solid; padding-left:8px; }
139
+ .space-edge-tooltip { position:fixed; z-index:9; max-width:260px; padding:8px 10px; border:1px solid #78949d66; border-radius:7px; background:#07121ff5; color:#e2edf0; font:12px/1.5 system-ui,sans-serif; pointer-events:none; }
140
+ .space-edge-tooltip[hidden] { display:none !important; }
token_space.js CHANGED
@@ -6,6 +6,9 @@
6
  let lastTime=Date.now(),mode='live',connections='attention';
7
  const lifetime=6000;
8
  let lastText='';
 
 
 
9
  let paused=false, previousMode='live';
10
  let textView=null,externalSelected=null,reader=null,readerSignature='',lastHighlighted=null;
11
  let running=false,awaitingGPU=false,ended=false,togglePending=false,toggleButton=null;
@@ -107,6 +110,36 @@
107
  const rect=canvas.getBoundingClientRect(),x=e.clientX-rect.left,y=e.clientY-rect.top;
108
  return hits.filter(p=>Math.hypot(p.x-x,p.y-y)<22).sort((a,b)=>Math.hypot(a.x-x,a.y-y)-Math.hypot(b.x-x,b.y-y))[0];
109
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  function details(){
111
  const box=root?.querySelector('.space-detail');if(!box)return;
112
  const point=history.find(p=>p.n===selected)||externalSelected||(connections==='attention'?sourcePoint():null);
@@ -119,35 +152,83 @@
119
  content=`Token #${point.n+1} ${JSON.stringify(point.label)} | ID ${point.id}. Earlier neighbours: ${neighbours.join('; ')||'none with positive cosine similarity in the retained window'}.`;
120
  }
121
  if(point && connections==='attention'){
122
- const row=point.attention;
123
- if(row){
124
- const signature=JSON.stringify([point.n,point.label,row]);
125
  if(box.dataset.attentionSignature===signature)return;
126
- const explanationOpen=Boolean(box.querySelector('details')?.open);
127
- const scroll=box.scrollTop||0;
128
- box.replaceChildren();box.dataset.attentionSignature=signature;
129
  function add(parent,tag,className,text){
130
  const node=document.createElement(tag);node.className=className;
131
  if(text!=null)node.textContent=text;parent.appendChild(node);return node;
132
  }
133
- add(box,'h3','attention-title',`Attention from #${point.n+1} ${JSON.stringify(point.label)}`);
134
- add(box,'p','attention-intro','What this token attended to while predicting the next token.');
135
- add(box,'p','attention-meta',`layer ${row.layer} / ${row.head===-1?'average across attention heads':'head '+row.head}`);
136
- const list=add(box,'div','attention-list');
137
- for(const link of row.links){
138
- const other=history.find(p=>p.n===link.n);
139
- const label=link.n===-1?'Start boundary':JSON.stringify(other?.label??link.label??('#'+(link.n+1)));
140
- const item=add(list,'div','attention-item');
141
- const token=add(item,'span','attention-token',label);
142
- token.title=link.n===-1?'The special token used to start this stream.':`Token #${link.n+1}`;
143
- const track=add(item,'span','attention-bar');track.setAttribute('aria-hidden','true');
144
- const fill=add(track,'span','attention-bar-fill');fill.style.width=`${Math.max(0,Math.min(100,100*link.score))}%`;
145
- add(item,'span','attention-percent',`${(100*link.score).toFixed(1)}%`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  }
147
- add(box,'p','attention-coverage',`${row.links.length} strongest connections shown: ${(100*row.shown_mass).toFixed(1)}% of total attention. Others: ${(100*Math.max(0,1-row.shown_mass)).toFixed(1)}%.`);
148
- const explanation=add(box,'details','attention-help');explanation.open=explanationOpen;
 
149
  add(explanation,'summary','','How to read this');
150
- add(explanation,'p','','Longer bars mean more attention to that context token, not a higher chance of generating it. Start boundary is the special token that begins the stream. This is one layer\u2019s attention, not a complete explanation of the model\u2019s decision. Layer and head indices start at 0.');
 
151
  box.scrollTop=scroll;
152
  return;
153
  }else content=externalSelected?'This token is outside the retained 512-token attention history. Its embedding is shown; no saved attention row is available.':'No attention captured for this token yet. Enable Capture attention and generate more tokens.';
@@ -169,12 +250,23 @@
169
  dragging=true;panning=e.shiftKey||e.button===2;moved=false;lastX=e.clientX;lastY=e.clientY;canvas.setPointerCapture(e.pointerId);
170
  });
171
  canvas.addEventListener('pointermove',e=>{
172
- if(!dragging)return;const dx=e.clientX-lastX,dy=e.clientY-lastY;
 
 
 
 
 
 
 
 
 
 
173
  if(Math.abs(dx)+Math.abs(dy)>2)moved=true;
174
  if(panning){panX+=dx;panY+=dy;}else{yaw+=dx*.006;pitch=Math.max(-1.5,Math.min(1.5,pitch+dy*.006));}
175
  lastX=e.clientX;lastY=e.clientY;
176
  });
177
  canvas.addEventListener('pointerup',()=>dragging=false);
 
178
  canvas.addEventListener('pointercancel',()=>dragging=false);
179
  canvas.addEventListener('contextmenu',e=>e.preventDefault());
180
  canvas.addEventListener('click',e=>{if(moved)return;const p=pick(e);selected=p?p.n:null;details();});
@@ -206,7 +298,7 @@
206
  }
207
  },700);
208
  }
209
- if(data.stream!==stream){stream=data.stream;seen=-1;history=[];selected=null;paused=false;textView=null;externalSelected=null;details();}
210
  const now=Date.now(),existing=new Set(history.map(p=>p.n));
211
  for(const p of data.points||[]){
212
  if(existing.has(p.n)){const old=history.find(q=>q.n===p.n);if(p.attention){if(!old.attention)old.attentionBorn=now;old.attention=p.attention;}continue;}
@@ -215,6 +307,14 @@
215
  history.push({...p,born:p.n<=seen?now-lifetime:now,attentionBorn:p.attention?now:0});seen=Math.max(seen,p.n);
216
  }
217
  if(data.text_view)textView=data.text_view;
 
 
 
 
 
 
 
 
218
  history.sort((a,b)=>a.n-b.n);history=history.slice(-512);
219
  if(Boolean(data.paused)!==paused){
220
  paused=Boolean(data.paused);
@@ -252,8 +352,9 @@
252
  const active=history.filter(p=>p.n<=cutoff&&(mode==='history'||paused||p.n===source?.n||now-p.born<lifetime));
253
  if(paused&&externalSelected)active.push({...externalSelected,born:now});
254
  const activeIndices=new Set(active.map(p=>p.n));
255
- if(source?.attention){
256
- for(const link of source.attention.links){
 
257
  if(activeIndices.has(link.n))continue;
258
  const old=history.find(p=>p.n===link.n);
259
  if(old||Array.isArray(link.xyz)){active.push({...old,n:link.n,id:link.id??old?.id,label:link.label??old?.label??'[context]',xyz:link.xyz??old.xyz,born:now,ghost:true});activeIndices.add(link.n);}
@@ -268,21 +369,31 @@
268
  }
269
  if(connections==='order')for(const p of rendered)line(byIndex.get(p.n-1),p,null);
270
  if(connections==='similarity')for(const p of rendered)for(const link of p.links||[])line(p,byIndex.get(link.n),link.score);
 
271
  if(connections==='attention'){
272
- const drawnSource=source?byIndex.get(source.n):null;
273
- if(drawnSource?.attention){
274
- const source=drawnSource;
275
- for(const link of source.attention.links){
276
- const end=byIndex.get(link.n);if(!end)continue;
277
- ctx.strokeStyle=`rgba(187,159,255,${Math.min(source.alpha,end.alpha)*(.2+.8*link.score)})`;
278
- ctx.lineWidth=1+8*link.score;ctx.beginPath();ctx.moveTo(source.x,source.y);
279
- if(source.n===end.n)ctx.arc(source.x,source.y,18,0,Math.PI*2);else ctx.lineTo(end.x,end.y);
280
- ctx.stroke();
281
- if(source.n!==end.n){
282
- const angle=Math.atan2(end.y-source.y,end.x-source.x),size=6+5*link.score;
283
- ctx.beginPath();ctx.moveTo(end.x,end.y);ctx.lineTo(end.x-size*Math.cos(angle-.4),end.y-size*Math.sin(angle-.4));
284
- ctx.moveTo(end.x,end.y);ctx.lineTo(end.x-size*Math.cos(angle+.4),end.y-size*Math.sin(angle+.4));ctx.stroke();
285
- }
 
 
 
 
 
 
 
 
 
286
  }
287
  }
288
  }
 
6
  let lastTime=Date.now(),mode='live',connections='attention';
7
  const lifetime=6000;
8
  let lastText='';
9
+ let layerCount=0,layerRows=new Map(),layerTargets=new Map();
10
+ let layerMode='three',layerLimit=3,minimumWeight=.01,hiddenLayers=new Set(),legendFocus=null;
11
+ let edgeHits=[],hoverEdge=null;
12
  let paused=false, previousMode='live';
13
  let textView=null,externalSelected=null,reader=null,readerSignature='',lastHighlighted=null;
14
  let running=false,awaitingGPU=false,ended=false,togglePending=false,toggleButton=null;
 
110
  const rect=canvas.getBoundingClientRect(),x=e.clientX-rect.left,y=e.clientY-rect.top;
111
  return hits.filter(p=>Math.hypot(p.x-x,p.y-y)<22).sort((a,b)=>Math.hypot(a.x-x,a.y-y)-Math.hypot(b.x-x,b.y-y))[0];
112
  }
113
+ function layerRGB(index){
114
+ const t=layerCount>1?index/(layerCount-1):1;
115
+ const stops=[[113,183,255],[183,155,232],[244,191,103]];
116
+ const a=t<.5?stops[0]:stops[1],b=t<.5?stops[1]:stops[2],u=t<.5?t*2:(t-.5)*2;
117
+ return a.map((value,i)=>Math.round(value+(b[i]-value)*u)).join(',');
118
+ }
119
+ function contextPoint(n){return layerTargets.get(n)||textView?.points[n]||history.find(p=>p.n===n);}
120
+ function attentionRows(point,includeHidden=false){
121
+ if(!point)return [];
122
+ const saved=layerRows.get(point.n);
123
+ let rows=[];
124
+ if(saved&&layerMode!=='selected'){
125
+ const count=saved.indices.length;
126
+ const chosen=layerMode==='all'?Array.from({length:count},(_,i)=>i):[...new Set([0,Math.floor((count-1)/2),count-1])];
127
+ rows=chosen.map(layer=>({query:point.n,layer,head:-1,keys:saved.keys[layer],
128
+ links:saved.indices[layer].map((n,i)=>({n,score:saved.scores[layer][i],...contextPoint(n)})).filter(link=>link.n>=-1&&link.score>0)}));
129
+ }else if(point.attention)rows=[point.attention];
130
+ return rows.filter(row=>includeHidden||!hiddenLayers.has(row.layer)).map(row=>{
131
+ const links=row.links.filter(link=>link.score>=minimumWeight).slice(0,layerLimit);
132
+ return {...row,links,shown_mass:links.reduce((sum,link)=>sum+link.score,0)};
133
+ });
134
+ }
135
+ function edgeTooltip(edge,event){
136
+ const box=root?.querySelector('.space-edge-tooltip');if(!box)return;
137
+ box.hidden=!edge;if(!edge)return;
138
+ const label=edge.n===-1?'Start boundary':JSON.stringify(contextPoint(edge.n)?.label??('#'+(edge.n+1)));
139
+ box.textContent=`Layer ${edge.layer} / ${label} / ${(100*edge.score).toFixed(2)}% attention`;
140
+ box.style.left=`${Math.max(8,Math.min(window.innerWidth-280,event.clientX+12))}px`;
141
+ box.style.top=`${Math.max(8,Math.min(window.innerHeight-65,event.clientY+12))}px`;
142
+ }
143
  function details(){
144
  const box=root?.querySelector('.space-detail');if(!box)return;
145
  const point=history.find(p=>p.n===selected)||externalSelected||(connections==='attention'?sourcePoint():null);
 
152
  content=`Token #${point.n+1} ${JSON.stringify(point.label)} | ID ${point.id}. Earlier neighbours: ${neighbours.join('; ')||'none with positive cosine similarity in the retained window'}.`;
153
  }
154
  if(point && connections==='attention'){
155
+ const available=attentionRows(point,true),rows=attentionRows(point);
156
+ if(available.length){
157
+ const signature=JSON.stringify([point.n,point.label,available,layerMode,layerLimit,minimumWeight,[...hiddenLayers]]);
158
  if(box.dataset.attentionSignature===signature)return;
159
+ const explanationOpen=Boolean(box.querySelector('details')?.open),scroll=box.scrollTop||0;
160
+ box.dataset.attentionSignature=signature;
 
161
  function add(parent,tag,className,text){
162
  const node=document.createElement(tag);node.className=className;
163
  if(text!=null)node.textContent=text;parent.appendChild(node);return node;
164
  }
165
+ let headingHost=box.querySelector('.attention-header');
166
+ if(!headingHost){
167
+ box.replaceChildren();
168
+ headingHost=add(box,'div','attention-header');
169
+ add(box,'div','layer-ui');
170
+ add(box,'div','attention-body');
171
+ }
172
+ const ui=box.querySelector('.layer-ui'),body=box.querySelector('.attention-body');
173
+ headingHost.replaceChildren();body.replaceChildren();
174
+ add(headingHost,'h3','attention-title',`Attention from #${point.n+1} ${JSON.stringify(point.label)}`);
175
+ add(headingHost,'p','attention-intro','What this token attended to while predicting the next token.');
176
+ ui.hidden=!layerRows.has(point.n);
177
+ const controlKey=JSON.stringify([layerMode,layerLimit,available.map(row=>row.layer),[...hiddenLayers]]);
178
+ if(!ui.hidden&&ui.dataset.controlKey!==controlKey){
179
+ ui.replaceChildren();ui.dataset.controlKey=controlKey;
180
+ const controls=add(ui,'div','layer-controls');
181
+ function select(label,choices,value,change){
182
+ const field=add(controls,'label','',label),input=add(field,'select','');
183
+ for(const [key,text] of choices){const option=add(input,'option','',text);option.value=key;}
184
+ input.value=value;input.addEventListener('change',event=>{change(event.target.value);legendFocus=null;details();});
185
+ }
186
+ select('Layers',[['three','Early / middle / final'],['all','All layers'],['selected','Selected layer / head']],layerMode,value=>{layerMode=value;hiddenLayers.clear();});
187
+ select('Links per layer',[1,2,3,5,8].map(n=>[String(n),String(n)]),String(layerLimit),value=>layerLimit=Number(value));
188
+ const filter=add(controls,'label','layer-filter','Minimum weight '),readout=add(filter,'span','',`${Math.round(minimumWeight*100)}%`);
189
+ const slider=add(filter,'input','');slider.type='range';slider.min=0;slider.max=30;slider.step=1;slider.value=minimumWeight*100;
190
+ slider.setAttribute('aria-label','Minimum attention weight');
191
+ slider.addEventListener('input',event=>{minimumWeight=Number(event.target.value)/100;readout.textContent=`${Math.round(minimumWeight*100)}%`;});
192
+ slider.addEventListener('change',()=>details());
193
+ add(ui,'p','layer-caption','Colour = layer. Thickness = weight. Click a colour to hide it; Shift-click to isolate it. Hover a colour to highlight it.');
194
+ const legend=add(ui,'div','layer-legend');
195
+ for(const row of available){
196
+ const button=add(legend,'button','layer-chip',`L${row.layer}`);button.type='button';
197
+ button.style.color=`rgb(${layerRGB(row.layer)})`;button.style.borderColor=`rgb(${layerRGB(row.layer)})`;
198
+ button.setAttribute('aria-pressed',String(!hiddenLayers.has(row.layer)));button.title=`Layer ${row.layer}: click to hide/show; Shift-click to isolate`;
199
+ button.addEventListener('mouseenter',()=>legendFocus=row.layer);button.addEventListener('mouseleave',()=>legendFocus=null);
200
+ button.addEventListener('click',event=>{
201
+ if(event.shiftKey){hiddenLayers=new Set(available.filter(other=>other.layer!==row.layer).map(other=>other.layer));}
202
+ else if(hiddenLayers.has(row.layer))hiddenLayers.delete(row.layer);else hiddenLayers.add(row.layer);
203
+ legendFocus=null;details();
204
+ });
205
+ }
206
+ if(hiddenLayers.size){const restore=add(legend,'button','layer-restore','Restore layers');restore.type='button';restore.addEventListener('click',()=>{hiddenLayers.clear();details();});}
207
+ }
208
+ if(!rows.length)add(body,'p','attention-meta','All layers are hidden. Restore a layer using the legend.');
209
+ for(const row of rows){
210
+ const group=add(body,'section','attention-layer');
211
+ const heading=add(group,'p','attention-meta',`layer ${row.layer} / ${row.head===-1?'average across attention heads':'head '+row.head}`);
212
+ heading.style.borderLeftColor=`rgb(${layerRGB(row.layer)})`;
213
+ const list=add(group,'div','attention-list');
214
+ for(const link of row.links){
215
+ const other=contextPoint(link.n);
216
+ const label=link.n===-1?'Start boundary':JSON.stringify(other?.label??link.label??('#'+(link.n+1)));
217
+ const item=add(list,'div','attention-item');
218
+ const token=add(item,'span','attention-token',label);token.title=link.n===-1?'The special token used to start this stream.':`Token #${link.n+1}`;
219
+ const track=add(item,'span','attention-bar');track.setAttribute('aria-hidden','true');
220
+ const fill=add(track,'span','attention-bar-fill');fill.style.width=`${Math.max(0,Math.min(100,100*link.score))}%`;fill.style.background=`rgb(${layerRGB(row.layer)})`;
221
+ add(item,'span','attention-percent',`${(100*link.score).toFixed(1)}%`);
222
+ }
223
+ if(!row.links.length)add(group,'p','attention-meta','No saved links meet this minimum weight.');
224
+ add(group,'p','attention-coverage',`${row.links.length} strongest connections shown: ${(100*row.shown_mass).toFixed(1)}% of total attention. Others: ${(100*Math.max(0,1-row.shown_mass)).toFixed(1)}%.`);
225
  }
226
+ let explanation=box.querySelector('.attention-help');
227
+ if(!explanation){
228
+ explanation=add(box,'details','attention-help');explanation.open=explanationOpen;
229
  add(explanation,'summary','','How to read this');
230
+ add(explanation,'p','','Longer bars mean more attention to that context token, not a higher chance of generating it. Coloured curves compare layers using the same token positions. Multi-layer views average across heads. Start boundary begins the stream. Only the eight strongest links per layer are saved; filters can show fewer. Layer and head indices start at 0. Attention is not a complete explanation of the decision.');
231
+ }
232
  box.scrollTop=scroll;
233
  return;
234
  }else content=externalSelected?'This token is outside the retained 512-token attention history. Its embedding is shown; no saved attention row is available.':'No attention captured for this token yet. Enable Capture attention and generate more tokens.';
 
250
  dragging=true;panning=e.shiftKey||e.button===2;moved=false;lastX=e.clientX;lastY=e.clientY;canvas.setPointerCapture(e.pointerId);
251
  });
252
  canvas.addEventListener('pointermove',e=>{
253
+ if(!dragging){
254
+ const rect=canvas.getBoundingClientRect(),x=e.clientX-rect.left,y=e.clientY-rect.top;
255
+ hoverEdge=null;let nearest=7;
256
+ for(const edge of edgeHits)for(let i=1;i<edge.path.length;i++){
257
+ const a=edge.path[i-1],b=edge.path[i],dx=b.x-a.x,dy=b.y-a.y;
258
+ const t=Math.max(0,Math.min(1,((x-a.x)*dx+(y-a.y)*dy)/(dx*dx+dy*dy||1)));
259
+ const distance=Math.hypot(x-a.x-t*dx,y-a.y-t*dy);
260
+ if(distance<nearest){nearest=distance;hoverEdge=edge;}
261
+ }
262
+ edgeTooltip(hoverEdge,e);return;
263
+ }const dx=e.clientX-lastX,dy=e.clientY-lastY;
264
  if(Math.abs(dx)+Math.abs(dy)>2)moved=true;
265
  if(panning){panX+=dx;panY+=dy;}else{yaw+=dx*.006;pitch=Math.max(-1.5,Math.min(1.5,pitch+dy*.006));}
266
  lastX=e.clientX;lastY=e.clientY;
267
  });
268
  canvas.addEventListener('pointerup',()=>dragging=false);
269
+ canvas.addEventListener('pointerleave',event=>{hoverEdge=null;edgeTooltip(null,event);});
270
  canvas.addEventListener('pointercancel',()=>dragging=false);
271
  canvas.addEventListener('contextmenu',e=>e.preventDefault());
272
  canvas.addEventListener('click',e=>{if(moved)return;const p=pick(e);selected=p?p.n:null;details();});
 
298
  }
299
  },700);
300
  }
301
+ if(data.stream!==stream){layerRows.clear();layerTargets.clear();hiddenLayers.clear();layerCount=0;hoverEdge=null;stream=data.stream;seen=-1;history=[];selected=null;paused=false;textView=null;externalSelected=null;details();}
302
  const now=Date.now(),existing=new Set(history.map(p=>p.n));
303
  for(const p of data.points||[]){
304
  if(existing.has(p.n)){const old=history.find(q=>q.n===p.n);if(p.attention){if(!old.attention)old.attentionBorn=now;old.attention=p.attention;}continue;}
 
307
  history.push({...p,born:p.n<=seen?now-lifetime:now,attentionBorn:p.attention?now:0});seen=Math.max(seen,p.n);
308
  }
309
  if(data.text_view)textView=data.text_view;
310
+ if(data.attention_layers){
311
+ layerCount=data.attention_layers.count;
312
+ for(const row of data.attention_layers.rows)layerRows.set(row.query,row);
313
+ for(const target of data.attention_layers.targets)layerTargets.set(target.n,target);
314
+ const first=Math.max(0,seen-512);
315
+ for(const query of layerRows.keys())if(query<first)layerRows.delete(query);
316
+ for(const n of layerTargets.keys())if(n>=0&&n<seen-4096)layerTargets.delete(n);
317
+ }
318
  history.sort((a,b)=>a.n-b.n);history=history.slice(-512);
319
  if(Boolean(data.paused)!==paused){
320
  paused=Boolean(data.paused);
 
352
  const active=history.filter(p=>p.n<=cutoff&&(mode==='history'||paused||p.n===source?.n||now-p.born<lifetime));
353
  if(paused&&externalSelected)active.push({...externalSelected,born:now});
354
  const activeIndices=new Set(active.map(p=>p.n));
355
+ const visibleRows=attentionRows(source);
356
+ if(source){
357
+ for(const link of visibleRows.flatMap(row=>row.links)){
358
  if(activeIndices.has(link.n))continue;
359
  const old=history.find(p=>p.n===link.n);
360
  if(old||Array.isArray(link.xyz)){active.push({...old,n:link.n,id:link.id??old?.id,label:link.label??old?.label??'[context]',xyz:link.xyz??old.xyz,born:now,ghost:true});activeIndices.add(link.n);}
 
369
  }
370
  if(connections==='order')for(const p of rendered)line(byIndex.get(p.n-1),p,null);
371
  if(connections==='similarity')for(const p of rendered)for(const link of p.links||[])line(p,byIndex.get(link.n),link.score);
372
+ edgeHits=[];
373
  if(connections==='attention'){
374
+ const start=source?byIndex.get(source.n):null;
375
+ if(start)for(const row of visibleRows)for(const link of row.links){
376
+ const end=byIndex.get(link.n);if(!end)continue;
377
+ const focused=legendFocus==null||legendFocus===row.layer;
378
+ const offset=layerCount>1?(row.layer/(layerCount-1)-.5)*70:0;
379
+ const dx=end.x-start.x,dy=end.y-start.y,length=Math.hypot(dx,dy)||1;
380
+ const control={x:(start.x+end.x)/2-dy/length*offset,y:(start.y+end.y)/2+dx/length*offset};
381
+ ctx.strokeStyle=`rgba(${layerRGB(row.layer)},${Math.min(start.alpha,end.alpha)*(.25+.75*link.score)*(focused?1:.08)})`;
382
+ ctx.lineWidth=1+8*link.score;ctx.beginPath();ctx.moveTo(start.x,start.y);
383
+ const path=[];
384
+ if(start.n===end.n){
385
+ const radius=14+(layerCount>1?row.layer/(layerCount-1)*24:0);
386
+ ctx.arc(start.x,start.y,radius,0,Math.PI*2);
387
+ for(let i=0;i<=24;i++){const a=i/24*Math.PI*2;path.push({x:start.x+Math.cos(a)*radius,y:start.y+Math.sin(a)*radius});}
388
+ }else{
389
+ ctx.quadraticCurveTo(control.x,control.y,end.x,end.y);
390
+ for(let i=0;i<=12;i++){const t=i/12,u=1-t;path.push({x:u*u*start.x+2*u*t*control.x+t*t*end.x,y:u*u*start.y+2*u*t*control.y+t*t*end.y});}
391
+ }
392
+ ctx.stroke();edgeHits.push({layer:row.layer,n:link.n,score:link.score,path});
393
+ if(start.n!==end.n){
394
+ const angle=Math.atan2(end.y-control.y,end.x-control.x),size=6+5*link.score;
395
+ ctx.beginPath();ctx.moveTo(end.x,end.y);ctx.lineTo(end.x-size*Math.cos(angle-.4),end.y-size*Math.sin(angle-.4));
396
+ ctx.moveTo(end.x,end.y);ctx.lineTo(end.x-size*Math.cos(angle+.4),end.y-size*Math.sin(angle+.4));ctx.stroke();
397
  }
398
  }
399
  }
token_space.py CHANGED
@@ -103,6 +103,30 @@ def _frame(flow, store, full=False):
103
  points = flow.space_history[-512 if full else -48:]
104
  data = {"continue_automatically": flow.continue_automatically, "stream": flow.stream_id, "revision": flow.view_revision, "paused": flow.paused, "running": flow.running,
105
  "ended": flow.ended, "points": points}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  if flow.paused and store.projection is not None and flow.model_key == store.key:
107
  if flow.text_snapshot_cache is None or flow.text_snapshot_cache[0] != len(tokens):
108
  flow.text_snapshot_cache = (len(tokens), text_snapshot(tokens, store.tokenizer, store.projection))
@@ -124,5 +148,6 @@ SCENE = '''<div id="token-universe">
124
  <span data-space-step>Live</span>
125
  </div>
126
  <div class="space-detail" aria-live="polite">Click a token to inspect its earlier neighbours.</div>
 
127
  <div class="space-bottom"><span>Drag to orbit · Shift-drag to pan · Wheel to zoom · Double-click a token to focus</span><span>Embedding PCA</span></div>
128
  </div>'''
 
103
  points = flow.space_history[-512 if full else -48:]
104
  data = {"continue_automatically": flow.continue_automatically, "stream": flow.stream_id, "revision": flow.view_revision, "paused": flow.paused, "running": flow.running,
105
  "ended": flow.ended, "points": points}
106
+ if flow.layer_rows is not None and store.projection is not None:
107
+ queries = sorted(q for q in flow.layer_queries if q >= max(0, len(tokens) - 513))
108
+ if not flow.paused:
109
+ queries = queries[-1:]
110
+ rows, target_indices = [], set()
111
+ for query in queries:
112
+ slot = query % 512
113
+ packed = flow.layer_rows[slot]
114
+ indices = packed[:, :, 0].to(torch.int32).tolist()
115
+ rows.append({"query": query, "indices": indices,
116
+ "scores": packed[:, :, 1].tolist(), "keys": flow.layer_keys[slot].tolist()})
117
+ if not flow.paused:
118
+ target_indices.update(n for layer in indices for n in layer if -1 <= n < len(tokens))
119
+ from engine import start_id
120
+ boundary = start_id(store.model, store.tokenizer)
121
+ targets = []
122
+ if flow.paused:
123
+ target_indices.add(-1) # other targets are already in the full text snapshot
124
+ for n in sorted(target_indices):
125
+ token_id = boundary if n == -1 else tokens[n]
126
+ targets.append({"n": n, "id": token_id, "xyz": store.projection.point(token_id),
127
+ "label": "[boundary]" if n == -1 else store.tokenizer.decode(
128
+ [token_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)})
129
+ data["attention_layers"] = {"count": flow.layer_rows.shape[1], "rows": rows, "targets": targets}
130
  if flow.paused and store.projection is not None and flow.model_key == store.key:
131
  if flow.text_snapshot_cache is None or flow.text_snapshot_cache[0] != len(tokens):
132
  flow.text_snapshot_cache = (len(tokens), text_snapshot(tokens, store.tokenizer, store.projection))
 
148
  <span data-space-step>Live</span>
149
  </div>
150
  <div class="space-detail" aria-live="polite">Click a token to inspect its earlier neighbours.</div>
151
+ <div class="space-edge-tooltip" role="tooltip" hidden></div>
152
  <div class="space-bottom"><span>Drag to orbit · Shift-drag to pan · Wheel to zoom · Double-click a token to focus</span><span>Embedding PCA</span></div>
153
  </div>'''