jejunepixels commited on
Commit
ae55e6a
·
verified ·
1 Parent(s): 673a352

Fix fading attention targets and add paused token-by-token inspection

Browse files
Files changed (5) hide show
  1. README.md +14 -1
  2. app.py +17 -2
  3. engine.py +4 -0
  4. token_space.js +56 -13
  5. token_space.py +22 -6
README.md CHANGED
@@ -88,7 +88,7 @@ attention weights from the latest query token, or from a token you click in Hist
88
  Thicker lines indicate larger weights. Self-attention is drawn as a loop.
89
  Click a token to see actual percentages, including any boundary-token weight.
90
  Top-eight values are not renormalized; the detail shows their total probability mass.
91
- Invisible or forgotten target points are omitted from the 3D lines, not reassigned weight.
92
 
93
  Layer -1 selects the last attention layer; head -1 averages across heads. Otherwise
94
  use zero-based indices. Model status reports the layer/head counts. Changes apply
@@ -104,6 +104,19 @@ long memory. Capture may be disabled. Unsupported custom attention architectures
104
  can generate with capture disabled. Attention weights describe one operation in the
105
  network and are not a complete causal explanation or access to private reasoning.
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  ## Controls
108
 
109
  **Automatically continue** is on by default. Generation keeps flowing past the
 
88
  Thicker lines indicate larger weights. Self-attention is drawn as a loop.
89
  Click a token to see actual percentages, including any boundary-token weight.
90
  Top-eight values are not renormalized; the detail shows their total probability mass.
91
+ Attention targets that have faded or fallen outside retained history reappear as faint context nodes, including the boundary token. Their weights are unchanged. Expired selections no longer block the latest attention row.
92
 
93
  Layer -1 selects the last attention layer; head -1 averages across heads. Otherwise
94
  use zero-based indices. Model status reports the layer/head counts. Changes apply
 
104
  can generate with capture disabled. Attention weights describe one operation in the
105
  network and are not a complete causal explanation or access to private reasoning.
106
 
107
+ ## Pause and token stepping
108
+
109
+ Pause generation finishes the current inference step and stops sampling. It switches
110
+ the viewer to a non-fading attention inspection mode. Step back and Step forward
111
+ move through the retained history (up to the last 512 token occurrences). The
112
+ view hides future tokens relative to the selected query and shows that query's
113
+ recorded attention, including faint older targets. Rows that were not captured
114
+ are labelled as unavailable; the final token has no row until it predicts another.
115
+ Stepping does not generate text, delete tokens, change the random state, or recompute
116
+ attention with different layer/head settings. Resume generation continues the same
117
+ text and RNG sequence and restores the prior viewer mode. Stop keeps its normal
118
+ fading behavior. Pausing also works after a pass has completed.
119
+
120
  ## Controls
121
 
122
  **Automatically continue** is on by default. Generation keeps flowing past the
app.py CHANGED
@@ -42,6 +42,7 @@ def clear(flow):
42
  flow.tokens.clear()
43
  flow.space_history.clear()
44
  flow.attention_history.clear()
 
45
  flow.text = ""
46
  flow.model_key = ""
47
  flow.seed = flow.rng_state = None
@@ -60,7 +61,16 @@ def load_model(repo, flow):
60
 
61
 
62
  def stop(flow):
 
63
  flow.stop.set()
 
 
 
 
 
 
 
 
64
 
65
 
66
  def control_handler(name):
@@ -83,6 +93,7 @@ def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128
83
  auto_continue=auto_continue, attention=attention,
84
  attention_layer=attention_layer, attention_head=attention_head)
85
  flow.stop.clear()
 
86
  panel = EMPTY
87
  started = time.monotonic()
88
  before = len(flow.tokens)
@@ -117,6 +128,8 @@ def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128
117
  reason = "The model emitted an end token. Start fresh to begin another stream."
118
  elif len(flow.tokens) >= 16384:
