jejunepixels commited on
Commit
9d3e0c7
·
verified ·
1 Parent(s): b0d4a08

Add optional projected original-dimension axis guides with opacity and origin controls

Browse files
Files changed (8) hide show
  1. README.md +8 -2
  2. app.py +1 -0
  3. engine.py +1 -0
  4. projection_axes.py +22 -0
  5. representations.py +7 -1
  6. style.css +20 -6
  7. token_space.js +65 -5
  8. token_space.py +16 -0
README.md CHANGED
@@ -36,7 +36,7 @@ GPU are available. Start with SmolLM2-135M; larger models can be slow on CPU.
36
  ## Hugging Face Space
37
 
38
  Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,
39
- `gpu_runtime.py`, `english_bias.py`, `representations.py`, `token_space.py`, `token_space.js`, `attention_view.py`, `requirements.txt`, and this `README.md`. The README contains the Space metadata.
40
  The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost.
41
  `FLOW_HOST` and `PORT` can override these defaults. No API token is
42
  needed for the supported public, ungated models. Start with CPU Basic and a small
@@ -44,7 +44,7 @@ model; hardware determines the practical model size. This project is prepared fo
44
  Spaces but does not create or publish a remote Space automatically.
45
 
46
  Run `python scripts/prepare_space.py` to create `outputs/let-it-flow-space.zip`.
47
- Extract the archive and upload its twelve files to the root of your Gradio Space.
48
 
49
  ## Token space
50
 
@@ -276,3 +276,9 @@ Capture layer representations is optional and enabled initially for this experim
276
  Only the last-position hidden states from the original generation calls are retained for capture. Each token trajectory belongs to the moment that occurrence was processed to predict the following token; the cloud is not a single full-context snapshot. The latest generated token has no trajectory until it is processed in another forward pass. Recording is bounded to the latest 128 processed token positions, plus the initial boundary when captured.
277
 
278
  Vectors are unit-normalised. One shared PCA basis and scale are fitted jointly across all stages of the first eight captured tokens, or fewer when a pass/pause ends early, then frozen for that stream. Calibration vectors are discarded after fitting; only the basis and 3D coordinates persist. This compares directions in a fixed compressed space, not semantic distance or importance. Input may include positional processing depending on architecture. Switching back to Live or History restores the original input-embedding view. No extra model calls, prompt tokens or random draws are introduced by layer playback.
 
 
 
 
 
 
 
36
  ## Hugging Face Space
37
 
38
  Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,
39
+ `gpu_runtime.py`, `english_bias.py`, `representations.py`, `projection_axes.py`, `token_space.py`, `token_space.js`, `attention_view.py`, `requirements.txt`, and this `README.md`. The README contains the Space metadata.
40
  The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost.
41
  `FLOW_HOST` and `PORT` can override these defaults. No API token is
42
  needed for the supported public, ungated models. Start with CPU Basic and a small
 
44
  Spaces but does not create or publish a remote Space automatically.
45
 
46
  Run `python scripts/prepare_space.py` to create `outputs/let-it-flow-space.zip`.
47
+ Extract the archive and upload its thirteen files to the root of your Gradio Space.
48
 
49
  ## Token space
50
 
 
276
  Only the last-position hidden states from the original generation calls are retained for capture. Each token trajectory belongs to the moment that occurrence was processed to predict the following token; the cloud is not a single full-context snapshot. The latest generated token has no trajectory until it is processed in another forward pass. Recording is bounded to the latest 128 processed token positions, plus the initial boundary when captured.
277
 
278
  Vectors are unit-normalised. One shared PCA basis and scale are fitted jointly across all stages of the first eight captured tokens, or fewer when a pass/pause ends early, then frozen for that stream. Calibration vectors are discarded after fitting; only the basis and 3D coordinates persist. This compares directions in a fixed compressed space, not semantic distance or importance. Input may include positional processing depending on architecture. Switching back to Live or History restores the original input-embedding view. No extra model calls, prompt tokens or random draws are introduced by layer playback.
279
+
280
+ ## Experimental original-dimension axes
281
+
282
+ All projected dimensions is off initially. Enable the checkbox above the connection panel for faint white guides, with opacity and origin options. Every original feature coordinate direction is transformed by the active PCA basis. A single common extent makes the guides visible while preserving their relative projected lengths. Axes may overlap or collapse when compressed into 3D; these are not attention links, model layers, semantic labels or individual learned parameters. Hover identifies a zero-based dimension index.
283
+
284
+ The default translates these directions to the PCA mean. Original vector origin instead uses the affine projection of the zero vector. In Layer representations, the basis belongs to the frozen, unit-normalised hidden-state projection, so axes stay fixed during layer playback. Embedding and representation geometry are sent only when first available or with full snapshots, rather than on every generated token. Controls are local to the visualisation and do not change generation.
app.py CHANGED
@@ -58,6 +58,7 @@ def clear(flow):
58
  flow.layer_rows = flow.layer_keys = None
