Spaces:
Running on Zero
Running on Zero
Add optional projected original-dimension axis guides with opacity and origin controls
Browse filesFiles changed (8)
- README.md+8-2
- app.py+1
- engine.py+1
- projection_axes.pyAdded+22
- representations.py+7-1
- style.css+20-6
- token_space.js+65-5
- token_space.py+16
35 unmodified lines363738394041421 unmodified line44454647484950225 unmodified lines27627727835 unmodified lines## Hugging Face SpaceCreate a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,`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.The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost.`FLOW_HOST` and `PORT` can override these defaults. No API token isneeded for the supported public, ungated models. Start with CPU Basic and a small1 unmodified lineSpaces but does not create or publish a remote Space automatically.Run `python scripts/prepare_space.py` to create `outputs/let-it-flow-space.zip`.Extract the archive and upload its twelve files to the root of your Gradio Space.## Token space225 unmodified linesOnly 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.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.35 unmodified lines363738394041421 unmodified line44454647484950225 unmodified lines27627727827928028128228328435 unmodified lines## Hugging Face SpaceCreate a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,`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.The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost.`FLOW_HOST` and `PORT` can override these defaults. No API token isneeded for the supported public, ungated models. Start with CPU Basic and a small1 unmodified lineSpaces but does not create or publish a remote Space automatically.Run `python scripts/prepare_space.py` to create `outputs/let-it-flow-space.zip`.Extract the archive and upload its thirteen files to the root of your Gradio Space.## Token space225 unmodified linesOnly 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.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.## Experimental original-dimension axesAll 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.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.
57 unmodified lines58596061626357 unmodified linesflow.layer_rows = flow.layer_keys = Noneflow.layer_queries = [-1] * 512flow.representations = Noneflow.text_snapshot_cache = Noneflow.continue_automatically = Falseflow.pass_remaining = None57 unmodified lines5859606162636457 unmodified linesflow.layer_rows = flow.layer_keys = Noneflow.layer_queries = [-1] * 512flow.representations = Noneflow.sent_dimension_axes_key = ""flow.text_snapshot_cache = Noneflow.continue_automatically = Falseflow.pass_remaining = None
21 unmodified lines22232425262721 unmodified linesself.layer_rows = self.layer_keys = Noneself.layer_queries = [-1] * 512self.representations = Noneself.paused = Falseself.running = Falseself.reset_requested = False21 unmodified lines2223242526272821 unmodified linesself.layer_rows = self.layer_keys = Noneself.layer_queries = [-1] * 512self.representations = Noneself.sent_dimension_axes_key = ""self.paused = Falseself.running = Falseself.reset_requested = False
12345678910111213141516171819202122"""Directions of original feature axes under the actual three-dimensional PCA map."""
import math
import torch
def projected_dimension_axes(basis, center, scale, space):
basis=basis.detach().float().cpu()
center=center.detach().float().cpu()
scale=float(scale)
if basis.ndim!=2 or not basis.shape[0] or basis.shape[1]!=3 or center.shape!=(basis.shape[0],):
raise ValueError("Axis geometry must use a D-by-3 basis and its D-dimensional centre.")
if not math.isfinite(scale) or scale<=0 or not torch.isfinite(basis).all() or not torch.isfinite(center).all():
raise ValueError("Axis projection must be finite with a positive scale.")
unit_directions=basis*(2.4/scale)
# One common extent preserves the relative projected lengths of all dimensions.
extent=3.2/float(torch.linalg.vector_norm(unit_directions,dim=1).quantile(.95).clamp_min(1e-8))
directions=unit_directions*extent
raw_origin=(-center@basis)*(2.4/scale)
rounded=lambda row:[round(float(value),6) for value in row]
return {"count":len(basis),"vectors":[rounded(row) for row in directions],
"raw_origin":rounded(raw_origin),"coordinate_extent":extent,
"guide_radius":3.2,"space":space,
"description":"Original feature directions through the chosen origin; a common extent is used for visibility"}13 unmodified lines14151617181923 unmodified lines43444546474812 unmodified lines6162636465663 unmodified lines7071727374757613 unmodified linesself.stages = 0self.fitted_samples = 0self.needs_full = Falsedef add(self, query, hidden_states):if not hidden_states:23 unmodified lines_, _, basis = torch.pca_lowrank(centered, q=dimensions, center=False, niter=3)self.basis = F.pad(basis, (0, 3-dimensions))self.scale = torch.linalg.vector_norm(centered @ self.basis, dim=1).quantile(.95).clamp_min(.01)self.coords = torch.zeros((self.capacity, self.stages, 3), dtype=torch.float32)self.fitted_samples = len(samples)pending, self.pending = self.pending, {}12 unmodified linesdef snapshot(self, token_count, full=False):ready = self.basis is not Nonequeries = sorted(q for q in self.queries if q >= max(0, token_count-self.capacity-1))if not (full or self.needs_full):queries = queries[-1:]3 unmodified linesif ready and self.boundary is not None:points.append(point(-1, self.boundary))self.needs_full = Falsereturn {"ready": ready, "stages": self.stages, "capacity": self.capacity,"calibrating": sum(q>=0 for q in self.pending), "calibration_target": self.calibration_size,"fitted_samples": self.fitted_samples, "points": points,"projection": "Shared PCA of unit-normalised hidden states; axes fixed for this stream"}13 unmodified lines1415161718192023 unmodified lines444546474849505112 unmodified lines646566676869703 unmodified lines74757677787980818213 unmodified linesself.stages = 0self.fitted_samples = 0self.needs_full = Falseself.dimension_axes = Nonedef add(self, query, hidden_states):if not hidden_states:23 unmodified lines_, _, basis = torch.pca_lowrank(centered, q=dimensions, center=False, niter=3)self.basis = F.pad(basis, (0, 3-dimensions))self.scale = torch.linalg.vector_norm(centered @ self.basis, dim=1).quantile(.95).clamp_min(.01)from projection_axes import projected_dimension_axesself.dimension_axes=projected_dimension_axes(self.basis,self.center,self.scale,"normalised_hidden_states")self.coords = torch.zeros((self.capacity, self.stages, 3), dtype=torch.float32)self.fitted_samples = len(samples)pending, self.pending = self.pending, {}12 unmodified linesdef snapshot(self, token_count, full=False):ready = self.basis is not Noneinclude_axes=ready and (full or self.needs_full)queries = sorted(q for q in self.queries if q >= max(0, token_count-self.capacity-1))if not (full or self.needs_full):queries = queries[-1:]3 unmodified linesif ready and self.boundary is not None:points.append(point(-1, self.boundary))self.needs_full = Falseresult={"ready": ready, "stages": self.stages, "capacity": self.capacity,"calibrating": sum(q>=0 for q in self.pending), "calibration_target": self.calibration_size,"fitted_samples": self.fitted_samples, "points": points,"projection": "Shared PCA of unit-normalised hidden states; axes fixed for this stream"}if include_axes:result["dimension_axes"]=self.dimension_axesreturn result
141 unmodified lines14214314414514614714814915015115215344 unmodified lines198199200141 unmodified lines.layer-controls label,.layer-controls label > span { color:#bacdd4 !important; }.layer-settings > summary { cursor:pointer; color:#f4bf67 !important; font:600 12px/1.5 system-ui,sans-serif; margin:10px 0; }.layer-caption-mobile { display:none; }: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; }:is(.layer-controls,.representation-layer-label) input[type="range"]::-webkit-slider-runnable-track { height:5px; border-radius:4px; background:#354654; }: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; }:is(.layer-controls,.representation-layer-label) input[type="range"]::-moz-range-track { height:5px; border-radius:4px; background:#354654; }:is(.layer-controls,.representation-layer-label) input[type="range"]::-moz-range-thumb { width:14px; height:14px; border:0; border-radius:50%; background:#f4bf67; }:is(.layer-controls,.representation-layer-label) input[type="range"]:focus-visible { outline:2px solid #f4bf67; outline-offset:3px; }@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; } }/* HTML theme rules set colours on child spans, so specify HUD text explicitly. */44 unmodified lines#token-universe[data-position-mode="representations"] .representation-controls .attention-help { margin-top:6px;padding-top:6px; }#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; }}141 unmodified lines14214314414514614714814915015115215344 unmodified lines198199200201202203204205206207208209210211212213214141 unmodified lines.layer-controls label,.layer-controls label > span { color:#bacdd4 !important; }.layer-settings > summary { cursor:pointer; color:#f4bf67 !important; font:600 12px/1.5 system-ui,sans-serif; margin:10px 0; }.layer-caption-mobile { display:none; }: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; }:is(.layer-controls,.representation-layer-label,.dimension-axes-options) input[type="range"]::-webkit-slider-runnable-track { height:5px; border-radius:4px; background:#354654; }: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; }:is(.layer-controls,.representation-layer-label,.dimension-axes-options) input[type="range"]::-moz-range-track { height:5px; border-radius:4px; background:#354654; }: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; }:is(.layer-controls,.representation-layer-label,.dimension-axes-options) input[type="range"]:focus-visible { outline:2px solid #f4bf67; outline-offset:3px; }@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; } }/* HTML theme rules set colours on child spans, so specify HUD text explicitly. */44 unmodified lines#token-universe[data-position-mode="representations"] .representation-controls .attention-help { margin-top:6px;padding-top:6px; }#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; }}.dimension-axes-controls { border-bottom:1px solid #ffffff20; padding-bottom:10px; margin-bottom:12px; }.dimension-axes-top { display:flex;align-items:center;justify-content:space-between;gap:8px; }.dimension-axes-top label { display:flex;align-items:center;flex-wrap:wrap;gap:5px;font:600 12px/1.4 system-ui,sans-serif; }.dimension-axes-top input { accent-color:#f4bf67; }.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; }.dimension-axes-options[hidden] { display:none !important; }.dimension-axes-options { padding-top:10px; }.dimension-axes-options label { display:flex;flex-direction:column;gap:6px;margin:9px 0;font:12px/1.5 system-ui,sans-serif; }.dimension-axes-options select { padding:5px 8px;border:1px solid #6b8796;border-radius:6px;background:#112530; }.dimension-axes-options p { font:12px/1.55 system-ui,sans-serif; margin:8px 0; }.dimension-axes-controls label,.dimension-axes-controls span,.dimension-axes-controls p { color:#eef3f5 !important; }.dimension-axis-status { color:#f4bf67 !important; }@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; } }
8 unmodified lines9101112131419 unmodified lines3435363738398 unmodified lines48495051525354130 unmodified lines185186187188189190191192174 unmodified lines36736836937037137237337437537637737837938015 unmodified lines39639739839940040114 unmodified lines41641741841942042142212 unmodified lines43543643743843944017 unmodified lines45845946046146246346415 unmodified lines4804814824834844858 unmodified lineslet layerCount=0,layerRows=new Map(),layerTargets=new Map();let layerMode='three',layerLimit=3,minimumWeight=.01,hiddenLayers=new Set(),legendFocus=null;let edgeHits=[],hoverEdge=null,lastNarrow=null;let paused=false, previousMode='live';let positionMode='embeddings',representationMeta=null,representationPoints=new Map();let representationStage=0,representationPlaying=false,representationTrail=true,lastRepresentationLayer=-1;19 unmodified linesif(toggleButton.textContent!==label)toggleButton.textContent=label;toggleButton.disabled=togglePending||(running&&paused);}function displayedPosition(point){if(positionMode!=='representations')return point.xyz;const layers=representationPoints.get(point.n);if(!layers?.length)return null;8 unmodified linesif(extra.dataset.layout!==key){extra.open=!(positionMode==='representations'&&window.innerWidth<=640);extra.dataset.layout=key;}}const host=root?.querySelector('.representation-controls');if(!host?.querySelector)return;host.hidden=positionMode!=='representations';if(host.hidden)return;const note=host.querySelector('[data-representation-note]'),slider=host.querySelector('[data-representation-layer]');const play=host.querySelector('[data-representation-play]'),caption=host.querySelector('[data-representation-stage]');const ready=Boolean(representationMeta?.ready),maximum=Math.max(0,(representationMeta?.stages||1)-1);130 unmodified linesfunction edgeTooltip(edge,event){const box=root?.querySelector('.space-edge-tooltip');if(!box)return;box.hidden=!edge;if(!edge)return;const label=edge.n===-1?'Start boundary':JSON.stringify(contextPoint(edge.n)?.label??('#'+(edge.n+1)));box.textContent=`Layer ${edge.layer} / ${label} / ${(100*edge.score).toFixed(2)}% attention`;box.style.left=`${Math.max(8,Math.min(window.innerWidth-280,event.clientX+12))}px`;box.style.top=`${Math.max(8,Math.min(window.innerHeight-65,event.clientY+12))}px`;}174 unmodified linesconst distance=Math.hypot(x-a.x-t*dx,y-a.y-t*dy);if(distance<nearest){nearest=distance;hoverEdge=edge;}}edgeTooltip(hoverEdge,e);return;}const dx=e.clientX-lastX,dy=e.clientY-lastY;if(Math.abs(dx)+Math.abs(dy)>2)moved=true;if(panning){panX+=dx;panY+=dy;}else{yaw+=dx*.006;pitch=Math.max(-1.5,Math.min(1.5,pitch+dy*.006));}lastX=e.clientX;lastY=e.clientY;});canvas.addEventListener('pointerup',()=>dragging=false);canvas.addEventListener('pointerleave',event=>{hoverEdge=null;edgeTooltip(null,event);});canvas.addEventListener('pointercancel',()=>dragging=false);canvas.addEventListener('contextmenu',e=>e.preventDefault());canvas.addEventListener('click',e=>{if(moved)return;const p=pick(e);selected=p?p.n:null;details();});15 unmodified lines});const trailInput=root.querySelector('[data-representation-trail]');if(trailInput){trailInput.checked=representationTrail;trailInput.addEventListener('change',event=>representationTrail=event.target.checked);}root.querySelector('[data-space-reset]')?.addEventListener('click',resetCamera);root.querySelector('[data-space-back]')?.addEventListener('click',()=>stepToken(-1));root.querySelector('[data-space-forward]')?.addEventListener('click',()=>stepToken(1));14 unmodified lines}},700);}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();}const now=Date.now(),existing=new Set(history.map(p=>p.n));for(const p of data.points||[]){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;}12 unmodified lines}if(data.representations){representationMeta=data.representations;if(!data.attention_layers&&data.representations.stages)layerCount=data.representations.stages-1;for(const point of data.representations.points)representationPoints.set(point.n,point.layers);for(const n of representationPoints.keys())if(n>=0&&n<seen-128)representationPoints.delete(n);17 unmodified lines}function tick(){if(disposed)return;mountGenerationControl();// Remount if Gradio replaced the canvas. Aging uses wall time, never server steps.mount();const now=Date.now(),dt=Math.min(now-lastTime,100);lastTime=now;if(!ctx||!width||!height)return;15 unmodified linesconst a=project(pair[0]),b=project(pair[1]);if(!a.visible||!b.visible)continue;ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();}const cutoff=paused&&selected!=null?selected:Infinity;const source=connections==='attention'?sourcePoint():null;let active=history.filter(p=>p.n<=cutoff&&(mode==='history'||paused||p.n===source?.n||now-p.born<lifetime));8 unmodified lines91011121314151619 unmodified lines363738394041424344454647484950518 unmodified lines60616263646566130 unmodified lines197198199200201202203204205206207208209174 unmodified lines38438538638738838939039139239339439539639739839940040140240340440540640715 unmodified lines42342442542642742842943043143243343443543643714 unmodified lines45245345445545645745845912 unmodified lines47247347447547647747817 unmodified lines49649749849950050150215 unmodified lines5185195205215225235245255265275285295305315325335345355365375385395405415425435445458 unmodified lineslet layerCount=0,layerRows=new Map(),layerTargets=new Map();let layerMode='three',layerLimit=3,minimumWeight=.01,hiddenLayers=new Set(),legendFocus=null;let edgeHits=[],hoverEdge=null,lastNarrow=null;let dimensionAxesEnabled=false,dimensionAxisOpacity=.04,dimensionAxisOrigin='mean';let embeddingDimensionAxes=null,representationDimensionAxes=null,dimensionAxisHits=[],hoverDimensionAxis=null;let paused=false, previousMode='live';let positionMode='embeddings',representationMeta=null,representationPoints=new Map();let representationStage=0,representationPlaying=false,representationTrail=true,lastRepresentationLayer=-1;19 unmodified linesif(toggleButton.textContent!==label)toggleButton.textContent=label;toggleButton.disabled=togglePending||(running&&paused);}function dimensionAxisGeometry(){return positionMode==='representations'?representationDimensionAxes:embeddingDimensionAxes;}function dimensionAxisControls(){const host=root?.querySelector('.dimension-axes-controls');if(!host?.querySelector)return;const geometry=dimensionAxisGeometry(),count=host.querySelector('[data-dimension-count]');host.querySelector('[data-dimension-axes]').checked=dimensionAxesEnabled;count.textContent=geometry?`(${geometry.count})`:'';const status=host.querySelector('[data-dimension-status]');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.`: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.';}function displayedPosition(point){if(positionMode!=='representations')return point.xyz;const layers=representationPoints.get(point.n);if(!layers?.length)return null;8 unmodified linesif(extra.dataset.layout!==key){extra.open=!(positionMode==='representations'&&window.innerWidth<=640);extra.dataset.layout=key;}}const host=root?.querySelector('.representation-controls');if(!host?.querySelector)return;host.hidden=positionMode!=='representations';dimensionAxisControls();if(host.hidden)return;const note=host.querySelector('[data-representation-note]'),slider=host.querySelector('[data-representation-layer]');const play=host.querySelector('[data-representation-play]'),caption=host.querySelector('[data-representation-stage]');const ready=Boolean(representationMeta?.ready),maximum=Math.max(0,(representationMeta?.stages||1)-1);130 unmodified linesfunction edgeTooltip(edge,event){const box=root?.querySelector('.space-edge-tooltip');if(!box)return;box.hidden=!edge;if(!edge)return;if(edge.type==='dimension-axis'){const geometry=dimensionAxisGeometry();box.textContent=`Dimension ${edge.dimension} / ${geometry?.count??'?'} original feature dimensions / projected direction, not a model parameter`;}else{const label=edge.n===-1?'Start boundary':JSON.stringify(contextPoint(edge.n)?.label??('#'+(edge.n+1)));box.textContent=`Layer ${edge.layer} / ${label} / ${(100*edge.score).toFixed(2)}% attention`;}box.style.left=`${Math.max(8,Math.min(window.innerWidth-280,event.clientX+12))}px`;box.style.top=`${Math.max(8,Math.min(window.innerHeight-65,event.clientY+12))}px`;}174 unmodified linesconst distance=Math.hypot(x-a.x-t*dx,y-a.y-t*dy);if(distance<nearest){nearest=distance;hoverEdge=edge;}}hoverDimensionAxis=null;if(!hoverEdge&&dimensionAxesEnabled){let nearestAxis=3;for(const axis of dimensionAxisHits){const a=axis.path[0],b=axis.path[1],dx=b.x-a.x,dy=b.y-a.y;const t=Math.max(0,Math.min(1,((x-a.x)*dx+(y-a.y)*dy)/(dx*dx+dy*dy||1)));const distance=Math.hypot(x-a.x-t*dx,y-a.y-t*dy);if(distance<nearestAxis){nearestAxis=distance;hoverDimensionAxis=axis;}}}edgeTooltip(hoverEdge||hoverDimensionAxis,e);return;}const dx=e.clientX-lastX,dy=e.clientY-lastY;if(Math.abs(dx)+Math.abs(dy)>2)moved=true;if(panning){panX+=dx;panY+=dy;}else{yaw+=dx*.006;pitch=Math.max(-1.5,Math.min(1.5,pitch+dy*.006));}lastX=e.clientX;lastY=e.clientY;});canvas.addEventListener('pointerup',()=>dragging=false);canvas.addEventListener('pointerleave',event=>{hoverEdge=null;hoverDimensionAxis=null;edgeTooltip(null,event);});canvas.addEventListener('pointercancel',()=>dragging=false);canvas.addEventListener('contextmenu',e=>e.preventDefault());canvas.addEventListener('click',e=>{if(moved)return;const p=pick(e);selected=p?p.n:null;details();});15 unmodified lines});const trailInput=root.querySelector('[data-representation-trail]');if(trailInput){trailInput.checked=representationTrail;trailInput.addEventListener('change',event=>representationTrail=event.target.checked);}root.querySelector('[data-dimension-axes]')?.addEventListener('change',event=>{dimensionAxesEnabled=event.target.checked;hoverDimensionAxis=null;edgeTooltip(null,event);dimensionAxisControls();});root.querySelector('[data-dimension-opacity]')?.addEventListener('input',event=>dimensionAxisOpacity=Number(event.target.value));root.querySelector('[data-dimension-origin]')?.addEventListener('change',event=>{dimensionAxisOrigin=event.target.value;hoverDimensionAxis=null;dimensionAxisControls();});root.querySelector('[data-dimension-options]')?.addEventListener('click',()=>{const options=root.querySelector('.dimension-axes-options'),button=root.querySelector('[data-dimension-options]');options.hidden=!options.hidden;button.setAttribute('aria-expanded',String(!options.hidden));dimensionAxisControls();});root.querySelector('[data-space-reset]')?.addEventListener('click',resetCamera);root.querySelector('[data-space-back]')?.addEventListener('click',()=>stepToken(-1));root.querySelector('[data-space-forward]')?.addEventListener('click',()=>stepToken(1));14 unmodified lines}},700);}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();}if(data.dimension_axes)embeddingDimensionAxes=data.dimension_axes;const now=Date.now(),existing=new Set(history.map(p=>p.n));for(const p of data.points||[]){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;}12 unmodified lines}if(data.representations){representationMeta=data.representations;if(data.representations.dimension_axes)representationDimensionAxes=data.representations.dimension_axes;if(!data.attention_layers&&data.representations.stages)layerCount=data.representations.stages-1;for(const point of data.representations.points)representationPoints.set(point.n,point.layers);for(const n of representationPoints.keys())if(n>=0&&n<seen-128)representationPoints.delete(n);17 unmodified lines}function tick(){if(disposed)return;mountGenerationControl();dimensionAxisControls();// Remount if Gradio replaced the canvas. Aging uses wall time, never server steps.mount();const now=Date.now(),dt=Math.min(now-lastTime,100);lastTime=now;if(!ctx||!width||!height)return;15 unmodified linesconst a=project(pair[0]),b=project(pair[1]);if(!a.visible||!b.visible)continue;ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();}dimensionAxisHits=[];const axes=dimensionAxisGeometry();if(dimensionAxesEnabled&&axes?.vectors){const origin=dimensionAxisOrigin==='raw'?axes.raw_origin:[0,0,0];ctx.strokeStyle=`rgba(255,255,255,${dimensionAxisOpacity})`;ctx.lineWidth=.6;ctx.beginPath();for(let dimension=0;dimension<axes.vectors.length;dimension++){const vector=axes.vectors[dimension];let a=origin.map((value,i)=>value-vector[i]),b=origin.map((value,i)=>value+vector[i]);let pa=project(a),pb=project(b);const da=7/zoom+pa.z,db=7/zoom+pb.z;if(da<=.09&&db<=.09)continue;if(da<=.09){const t=(.09-da)/(db-da);a=a.map((value,i)=>value+(b[i]-value)*t);pa=project(a);}else if(db<=.09){const t=(.09-db)/(da-db);b=b.map((value,i)=>value+(a[i]-value)*t);pb=project(b);}if(![pa.x,pa.y,pb.x,pb.y].every(Number.isFinite)||Math.hypot(pa.x-pb.x,pa.y-pb.y)<.2)continue;ctx.moveTo(pa.x,pa.y);ctx.lineTo(pb.x,pb.y);dimensionAxisHits.push({type:'dimension-axis',dimension,path:[pa,pb]});}ctx.stroke();const highlighted=dimensionAxisHits.find(axis=>axis.dimension===hoverDimensionAxis?.dimension);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();}ctx.lineWidth=1;}const cutoff=paused&&selected!=null?selected:Infinity;const source=connections==='attention'?sourcePoint():null;let active=history.filter(p=>p.n<=cutoff&&(mode==='history'||paused||p.n===source?.n||now-p.born<lifetime));
50 unmodified lines51525354555646 unmodified lines10310410510610710841 unmodified lines15015115215315415550 unmodified linesscale = torch.linalg.vector_norm(sample @ basis, dim=1).quantile(.95).clamp_min(1e-6)coords = coords / scale * 2.4self.coords = torch.nn.functional.pad(coords, (0, 3 - dimensions)).tolist()def point(self, token_id):return self.coords[token_id]46 unmodified linespoints = flow.space_history[-512 if full else -48:]data = {"continue_automatically": flow.continue_automatically, "stream": flow.stream_id, "revision": flow.view_revision, "paused": flow.paused, "running": flow.running,"ended": flow.ended, "points": points}if flow.layer_rows is not None and store.projection is not None:queries = sorted(q for q in flow.layer_queries if q >= max(0, len(tokens) - 513))if not flow.paused:41 unmodified lines<span data-space-step>Live</span></div><div class="space-detail"><section class="representation-controls" hidden><h3 class="attention-title">Representations through layers</h3><p class="representation-note" data-representation-note></p>50 unmodified lines51525354555657585946 unmodified lines10610710810911011111211311411541 unmodified lines15715815916016116216316416516616716816917017150 unmodified linesscale = torch.linalg.vector_norm(sample @ basis, dim=1).quantile(.95).clamp_min(1e-6)coords = coords / scale * 2.4self.coords = torch.nn.functional.pad(coords, (0, 3 - dimensions)).tolist()from projection_axes import projected_dimension_axespadded_basis=torch.nn.functional.pad(basis,(0,3-dimensions))self.dimension_axes=projected_dimension_axes(padded_basis,center,scale,"input_embeddings")def point(self, token_id):return self.coords[token_id]46 unmodified linespoints = flow.space_history[-512 if full else -48:]data = {"continue_automatically": flow.continue_automatically, "stream": flow.stream_id, "revision": flow.view_revision, "paused": flow.paused, "running": flow.running,"ended": flow.ended, "points": points}axes=getattr(store.projection,"dimension_axes",None)if axes is not None and (full or flow.sent_dimension_axes_key != store.key):data["dimension_axes"]=axesflow.sent_dimension_axes_key=store.keyif flow.layer_rows is not None and store.projection is not None:queries = sorted(q for q in flow.layer_queries if q >= max(0, len(tokens) - 513))if not flow.paused:41 unmodified lines<span data-space-step>Live</span></div><div class="space-detail"><section class="dimension-axes-controls"><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><div class="dimension-axes-options" hidden><p class="dimension-axis-status" data-dimension-status></p><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><label>Origin <select data-dimension-origin><option value="mean">Projection centre</option><option value="raw">Original vector origin</option></select></label><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></div></section><section class="representation-controls" hidden><h3 class="attention-title">Representations through layers</h3><p class="representation-note" data-representation-note></p>
README.md+8-2
app.py+1
engine.py+1
projection_axes.pyAdded+22
representations.py+7-1
style.css+20-6
token_space.js+65-5
token_space.py+16