119
  reason = "Session limit of 16,384 tokens reached. Download your text and start fresh."
 
 
120
  elif flow.stop.is_set():
121
  reason = "Stopped. Continue preserves the text and random sequence."
122
  else:
@@ -186,7 +199,8 @@ def build_app():
186
  info="-1 = average heads; otherwise a head index starting at 0.")
187
  with gr.Row(elem_id="stream-buttons"):
188
  start = gr.Button("Begin", variant="primary")
189
- resume = gr.Button("Continue")
 
190
  halt = gr.Button("Stop", variant="stop")
191
  reset = gr.Button("Start fresh")
192
  gr.HTML(SCENE, elem_id="space-scene")
@@ -236,7 +250,8 @@ def build_app():
236
  change_model.click(choose_model, [flow], [picker, workspace], queue=False)
237
  start.click(begin, inputs, outputs, **common)
238
  resume.click(run, inputs, outputs, **common)
239
- halt.click(stop, [flow], [], queue=False)
 
240
  reset.click(reset_view, [flow], outputs, api_name="clear", **common)
241
  save.click(export, [flow], download, **common)
242
  return demo.queue(max_size=16, default_concurrency_limit=1)
 
42
  flow.tokens.clear()
43
  flow.space_history.clear()
44
  flow.attention_history.clear()
45
+ flow.paused = False
46
  flow.text = ""
47
  flow.model_key = ""
48
  flow.seed = flow.rng_state = None
 
61
 
62
 
63
  def stop(flow):
64
+ flow.paused = False
65
  flow.stop.set()
66
+ return frame(flow, STORE, full=True)
67
+
68
+
69
+ def pause_generation(flow):
70
+ flow.paused = True
71
+ flow.stop.set()
72
+ return ("Pausing after the current token. Use Step back / Step forward in the 3D view, then Resume generation.",
73
+ frame(flow, STORE, full=True))
74
 
75
 
76
  def control_handler(name):
 
93
  auto_continue=auto_continue, attention=attention,
94
  attention_layer=attention_layer, attention_head=attention_head)
95
  flow.stop.clear()
96
+ flow.paused = False
97
  panel = EMPTY
98
  started = time.monotonic()
99
  before = len(flow.tokens)
 
128
  reason = "The model emitted an end token. Start fresh to begin another stream."
129
  elif len(flow.tokens) >= 16384:
130
  reason = "Session limit of 16,384 tokens reached. Download your text and start fresh."
131
+ elif flow.paused:
132
+ reason = "Paused. Step back / Step forward inspect saved attention; Resume generation continues the same stream."
133
  elif flow.stop.is_set():
134
  reason = "Stopped. Continue preserves the text and random sequence."
135
  else:
 
199
  info="-1 = average heads; otherwise a head index starting at 0.")
200
  with gr.Row(elem_id="stream-buttons"):
201
  start = gr.Button("Begin", variant="primary")
202
+ resume = gr.Button("Resume generation")
203
+ pause = gr.Button("Pause generation")
204
  halt = gr.Button("Stop", variant="stop")
205
  reset = gr.Button("Start fresh")
206
  gr.HTML(SCENE, elem_id="space-scene")
 
250
  change_model.click(choose_model, [flow], [picker, workspace], queue=False)
251
  start.click(begin, inputs, outputs, **common)
252
  resume.click(run, inputs, outputs, **common)
253
+ halt.click(stop, [flow], transport, queue=False)
254
+ pause.click(pause_generation, [flow], [status, transport], queue=False)
255
  reset.click(reset_view, [flow], outputs, api_name="clear", **common)
256
  save.click(export, [flow], download, **common)
257
  return demo.queue(max_size=16, default_concurrency_limit=1)
engine.py CHANGED
@@ -13,6 +13,8 @@ class Flow:
13
  self.stream_id = uuid.uuid4().hex
14
  self.space_history = []
15
  self.attention_history = {}
 
 
16
  self.text = text
17
  self.model_key = model_key