59
  flow.layer_queries = [-1] * 512
60
  flow.representations = None
 
61
  flow.text_snapshot_cache = None
62
  flow.continue_automatically = False
63
  flow.pass_remaining = None
 
58
  flow.layer_rows = flow.layer_keys = None
59
  flow.layer_queries = [-1] * 512
60
  flow.representations = None
61
+ flow.sent_dimension_axes_key = ""
62
  flow.text_snapshot_cache = None
63
  flow.continue_automatically = False
64
  flow.pass_remaining = None
engine.py CHANGED
@@ -22,6 +22,7 @@ class Flow:
22
  self.layer_rows = self.layer_keys = None
23
  self.layer_queries = [-1] * 512
24
  self.representations = None
 
25
  self.paused = False
26
  self.running = False
27
  self.reset_requested = False
 
22
  self.layer_rows = self.layer_keys = None
23
  self.layer_queries = [-1] * 512
24
  self.representations = None
25
+ self.sent_dimension_axes_key = ""
26
  self.paused = False
27
  self.running = False
28
  self.reset_requested = False
projection_axes.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Directions of original feature axes under the actual three-dimensional PCA map."""
2
+ import math
3
+ import torch
4
+
5
+ def projected_dimension_axes(basis, center, scale, space):
6
+ basis=basis.detach().float().cpu()
7
+ center=center.detach().float().cpu()
8
+ scale=float(scale)
9
+ if basis.ndim!=2 or not basis.shape[0] or basis.shape[1]!=3 or center.shape!=(basis.shape[0],):
10
+ raise ValueError("Axis geometry must use a D-by-3 basis and its D-dimensional centre.")
11
+ if not math.isfinite(scale) or scale<=0 or not torch.isfinite(basis).all() or not torch.isfinite(center).all():
12
+ raise ValueError("Axis projection must be finite with a positive scale.")
13
+ unit_directions=basis*(2.4/scale)
14
+ # One common extent preserves the relative projected lengths of all dimensions.
15
+ extent=3.2/float(torch.linalg.vector_norm(unit_directions,dim=1).quantile(.95).clamp_min(1e-8))
16
+ directions=unit_directions*extent
17
+ raw_origin=(-center@basis)*(2.4/scale)
18
+ rounded=lambda row:[round(float(value),6) for value in row]
19
+ return {"count":len(basis),"vectors":[rounded(row) for row in directions],
20
+ "raw_origin":rounded(raw_origin),"coordinate_extent":extent,
21
+ "guide_radius":3.2,"space":space,
22
+ "description":"Original feature directions through the chosen origin; a common extent is used for visibility"}
representations.py CHANGED
@@ -14,6 +14,7 @@ class RepresentationState:
14
  self.stages = 0
15
  self.fitted_samples = 0
16
  self.needs_full = False
 
17
 
18
  def add(self, query, hidden_states):
19
  if not hidden_states:
@@ -43,6 +44,8 @@ class RepresentationState:
43
  _, _, basis = torch.pca_lowrank(centered, q=dimensions, center=False, niter=3)
44
  self.basis = F.pad(basis, (0, 3-dimensions))
45
  self.scale = torch.linalg.vector_norm(centered @ self.basis, dim=1).quantile(.95).clamp_min(.01)
 
 
46
  self.coords = torch.zeros((self.capacity, self.stages, 3), dtype=torch.float32)
47
  self.fitted_samples = len(samples)
48
  pending, self.pending = self.pending, {}
@@ -61,6 +64,7 @@ class RepresentationState:
61
 
62
  def snapshot(self, token_count, full=False):
63
  ready = self.basis is not None
 
64
  queries = sorted(q for q in self.queries if q >= max(0, token_count-self.capacity-1))
65
  if not (full or self.needs_full):
66
  queries = queries[-1:]
@@ -70,7 +74,9 @@ class RepresentationState:
70
  if ready and self.boundary is not None:
71
  points.append(point(-1, self.boundary))
72
  self.needs_full = False
73
- return {"ready": ready, "stages": self.stages, "capacity": self.capacity,
74
  "calibrating": sum(q>=0 for q in self.pending), "calibration_target": self.calibration_size,
75
  "fitted_samples": self.fitted_samples, "points": points,
76
  "projection": "Shared PCA of unit-normalised hidden states; axes fixed for this stream"}
 
 
 
14
  self.stages = 0
15
  self.fitted_samples = 0
16
  self.needs_full = False
17
+ self.dimension_axes = None
18
 
19
  def add(self, query, hidden_states):
20
  if not hidden_states:
 
44
  _, _, basis = torch.pca_lowrank(centered, q=dimensions, center=False, niter=3)
45
  self.basis = F.pad(basis, (0, 3-dimensions))
46
  self.scale = torch.linalg.vector_norm(centered @ self.basis, dim=1).quantile(.95).clamp_min(.01)
47
+ from projection_axes import projected_dimension_axes
48
+ self.dimension_axes=projected_dimension_axes(self.basis,self.center,self.scale,"normalised_hidden_states")
49
  self.coords = torch.zeros((self.capacity, self.stages, 3), dtype=torch.float32)
50
  self.fitted_samples = len(samples)
51
  pending, self.pending = self.pending, {}
 
64
 
65
  def snapshot(self, token_count, full=False):
66
  ready = self.basis is not None
67
+ include_axes=ready and (full or self.needs_full)
68
  queries = sorted(q for q in self.queries if q >= max(0, token_count-self.capacity-1))
69
  if not (full or self.needs_full):
70
  queries = queries[-1:]
 
74
  if ready and self.boundary is not None:
75
  points.append(point(-1, self.boundary))
76
  self.needs_full = False
77
+ result={"ready": ready, "stages": self.stages, "capacity": self.capacity,
78
  "calibrating": sum(q>=0 for q in self.pending), "calibration_target": self.calibration_size,
79
  "fitted_samples": self.fitted_samples, "points": points,
80
  "projection": "Shared PCA of unit-normalised hidden states; axes fixed for this stream"}
81
+ if include_axes:result["dimension_axes"]=self.dimension_axes
82
+ return result
style.css CHANGED
@@ -142,12 +142,12 @@ header p { font: 18px/1.6 Georgia, serif; color: #777; }
142
  .layer-controls label,.layer-controls label > span { color:#bacdd4 !important; }
143
  .layer-settings > summary { cursor:pointer; color:#f4bf67 !important; font:600 12px/1.5 system-ui,sans-serif; margin:10px 0; }
144
  .layer-caption-mobile { display:none; }
145
- :is(.layer-controls,.representation-layer-label) input[type="range"] { appearance:none; height:20px; padding:0 !important; border:0 !important; background:transparent !important; box-shadow:none !important; }
146
- :is(.layer-controls,.representation-layer-label) input[type="range"]::-webkit-slider-runnable-track { height:5px; border-radius:4px; background:#354654; }
147
- :is(.layer-controls,.representation-layer-label) input[type="range"]::-webkit-slider-thumb { appearance:none; width:14px; height:14px; margin-top:-4.5px; border:0; border-radius:50%; background:#f4bf67; cursor:ew-resize; }
148
- :is(.layer-controls,.representation-layer-label) input[type="range"]::-moz-range-track { height:5px; border-radius:4px; background:#354654; }
149
- :is(.layer-controls,.representation-layer-label) input[type="range"]::-moz-range-thumb { width:14px; height:14px; border:0; border-radius:50%; background:#f4bf67; }
150
- :is(.layer-controls,.representation-layer-label) input[type="range"]:focus-visible { outline:2px solid #f4bf67; outline-offset:3px; }
151
  @media(max-width:640px) { .space-detail { max-height:max(160px,min(40dvh,calc(100dvh - 440px))); } .layer-caption-desktop { display:none; } .layer-caption-mobile { display:inline; } }
152
 
153
  /* HTML theme rules set colours on child spans, so specify HUD text explicitly. */
@@ -198,3 +198,17 @@ header p { font: 18px/1.6 Georgia, serif; color: #777; }
198
  #token-universe[data-position-mode="representations"] .representation-controls .attention-help { margin-top:6px;padding-top:6px; }
199
  #token-universe[data-position-mode="representations"] .representation-connection-details > summary { display:list-item;color:#f4bf67 !important;cursor:pointer;font:12px/1.5 system-ui,sans-serif;margin:6px 0; }
200
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  .layer-controls label,.layer-controls label > span { color:#bacdd4 !important; }
143
  .layer-settings > summary { cursor:pointer; color:#f4bf67 !important; font:600 12px/1.5 system-ui,sans-serif; margin:10px 0; }
144
  .layer-caption-mobile { display:none; }
145
+ :is(.layer-controls,.representation-layer-label,.dimension-axes-options) input[type="range"] { appearance:none; height:20px; padding:0 !important; border:0 !important; background:transparent !important; box-shadow:none !important; }
146
+ :is(.layer-controls,.representation-layer-label,.dimension-axes-options) input[type="range"]::-webkit-slider-runnable-track { height:5px; border-radius:4px; background:#354654; }
147
+ :is(.layer-controls,.representation-layer-label,.dimension-axes-options) input[type="range"]::-webkit-slider-thumb { appearance:none; width:14px; height:14px; margin-top:-4.5px; border:0; border-radius:50%; background:#f4bf67; cursor:ew-resize; }
148
+ :is(.layer-controls,.representation-layer-label,.dimension-axes-options) input[type="range"]::-moz-range-track { height:5px; border-radius:4px; background:#354654; }
149
+ :is(.layer-controls,.representation-layer-label,.dimension-axes-options) input[type="range"]::-moz-range-thumb { width:14px; height:14px; border:0; border-radius:50%; background:#f4bf67; }
150
+ :is(.layer-controls,.representation-layer-label,.dimension-axes-options) input[type="range"]:focus-visible { outline:2px solid #f4bf67; outline-offset:3px; }
151
  @media(max-width:640px) { .space-detail { max-height:max(160px,min(40dvh,calc(100dvh - 440px))); } .layer-caption-desktop { display:none; } .layer-caption-mobile { display:inline; } }
152
 
153
  /* HTML theme rules set colours on child spans, so specify HUD text explicitly. */
 
198
  #token-universe[data-position-mode="representations"] .representation-controls .attention-help { margin-top:6px;padding-top:6px; }
199
  #token-universe[data-position-mode="representations"] .representation-connection-details > summary { display:list-item;color:#f4bf67 !important;cursor:pointer;font:12px/1.5 system-ui,sans-serif;margin:6px 0; }
200
  }
201
+
202
+ .dimension-axes-controls { border-bottom:1px solid #ffffff20; padding-bottom:10px; margin-bottom:12px; }
203
+ .dimension-axes-top { display:flex;align-items:center;justify-content:space-between;gap:8px; }
204
+ .dimension-axes-top label { display:flex;align-items:center;flex-wrap:wrap;gap:5px;font:600 12px/1.4 system-ui,sans-serif; }
205
+ .dimension-axes-top input { accent-color:#f4bf67; }
206
+ .dimension-axes-top button { padding:3px 7px;border:1px solid #6b8796;border-radius:5px;background:#112530;color:#eef3f5 !important;font:12px/1.4 system-ui,sans-serif;cursor:pointer; }
207
+ .dimension-axes-options[hidden] { display:none !important; }
208
+ .dimension-axes-options { padding-top:10px; }
209
+ .dimension-axes-options label { display:flex;flex-direction:column;gap:6px;margin:9px 0;font:12px/1.5 system-ui,sans-serif; }
210
+ .dimension-axes-options select { padding:5px 8px;border:1px solid #6b8796;border-radius:6px;background:#112530; }
211
+ .dimension-axes-options p { font:12px/1.55 system-ui,sans-serif; margin:8px 0; }
212
+ .dimension-axes-controls label,.dimension-axes-controls span,.dimension-axes-controls p { color:#eef3f5 !important; }
213
+ .dimension-axis-status { color:#f4bf67 !important; }
214
+ @media(max-width:640px) { .dimension-axes-controls { margin-bottom:8px;padding-bottom:8px; } .dimension-axes-top label { font-size:11px; } .dimension-axes-top button { font-size:11px; } }
token_space.js CHANGED
@@ -9,6 +9,8 @@
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,lastNarrow=null;
 
 
12
  let paused=false, previousMode='live';
13
  let positionMode='embeddings',representationMeta=null,representationPoints=new Map();
14
  let representationStage=0,representationPlaying=false,representationTrail=true,lastRepresentationLayer=-1;
@@ -34,6 +36,16 @@
34
  if(toggleButton.textContent!==label)toggleButton.textContent=label;
35
  toggleButton.disabled=togglePending||(running&&paused);
36
  }
 
 
 
 
 
 
 
 
 
 
37
  function displayedPosition(point){
38
  if(positionMode!=='representations')return point.xyz;
39
  const layers=representationPoints.get(point.n);if(!layers?.length)return null;
@@ -48,7 +60,7 @@
48
  if(extra.dataset.layout!==key){extra.open=!(positionMode==='representations'&&window.innerWidth<=640);extra.dataset.layout=key;}
49
  }
50
  const host=root?.querySelector('.representation-controls');if(!host?.querySelector)return;
51
- host.hidden=positionMode!=='representations';if(host.hidden)return;
52
  const note=host.querySelector('[data-representation-note]'),slider=host.querySelector('[data-representation-layer]');
53
  const play=host.querySelector('[data-representation-play]'),caption=host.querySelector('[data-representation-stage]');
54
  const ready=Boolean(representationMeta?.ready),maximum=Math.max(0,(representationMeta?.stages||1)-1);
@@ -185,8 +197,13 @@
185
  function edgeTooltip(edge,event){
186
  const box=root?.querySelector('.space-edge-tooltip');if(!box)return;
187
  box.hidden=!edge;if(!edge)return;
 
 
 
 
188
  const label=edge.n===-1?'Start boundary':JSON.stringify(contextPoint(edge.n)?.label??('#'+(edge.n+1)));
189
  box.textContent=`Layer ${edge.layer} / ${label} / ${(100*edge.score).toFixed(2)}% attention`;
 
190
  box.style.left=`${Math.max(8,Math.min(window.innerWidth-280,event.clientX+12))}px`;
191
  box.style.top=`${Math.max(8,Math.min(window.innerHeight-65,event.clientY+12))}px`;
192
  }
@@ -367,14 +384,24 @@
367
  const distance=Math.hypot(x-a.x-t*dx,y-a.y-t*dy);
368
  if(distance<nearest){nearest=distance;hoverEdge=edge;}
369
  }
370
- edgeTooltip(hoverEdge,e);return;
 
 
 
 
 
 
 
 
 
 
371
  }const dx=e.clientX-lastX,dy=e.clientY-lastY;
372
  if(Math.abs(dx)+Math.abs(dy)>2)moved=true;
373
  if(panning){panX+=dx;panY+=dy;}else{yaw+=dx*.006;pitch=Math.max(-1.5,Math.min(1.5,pitch+dy*.006));}
374
  lastX=e.clientX;lastY=e.clientY;
375
  });
376
  canvas.addEventListener('pointerup',()=>dragging=false);
377
- canvas.addEventListener('pointerleave',event=>{hoverEdge=null;edgeTooltip(null,event);});
378
  canvas.addEventListener('pointercancel',()=>dragging=false);
379
  canvas.addEventListener('contextmenu',e=>e.preventDefault());
380
  canvas.addEventListener('click',e=>{if(moved)return;const p=pick(e);selected=p?p.n:null;details();});
@@ -396,6 +423,15 @@
396
  });
397
  const trailInput=root.querySelector('[data-representation-trail]');
398
  if(trailInput){trailInput.checked=representationTrail;trailInput.addEventListener('change',event=>representationTrail=event.target.checked);}
 
 
 
 
 
 
 
 
 
399
  root.querySelector('[data-space-reset]')?.addEventListener('click',resetCamera);
400
  root.querySelector('[data-space-back]')?.addEventListener('click',()=>stepToken(-1));
401
  root.querySelector('[data-space-forward]')?.addEventListener('click',()=>stepToken(1));
@@ -416,7 +452,8 @@
416
  }
417
  },700);
418
  }
419
- if(data.stream!==stream){positionMode='embeddings';const view=root?.querySelector('[data-space-mode]');if(view)view.value=mode;representationPoints.clear();representationMeta=null;representationPlaying=false;representationStage=0;lastRepresentationLayer=-1;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();}
 
420
  const now=Date.now(),existing=new Set(history.map(p=>p.n));
421
  for(const p of data.points||[]){
422
  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;}
@@ -435,6 +472,7 @@
435
  }
436
  if(data.representations){
437
  representationMeta=data.representations;
 
438
  if(!data.attention_layers&&data.representations.stages)layerCount=data.representations.stages-1;
439
  for(const point of data.representations.points)representationPoints.set(point.n,point.layers);
440
  for(const n of representationPoints.keys())if(n>=0&&n<seen-128)representationPoints.delete(n);
@@ -458,7 +496,7 @@
458
  }
459
  function tick(){
460
  if(disposed)return;
461
- mountGenerationControl();
462
  // Remount if Gradio replaced the canvas. Aging uses wall time, never server steps.
463
  mount();const now=Date.now(),dt=Math.min(now-lastTime,100);lastTime=now;
464
  if(!ctx||!width||!height)return;
@@ -480,6 +518,28 @@
480
  const a=project(pair[0]),b=project(pair[1]);if(!a.visible||!b.visible)continue;
481
  ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();
482
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
  const cutoff=paused&&selected!=null?selected:Infinity;
484
  const source=connections==='attention'?sourcePoint():null;
485
  let active=history.filter(p=>p.n<=cutoff&&(mode==='history'||paused||p.n===source?.n||now-p.born<lifetime));
 
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,lastNarrow=null;
12
+ let dimensionAxesEnabled=false,dimensionAxisOpacity=.04,dimensionAxisOrigin='mean';
13
+ let embeddingDimensionAxes=null,representationDimensionAxes=null,dimensionAxisHits=[],hoverDimensionAxis=null;
14
  let paused=false, previousMode='live';
15
  let positionMode='embeddings',representationMeta=null,representationPoints=new Map();
16
  let representationStage=0,representationPlaying=false,representationTrail=true,lastRepresentationLayer=-1;
 
36
  if(toggleButton.textContent!==label)toggleButton.textContent=label;
37
  toggleButton.disabled=togglePending||(running&&paused);
38
  }
39
+ function dimensionAxisGeometry(){return positionMode==='representations'?representationDimensionAxes:embeddingDimensionAxes;}
40
+ function dimensionAxisControls(){
41
+ const host=root?.querySelector('.dimension-axes-controls');if(!host?.querySelector)return;
42
+ const geometry=dimensionAxisGeometry(),count=host.querySelector('[data-dimension-count]');
43
+ host.querySelector('[data-dimension-axes]').checked=dimensionAxesEnabled;
44
+ count.textContent=geometry?`(${geometry.count})`:'';
45
+ const status=host.querySelector('[data-dimension-status]');
46
+ status.textContent=geometry?`${geometry.count} feature dimensions / ${geometry.space==='input_embeddings'?'input-embedding projection':'normalised hidden-state projection'} / ${dimensionAxisOrigin==='raw'?'projected zero-vector origin':'centred at the PCA mean'}. Short or overlapping projections may be hard to distinguish.`:
47
+ positionMode==='representations'?'Axes appear once the shared representation projection is ready. Generate a few tokens and pause.':'Load a model to prepare the original dimension directions.';
48
+ }
49
  function displayedPosition(point){
50
  if(positionMode!=='representations')return point.xyz;
51
  const layers=representationPoints.get(point.n);if(!layers?.length)return null;
 
60
  if(extra.dataset.layout!==key){extra.open=!(positionMode==='representations'&&window.innerWidth<=640);extra.dataset.layout=key;}
61
  }
62
  const host=root?.querySelector('.representation-controls');if(!host?.querySelector)return;
63
+ host.hidden=positionMode!=='representations';dimensionAxisControls();if(host.hidden)return;
64
  const note=host.querySelector('[data-representation-note]'),slider=host.querySelector('[data-representation-layer]');
65
  const play=host.querySelector('[data-representation-play]'),caption=host.querySelector('[data-representation-stage]');
66
  const ready=Boolean(representationMeta?.ready),maximum=Math.max(0,(representationMeta?.stages||1)-1);
 
197
  function edgeTooltip(edge,event){
198
  const box=root?.querySelector('.space-edge-tooltip');if(!box)return;
199
  box.hidden=!edge;if(!edge)return;
200
+ if(edge.type==='dimension-axis'){
201
+ const geometry=dimensionAxisGeometry();
202
+ box.textContent=`Dimension ${edge.dimension} / ${geometry?.count??'?'} original feature dimensions / projected direction, not a model parameter`;
203
+ }else{
204
  const label=edge.n===-1?'Start boundary':JSON.stringify(contextPoint(edge.n)?.label??('#'+(edge.n+1)));
205
  box.textContent=`Layer ${edge.layer} / ${label} / ${(100*edge.score).toFixed(2)}% attention`;
206
+ }
207
  box.style.left=`${Math.max(8,Math.min(window.innerWidth-280,event.clientX+12))}px`;
208
  box.style.top=`${Math.max(8,Math.min(window.innerHeight-65,event.clientY+12))}px`;
209
  }
 
384
  const distance=Math.hypot(x-a.x-t*dx,y-a.y-t*dy);
385
  if(distance<nearest){nearest=distance;hoverEdge=edge;}
386
  }
387
+ hoverDimensionAxis=null;
388
+ if(!hoverEdge&&dimensionAxesEnabled){
389
+ let nearestAxis=3;
390
+ for(const axis of dimensionAxisHits){
391
+ const a=axis.path[0],b=axis.path[1],dx=b.x-a.x,dy=b.y-a.y;
392
+ const t=Math.max(0,Math.min(1,((x-a.x)*dx+(y-a.y)*dy)/(dx*dx+dy*dy||1)));
393
+ const distance=Math.hypot(x-a.x-t*dx,y-a.y-t*dy);
394
+ if(distance<nearestAxis){nearestAxis=distance;hoverDimensionAxis=axis;}
395
+ }
396
+ }
397
+ edgeTooltip(hoverEdge||hoverDimensionAxis,e);return;
398
  }const dx=e.clientX-lastX,dy=e.clientY-lastY;
399
  if(Math.abs(dx)+Math.abs(dy)>2)moved=true;
400
  if(panning){panX+=dx;panY+=dy;}else{yaw+=dx*.006;pitch=Math.max(-1.5,Math.min(1.5,pitch+dy*.006));}
401
  lastX=e.clientX;lastY=e.clientY;
402
  });
403
  canvas.addEventListener('pointerup',()=>dragging=false);
404
+ canvas.addEventListener('pointerleave',event=>{hoverEdge=null;hoverDimensionAxis=null;edgeTooltip(null,event);});
405
  canvas.addEventListener('pointercancel',()=>dragging=false);
406
  canvas.addEventListener('contextmenu',e=>e.preventDefault());
407
  canvas.addEventListener('click',e=>{if(moved)return;const p=pick(e);selected=p?p.n:null;details();});
 
423
  });
424
  const trailInput=root.querySelector('[data-representation-trail]');
425
  if(trailInput){trailInput.checked=representationTrail;trailInput.addEventListener('change',event=>representationTrail=event.target.checked);}
426
+ root.querySelector('[data-dimension-axes]')?.addEventListener('change',event=>{
427
+ dimensionAxesEnabled=event.target.checked;hoverDimensionAxis=null;edgeTooltip(null,event);dimensionAxisControls();
428
+ });
429
+ root.querySelector('[data-dimension-opacity]')?.addEventListener('input',event=>dimensionAxisOpacity=Number(event.target.value));
430
+ root.querySelector('[data-dimension-origin]')?.addEventListener('change',event=>{dimensionAxisOrigin=event.target.value;hoverDimensionAxis=null;dimensionAxisControls();});
431
+ root.querySelector('[data-dimension-options]')?.addEventListener('click',()=>{
432
+ const options=root.querySelector('.dimension-axes-options'),button=root.querySelector('[data-dimension-options]');
433
+ options.hidden=!options.hidden;button.setAttribute('aria-expanded',String(!options.hidden));dimensionAxisControls();
434
+ });
435
  root.querySelector('[data-space-reset]')?.addEventListener('click',resetCamera);
436
  root.querySelector('[data-space-back]')?.addEventListener('click',()=>stepToken(-1));
437
  root.querySelector('[data-space-forward]')?.addEventListener('click',()=>stepToken(1));
 
452
  }
453
  },700);
454
  }
455
+ if(data.stream!==stream){positionMode='embeddings';const view=root?.querySelector('[data-space-mode]');if(view)view.value=mode;representationPoints.clear();representationMeta=null;representationDimensionAxes=null;representationPlaying=false;representationStage=0;lastRepresentationLayer=-1;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();}
456
+ if(data.dimension_axes)embeddingDimensionAxes=data.dimension_axes;
457
  const now=Date.now(),existing=new Set(history.map(p=>p.n));
458
  for(const p of data.points||[]){
459
  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;}
 
472
  }
473
  if(data.representations){
474
  representationMeta=data.representations;
475
+ if(data.representations.dimension_axes)representationDimensionAxes=data.representations.dimension_axes;
476
  if(!data.attention_layers&&data.representations.stages)layerCount=data.representations.stages-1;
477
  for(const point of data.representations.points)representationPoints.set(point.n,point.layers);
478
  for(const n of representationPoints.keys())if(n>=0&&n<seen-128)representationPoints.delete(n);
 
496
  }
497
  function tick(){
498
  if(disposed)return;
499
+ mountGenerationControl();dimensionAxisControls();
500
  // Remount if Gradio replaced the canvas. Aging uses wall time, never server steps.
501
  mount();const now=Date.now(),dt=Math.min(now-lastTime,100);lastTime=now;
502
  if(!ctx||!width||!height)return;
 
518
  const a=project(pair[0]),b=project(pair[1]);if(!a.visible||!b.visible)continue;
519
  ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();
520
  }
521
+ dimensionAxisHits=[];
522
+ const axes=dimensionAxisGeometry();
523
+ if(dimensionAxesEnabled&&axes?.vectors){
524
+ const origin=dimensionAxisOrigin==='raw'?axes.raw_origin:[0,0,0];
525
+ ctx.strokeStyle=`rgba(255,255,255,${dimensionAxisOpacity})`;ctx.lineWidth=.6;ctx.beginPath();
526
+ for(let dimension=0;dimension<axes.vectors.length;dimension++){
527
+ const vector=axes.vectors[dimension];
528
+ let a=origin.map((value,i)=>value-vector[i]),b=origin.map((value,i)=>value+vector[i]);
529
+ let pa=project(a),pb=project(b);
530
+ const da=7/zoom+pa.z,db=7/zoom+pb.z;
531
+ if(da<=.09&&db<=.09)continue;
532
+ if(da<=.09){const t=(.09-da)/(db-da);a=a.map((value,i)=>value+(b[i]-value)*t);pa=project(a);}
533
+ else if(db<=.09){const t=(.09-db)/(da-db);b=b.map((value,i)=>value+(a[i]-value)*t);pb=project(b);}
534
+ if(![pa.x,pa.y,pb.x,pb.y].every(Number.isFinite)||Math.hypot(pa.x-pb.x,pa.y-pb.y)<.2)continue;
535
+ ctx.moveTo(pa.x,pa.y);ctx.lineTo(pb.x,pb.y);
536
+ dimensionAxisHits.push({type:'dimension-axis',dimension,path:[pa,pb]});
537
+ }
538
+ ctx.stroke();
539
+ const highlighted=dimensionAxisHits.find(axis=>axis.dimension===hoverDimensionAxis?.dimension);
540
+ if(highlighted){const[a,b]=highlighted.path;ctx.strokeStyle='rgba(255,255,255,.5)';ctx.lineWidth=1.1;ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();}
541
+ ctx.lineWidth=1;
542
+ }
543
  const cutoff=paused&&selected!=null?selected:Infinity;
544
  const source=connections==='attention'?sourcePoint():null;
545
  let active=history.filter(p=>p.n<=cutoff&&(mode==='history'||paused||p.n===source?.n||now-p.born<lifetime));
token_space.py CHANGED
@@ -51,6 +51,9 @@ class TokenProjection:
51
  scale = torch.linalg.vector_norm(sample @ basis, dim=1).quantile(.95).clamp_min(1e-6)
52
  coords = coords / scale * 2.4
53
  self.coords = torch.nn.functional.pad(coords, (0, 3 - dimensions)).tolist()
 
 
 
54
 
55
  def point(self, token_id):
56
  return self.coords[token_id]
@@ -103,6 +106,10 @@ 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.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:
@@ -150,6 +157,15 @@ SCENE = '''<div id="token-universe">
150
  <span data-space-step>Live</span>
151
  </div>
152
  <div class="space-detail">
 
 
 
 
 
 
 
 
 
153
  <section class="representation-controls" hidden>
154
  <h3 class="attention-title">Representations through layers</h3>
155
  <p class="representation-note" data-representation-note></p>
 
51
  scale = torch.linalg.vector_norm(sample @ basis, dim=1).quantile(.95).clamp_min(1e-6)
52
  coords = coords / scale * 2.4
53
  self.coords = torch.nn.functional.pad(coords, (0, 3 - dimensions)).tolist()
54
+ from projection_axes import projected_dimension_axes
55
+ padded_basis=torch.nn.functional.pad(basis,(0,3-dimensions))
56
+ self.dimension_axes=projected_dimension_axes(padded_basis,center,scale,"input_embeddings")
57
 
58
  def point(self, token_id):
59
  return self.coords[token_id]
 
106
  points = flow.space_history[-512 if full else -48:]
107
  data = {"continue_automatically": flow.continue_automatically, "stream": flow.stream_id, "revision": flow.view_revision, "paused": flow.paused, "running": flow.running,
108
  "ended": flow.ended, "points": points}
109
+ axes=getattr(store.projection,"dimension_axes",None)
110
+ if axes is not None and (full or flow.sent_dimension_axes_key != store.key):
111
+ data["dimension_axes"]=axes
112
+ flow.sent_dimension_axes_key=store.key
113
  if flow.layer_rows is not None and store.projection is not None:
114
  queries = sorted(q for q in flow.layer_queries if q >= max(0, len(tokens) - 513))
115
  if not flow.paused:
 
157
  <span data-space-step>Live</span>
158
  </div>
159
  <div class="space-detail">
160
+ <section class="dimension-axes-controls">
161
+ <div class="dimension-axes-top"><label><input type="checkbox" data-dimension-axes> All projected dimensions <span data-dimension-count></span></label><button type="button" data-dimension-options aria-expanded="false">Options</button></div>
162
+ <div class="dimension-axes-options" hidden>
163
+ <p class="dimension-axis-status" data-dimension-status></p>
164
+ <label>Line opacity <input type="range" min="0.005" max="0.15" step="0.005" value="0.04" data-dimension-opacity aria-label="Dimension axis opacity"></label>
165
+ <label>Origin <select data-dimension-origin><option value="mean">Projection centre</option><option value="raw">Original vector origin</option></select></label>
166
+ <p>White lines show every original feature direction projected into this 3D space. They are not attention links, model layers, or individual learned parameters. All lines use one common extent for visibility, preserving their relative projected lengths. Length is not importance. The default translates directions to the projection centre; the other option uses the projected zero-vector origin. Hidden-state dimensions are unit-normalised in representation mode. Hover a line to identify its dimension index.</p>
167
+ </div>
168
+ </section>
169
  <section class="representation-controls" hidden>
170
  <h3 class="attention-title">Representations through layers</h3>
171
  <p class="representation-note" data-representation-note></p>