18
  self.seed = seed
@@ -141,6 +143,8 @@ def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, se
141
  if probe is not None and flow.tokens:
142
  query = len(flow.tokens) - 1
143
  flow.attention_history[query] = probe.record(len(all_ids) - len(probe.row), query)
 
 
144
  flow.attention_history = {i: row for i, row in flow.attention_history.items() if i >= query - 511}
145
  cache = result.past_key_values
146
  probs, before_nucleus = distribution(result.logits[0, -1], window,
 
13
  self.stream_id = uuid.uuid4().hex
14
  self.space_history = []
15
  self.attention_history = {}
16
+ self.paused = False
17
+ self.view_lock = threading.RLock()
18
  self.text = text
19
  self.model_key = model_key
20
  self.seed = seed
 
143
  if probe is not None and flow.tokens:
144
  query = len(flow.tokens) - 1
145
  flow.attention_history[query] = probe.record(len(all_ids) - len(probe.row), query)
146
+ for link in flow.attention_history[query]["links"]:
147
+ link["id"] = all_ids[link["n"] + 1]
148
  flow.attention_history = {i: row for i, row in flow.attention_history.items() if i >= query - 511}
149
  cache = result.past_key_values
150
  probs, before_nucleus = distribution(result.logits[0, -1], window,
token_space.js CHANGED
@@ -5,6 +5,22 @@
5
  let dragging=false,panning=false,moved=false,lastX=0,lastY=0,width=0,height=0;
6
  let lastTime=Date.now(),mode='live',connections='attention';
7
  const lifetime=6000;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  function resetCamera(){yaw=.35;pitch=-.15;zoom=1;target=[0,0,0];panX=panY=0;}
9
  function pick(e){
10
  const rect=canvas.getBoundingClientRect(),x=e.clientX-rect.left,y=e.clientY-rect.top;
@@ -12,7 +28,7 @@
12
  }
13
  function details(){
14
  const box=root?.querySelector('.space-detail');if(!box)return;
15
- const point=history.find(p=>p.n===selected);
16
  let content='Click a token to inspect its earlier neighbours.';
17
  if(point){
18
  const neighbours=(point.links||[]).map(link=>{
@@ -26,7 +42,7 @@
26
  if(row){
27
  const targets=row.links.map(link=>{
28
  const other=history.find(p=>p.n===link.n);
29
- return `${link.n===-1?'[boundary token]':other?JSON.stringify(other.label):'#'+(link.n+1)}: ${(100*link.score).toFixed(1)}%`;
30
  });
31
  content=`Attention from #${point.n+1} ${JSON.stringify(point.label)}, layer ${row.layer}, ${row.head===-1?'mean across heads':'head '+row.head}, while predicting the following token. ${targets.join('; ')}. Top-8 mass: ${(100*row.shown_mass).toFixed(1)}%.`;
32
  }else content='No attention captured for this token yet. Enable Capture attention and generate more tokens.';
@@ -65,21 +81,32 @@
65
  const linksInput=root.querySelector('[data-space-links]');
66
  if(linksInput){linksInput.value=connections;linksInput.addEventListener('change',e=>{connections=e.target.value;details();});}
67
  root.querySelector('[data-space-reset]')?.addEventListener('click',resetCamera);
 
 
68
  details();
69
  }
70
  function receive(){
71
  mount();const node=document.querySelector('[data-flow-frame]');if(!node)return;
72
  const raw=node.getAttribute('data-flow-frame');if(raw===payload)return;
73
  payload=raw;let data;try{data=JSON.parse(raw);}catch{return;}
74
- if(data.stream!==stream){stream=data.stream;seen=-1;history=[];selected=null;details();}
75
  const now=Date.now(),existing=new Set(history.map(p=>p.n));
76
  for(const p of data.points||[]){
77
- if(existing.has(p.n)){const old=history.find(q=>q.n===p.n);if(p.attention)old.attention=p.attention;continue;}
78
  if(!Array.isArray(p.xyz)||!p.xyz.every(Number.isFinite))continue;
79
  // Recovered old history must not reappear as freshly generated live points.
80
- history.push({...p,born:p.n<=seen?now-lifetime:now});seen=Math.max(seen,p.n);
 
 
 
 
 
 
 
 
81
  }
82
- history.sort((a,b)=>a.n-b.n);history=history.slice(-512);details();
 
83
  }
84
  function project(v){
85
  const[x,y,z]=v.map((a,i)=>a-target[i]),cy=Math.cos(yaw),sy=Math.sin(yaw),rx=x*cy+z*sy,rz=-x*sy+z*cy;
@@ -92,7 +119,7 @@
92
  // Remount if Gradio replaced the canvas. Aging uses wall time, never server steps.
93
  mount();const now=Date.now(),dt=Math.min(now-lastTime,100);lastTime=now;
94
  if(!ctx||!width||!height)return;
95
- if(!dragging&&mode==='live'&&!matchMedia('(prefers-reduced-motion: reduce)').matches)yaw+=dt*.000025;
96
  ctx.clearRect(0,0,width,height);
97
  const wash=ctx.createRadialGradient(width*.48,height*.48,0,width*.5,height*.5,width*.6);
98
  wash.addColorStop(0,'#142b34');wash.addColorStop(1,'#080f18');ctx.fillStyle=wash;ctx.fillRect(0,0,width,height);
@@ -101,8 +128,18 @@
101
  const a=project(pair[0]),b=project(pair[1]);if(!a.visible||!b.visible)continue;
102
  ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();
103
  }
104
- const active=history.filter(p=>mode==='history'||now-p.born<lifetime);
105
- const rendered=active.map(p=>({...p,...project(p.xyz),alpha:mode==='history'?.7:Math.pow(Math.max(0,1-(now-p.born)/lifetime),1.5)})).filter(p=>p.visible);
 
 
 
 
 
 
 
 
 
 
106
  const byIndex=new Map(rendered.map(p=>[p.n,p]));
107
  function line(a,b,score){
108
  if(!a||!b)return;const highlight=selected===a.n||selected===b.n;
@@ -112,8 +149,9 @@
112
  if(connections==='order')for(const p of rendered)line(byIndex.get(p.n-1),p,null);
113
  if(connections==='similarity')for(const p of rendered)for(const link of p.links||[])line(p,byIndex.get(link.n),link.score);
114
  if(connections==='attention'){
115
- const source=selected!=null?byIndex.get(selected):[...rendered].reverse().find(p=>p.attention);
116
- if(source?.attention){
 
117
  for(const link of source.attention.links){
118
  const end=byIndex.get(link.n);if(!end)continue;
119
  ctx.strokeStyle=`rgba(187,159,255,${Math.min(source.alpha,end.alpha)*(.2+.8*link.score)})`;
@@ -131,18 +169,23 @@
131
  rendered.sort((a,b)=>b.z-a.z);hits=rendered;
132
  for(const p of rendered){
133
  const highlight=p.n===selected,newest=p.n===seen;ctx.globalAlpha=highlight?1:p.alpha;
134
- ctx.fillStyle=highlight?'#f7be6b':newest?'#faf0bd':'#83dfd2';ctx.shadowColor=ctx.fillStyle;ctx.shadowBlur=newest||highlight?18:8;
135
  ctx.beginPath();ctx.arc(p.x,p.y,Math.max(2,Math.min(12,(newest||highlight?5:3)*p.scale)),0,Math.PI*2);ctx.fill();ctx.shadowBlur=0;
136
  ctx.font=`${newest||highlight?600:400} ${Math.max(11,Math.min(19,14*p.scale))}px ui-monospace,monospace`;
137
  let label=p.label.replace(/\n/g,'↵').replace(/\t/g,'⇥').replace(/ /g,'·');
138
  if(!label)label=`[${p.id}]`;if(label.length>32)label=label.slice(0,31)+'…';
139
- if(mode==='live'||highlight||newest||rendered.length<100)ctx.fillText(label,p.x+9,p.y-8-(p.n%3)*5);
140
  }
141
  ctx.globalAlpha=1;ctx.lineWidth=1;
142
  const counter=root.querySelector('.space-count'),empty=root.querySelector('.space-empty');
143
  const count=`${active.length} visible · ${seen+1} generated · zoom ${zoom.toFixed(1)}×`;
144
  if(counter&&counter.textContent!==count)counter.textContent=count;
145
  if(empty){const display=seen<0?'flex':'none';if(empty.style.display!==display)empty.style.display=display;}
 
 
 
 
 
146
  const text=document.querySelector('#page textarea');if(text&&document.activeElement!==text)text.scrollTop=text.scrollHeight;
147
  }
148
  observer=new MutationObserver(receive);
 
5
  let dragging=false,panning=false,moved=false,lastX=0,lastY=0,width=0,height=0;
6
  let lastTime=Date.now(),mode='live',connections='attention';
7
  const lifetime=6000;
8
+ let paused=false, previousMode='live';
9
+ function sourcePoint(){
10
+ const pinned=history.find(p=>p.n===selected);
11
+ if(paused)return pinned;
12
+ if(pinned?.attention&&(mode==='history'||Date.now()-Math.max(pinned.born,pinned.attentionBorn??0)<lifetime))return pinned;
13
+ return [...history].reverse().find(p=>p.attention&&(mode==='history'||Date.now()-Math.max(p.born,p.attentionBorn??0)<lifetime));
14
+ }
15
+ function stepToken(direction){
16
+ if(!paused||!history.length)return;
17
+ let index=history.findIndex(p=>p.n===selected);
18
+ if(index<0)index=history.length-1;
19
+ index=Math.max(0,Math.min(history.length-1,index+direction));
20
+ selected=history[index].n;connections='attention';
21
+ const input=root.querySelector('[data-space-links]');if(input)input.value=connections;
22
+ details();
23
+ }
24
  function resetCamera(){yaw=.35;pitch=-.15;zoom=1;target=[0,0,0];panX=panY=0;}
25
  function pick(e){
26
  const rect=canvas.getBoundingClientRect(),x=e.clientX-rect.left,y=e.clientY-rect.top;
 
28
  }
29
  function details(){
30
  const box=root?.querySelector('.space-detail');if(!box)return;
31
+ const point=history.find(p=>p.n===selected)||(connections==='attention'?sourcePoint():null);
32
  let content='Click a token to inspect its earlier neighbours.';
33
  if(point){
34
  const neighbours=(point.links||[]).map(link=>{
 
42
  if(row){
43
  const targets=row.links.map(link=>{
44
  const other=history.find(p=>p.n===link.n);
45
+ return `${link.n===-1?'[boundary token]':other?JSON.stringify(other.label):link.label?JSON.stringify(link.label):'#'+(link.n+1)}: ${(100*link.score).toFixed(1)}%`;
46
  });
47
  content=`Attention from #${point.n+1} ${JSON.stringify(point.label)}, layer ${row.layer}, ${row.head===-1?'mean across heads':'head '+row.head}, while predicting the following token. ${targets.join('; ')}. Top-8 mass: ${(100*row.shown_mass).toFixed(1)}%.`;
48
  }else content='No attention captured for this token yet. Enable Capture attention and generate more tokens.';
 
81
  const linksInput=root.querySelector('[data-space-links]');
82
  if(linksInput){linksInput.value=connections;linksInput.addEventListener('change',e=>{connections=e.target.value;details();});}
83
  root.querySelector('[data-space-reset]')?.addEventListener('click',resetCamera);
84
+ root.querySelector('[data-space-back]')?.addEventListener('click',()=>stepToken(-1));
85
+ root.querySelector('[data-space-forward]')?.addEventListener('click',()=>stepToken(1));
86
  details();
87
  }
88
  function receive(){
89
  mount();const node=document.querySelector('[data-flow-frame]');if(!node)return;
90
  const raw=node.getAttribute('data-flow-frame');if(raw===payload)return;
91
  payload=raw;let data;try{data=JSON.parse(raw);}catch{return;}
92
+ if(data.stream!==stream){stream=data.stream;seen=-1;history=[];selected=null;paused=false;details();}
93
  const now=Date.now(),existing=new Set(history.map(p=>p.n));
94
  for(const p of data.points||[]){
95
+ 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;}
96
  if(!Array.isArray(p.xyz)||!p.xyz.every(Number.isFinite))continue;
97
  // Recovered old history must not reappear as freshly generated live points.
98
+ history.push({...p,born:p.n<=seen?now-lifetime:now,attentionBorn:p.attention?now:0});seen=Math.max(seen,p.n);
99
+ }
100
+ history.sort((a,b)=>a.n-b.n);history=history.slice(-512);
101
+ if(Boolean(data.paused)!==paused){
102
+ paused=Boolean(data.paused);
103
+ if(paused){previousMode=mode;mode='history';selected=[...history].reverse().find(p=>p.attention)?.n??history.at(-1)?.n??null;connections='attention';}
104
+ else{mode=previousMode;selected=null;}
105
+ const modeInput=root.querySelector('[data-space-mode]');if(modeInput)modeInput.value=mode;
106
+ const linksInput=root.querySelector('[data-space-links]');if(linksInput)linksInput.value=connections;
107
  }
108
+ if(!paused&&mode==='live'&&selected!=null&&!history.some(p=>p.n===selected&&now-p.born<lifetime))selected=null;
109
+ details();
110
  }
111
  function project(v){
112
  const[x,y,z]=v.map((a,i)=>a-target[i]),cy=Math.cos(yaw),sy=Math.sin(yaw),rx=x*cy+z*sy,rz=-x*sy+z*cy;
 
119
  // Remount if Gradio replaced the canvas. Aging uses wall time, never server steps.
120
  mount();const now=Date.now(),dt=Math.min(now-lastTime,100);lastTime=now;
121
  if(!ctx||!width||!height)return;
122
+ if(!paused&&!dragging&&mode==='live'&&!matchMedia('(prefers-reduced-motion: reduce)').matches)yaw+=dt*.000025;
123
  ctx.clearRect(0,0,width,height);
124
  const wash=ctx.createRadialGradient(width*.48,height*.48,0,width*.5,height*.5,width*.6);
125
  wash.addColorStop(0,'#142b34');wash.addColorStop(1,'#080f18');ctx.fillStyle=wash;ctx.fillRect(0,0,width,height);
 
128
  const a=project(pair[0]),b=project(pair[1]);if(!a.visible||!b.visible)continue;
129
  ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();
130
  }
131
+ const cutoff=paused&&selected!=null?selected:Infinity;
132
+ const source=connections==='attention'?sourcePoint():null;
133
+ const active=history.filter(p=>p.n<=cutoff&&(mode==='history'||paused||p.n===source?.n||now-p.born<lifetime));
134
+ const activeIndices=new Set(active.map(p=>p.n));
135
+ if(source?.attention){
136
+ for(const link of source.attention.links){
137
+ if(activeIndices.has(link.n))continue;
138
+ const old=history.find(p=>p.n===link.n);
139
+ 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);}
140
+ }
141
+ }
142
+ const rendered=active.map(p=>({...p,...project(p.xyz),alpha:p.ghost ? .55 : (mode==='history'||paused) ? .7 : Math.pow(Math.max(0,1-(now-Math.max(p.born,p.n===source?.n?(p.attentionBorn??0):0))/lifetime),1.5)})).filter(p=>p.visible);
143
  const byIndex=new Map(rendered.map(p=>[p.n,p]));
144
  function line(a,b,score){
145
  if(!a||!b)return;const highlight=selected===a.n||selected===b.n;
 
149
  if(connections==='order')for(const p of rendered)line(byIndex.get(p.n-1),p,null);
150
  if(connections==='similarity')for(const p of rendered)for(const link of p.links||[])line(p,byIndex.get(link.n),link.score);
151
  if(connections==='attention'){
152
+ const drawnSource=source?byIndex.get(source.n):null;
153
+ if(drawnSource?.attention){
154
+ const source=drawnSource;
155
  for(const link of source.attention.links){
156
  const end=byIndex.get(link.n);if(!end)continue;
157
  ctx.strokeStyle=`rgba(187,159,255,${Math.min(source.alpha,end.alpha)*(.2+.8*link.score)})`;
 
169
  rendered.sort((a,b)=>b.z-a.z);hits=rendered;
170
  for(const p of rendered){
171
  const highlight=p.n===selected,newest=p.n===seen;ctx.globalAlpha=highlight?1:p.alpha;
172
+ ctx.fillStyle=p.ghost?'#bba2eb':highlight?'#f7be6b':newest?'#faf0bd':'#83dfd2';ctx.shadowColor=ctx.fillStyle;ctx.shadowBlur=newest||highlight?18:8;
173
  ctx.beginPath();ctx.arc(p.x,p.y,Math.max(2,Math.min(12,(newest||highlight?5:3)*p.scale)),0,Math.PI*2);ctx.fill();ctx.shadowBlur=0;
174
  ctx.font=`${newest||highlight?600:400} ${Math.max(11,Math.min(19,14*p.scale))}px ui-monospace,monospace`;
175
  let label=p.label.replace(/\n/g,'↵').replace(/\t/g,'⇥').replace(/ /g,'·');
176
  if(!label)label=`[${p.id}]`;if(label.length>32)label=label.slice(0,31)+'…';
177
+ if(p.ghost||mode==='live'||highlight||newest||rendered.length<100)ctx.fillText(label,p.x+9,p.y-8-(p.n%3)*5);
178
  }
179
  ctx.globalAlpha=1;ctx.lineWidth=1;
180
  const counter=root.querySelector('.space-count'),empty=root.querySelector('.space-empty');
181
  const count=`${active.length} visible · ${seen+1} generated · zoom ${zoom.toFixed(1)}×`;
182
  if(counter&&counter.textContent!==count)counter.textContent=count;
183
  if(empty){const display=seen<0?'flex':'none';if(empty.style.display!==display)empty.style.display=display;}
184
+ const back=root.querySelector('[data-space-back]'),forward=root.querySelector('[data-space-forward]'),step=root.querySelector('[data-space-step]');
185
+ if(back)back.disabled=!paused||selected==null||selected<=history[0]?.n;
186
+ if(forward)forward.disabled=!paused||selected==null||selected>=history.at(-1)?.n;
187
+ const stepText=paused?`Paused ? inspecting token #${selected==null?'?':selected+1}`:'Live';
188
+ if(step&&step.textContent!==stepText)step.textContent=stepText;
189
  const text=document.querySelector('#page textarea');if(text&&document.activeElement!==text)text.scrollTop=text.scrollHeight;
190
  }
191
  observer=new MutationObserver(receive);
token_space.py CHANGED
@@ -41,23 +41,36 @@ class TokenProjection:
41
 
42
 
43
  def frame(flow, store, full=False):
 
 
 
 
 
 
44
  points = []
45
  if store.projection is not None and flow.model_key == store.key:
46
  first_new = flow.space_history[-1]["n"] + 1 if flow.space_history else 0
47
- for index in range(first_new, len(flow.tokens)):
48
- token_id = flow.tokens[index]
49
  piece = store.tokenizer.decode([token_id], skip_special_tokens=False,
50
  clean_up_tokenization_spaces=False)
51
- previous = list(enumerate(flow.tokens[max(0, index - 512):index], start=max(0, index - 512)))
52
  links = store.projection.relatives(token_id, previous)
53
  flow.space_history.append({"n": index, "id": token_id, "label": piece,
54
  "xyz": store.projection.point(token_id), "links": links})
55
  flow.space_history = flow.space_history[-512:]
56
  for point in flow.space_history:
57
- if point["n"] in flow.attention_history:
58
- point["attention"] = flow.attention_history[point["n"]]
 
 
 
 
 
 
 
59
  points = flow.space_history[-512 if full else -48:]
60
- payload = json.dumps({"stream": flow.stream_id, "points": points}, ensure_ascii=True)
61
  return '<div data-flow-frame="' + html.escape(payload, quote=True) + '"></div>'
62
 
63
 
@@ -69,6 +82,9 @@ SCENE = '''<div id="token-universe">
69
  <label>View <select data-space-mode><option value="live">Live · fade after 6s</option><option value="history">History · last 512 tokens</option></select></label>
70
  <label>Connections <select data-space-links><option value="attention">Attention weights</option><option value="order">Generation order</option><option value="similarity">Embedding similarity</option><option value="none">None</option></select></label>
71
  <button type="button" data-space-reset>Reset camera</button>
 
 
 
72
  </div>
73
  <div class="space-detail" aria-live="polite">Click a token to inspect its earlier neighbours.</div>
74
  <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>
 
41
 
42
 
43
  def frame(flow, store, full=False):
44
+ with flow.view_lock:
45
+ return _frame(flow, store, full)
46
+
47
+
48
+ def _frame(flow, store, full=False):
49
+ tokens = flow.tokens.copy()
50
  points = []
51
  if store.projection is not None and flow.model_key == store.key:
52
  first_new = flow.space_history[-1]["n"] + 1 if flow.space_history else 0
53
+ for index in range(first_new, len(tokens)):
54
+ token_id = tokens[index]
55
  piece = store.tokenizer.decode([token_id], skip_special_tokens=False,
56
  clean_up_tokenization_spaces=False)
57
+ previous = list(enumerate(tokens[max(0, index - 512):index], start=max(0, index - 512)))
58
  links = store.projection.relatives(token_id, previous)
59
  flow.space_history.append({"n": index, "id": token_id, "label": piece,
60
  "xyz": store.projection.point(token_id), "links": links})
61
  flow.space_history = flow.space_history[-512:]
62
  for point in flow.space_history:
63
+ row = flow.attention_history.get(point["n"])
64
+ if row is not None:
65
+ point["attention"] = row
66
+ for link in point["attention"]["links"]:
67
+ if "id" in link and "xyz" not in link:
68
+ link["xyz"] = store.projection.point(link["id"])
69
+ link["label"] = ("[boundary]" if link["n"] == -1 else
70
+ store.tokenizer.decode([link["id"]], skip_special_tokens=False,
71
+ clean_up_tokenization_spaces=False))
72
  points = flow.space_history[-512 if full else -48:]
73
+ payload = json.dumps({"stream": flow.stream_id, "paused": flow.paused, "points": points}, ensure_ascii=True)
74
  return '<div data-flow-frame="' + html.escape(payload, quote=True) + '"></div>'
75
 
76
 
 
82
  <label>View <select data-space-mode><option value="live">Live · fade after 6s</option><option value="history">History · last 512 tokens</option></select></label>
83
  <label>Connections <select data-space-links><option value="attention">Attention weights</option><option value="order">Generation order</option><option value="similarity">Embedding similarity</option><option value="none">None</option></select></label>
84
  <button type="button" data-space-reset>Reset camera</button>
85
+ <button type="button" data-space-back disabled>Step back</button>
86
+ <button type="button" data-space-forward disabled>Step forward</button>
87
+ <span data-space-step>Live</span>
88
  </div>
89
  <div class="space-detail" aria-live="polite">Click a token to inspect its earlier neighbours.</div>
90
  <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>