Spaces:
Running on Zero
Running on Zero
Upload Chat Visualiser
Browse filesFiles changed (19)
- .gitignoreAdded+6
- README.md+17-6
- app.pyAdded+313
- attention_view.pyAdded+92
- brand.cssAdded+293
- brand_theme.pyAdded+61
- engine.pyAdded+284
- english_bias.pyAdded+63
- gpu_runtime.pyAdded+9
- hf_login.pyAdded+54
- hf_login.pyiAdded+44
- models.pyAdded+105
- projection_axes.pyAdded+22
- representations.pyAdded+82
- requirements.txtAdded+9
- start.ps1Added+9
- style.cssAdded+218
- token_space.jsAdded+643
- token_space.pyAdded+200
123456.venv/.model-cache/__pycache__/*.log.pytest_cache/outputs/12345678910111213---title: Chat Visualiseremoji: 📊colorFrom: pinkcolorTo: pinksdk: gradiosdk_version: 6.32.0python_version: '3.13'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324---title: Chat Visualiseremoji: 🌊colorFrom: greencolorTo: graysdk: gradiosdk_version: 5.49.1app_file: app.pypinned: falsepython_version: '3.12'hf_oauth: true---# Chat VisualiserA chat edition of Stream of Conciousness. The original introduction leads into the same 3D token space. Prompt tokens appear in amber and model reply tokens appear in teal.## Run locallyFrom PowerShell in this directory, run `./start.ps1` and open `http://127.0.0.1:7860`. Choose a model, enter the space, and send a message. SmolLM2 135M Instruct is the default.The app downloads public Hugging Face safetensors models and runs them through Transformers on the local CPU or CUDA GPU. Custom models need a fast tokenizer and a chat template. The default model download limit is 2 GB, configurable via `FLOW_MAX_DOWNLOAD_GB`.Drag to orbit, Shift-drag to pan, and scroll to zoom. Select **Inspect tokens** after a reply to step through the chat, inspect attention, or explore recorded layer representations. Settings include the context window, reply length, and sampling controls. Earlier turns remain in the transcript when the context window fills.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313"""Chat with Hugging Face models in the original token space."""
from gpu_runtime import ZERO_GPU, spaces
import html
from pathlib import Path
import secrets
import time
import uuid
import gradio as gr
from engine import Flow, generate
from models import ModelStore, PRESETS, MODEL_LABELS, repository
from token_space import SCENE, frame
from hf_login import TopLevelLoginButton
from brand_theme import brand_theme
STORE = ModelStore()
POOL = {}
if ZERO_GPU:
for model_id in PRESETS:
entry = ModelStore()
entry.load(model_id)
POOL[model_id] = entry
def inspector(tokenizer, step, number):
rows = []
for token_id, probability in step["candidates"]:
piece = tokenizer.decode([token_id], skip_special_tokens=False,
clean_up_tokenization_spaces=False)
# repr makes spaces and linebreaks visible; escaping prevents generated HTML execution.
label = html.escape(repr(piece))
selected = token_id == step["chosen"]
rows.append(f'<div class="candidate {"selected" if selected else ""}">'
f'<div class="candidate-label"><code>{label}</code>'
f'<span>{probability:.2%}{" · selected" if selected else ""}</span></div>'
f'<div class="track"><div style="width:{probability * 100:.4f}%"></div></div>'
f'<small>token {token_id}</small></div>')
return (f'<div class="inspector"><div class="eyebrow">CHOICE {number}</div>'
'<h3>What could come next?</h3><p>Probabilities immediately before the latest token was selected.</p>'
+ "".join(rows) + f'<p>Other tokens: {step["other"]:.2%}</p>'
f'<small>Top-p retained {step["retained_mass"]:.2%} of the distribution after '
'temperature and repetition penalty. Bars show probabilities renormalized over that set. '
'The selected token may be outside the eight leading candidates.</small></div>')
EMPTY = '<div class="inspector"><div class="eyebrow">WATCH THE NEXT TOKEN</div><h3>A field of possibilities.</h3><p>Enable the inspector and begin. Each choice will show candidate tokens, their sampling probabilities, and the selected token.</p></div>'
def session_store(flow):
if ZERO_GPU:
return POOL[flow.selected_repo]
if not STORE.key.startswith(flow.selected_repo + "@"):
STORE.load(flow.selected_repo)
return STORE
def transcript(flow):
return "\n\n".join(
("You" if message["role"] == "user" else "Model") + "\n" + message["content"]
for message in flow.messages
)
def chat_context(flow, store, prompt, memory, count):
"""Format the recent conversation and map actual input tokens to canvas points."""
tokenizer = store.tokenizer
messages = flow.messages + [{"role": "user", "content": prompt}]
maximum = int(getattr(store.model.config, "max_position_embeddings", memory))
limit = min(memory, maximum)
if count >= limit:
raise ValueError("Increase the context window or reduce the reply token limit.")
start = 0
while True:
recent = messages[start:]
rendered = tokenizer.apply_chat_template(
recent, tokenize=False, add_generation_prompt=True, enable_thinking=False
)
encoded = tokenizer(rendered, add_special_tokens=False, return_offsets_mapping=True)
ids = encoded.input_ids
if len(ids) + count <= limit:
break
start += 2
if start >= len(messages):
raise ValueError("This prompt is too long for the context window and reply token limit.")
# Mark the current prompt to distinguish it from identical text in older turns or role headers.
marker = uuid.uuid4().hex
marked = tokenizer.apply_chat_template(
[*recent[:-1], {"role": "user", "content": marker}],
tokenize=False, add_generation_prompt=True, enable_thinking=False
)
before, separator, after = marked.partition(marker)
if separator and rendered.startswith(before) and rendered.endswith(after):
prompt_first = len(before)
prompt_last = len(rendered) - len(after)
else:
prompt_first = rendered.rfind(prompt)
if prompt_first < 0:
raise ValueError("The chat template rewrites this prompt and its tokens cannot be located.")
prompt_last = prompt_first + len(prompt)
offsets = encoded.offset_mapping
mapping = [None] * len(ids)
search_from = 0
for message, (first, last) in zip(recent[:-1], flow.message_tokens[start:]):
content = message["content"].strip()
if not content:
continue
position = rendered.find(content, search_from, prompt_first)
if position < 0:
continue
end = position + len(content)
search_from = end
slots = [i for i, (a, b) in enumerate(offsets) if a < end and b > position and a < b]
visible = [n for n in range(first, last) if flow.tokens[n] not in tokenizer.all_special_ids]
if [ids[i] for i in slots] == [flow.tokens[n] for n in visible]:
for slot, n in zip(slots, visible):
mapping[slot] = n
prompt_ids = []
for i, (a, b) in enumerate(offsets):
if a < prompt_last and b > prompt_first and a < b:
mapping[i] = len(flow.tokens) + len(prompt_ids)
prompt_ids.append(ids[i])
if not prompt_ids:
raise ValueError("The prompt did not produce any visible tokens.")
return (ids, mapping), prompt_ids, start > 0
def load_model(repo):
candidate = Flow()
try:
candidate.selected_repo = repository(repo)
store = session_store(candidate)
return (candidate, "", "", EMPTY, "Send a message to begin.", frame(candidate, store),
store.description, "<span>" + html.escape(candidate.selected_repo) + "</span>",
gr.update(visible=False), gr.update(visible=True), "Inspect tokens")
except Exception as error:
raise gr.Error(f"Could not load model: {error}") from error
@spaces.GPU(duration=90)
def send(prompt, flow, temperature, top_p, penalty, count, memory, delay,
attention, attention_layer, attention_head, capture_representations):
prompt = prompt.strip()
if not prompt:
return
if not flow.selected_repo:
raise gr.Error("Load a model first.")
try:
store = session_store(flow)
count, memory = int(count), int(memory)
context, prompt_ids, trimmed = chat_context(flow, store, prompt, memory, count)
if len(flow.tokens) + len(prompt_ids) + count > 16384:
raise ValueError("This chat has reached its token limit. Clear it to start a new conversation.")
except Exception as error:
raise gr.Error(str(error)) from error
first = len(flow.tokens)
reply_start = first + len(prompt_ids)
flow.tokens.extend(prompt_ids)
flow.roles.update(dict.fromkeys(range(first, reply_start), "user"))
flow.messages.extend([{"role": "user", "content": prompt}, {"role": "assistant", "content": ""}])
flow.message_tokens.extend([(first, reply_start), (reply_start, reply_start)])
flow.model_key = store.key
flow.seed = flow.seed if flow.seed is not None else secrets.randbits(32)
flow.ended = flow.paused = False
flow.stop.clear()
flow.running = True
panel = EMPTY
started = time.monotonic()
def update(status, full=False, composer=gr.skip()):
return (transcript(flow), panel, status, frame(flow, store, full=full), composer,
"Inspect tokens", flow)
try:
yield update("Generating…", full=True, composer="")
settings = {"attention": attention and bool(store.attention_modules),
"attention_layer": int(attention_layer), "attention_head": int(attention_head),
"capture_representations": capture_representations}
for step in generate(store.model, store.tokenizer, flow, store.key, count, temperature,
top_p, penalty, flow.seed, context_limit=memory,
live_settings=lambda: settings, attention_modules=store.attention_modules,
chat_context=context):
flow.messages[-1]["content"] = step["text"]
flow.message_tokens[-1] = (reply_start, len(flow.tokens))
panel = inspector(store.tokenizer, step, len(flow.tokens) - reply_start)
yield update(f"Generating… · {len(flow.tokens) - reply_start} reply tokens")
if delay and flow.stop.wait(delay):
break
if ZERO_GPU and time.monotonic() - started >= 75:
flow.stop.set()
break
reason = "Reply stopped." if flow.stop.is_set() else "Reply complete."
except Exception as error:
reason = "Reply interrupted."
gr.Warning(str(error))
finally:
flow.running = False
if flow.representations is not None:
flow.representations.finalize()
if trimmed:
reason += " Earlier turns were outside the model’s context."
yield update(reason, full=True)
def inspect(flow):
if not flow.selected_repo or not flow.tokens or flow.running:
return gr.skip(), gr.skip()
store = POOL.get(flow.selected_repo, STORE)
if flow.model_key != store.key:
return gr.skip(), gr.skip()
flow.paused = not flow.paused
return frame(flow, store, full=True), "Return to live view" if flow.paused else "Inspect tokens"
def stop(flow):
flow.stop.set()
def clear_chat(flow):
clean = Flow()
clean.selected_repo = flow.selected_repo
return "", EMPTY, "Send a message to begin.", frame(clean, session_store(clean)), "", "Inspect tokens", clean
def build_app():
css = "\n".join(Path(__file__).with_name(name).read_text(encoding="utf-8") for name in ("brand.css", "style.css"))
js = Path(__file__).with_name("token_space.js").read_text(encoding="utf-8")
with gr.Blocks(title="Chat Visualiser", css=css, js=js, theme=brand_theme(),
delete_cache=(3600, 3600)) as demo:
flow = gr.State(Flow())
with gr.Column(elem_id="model-picker", elem_classes=["brand-start"]) as picker:
gr.HTML('<header class="brand-header"><div class="eyebrow">AN EXPERIMENT IN AUTOMATIC WRITING</div>'
'<h1 class="brand-title">Automatic Token Generation<span class="title-stop">.</span></h1>'
'<p class="brand-intro">Inspired by the Surrealists\u2019 practice of automatic writing, this experiment lets language unfold without a written prompt. '
'A language model uses recent tokens to predict what could come next, then selects the next token by sampling from those probabilities. '
'A 3D view tracks attention weights from a selected layer and maps tokens through their embeddings.</p>'
'<p class="brand-intro">The model has no unconscious mind to uncover. This demo offers a look under the hood of how large language models generate text '
'through learned patterns, attention, and probabilistic sampling within a limited context window.</p></header>',
padding=False)
if ZERO_GPU:
TopLevelLoginButton(elem_id="hf-login-picker")
gr.Markdown("Sign in to use your Hugging Face ZeroGPU quota. Sign-in opens in this tab and brings you back here.",
elem_classes=["signin-note"])
repo = gr.Dropdown([(MODEL_LABELS[preset], preset) for preset in PRESETS],
value=PRESETS[0], allow_custom_value=not ZERO_GPU, label="Model",
info=None if ZERO_GPU else "Or paste a public chat model repository ID or Hugging Face URL.")
load = gr.Button("Load model & enter space", variant="primary", elem_id="load-model",
elem_classes=["brand-primary"])
gr.Markdown("**Chat edition.** Send a message and watch your prompt tokens appear in amber and "
"the model’s reply tokens unfold in teal. Choose an instruction-tuned model.",
elem_classes=["brand-note"])
with gr.Column(visible=False, elem_id="flow-workspace") as workspace:
gr.HTML(SCENE, elem_id="space-scene")
with gr.Column(elem_id="text-overlay"):
model_badge = gr.HTML("", elem_id="model-name", elem_classes=["brand-caption"])
page = gr.Textbox(label="Conversation", lines=5, max_lines=8, placeholder="Send a message to begin.",
show_label=False, interactive=False, show_copy_button=True, elem_id="page")
home = gr.Button("Change model / sign in", elem_id="reset-model", elem_classes=["return-home"],
size="sm", min_width=0)
with gr.Column(elem_id="control-dock", elem_classes=["brand-dock"]):
with gr.Row(elem_id="stream-buttons"):
prompt = gr.Textbox(label="Message", show_label=False, placeholder="Write a message…",
lines=1, max_lines=1, elem_id="chat-prompt", scale=8)
send_button = gr.Button("Send", variant="primary", scale=1)
with gr.Row(elem_id="chat-actions"):
inspect_button = gr.Button("Inspect tokens", size="sm")
halt = gr.Button("Stop reply", size="sm")
reset = gr.Button("Clear chat", size="sm")
with gr.Accordion("Settings, model & attention", open=False, elem_id="settings-drawer"):
with gr.Row(elem_id="sampling-controls"):
temperature = gr.Slider(.05, 2, value=.7, step=.05, label="Temperature")
top_p = gr.Slider(.05, 1, value=.9, step=.01, label="Top-p")
penalty = gr.Slider(1, 2, value=1.05, step=.01, label="Repetition penalty")
with gr.Row():
memory = gr.Slider(256, 2048, value=1024, step=1, label="Context window (tokens)")
count = gr.Slider(1, 1024, value=160, step=1, label="Maximum reply tokens")
delay = gr.Slider(0, .5, value=0 if ZERO_GPU else .06, step=.02, label="Reading delay (seconds)")
with gr.Row():
attention = gr.Checkbox(value=True, label="Capture attention")
attention_layer = gr.Number(value=-1, precision=0, label="Attention layer (-1 = last)")
attention_head = gr.Number(value=-1, precision=0, label="Attention head (-1 = mean)")
capture = gr.Checkbox(value=True, label="Capture layer representations")
status = gr.Textbox(label="Chat status", interactive=False)
model_status = gr.Textbox(label="Loaded model", interactive=False)
panel = gr.HTML(EMPTY)
gr.Markdown("Drag to orbit, Shift-drag to pan, and scroll to zoom. "
"Inspect tokens to step through the conversation or explore layer representations.")
transport = gr.HTML("", elem_id="space-transport", elem_classes=["space-transport"])
common = dict(concurrency_id="model", concurrency_limit=1)
outputs = [page, panel, status, transport, prompt, inspect_button, flow]
inputs = [prompt, flow, temperature, top_p, penalty, count, memory, delay,
attention, attention_layer, attention_head, capture]
load.click(load_model, repo, [flow, page, prompt, panel, status, transport,
model_status, model_badge, picker, workspace, inspect_button], **common)
gr.on([send_button.click, prompt.submit], send, inputs, outputs, api_name="chat", **common)
halt.click(stop, flow, None, queue=False)
inspect_button.click(inspect, flow, [transport, inspect_button], **common)
reset.click(clear_chat, flow, outputs, **common)
home.click(stop, flow, None, queue=False).then(
lambda: (gr.update(visible=True), gr.update(visible=False)),
outputs=[picker, workspace], **common)
return demo.queue(max_size=16, default_concurrency_limit=1)
if __name__ == "__main__":
import os
default_host = "0.0.0.0" if os.environ.get("SPACE_ID") else "127.0.0.1"
build_app().launch(server_name=os.environ.get("FLOW_HOST", default_host),
server_port=int(os.environ.get("PORT", "7860")), show_error=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Capture one real attention row without retaining every layer's attention matrix."""
import torch
def attention_modules(model):
return [(name, module) for name, module in model.named_modules()
if name.endswith((".self_attn", ".attn")) and not getattr(module, "is_cross_attention", False)]
class AttentionProbe:
def __init__(self, modules, layer=-1, head=-1):
self.layer = len(modules) - 1 if layer == -1 else int(layer)
if not 0 <= self.layer < len(modules):
raise ValueError(f"Attention layer must be 0–{len(modules)-1}, or -1 for the last layer.")
self.module = modules[self.layer][1]
self.head = int(head)
self.row = None
def __enter__(self):
def capture(module, inputs, output):
weights = output[1] if isinstance(output, tuple) and len(output) > 1 else None
if not isinstance(weights, torch.Tensor) or weights.ndim != 4:
raise ValueError("This model does not expose supported attention weights.")
row = weights[0, :, -1, :].detach().float()
if self.head == -1:
row = row.mean(0)
elif 0 <= self.head < len(row):
row = row[self.head]
else:
raise ValueError(f"Attention head must be 0–{len(row)-1}, or -1 to average heads.")
self.row = row.cpu()
self.handle = self.module.register_forward_hook(capture)
return self
def __exit__(self, *args):
self.handle.remove()
def record(self, key_start, query):
if self.row is None:
raise ValueError("The selected attention module did not return attention weights.")
values, indices = torch.topk(self.row, min(8, len(self.row)))
return {"query": query, "layer": self.layer, "head": self.head,
"links": [{"n": key_start + int(i) - 1, "score": float(v)}
for v, i in zip(values, indices)],
"shown_mass": float(values.sum()), "keys": len(self.row)}
class LayerAttentionProbe:
"""Capture head means for all layers, plus the chosen layer/head for inspection."""
def __init__(self, modules, layer=-1, head=-1):
self.probes = [AttentionProbe(modules, index, -1) for index in range(len(modules))]
selected = len(modules) - 1 if layer == -1 else int(layer)
if not 0 <= selected < len(modules):
raise ValueError("Attention layer is outside this model's range.")
self.primary = self.probes[selected] if head == -1 else AttentionProbe(modules, selected, head)
def __enter__(self):
from contextlib import ExitStack
self.stack = ExitStack()
try:
for probe in self.probes:
self.stack.enter_context(probe)
if self.primary not in self.probes:
self.stack.enter_context(self.primary)
except BaseException:
self.stack.close()
raise
return self
def __exit__(self, *args):
return self.stack.__exit__(*args)
@property
def row(self):
return self.primary.row
def record(self, key_start, query):
return self.primary.record(key_start, query)
def layer_record(self, key_end):
# A fixed-size CPU tensor avoids thousands of dictionaries in GPU session snapshots.
packed = torch.zeros((len(self.probes), 8, 2), dtype=torch.float32)
packed[:, :, 0] = -2 # padding, distinct from boundary token index -1
keys = torch.zeros(len(self.probes), dtype=torch.int32)
for layer, probe in enumerate(self.probes):
if probe.row is None:
raise ValueError("A layer did not expose its attention weights.")
values, indices = torch.topk(probe.row, min(8, len(probe.row)))
packed[layer, :len(values), 0] = indices + key_end - len(probe.row) - 1
packed[layer, :len(values), 1] = values
keys[layer] = len(probe.row)
return packed, keys123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293/* ========================================================================== Shared look for the Hugging Face Spaces in this folder: Automatic Drawing, Stream of Consciousness (Let It Flow), Token Visualiser.
Canonical copy: shared-ui/brand.css. Edit it there, then run `python shared-ui/sync.py` to copy it into each project.
- Start page: follows the browser's light/dark setting. - Workspace: a dark stage with a pale mint control panel, identical in both modes. ========================================================================== */
:root { /* Workspace: the same in light and dark browser modes. */ --brand-stage: #080f18; --brand-stage-raised: #112530; --brand-stage-line: #577f89; --brand-stage-text: #eef3f5; --brand-stage-caption: #c5e2dd; --brand-amber: #f4bf67; --brand-amber-hover: #e7aa45; --brand-amber-deep: #b77a20; --brand-on-amber: #17242b; --brand-mint: #eaf2eff2; --brand-mint-solid: #eaf2ef; --brand-mint-surface: #f4f8f6; --brand-mint-text: #203c3a; --brand-mint-label: #29433f; --brand-mint-subdued: #526b68; --brand-mint-line: #b3c7bd; --brand-mint-border: #6d9f9b66; --brand-shadow: 0 12px 50px #0006; --brand-radius-panel: 18px; --brand-radius-control: 10px; --brand-serif: Georgia, 'Times New Roman', serif; --brand-sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
/* Start page, light browser mode. */ --brand-page: #f4f8f6; --brand-surface: #ffffff; --brand-heading: #17242b; --brand-text: #203c3a; --brand-subdued: #526b68; --brand-eyebrow: #92601c; --brand-link: #92601c; --brand-line: #b3c7bd; --brand-input: #ffffff; --brand-input-hover: #f4f8f6; --brand-focus: #b77a20;}
/* Start page, dark browser mode. Gradio puts .dark on an ancestor of the app and honours ?__theme=. Streamlit follows the system setting, hence the media query. */.dark { --brand-page: #080f18; --brand-surface: #091622; --brand-heading: #eef3f5; --brand-text: #d5e3e6; --brand-subdued: #a8bdc4; --brand-eyebrow: #f4bf67; --brand-link: #f4bf67; --brand-line: #577f89; --brand-input: #112530; --brand-input-hover: #193442; --brand-focus: #f4bf67;}@media (prefers-color-scheme: dark) { .stApp { --brand-page: #080f18; --brand-surface: #091622; --brand-heading: #eef3f5; --brand-text: #d5e3e6; --brand-subdued: #a8bdc4; --brand-eyebrow: #f4bf67; --brand-link: #f4bf67; --brand-line: #577f89; --brand-input: #112530; --brand-input-hover: #193442; --brand-focus: #f4bf67; }}
/* ---- Start page --------------------------------------------------------- *//* Order: eyebrow, title, intro, sign-in + note, model, primary action, note. *//* .st-key-start_page is Token Visualiser's Streamlit start-page container. */.brand-start, .st-key-start_page { box-sizing: border-box; width: calc(100% - 24px) !important; max-width: 680px !important; margin: 7vh auto !important; padding: 24px !important; gap: 18px !important;}/* Gradio wraps fields in a bordered card; keep the start page flat (label above field), as in Token Visualiser. */.brand-start .form { border: 0 !important; background: transparent !important; box-shadow: none !important; }.brand-start .form > .block { padding: 0 !important; border: 0 !important; background: transparent !important; box-shadow: none !important;}.brand-start .form > .block [data-testid="block-info"] { padding-left: 0 !important; padding-right: 0 !important; font-weight: 600; color: var(--brand-text) !important;}/* Gradio pads HTML blocks; align the title with the controls below it. */.brand-start .html-container { padding-left: 0 !important; padding-right: 0 !important; }.brand-header { padding: 12px 0 6px; }.eyebrow { font: 600 11px/1.5 var(--brand-sans); letter-spacing: .18em; text-transform: uppercase; color: var(--brand-eyebrow) !important;}.brand-title { margin: 14px 0 18px !important; padding: 0 !important; border: 0 !important; font: 400 clamp(38px, 6vw, 62px)/1.06 var(--brand-serif) !important; letter-spacing: -.04em !important; color: var(--brand-heading) !important;}.title-stop { color: var(--brand-amber) !important; }.brand-intro { margin: 0 0 12px !important; font: 16px/1.7 var(--brand-sans) !important; color: var(--brand-text) !important;}.brand-note, .brand-note p, .brand-note li,.signin-note, .signin-note p { margin: 0; font: 14px/1.6 var(--brand-sans) !important; color: var(--brand-subdued) !important;}.brand-note strong, .signin-note strong { color: var(--brand-text) !important; }.brand-note a, .signin-note a, .brand-header a { color: var(--brand-link) !important; }/* .st-key-hf_load_preset is Token Visualiser's "Load model" button. */.brand-primary, .st-key-hf_load_preset button { min-height: 48px !important; border: 0 !important; border-radius: var(--brand-radius-control) !important; background: var(--brand-amber) !important; color: var(--brand-on-amber) !important; font: 600 16px/1.4 var(--brand-sans) !important;}.brand-primary:hover, .st-key-hf_load_preset button:hover { background: var(--brand-amber-hover) !important; }.brand-primary:focus-visible, .st-key-hf_load_preset button:focus-visible { outline: 3px solid var(--brand-focus) !important; outline-offset: 2px;}@media (max-width: 640px) { .brand-start, .st-key-start_page { margin: 3vh auto !important; padding: 18px !important; }}
/* ---- Workspace ---------------------------------------------------------- *//* Floating mint panel. A light island: readable in both browser modes. */.brand-dock { box-sizing: border-box; border: 1px solid var(--brand-mint-border) !important; border-radius: var(--brand-radius-panel) !important; background: var(--brand-mint) !important; backdrop-filter: blur(18px); box-shadow: var(--brand-shadow); color: var(--brand-mint-text); color-scheme: light; /* Start-page tokens revert to their light values inside the panel. */ --brand-heading: #17242b; --brand-text: #203c3a; --brand-subdued: #526b68; --brand-eyebrow: #92601c; --brand-link: #92601c; --brand-line: #b3c7bd; --brand-input: #ffffff; --brand-input-hover: #f4f8f6; --brand-focus: #b77a20; /* Gradio theme variables, so the panel ignores Gradio's dark mode. */ --body-text-color: #203c3a; --body-text-color-subdued: #526b68; --block-background-fill: #f4f8f6; --background-fill-primary: #f4f8f6; --background-fill-secondary: #e3ece7; --block-label-background-fill: #f4f8f6; --block-label-text-color: #29433f; --block-title-text-color: #203c3a; --block-title-background-fill: transparent; --block-title-border-color: transparent; --block-info-text-color: #526b68; --block-border-color: #bdcdc5; --border-color-primary: #b3c7bd; --input-background-fill: #ffffff; --input-background-fill-hover: #f4f8f6; --input-background-fill-focus: #ffffff; --input-border-color: #b3c7bd; --input-text-color: #1c3536; --input-placeholder-color: #526b68; --accordion-text-color: #203c3a; --checkbox-background-color: #ffffff; --checkbox-border-color: #8aa49c; --checkbox-label-background-fill: #f4f8f6; --checkbox-label-text-color: #203c3a; --button-secondary-background-fill: #f4f8f6; --button-secondary-background-fill-hover: #dce9e1; --button-secondary-text-color: #203c3a; --button-secondary-text-color-hover: #17242b; --button-secondary-border-color: #b3c7bd; --link-text-color: #725020; --table-even-background-fill: #ffffff; --table-odd-background-fill: #f4f8f6;}.brand-dock .prose, .brand-dock .prose strong { color: var(--brand-mint-text) !important; }.brand-dock label, .brand-dock .label-wrap, .brand-dock .label-wrap span { color: var(--brand-mint-label) !important; background: transparent !important;}.brand-dock input[type="number"], .brand-dock input[type="text"], .brand-dock textarea { max-width: 100%; color: #1c3536 !important; -webkit-text-fill-color: #1c3536 !important; background: #ffffff !important;}.brand-dock .block-info { color: var(--brand-mint-subdued) !important; }.brand-dock button:focus-visible { outline: 3px solid var(--brand-amber-deep) !important; outline-offset: 2px; }
/* Model and status line at the top left of the stage. */.brand-caption, .brand-caption .prose, .brand-caption p { color: var(--brand-stage-caption) !important; font: 13px/1.5 var(--brand-sans) !important;}.brand-caption strong { color: var(--brand-amber) !important; font-weight: 600; }
/* Round "change model" button, bottom right, outside the panel. Its text stays as the accessible name; the ↺ glyph is drawn instead. .st-key-clear_model is the Streamlit wrapper of Token Visualiser's button. */.return-home, .st-key-clear_model button { position: fixed !important; right: max(16px, env(safe-area-inset-right)); bottom: max(16px, env(safe-area-inset-bottom)); z-index: 60; display: flex !important; align-items: center; justify-content: center; box-sizing: border-box; width: 40px !important; height: 40px !important; min-width: 40px !important; min-height: 40px !important; padding: 0 !important; border: 1px solid #86b6b366 !important; border-radius: 50% !important; background: #112530ed !important; color: var(--brand-stage-caption) !important; font-size: 0 !important; box-shadow: 0 3px 16px #0004; cursor: pointer;}.return-home::before, .st-key-clear_model button::before { content: "\21ba"; font: 22px/1 var(--brand-sans); color: var(--brand-stage-caption);}.return-home::after, .st-key-clear_model button::after { content: var(--brand-return-label, "Change model"); position: absolute; top: 50%; right: 50px; transform: translateY(-50%); padding: 5px 9px; border: 1px solid #78949d66; border-radius: 7px; background: #07121ff5; color: #e2edf0; font: 12px/1.4 var(--brand-sans); white-space: nowrap; opacity: 0; pointer-events: none; transition: opacity .15s;}.return-home:hover, .st-key-clear_model button:hover { background: #23434d !important; }.return-home:hover::after, .return-home:focus-visible::after,.st-key-clear_model button:hover::after, .st-key-clear_model button:focus-visible::after { opacity: 1; }.return-home:focus-visible, .st-key-clear_model button:focus-visible { outline: 2px solid var(--brand-amber) !important; outline-offset: 3px;}@media (max-width: 640px) { .return-home, .st-key-clear_model button { right: 12px; bottom: 12px; }}
/* Gradio's "Use via API · Built with Gradio" footer. */footer { display: none !important; }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061"""Gradio theme shared by the Spaces in this folder.
Canonical copy: shared-ui/brand_theme.py. Edit it there, then run`python shared-ui/sync.py` to copy it into each project.
The start page follows the browser's light/dark setting: plain keys hold thelight palette and `*_dark` keys the dark one. The workspace sets its own colours(see brand.css), so it looks the same in both modes."""import gradio as gr
LIGHT = { "body_background_fill": "#f4f8f6", "body_text_color": "#203c3a", "body_text_color_subdued": "#526b68", "background_fill_primary": "#f4f8f6", "background_fill_secondary": "#eaf2ef", "block_background_fill": "#ffffff", "block_border_color": "#cfdcd6", "block_label_background_fill": "#ffffff", "block_label_text_color": "#29433f", "block_title_background_fill": "transparent", "block_title_text_color": "#203c3a", "block_info_text_color": "#526b68", "panel_background_fill": "#eaf2ef", "input_background_fill": "#ffffff", "input_background_fill_hover": "#f4f8f6", "input_background_fill_focus": "#ffffff", "input_border_color": "#b3c7bd", "input_placeholder_color": "#6b827e", "accordion_text_color": "#203c3a", "border_color_primary": "#b3c7bd", "button_secondary_background_fill": "#eaf2ef", "button_secondary_background_fill_hover": "#dce9e1", "button_secondary_text_color": "#203c3a", "button_secondary_text_color_hover": "#17242b", "link_text_color": "#92601c", "link_text_color_hover": "#b77a20",}DARK = { "body_background_fill": "#080f18", "body_text_color": "#eef3f5", "body_text_color_subdued": "#a8bdc4", "background_fill_primary": "#091622", "background_fill_secondary": "#112530", "block_background_fill": "#091622", "block_border_color": "#577f89", "block_label_background_fill": "#091622", "block_label_text_color": "#eef3f5", "block_title_background_fill": "transparent", "block_title_text_color": "#eef3f5", "block_info_text_color": "#a8bdc4", "panel_background_fill": "#091622", "input_background_fill": "#112530", "input_background_fill_hover": "#193442", "input_background_fill_focus": "#112530", "input_border_color": "#577f89", "input_placeholder_color": "#a8bdc4", "accordion_text_color": "#eef3f5", "border_color_primary": "#577f89", "button_secondary_background_fill": "#193442", "button_secondary_background_fill_hover": "#577f89", "button_secondary_text_color": "#eef3f5", "button_secondary_text_color_hover": "#ffffff", "link_text_color": "#f4bf67", "link_text_color_hover": "#f8d49a",}# Same system font stack as brand.css (--brand-sans) and Token Visualiser's Streamlit theme.FONT = ["system-ui", "-apple-system", "Segoe UI", "Roboto", "sans-serif"]# Amber primary actions and plain bordered inputs (as in Token Visualiser) in both modes.PRIMARY = { "input_border_width": "1px", "input_shadow": "none", "input_shadow_focus": "0 0 0 2px #f4bf6733", "input_border_color_focus": "#f4bf67", "button_primary_background_fill": "#f4bf67", "button_primary_background_fill_hover": "#e7aa45", "button_primary_text_color": "#17242b", "button_primary_text_color_hover": "#17242b", "button_primary_border_color": "#f4bf67", "button_primary_border_color_hover": "#e7aa45",}
# Settings Gradio applies to both modes at once (no *_dark variant).BOTH_MODES = {"input_radius": "10px"}
def brand_theme(): values = {**LIGHT, **PRIMARY, **BOTH_MODES} values.update({key + "_dark": value for key, value in {**DARK, **PRIMARY}.items()}) return gr.themes.Soft(primary_hue="amber", neutral_hue="stone", font=FONT).set(**values)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284"""Causal sampling with probabilities and optional model internals."""
from gpu_runtime import manager
import secrets
import threading
import uuid
from contextlib import nullcontext
import torch
class Flow:
def __init__(self, tokens=None, text="", model_key="", seed=None, ended=False):
shared = manager()
self._shared = shared is not None
self._status = shared.dict() if shared else {}
self.selected_repo = ""
self.continue_automatically = False
self.tokens = list(tokens or [])
self.roles = {}
self.messages = []
self.message_tokens = []
self.stream_id = uuid.uuid4().hex
self.space_history = []
self.attention_history = {}
self.layer_rows = self.layer_keys = None
self.layer_queries = [-1] * 512
self.representations = None
self.sent_dimension_axes_key = ""
self.paused = False
self.running = False
self.reset_requested = False
self.view_revision = 0
self.view_lock = threading.RLock()
self.text_snapshot_cache = None
self.text = text
self.model_key = model_key
self.seed = seed
self.rng_state = None
self.ended = ended
self.stop = shared.Event() if shared else threading.Event()
self._control_lock = shared.RLock() if shared else threading.Lock()
self._controls = shared.dict() if shared else {}
@property
def paused(self):
return self._status.get("paused", False)
@paused.setter
def paused(self, value):
self._status["paused"] = value
@property
def running(self):
return self._status.get("running", False)
@running.setter
def running(self, value):
self._status["running"] = value
@property
def reset_requested(self):
return self._status.get("reset_requested", False)
@reset_requested.setter
def reset_requested(self, value):
self._status["reset_requested"] = value
@property
def continue_automatically(self):
return self._status.get("continue_automatically", False)
@continue_automatically.setter
def continue_automatically(self, value):
self._status["continue_automatically"] = value
def __getstate__(self):
state = self.__dict__.copy()
state.pop("view_lock", None)
if not self._shared:
state["_stopped"] = self.stop.is_set()
state.pop("stop", None)
state.pop("_control_lock", None)
return state
def __setstate__(self, state):
self.__dict__.update(state)
self.view_lock = threading.RLock()
if not self._shared:
self.stop = threading.Event()
if self.__dict__.pop("_stopped", False):
self.stop.set()
self._control_lock = threading.Lock()
def update_controls(self, **changes):
bounds = {"temperature": (.05, 2), "top_p": (.05, 1), "penalty": (1, 2),
"memory": (16, 2048), "count": (1, 1024), "delay": (0, .5), "english_bias": (0, 4)}
for name, value in changes.items():
if name in ("watch", "auto_continue", "attention", "capture_representations"):
if not isinstance(value, bool):
raise ValueError("Watch must be true or false.")
elif name in ("attention_layer", "attention_head"):
if int(value) != value or value < -1:
raise ValueError(f"{name} must be -1 or a nonnegative integer.")
elif name not in bounds or not bounds[name][0] <= value <= bounds[name][1]:
raise ValueError(f"Invalid live setting: {name}.")
elif name in ("memory", "count") and int(value) != value:
raise ValueError(f"{name} must be an integer.")
with self._control_lock:
self._controls.update(changes)
def controls(self):
with self._control_lock:
return self._controls.copy()
def __deepcopy__(self, memo):
return Flow() # Gradio creates an independent state for each visitor.
def distribution(logits, history, temperature, top_p, repetition_penalty, english_prior=None, english_bias=0):
"""Repetition penalty, optional language prior, temperature, then nucleus filtering."""
if not 0.05 <= temperature <= 2 or not 0 < top_p <= 1 or not 1 <= repetition_penalty <= 2:
raise ValueError("Sampling settings are outside the supported range.")
scores = logits.detach().float().cpu().clone()
if history and repetition_penalty != 1:
ids = torch.tensor(sorted(set(history)), dtype=torch.long)
values = scores[ids]
scores[ids] = torch.where(values < 0, values * repetition_penalty, values / repetition_penalty)
if not 0 <= english_bias <= 4:
raise ValueError("English bias must be between 0 and 4.")
if english_bias and english_prior is not None:
if english_prior.shape != scores.shape:
raise ValueError("Language prior does not match model vocabulary.")
scores += english_prior * english_bias
scores /= temperature
raw = torch.softmax(scores, dim=-1)
ordered, indices = torch.sort(raw, descending=True)
# Keep the first token that crosses p, including the highest-probability token.
remove = ordered.cumsum(0) - ordered >= top_p
filtered = raw.clone()
filtered[indices[remove]] = 0
filtered /= filtered.sum()
if not torch.isfinite(filtered).all():
raise ValueError("The model returned invalid probabilities.")
return filtered, raw
def start_id(model, tokenizer):
for value in (tokenizer.bos_token_id, model.config.bos_token_id,
tokenizer.eos_token_id, model.config.eos_token_id):
if value is not None:
return int(value[0] if isinstance(value, (tuple, list)) else value)
raise ValueError("This model has no BOS or EOS token. Prompt-free startup is unavailable.")
def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, seed,
context_limit=128, live_settings=None, attention_modules=None, english_prior=None,
chat_context=None):
if int(context_limit) != context_limit or not 1 <= context_limit <= 2048:
raise ValueError("Memory span must be an integer from 1 to 2048 tokens.")
context_limit = int(context_limit)
if flow.model_key and flow.model_key != key:
raise ValueError("The loaded model changed. Choose Start fresh before continuing.")
if flow.ended:
raise ValueError("The model ended this stream. Choose Start fresh for another.")
fresh = not flow.model_key
if fresh:
if seed is not None and (int(seed) != seed or not 0 <= seed <= 2**32 - 1):
raise ValueError("Seed must be an integer from 0 to 4294967295, or blank.")
flow.seed = int(seed) if seed is not None else secrets.randbits(32)
flow.model_key = key
rng = torch.Generator(device="cpu")
if flow.rng_state is not None:
rng.set_state(flow.rng_state)
else:
rng.manual_seed(flow.seed)
prefix, prefix_indices = chat_context or ([start_id(model, tokenizer)], [-1])
reply_start = len(flow.tokens) if chat_context else 0
eos = model.generation_config.eos_token_id
eos_ids = set(eos if isinstance(eos, (list, tuple)) else [eos]) if eos is not None else set()
eos_ids.update([tokenizer.eos_token_id] if tokenizer.eos_token_id is not None else [])
limit = min(context_limit, int(getattr(model.config, "max_position_embeddings", context_limit)))
cache = None
consumed = 0
emitted = 0
with torch.inference_mode():
while True:
settings = live_settings() if live_settings is not None else {}
if not settings.get("auto_continue", False) and emitted >= int(settings.get("count", count)):
break
next_limit = min(int(settings.get("memory", context_limit)),
int(getattr(model.config, "max_position_embeddings", context_limit)))
if next_limit != limit:
cache = None # Old cached activations must not leak forgotten context.
limit = next_limit
current_temperature = settings.get("temperature", temperature)
current_top_p = settings.get("top_p", top_p)
current_penalty = settings.get("penalty", penalty)
if flow.stop.is_set():
break
if len(flow.tokens) >= 16384:
break
all_ids = prefix + flow.tokens[reply_start:]
visible_indices = prefix_indices + list(range(reply_start, len(flow.tokens)))
query = visible_indices[-1]
window = all_ids[-limit:]
if cache is None or consumed >= limit:
cache = None
input_ids = torch.tensor([window], device=model.device)
consumed = len(window)
else:
input_ids = torch.tensor([[flow.tokens[-1]]], device=model.device)
consumed += 1
probe = None
if settings.get("attention", False):
from attention_view import LayerAttentionProbe
probe = LayerAttentionProbe(attention_modules or [], settings.get("attention_layer", -1),
settings.get("attention_head", -1))
with probe if probe is not None else nullcontext():
capture_representations = settings.get("capture_representations", False)
extra = {"output_hidden_states": True} if capture_representations else {}
result = model(input_ids=input_ids, past_key_values=cache, use_cache=True, **extra)
if capture_representations:
from representations import RepresentationState
if flow.representations is None:
flow.representations = RepresentationState()
if chat_context and emitted == 0:
window_indices = visible_indices[-len(window):]
for position, n in enumerate(window_indices):
if n is not None and n >= flow.message_tokens[-2][0]:
flow.representations.add(n, result.hidden_states, position)
elif query is not None:
flow.representations.add(query, result.hidden_states)
if probe is not None and query is not None and query >= 0:
row = probe.record(len(all_ids) - len(probe.row), query)
for link in row["links"]:
position = link["n"] + 1
link["n"] = visible_indices[position]
link["id"] = all_ids[position]
row["links"] = [link for link in row["links"] if link["n"] is not None]
flow.attention_history[query] = row
packed, keys = probe.layer_record(len(all_ids))
lookup = torch.tensor([-2, *(n if n is not None else -2 for n in visible_indices)])
packed[:, :, 0] = lookup[packed[:, :, 0].long() + 2]
if flow.layer_rows is None or flow.layer_rows.shape[1] != len(packed):
flow.layer_rows = torch.zeros((512, *packed.shape), dtype=torch.float32)
flow.layer_keys = torch.zeros((512, len(packed)), dtype=torch.int32)
flow.layer_queries = [-1] * 512
slot = query % 512
flow.layer_rows[slot].copy_(packed)
flow.layer_keys[slot].copy_(keys)
flow.layer_queries[slot] = query
flow.attention_history = {i: row for i, row in flow.attention_history.items() if i >= query - 511}
cache = result.past_key_values
probs, before_nucleus = distribution(result.logits[0, -1], window,
current_temperature, current_top_p, current_penalty,
english_prior, settings.get("english_bias", 0))
result = None # Release optional full hidden-state outputs before yielding session state.
chosen = int(torch.multinomial(probs, 1, generator=rng))
if chat_context:
flow.roles[len(flow.tokens)] = "assistant"
flow.tokens.append(chosen)
emitted += 1
flow.rng_state = rng.get_state()
flow.ended = chosen in eos_ids
flow.text = tokenizer.decode(flow.tokens[reply_start:], skip_special_tokens=True,
clean_up_tokenization_spaces=False)
values, ids = torch.topk(probs, min(8, len(probs)))
candidates = [(int(i), float(p)) for i, p in zip(ids, values) if p > 0]
if chosen not in [i for i, _ in candidates]:
candidates.append((chosen, float(probs[chosen])))
yield {
"text": flow.text,
"candidates": candidates, "chosen": chosen,
"chosen_probability": float(probs[chosen]),
"retained_mass": float(before_nucleus[probs > 0].sum()),
"other": max(0., 1. - sum(p for _, p in candidates)),
"context_trimmed": len(all_ids) > limit,
"context_limit": limit,
"temperature": current_temperature, "top_p": current_top_p,
"penalty": current_penalty,
"english_bias": settings.get("english_bias", 0),
}
if flow.ended:
break123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""Soft token priors from word frequencies, never a hidden text prompt."""
from functools import lru_cache
import math
import re
import unicodedata
import torch
from wordfreq import get_frequency_dict
WORDS = re.compile(r"[^\W\d_]+", re.UNICODE)
@lru_cache(maxsize=1)
def lexicon():
english = get_frequency_dict("en", wordlist="small")
others = {}
for lang in ("es", "fr", "de", "it", "pt", "nl", "pl", "tr"):
for word, frequency in get_frequency_dict(lang, wordlist="small").items():
others[word] = max(others.get(word, 0), frequency)
fragments = set()
for word in english:
if word.isascii() and word.isalpha():
for length in range(2, min(len(word), 10)):
fragments.add(word[:length])
fragments.add(word[-length:])
return english, others, fragments
@lru_cache(maxsize=150000)
def piece_score(piece):
# Incomplete byte tokens remain neutral, preserving UTF-8 continuations.
if "\ufffd" in piece:
return 0.0
words = WORDS.findall(unicodedata.normalize("NFC", piece).casefold())
if not words:
return 0.0
english, others, fragments = lexicon()
values = []
for word in words:
en, other = english.get(word, 0), others.get(word, 0)
if en >= 1e-5:
value = 0.5 + min(0.5, max(0, math.log((en + 1e-8) / (other + 1e-8)) * 0.2))
elif en:
value = max(-0.5, min(0.75, math.log((en + 1e-8) / (other + 1e-8)) * 0.35))
elif any("LATIN" not in unicodedata.name(char, "") for char in word if char.isalpha()):
value = -2.0
elif other:
value = -1.5
elif len(word) <= 2 or word in fragments:
value = 0.15
else:
value = -0.35
values.append(value)
return sum(values) / len(values)
def build_prior(tokenizer, vocab_size):
prior = torch.zeros(vocab_size, dtype=torch.float32)
special = set(tokenizer.all_special_ids)
limit = min(len(tokenizer), vocab_size)
for start in range(0, limit, 4096):
ids = list(range(start, min(limit, start + 4096)))
pieces = tokenizer.batch_decode([[i] for i in ids], skip_special_tokens=False,
clean_up_tokenization_spaces=False)
prior[start:start + len(ids)] = torch.tensor([
0.0 if i in special else piece_score(piece) for i, piece in zip(ids, pieces)])
return prior123456789"""ZeroGPU setup must precede model and CUDA imports."""
import spaces
import os
import multiprocessing
ZERO_GPU = os.environ.get("SPACES_ZERO_GPU", "").lower() in ("1", "true")
_MANAGER = multiprocessing.get_context("fork").Manager() if ZERO_GPU else None
def manager():
return _MANAGER123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""Hugging Face sign-in shared by the Gradio Spaces in this folder.
Canonical copy: shared-ui/hf_login.py. Edit it there, then run`python shared-ui/sync.py` to copy it into each project.
The button opens the OAuth route of the Space's canonical *.hf.space origin inthe same tab (target `_top`). The cookie-based round trip therefore happensoutside the huggingface.co iframe and then returns to the app. Gradio's ownOAuth state validation, callback, expiry checks and logout stay in use.Only basic profile identity is requested."""import jsonimport osimport re
import gradio as gr
HOST_PATTERN = re.compile(r"[a-z0-9][a-z0-9-]*\.hf\.space")
def canonical_space_origin(): """The Space's canonical https origin, or None when not running on Spaces.""" host = os.environ.get("SPACE_HOST", "").split(",", 1)[0].strip().lower() if not host: return None if not HOST_PATTERN.fullmatch(host): raise ValueError("Expected the canonical hf.space hostname for OAuth.") return "https://" + host
def login_redirect_js(default_value): # Outside Spaces (local runs) the page's own origin is used, which reaches # Gradio's local mocked sign-in. return """(buttonValue) => { const origin = ORIGIN || window.location.origin; const route = buttonValue === DEFAULT ? '/login/huggingface' : '/logout'; const url = new URL(route, origin); url.searchParams.set('_target_url', '/'); window.open(url.href, '_top'); }""".replace("ORIGIN", json.dumps(canonical_space_origin())).replace("DEFAULT", json.dumps(default_value))
class TopLevelLoginButton(gr.LoginButton): """Gradio's LoginButton, rendered as a normal button, signing in in the same tab."""
def get_block_name(self): return "button"
def get_block_class(self): return "button"
def activate(self): self.click(fn=None, inputs=[self], outputs=None, js=login_redirect_js(self.value)) self.attach_load_event(self._check_login_status, None)1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Keep Hugging Face OAuth outside embedded frames; retain Gradio's auth checks."""import jsonimport osimport reimport gradio as gr
def canonical_space_origin(): host=os.environ.get("SPACE_HOST","jejunepixels-let-it-flow.hf.space").split(",",1)[0].strip().lower() if not re.fullmatch(r"[a-z0-9][a-z0-9-]*\.hf\.space",host): raise ValueError("Expected the canonical hf.space hostname for OAuth.") return "https://"+host
def login_redirect_js(default_value): origin=json.dumps(canonical_space_origin()) default=json.dumps(default_value) return """(buttonValue) => { const origin = ORIGIN; const route = buttonValue === DEFAULT ? '/login/huggingface' : '/logout'; const url = new URL(route, origin); url.searchParams.set('_target_url', '/'); window.open(url.href, '_blank', 'noopener,noreferrer'); }""".replace("ORIGIN",origin).replace("DEFAULT",default)
from gradio.events import Dependency
class TopLevelLoginButton(gr.LoginButton): """Gradio's LoginButton, rendered as a normal button, signing in in the same tab."""
def get_block_name(self): return "button"
def get_block_class(self): return "button"
def activate(self): self.click(fn=None, inputs=[self], outputs=None, js=login_redirect_js(self.value)) self.attach_load_event(self._check_login_status, None) from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING from gradio.blocks import Block if TYPE_CHECKING: from gradio.components import Timer from gradio.components.base import Component123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""Public Hub model loading with pinned downloads and bounded resource use."""
from gpu_runtime import ZERO_GPU
import gc
import os
from pathlib import Path
import shutil
from urllib.parse import urlsplit
from huggingface_hub import HfApi, snapshot_download
from huggingface_hub.utils import validate_repo_id
import torch
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
CACHE = Path(__file__).parent / ".model-cache"
MODEL_LABELS = {
"HuggingFaceTB/SmolLM2-135M-Instruct": "SmolLM2 135M · quick CPU start",
"HuggingFaceTB/SmolLM2-360M-Instruct": "SmolLM2 360M",
"Qwen/Qwen2.5-0.5B-Instruct": "Qwen2.5 0.5B · multilingual",
"Qwen/Qwen3-0.6B": "Qwen3 0.6B · multilingual",
}
PRESETS = list(MODEL_LABELS)
def repository(value):
value = value.strip()
# Accept labels from older/cached dropdown UIs as well as canonical IDs.
value = {label: repo for repo, label in MODEL_LABELS.items()}.get(value, value)
if "://" in value:
url = urlsplit(value)
if url.scheme != "https" or url.netloc != "huggingface.co":
raise ValueError("Enter a Hugging Face model repository URL or owner/model.")
parts = url.path.strip("/").split("/")
if parts[0] in ("spaces", "datasets") or len(parts) != 2:
raise ValueError("Use the model's main repository URL, without a file path.")
value = "/".join(parts)
validate_repo_id(value)
return value
class ModelStore:
def __init__(self):
self.model = self.tokenizer = None
self.key = ""
self.projection = None
self.attention_modules = []
self.description = "No model loaded."
self.english_prior = None
def load(self, value):
repo = repository(value)
info = HfApi().model_info(repo, files_metadata=True, token=False)
if info.private or info.gated:
raise ValueError("This version supports public, ungated models.")
patterns = ["*.json", "*.safetensors", "*.model", "*.txt", "*.tiktoken"]
import fnmatch
files = [f for f in info.siblings if any(fnmatch.fnmatch(f.rfilename, p) for p in patterns)
and "/" not in f.rfilename]
if not any(f.rfilename.endswith(".safetensors") for f in files):
raise ValueError("Choose a model with safetensors weights. GGUF is not supported yet.")
size = sum(f.size or 0 for f in files)
if any(f.size is None for f in files):
raise ValueError("Cannot determine the model download size.")
max_bytes = float(os.environ.get("FLOW_MAX_DOWNLOAD_GB", "8" if ZERO_GPU else "2")) * 1024**3
if size > max_bytes:
raise ValueError(f"Download is {size / 1024**3:.2f} GB; the limit is {max_bytes / 1024**3:g} GB.")
CACHE.mkdir(exist_ok=True)
if shutil.disk_usage(CACHE).free < size + 1024**3:
raise ValueError("Insufficient disk space; leave at least 1 GB free after download.")
config = AutoConfig.from_pretrained(repo, revision=info.sha, token=False,
trust_remote_code=False, cache_dir=CACHE)
if getattr(config, "is_encoder_decoder", False):
raise ValueError("Choose a decoder-only text-generation model.")
# Release the previous model before allocating the next one.
self.model = self.tokenizer = None
self.projection = None
self.attention_modules = []
self.key = ""
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
path = snapshot_download(repo, revision=info.sha, token=False, cache_dir=CACHE,
allow_patterns=[f.rfilename for f in files])
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=False)
if not tokenizer.chat_template or not tokenizer.is_fast:
raise ValueError("Choose an instruction-tuned model with a chat template and fast tokenizer.")
compute_dtype = (torch.bfloat16 if str(config.model_type).startswith("gemma") else torch.float16) if ZERO_GPU else torch.float32
model = AutoModelForCausalLM.from_pretrained(path, config=config, use_safetensors=True,
trust_remote_code=False, torch_dtype=compute_dtype,
attn_implementation="eager")
model.eval()
from token_space import TokenProjection
self.projection = TokenProjection(model.get_input_embeddings().weight)
if ZERO_GPU or torch.cuda.is_available():
model = model.to(device="cuda", dtype=compute_dtype if ZERO_GPU else torch.float16)
self.projection.weights = model.get_input_embeddings().weight
self.model, self.tokenizer = model, tokenizer
from attention_view import attention_modules
self.attention_modules = attention_modules(model)
self.key = f"{repo}@{info.sha}"
device = "GPU" if torch.cuda.is_available() else "CPU"
self.description = (f"{repo} · {info.sha[:8]} · {device} · "
f"{size / 1024**2:.0f} MB download · "
f"{len(self.attention_modules)} attention layers · "
f"{getattr(config, 'num_attention_heads', '?')} heads")
return self.description12345678910111213141516171819202122"""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"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""Bounded, historical token trajectories in one shared, frozen PCA space."""
import torch
import torch.nn.functional as F
class RepresentationState:
capacity = 128
calibration_size = 8
def __init__(self):
self.pending = {}
self.basis = self.center = self.scale = self.coords = None
self.boundary = None
self.queries = [-2] * self.capacity
self.stages = 0
self.fitted_samples = 0
self.needs_full = False
self.dimension_axes = None
def add(self, query, hidden_states, position=-1):
if not hidden_states:
raise ValueError("This model did not expose layer hidden states.")
vectors = torch.stack([state[0, position].detach().float() for state in hidden_states])
vectors = F.normalize(vectors, dim=-1).cpu()
if not torch.isfinite(vectors).all():
raise ValueError("The model returned non-finite hidden states.")
self.stages = len(vectors)
if self.basis is None:
self.pending[query] = vectors
if sum(q >= 0 for q in self.pending) >= self.calibration_size:
self.finalize()
else:
self._record(query, vectors)
def finalize(self):
samples = [vectors for query, vectors in self.pending.items() if query >= 0]
if self.basis is not None or not samples:
return
sample = torch.cat(samples)
self.center = sample.mean(0)
centered = sample - self.center
dimensions = min(3, *centered.shape)
with torch.random.fork_rng(devices=[]):
torch.manual_seed(42)
_, _, 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_axes
self.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, {}
for query, vectors in pending.items():
self._record(query, vectors)
self.needs_full = True
def _record(self, query, vectors):
coords = (vectors - self.center) @ self.basis / self.scale * 2.4
if query == -1:
self.boundary = coords
else:
slot = query % self.capacity
self.coords[slot].copy_(coords)
self.queries[slot] = query
def snapshot(self, token_count, full=False):
ready = self.basis is not None
include_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:]
def point(query, coords):
return {"n": query, "layers": [[round(value,5) for value in row] for row in coords.tolist()]}
points = [point(q, self.coords[q % self.capacity]) for q in queries] if ready else []
if ready and self.boundary is not None:
points.append(point(-1, self.boundary))
self.needs_full = False
result={"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_axes
return result123456789gradio==5.49.1
transformers==4.57.3
torch==2.8.0
huggingface-hub==0.36.0
spaces>=0.51.3,<0.53
authlib==1.6.5
wordfreq==3.1.1123456789$ErrorActionPreference = 'Stop'Set-Location -LiteralPath $PSScriptRootif (-not (Test-Path -LiteralPath '.venv\Scripts\python.exe')) { python -m venv .venv if ($LASTEXITCODE -ne 0) { throw 'Could not create Python environment.' }}& .\.venv\Scripts\python.exe -m pip install --no-cache-dir -r requirements.txtif ($LASTEXITCODE -ne 0) { throw 'Could not install dependencies.' }& .\.venv\Scripts\python.exe app.py123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218.gradio-container { max-width: 1600px !important; margin: auto; }/* Start page, eyebrow, title, dock and round return button: see brand.css (shared-ui/). */#page textarea { font: 18px/1.65 Georgia, 'Times New Roman', serif !important; padding: 14px 20px !important; }.inspector { padding: 22px; border: 1px solid #82968b40; border-radius: 14px; min-height: 230px; }.inspector h3 { font: 26px/1.2 Georgia, serif; margin: 12px 0; }.inspector p, .inspector small { opacity: .75; line-height: 1.6; }.candidate { padding: 8px 10px; margin: 6px 0; border-radius: 8px; }.candidate.selected { background: #f4bf6726; outline: 1px solid #f4bf6780; }.candidate-label { display: flex; justify-content: space-between; gap: 12px; font-size: 12px; }.candidate-label code { white-space: pre-wrap; overflow-wrap: anywhere; }.candidate small { font-size: 10px; }.track { height: 5px; background: #82968b20; border-radius: 8px; margin: 7px 0 3px; overflow: hidden; }.track div { height: 100%; background: #f4bf67; border-radius: 8px; }
#flow-workspace { gap:10px; }#workspace-top textarea { font-size:11px; }#sampling-controls { gap:8px; }#space-scene { padding:0 !important; border:0 !important; }#token-universe { position:relative; height:clamp(340px,55vh,800px); overflow:hidden; border-radius:16px; background:#080f18; color:#bdd8dd; }#token-universe canvas { width:100%; height:100%; display:block; cursor:grab; touch-action:none; }#token-universe canvas:active { cursor:grabbing; }.space-top,.space-bottom { position:absolute; left:22px; right:22px; display:flex; justify-content:space-between; gap:16px; pointer-events:none; font:11px/1.5 system-ui,sans-serif; }.space-top { top:18px; letter-spacing:.12em; }.space-bottom { bottom:16px; opacity:.6; }.space-brand { color:#f4bf67; }.space-empty { position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:14px; pointer-events:none; font:clamp(20px,3vw,34px)/1.4 Georgia,serif; color:#b9d0d4; }.space-empty small { font:13px/1.5 system-ui,sans-serif; opacity:.65; }.space-transport { display:none !important; }@media(max-width:640px) { .space-bottom { font-size:9px;left:12px;right:12px; } .space-top { left:12px;right:12px;font-size:9px; } }.space-tools { position:absolute; top:48px; left:22px; right:22px; display:flex; align-items:center; gap:14px; flex-wrap:wrap; font:12px/1.4 system-ui,sans-serif; }.space-tools label { display:flex; align-items:center; gap:7px; color:#c2dadc; }.space-tools select,.space-tools button { border:1px solid #577f89; border-radius:7px; padding:6px 8px; background:#112530; color:#d6e9e9; cursor:pointer; font:inherit; }.space-detail { position:absolute; left:22px; bottom:44px; max-width:min(650px,85%); padding:8px 12px; border-radius:7px; background:#0a1726d9; color:#c4d8da; font:11px/1.5 system-ui,sans-serif; pointer-events:none; }@media(max-width:640px){ .space-tools{top:43px;left:12px;right:12px;gap:7px;font-size:10px;} .space-detail{left:12px;bottom:55px;font-size:10px;} .space-bottom{flex-wrap:wrap;} }/* Loaded experience: a viewport-sized canvas with text and controls above it. */.gradio-container { max-width:none !important; min-height:100dvh !important; }#flow-workspace { position:fixed !important; inset:0 !important; width:100vw !important; height:100dvh !important; margin:0 !important; padding:0 !important; gap:0 !important; overflow:hidden !important; background:#080f18; z-index:50; }#space-scene { position:absolute !important; inset:0 !important; width:100% !important; height:100% !important; z-index:0; }#token-universe { width:100%; height:100% !important; border-radius:0 !important; }#page { position:absolute !important; top:max(18px,env(safe-area-inset-top)); left:clamp(16px,4vw,72px); right:clamp(16px,4vw,72px); width:auto !important; z-index:2; padding:0 !important; border:1px solid #b4dad52b !important; border-radius:16px !important; background:#091622 !important; backdrop-filter:blur(10px); box-shadow:0 10px 40px #0003; }#page textarea { height:clamp(110px,22vh,240px) !important; min-height:110px !important; max-height:45vh !important; overflow-y:auto !important; resize:vertical !important; color:#e0eeeb !important; background:transparent !important; border:none !important; font:clamp(16px,1.5vw,21px)/1.7 Georgia,serif !important; padding:20px 24px !important; scrollbar-color:#668c8b #10232d; }#page > div { background:transparent !important; }#control-dock { position:absolute !important; bottom:max(16px,env(safe-area-inset-bottom)); left:50%; transform:translateX(-50%); width:min(940px,calc(100vw - 32px)) !important; max-height:65dvh; overflow-y:auto; z-index:4; padding:12px !important; gap:8px !important; }#stream-buttons { gap:10px !important; flex-wrap:nowrap !important; }#stream-buttons button { min-height:44px; min-width:0 !important; }#settings-drawer { border:0 !important; background:transparent !important; }#sampling-controls { flex-wrap:wrap; }#sampling-controls > div { min-width:180px !important; }.space-top { top:auto !important; bottom:8px; left:18px; right:18px; font-size:9px; opacity:.5; }.space-tools { top:auto !important; bottom:150px; left:24px; right:24px; justify-content:center; gap:10px; z-index:1; }.space-detail { bottom:203px; left:24px; max-width:min(720px,calc(100vw - 48px)); z-index:1; }.space-bottom { display:none !important; }@media(max-width:640px) { #page { left:12px;right:12px;top:12px; } #page textarea { height:20vh !important; font-size:16px !important; padding:12px 16px !important; } #control-dock { bottom:12px;width:calc(100vw - 24px) !important;padding:8px !important;max-height:60dvh; } .space-tools { bottom:145px;left:12px;right:12px;font-size:10px;gap:6px; } .space-detail { bottom:228px;left:12px;max-width:calc(100vw - 24px);font-size:10px; } }#token-universe { position:fixed !important; inset:0 !important; width:100vw !important; height:100dvh !important; }#stream-buttons { position:sticky; top:0; z-index:6; background:#eaf2eff2; }#page[data-token-inspection="true"] textarea { display:none !important; }.paused-token-reader { position:relative; height:clamp(110px,22vh,240px); max-height:45vh; overflow-y:auto; padding:14px 24px 20px; color:#e0eeeb; font:clamp(16px,1.5vw,21px)/1.7 Georgia,serif; scrollbar-color:#668c8b #10232d; }.token-reader-hint { position:sticky; top:-14px; padding:6px 0 10px; background:#0c1c27f5; color:#f4bf67; font:11px/1.4 system-ui,sans-serif; letter-spacing:.04em; z-index:1; }.paused-token-content { white-space:pre-wrap; overflow-wrap:anywhere; }.paused-token-reader button.text-token { all:unset; display:inline; white-space:pre-wrap; font:inherit; color:inherit; cursor:pointer; border-radius:4px; }.paused-token-reader button.text-token:hover { background:#ffffff20; box-shadow:0 0 0 1px #f4bf6766; }.paused-token-reader button.text-token.is-selected { background:#f4bf67; color:#17242b; box-shadow:0 0 0 2px #f4bf6755; }.paused-token-reader button.text-token:focus-visible { outline:2px solid #f4bf67; outline-offset:2px; }.token-piece-choices { margin-top:8px; color:#b4cdd2; font:12px/1.7 ui-monospace,monospace; }@media(max-width:640px){.paused-token-reader { height:20vh;padding:12px 16px;font-size:16px; }}.generation-proxy { display:none !important; }#generation-toggle { border:0 !important; padding:0 !important; background:transparent !important; flex:3 !important; min-width:0 !important; }
.generation-toggle-button { width:100%; min-height:44px; padding:10px 18px; border:0; border-radius:10px; background:#f4bf67; color:#17242b; font:600 16px/1.4 system-ui,sans-serif; cursor:pointer; box-shadow:0 2px 8px #173c381a; }.generation-toggle-button:hover { background:#e7aa45; }.generation-toggle-button:disabled { opacity:.65; cursor:wait; }.generation-toggle-button:focus-visible { outline:3px solid #f4bf67; outline-offset:2px; }
/* Model caption and compact reset remain outside the expandable dock. */#text-overlay { position:absolute !important; top:max(18px,env(safe-area-inset-top)); left:clamp(16px,4vw,72px); right:clamp(16px,4vw,72px); width:auto !important; gap:7px !important; z-index:2; }#model-name { padding:0 24px !important; border:0 !important; min-height:18px !important; background:transparent !important; color:#c5e2dd; text-align:left; font:600 13px/1.5 system-ui,sans-serif; overflow-wrap:anywhere; }#page { position:relative !important; top:auto !important; left:auto !important; right:auto !important; width:100% !important; }#flow-workspace { --brand-return-label:"Change model / sign in"; }#control-dock { width:min(940px,calc(100vw - 120px)) !important; }@media(max-width:640px) { #text-overlay { top:12px;left:12px;right:12px;gap:5px !important; } #model-name { font-size:12px;padding:0 16px !important; } #control-dock { left:12px;transform:none;width:calc(100vw - 72px) !important; } }
/* Override theme colours on rendered HTML children and the textbox's form shell. */#model-name, #model-name * { color:var(--brand-stage-caption) !important; opacity:1 !important; font:600 13px/1.5 var(--brand-sans) !important; }#text-overlay { --body-text-color:#d9f6ef; --body-text-color-subdued:#a8c9c5; --block-background-fill:transparent; --input-background-fill:#091622; }#text-overlay > .form { background:transparent !important; border:0 !important; border-radius:16px !important; box-shadow:none !important; overflow:hidden !important; }#page { overflow:hidden !important; background:#091622 !important; background-image:none !important; box-shadow:none !important; }#page > div, #page label, #page .input-container, #page .input-container:focus-within { background:transparent !important; background-image:none !important; border:0 !important; box-shadow:none !important; }#page textarea { background:transparent !important; background-image:none !important; border-radius:0 !important; box-shadow:none !important; resize:none !important; }
/* Amber links the title punctuation, primary actions, focus and selections. */.gradio-container { --primary-400:#f8d49a !important; --primary-500:#f4bf67 !important; --primary-600:#b77a20 !important; --color-accent:#f4bf67 !important; --color-accent-soft:#f4bf6726 !important; }.space-tools button:hover,.space-tools select:focus-visible { border-color:#f4bf67; }
/* A readable attention inspector, with raw weights rather than renormalized bars. */.space-detail { width:440px; max-width:calc(100vw - 48px); max-height:42dvh; overflow-y:auto; padding:18px 20px; border:1px solid #78949d45; border-radius:14px; background:#0a1726f5; color:#d5e3e6; font:14px/1.55 system-ui,sans-serif; pointer-events:auto; scrollbar-color:#687c88 #0a1726; }.attention-title { margin:0 0 6px; color:#f4bf67 !important; font:600 18px/1.35 system-ui,sans-serif; overflow-wrap:anywhere; }.attention-intro { margin:0 0 6px; color:#d5e3e6 !important; }.attention-meta { margin:0 0 14px; color:#9fb5bd !important; font-size:12px; }.attention-list { display:grid; gap:9px; }.attention-item { display:grid; grid-template-columns:minmax(80px,1fr) minmax(65px,1.15fr) 48px; gap:12px; align-items:center; }.attention-token { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; color:#e0ebed !important; font:13px/1.5 ui-monospace,monospace; }.attention-bar { height:7px; overflow:hidden; border-radius:4px; background:#ffffff15; }.attention-bar-fill { display:block; height:100%; background:#f4bf67; border-radius:4px; }.attention-percent { color:#f4bf67 !important; text-align:right; font-variant-numeric:tabular-nums; font-size:13px; }.attention-coverage { margin:14px 0 0; color:#a8bdc4 !important; font-size:12px; }.attention-help { margin-top:12px; border-top:1px solid #ffffff18; padding-top:10px; color:#b8cbd1 !important; font-size:12px; }.attention-help summary { cursor:pointer; color:#f4bf67; }.attention-help p { margin:9px 0 0; color:#b8cbd1 !important; }@media(max-width:640px) { .space-detail { bottom:228px; width:calc(100vw - 24px); max-width:calc(100vw - 24px); max-height:30dvh; padding:14px; font-size:13px; box-sizing:border-box; } .attention-title { font-size:16px; } .attention-item { grid-template-columns:minmax(65px,1fr) minmax(50px,1fr) 43px; gap:8px; } }
.layer-controls { display:flex; flex-wrap:wrap; gap:10px; margin:12px 0; }.layer-controls label { display:flex; flex-direction:column; gap:4px; color:#bacdd4; font:12px/1.4 system-ui,sans-serif; }.layer-controls select { padding:6px 8px; border:1px solid #6b8796; border-radius:6px; background:#112530; color:#e0ebed; font:inherit; }.layer-filter { flex:1 1 100%; }.layer-filter input { width:100%; accent-color:#f4bf67; }.layer-caption { margin:10px 0; color:#a8bdc4 !important; font:12px/1.5 system-ui,sans-serif; }.layer-legend { display:flex; flex-wrap:wrap; gap:6px; margin-bottom:15px; }.layer-chip,.layer-restore { padding:4px 8px; border:1px solid; border-radius:6px; background:#ffffff08; font:600 12px/1.5 system-ui,sans-serif; cursor:pointer; }.layer-chip[aria-pressed="false"] { opacity:.35; text-decoration:line-through; }.layer-chip:focus-visible,.layer-restore:focus-visible { outline:2px solid #f4bf67; outline-offset:2px; }.layer-restore { border-color:#78949d; color:#d5e3e6; }.attention-layer + .attention-layer { margin-top:16px; padding-top:12px; border-top:1px solid #ffffff18; }.attention-layer > .attention-meta { border-left:3px solid; padding-left:8px; }.space-edge-tooltip { position:fixed; z-index:9; max-width:260px; padding:8px 10px; border:1px solid #78949d66; border-radius:7px; background:#07121ff5; color:#e2edf0; font:12px/1.5 system-ui,sans-serif; pointer-events:none; }.space-edge-tooltip[hidden] { display:none !important; }
.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. */.layer-caption,.layer-caption span { color:#a8bdc4 !important; }.layer-restore { color:#d5e3e6 !important; }.space-tools [data-space-step],.space-empty small { color:#b8cbd1 !important; }.space-top .space-count { color:#8aa4ad !important; }.space-top .space-brand { color:#f4bf67 !important; }
/* Keep native popup options and explanatory text readable on the dark canvas. */#token-universe select,#token-universe select option { color:#f4f7f8 !important; background-color:#112530 !important; color-scheme:dark; opacity:1 !important; }.space-tools label,.layer-controls label,.layer-controls label > span,.layer-caption,.layer-caption span,.attention-intro,.attention-meta,.attention-coverage,.attention-help p { color:#eef3f5 !important; }.connection-explanation,.connection-note,.connection-selected,.connection-token { color:#eef3f5 !important; }.connection-explanation { margin:8px 0 12px; font:14px/1.6 system-ui,sans-serif; }.connection-note { margin:10px 0; font:13px/1.6 system-ui,sans-serif; }.connection-selected { margin:16px 0 10px; font:600 13px/1.5 system-ui,sans-serif; overflow-wrap:anywhere; }.connection-matches { display:grid; gap:9px; margin:12px 0; }.connection-match { display:flex; justify-content:space-between; align-items:baseline; gap:12px; }.connection-token { min-width:0; overflow-wrap:anywhere; font:13px/1.5 ui-monospace,monospace; }.connection-score { color:#f4bf67 !important; flex-shrink:0; font:12px/1.5 ui-monospace,monospace; }
.representation-controls[hidden] { display:none !important; }.representation-controls { border-bottom:1px solid #ffffff26; padding-bottom:15px; margin-bottom:15px; }.representation-note,.representation-stage,.representation-layer-label,.representation-actions label { color:#eef3f5 !important; font:13px/1.55 system-ui,sans-serif; }.representation-note { margin:8px 0 12px; }.representation-layer-label { display:flex; flex-direction:column; gap:8px; }.representation-layer-label input { width:100%; accent-color:#f4bf67; color-scheme:dark; }.representation-stage { font-weight:600; color:#f4bf67 !important; margin:8px 0 12px; }.representation-actions { display:flex; align-items:center; flex-wrap:wrap; gap:12px; }.representation-actions button { border:1px solid #f4bf67; border-radius:7px; padding:6px 10px; background:#f4bf67; color:#17242b !important; font:600 13px/1.5 system-ui,sans-serif; cursor:pointer; }.representation-actions button:disabled { opacity:.5; cursor:default; }.representation-actions label { display:flex; align-items:center; gap:7px; }.representation-actions input { accent-color:#f4bf67; }
.connection-detail { color:#eef3f5 !important; }
.representation-connection-details > summary { display:none; }@media(max-width:640px) { #token-universe[data-position-mode="representations"] .space-detail { max-height:210px; } #token-universe[data-position-mode="representations"] .representation-controls { margin-bottom:8px;padding-bottom:8px; } #token-universe[data-position-mode="representations"] .representation-controls > .attention-title { display:none; } #token-universe[data-position-mode="representations"] .representation-note { font-size:11px;line-height:1.35;margin:0 0 6px;max-height:32px;overflow:auto; } #token-universe[data-position-mode="representations"] .representation-layer-label { font-size:0;line-height:0;gap:0; } #token-universe[data-position-mode="representations"] .representation-stage { font-size:12px;margin:4px 0 8px; } #token-universe[data-position-mode="representations"] .representation-actions { gap:8px; } #token-universe[data-position-mode="representations"] .representation-actions button { font-size:12px;padding:4px 8px; } #token-universe[data-position-mode="representations"] .representation-actions label { font-size:11px; } #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 { position:absolute; right:24px; bottom:203px; z-index:1; width:360px; max-width:calc(50vw - 36px); max-height:42dvh; overflow-y:auto; box-sizing:border-box; padding:18px 20px; border:1px solid #78949d45; border-radius:14px; background:#0a1726f5; color:#eef3f5; scrollbar-color:#687c88 #0a1726; }@media(min-width:641px) { .space-detail { box-sizing:border-box; max-width:calc(50vw - 36px); } }.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[type="checkbox"] { appearance:none !important; -webkit-appearance:none !important; display:inline-block !important; position:relative; flex:0 0 22px; width:22px !important; height:22px !important; margin:0 5px 0 0 !important; padding:0 !important; border:2px solid #eef3f5 !important; border-radius:4px; background:#112530 !important; cursor:pointer; }.dimension-axes-top input[type="checkbox"]:checked { border-color:#f4bf67 !important; background:#f4bf67 !important; }.dimension-axes-top input[type="checkbox"]:checked::after { content:""; position:absolute; left:6px; top:2px; width:6px; height:11px; border:solid #091622; border-width:0 3px 3px 0; transform:rotate(45deg); }.dimension-axes-top input[type="checkbox"]:focus-visible { outline:2px solid #f4bf67 !important; outline-offset:4px; }.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 { right:12px; top:calc(20dvh + 100px); bottom:auto; width:calc(100vw - 24px); max-width:360px; max-height:22dvh; padding:12px 14px; } .dimension-axes-top label { font-size:11px; } .dimension-axes-top button { font-size:11px; } }
.chat-legend { display:inline-flex; gap:10px; white-space:nowrap; }.chat-user { color:#f4bf67 !important; }.chat-assistant { color:#83dfd2 !important; }#chat-prompt { min-width:0 !important; }#chat-prompt textarea { min-height:44px; }#chat-actions { gap:8px !important; flex-wrap:nowrap !important; }#chat-actions button { min-width:0 !important; }.space-tools { bottom:175px; }.space-detail,.dimension-axes-controls { bottom:228px; }@media(max-width:640px) { .space-tools { bottom:168px; } .space-detail { bottom:253px; } .dimension-axes-controls { bottom:auto; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643() => {
if (window.__letItFlowSpace) window.__letItFlowSpace();
let root,canvas,ctx,resize,observer,timer,stream=null,seen=-1,payload='',disposed=false;
let history=[],hits=[],selected=null,yaw=.35,pitch=-.15,zoom=1,target=[0,0,0],panX=0,panY=0;
let dragging=false,panning=false,moved=false,lastX=0,lastY=0,width=0,height=0;
let lastTime=Date.now(),mode='live',connections='attention';
const lifetime=6000;
let lastText='';
let 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;
let textView=null,externalSelected=null,reader=null,readerSignature='',lastHighlighted=null;
let running=false,awaitingGPU=false,ended=false,togglePending=false,toggleButton=null;
function generationClick(){
if(togglePending||(running&&paused))return;
const pausing=(running||awaitingGPU)&&!paused;
const host=document.querySelector(pausing?'#generation-pause':ended?'#generation-new':'#generation-run');
const proxy=host?.querySelector?.('button')||host;
if(typeof proxy?.click!=='function')return;
togglePending=true;toggleButton.textContent=pausing?'Pausing...':'Starting...';toggleButton.disabled=true;
proxy.click();
}
function mountGenerationControl(){
const button=document.querySelector('[data-generation-toggle]');
if(!button||typeof button.addEventListener!=='function')return;
if(button!==toggleButton){
toggleButton?.removeEventListener?.('click',generationClick);toggleButton=button;
toggleButton.addEventListener('click',generationClick);
}
const label=togglePending?toggleButton.textContent:(running||awaitingGPU)?(paused?'Pausing...':'Pause'):paused&&!ended?'Resume':seen>=0&&!ended?'Resume':'Start';
if(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;
const stage=Math.max(0,Math.min(layers.length-1,representationStage)),a=Math.floor(stage),b=Math.min(a+1,layers.length-1),t=stage-a;
return layers[a].map((value,i)=>value*(1-t)+layers[b][i]*t);
}
function representationControls(){
if(root?.dataset)root.dataset.positionMode=positionMode;
const extra=root?.querySelector('.representation-connection-details');
if(extra?.dataset){
const key=`${positionMode}:${window.innerWidth<=640}`;
if(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);
representationStage=Math.min(representationStage,maximum);slider.max=maximum;slider.value=Math.round(representationStage);
slider.disabled=!ready||!paused;play.disabled=!ready||!paused;
play.textContent=representationPlaying?'Pause layers':'Play layers';
const stage=Math.round(representationStage),between=Math.abs(representationStage-stage)>.04;
caption.textContent=stage===0?'Input to first layer':`After layer ${stage-1}${stage===maximum?' + final normalisation':''}`;
if(between)caption.textContent+=' / interpolating';
slider.setAttribute('aria-valuetext',caption.textContent);
let message=!representationMeta?'Enable Capture layer representations in Settings, then generate a new stream.':
!ready?`Collecting token states: ${representationMeta.calibrating} / ${representationMeta.calibration_target}. Pause after a few tokens to fit the shared projection.`:
`${[...representationPoints.keys()].filter(n=>n>=0).length} token trajectories / ${maximum} layers / one fixed projection.`;
if(ready&&selected!=null&&!representationPoints.has(selected))message+=' This token has no saved trajectory: it may be outside the 128-token history, or the latest token has not been processed yet.';
if(ended&&!ready)message='The stream ended before a generated token could be processed. Start a new stream to capture trajectories.';
if(!paused)message+=' Pause generation to scrub or play layers.';
note.textContent=message;
}
function setPositionView(value){
representationPlaying=false;
if(value==='representations'){
positionMode='representations';mode='history';representationStage=0;connections='attention';legendFocus=null;
const links=root?.querySelector('[data-space-links]');if(links)links.value='attention';
target=[0,0,0];panX=panY=0;zoom=window.innerWidth<=640?.8:1;
if(selected==null||!representationPoints.has(selected))selected=Math.max(-1,...[...representationPoints.keys()].filter(n=>n>=0));
if(selected<0)selected=history.at(-1)?.n??null;
if(!paused){
const proxy=document.querySelector('#generation-pause');(proxy?.querySelector?.('button')||proxy)?.click();
}
}else{positionMode='embeddings';mode=value;target=[0,0,0];panX=panY=0;zoom=1;}
representationControls();details();
}
function sourcePoint(){
const pinned=history.find(p=>p.n===selected)||externalSelected;
if(paused)return pinned;
if(pinned?.attention&&(mode==='history'||Date.now()-Math.max(pinned.born,pinned.attentionBorn??0)<lifetime))return pinned;
return [...history].reverse().find(p=>p.attention&&(mode==='history'||Date.now()-Math.max(p.born,p.attentionBorn??0)<lifetime));
}
function chooseToken(index,focus=true){
if(!paused)return;
const point=history.find(p=>p.n===index)||textView?.points.find(p=>p.n===index);
if(!point)return;
selected=index;externalSelected=history.some(p=>p.n===index)?null:point;connections='attention';
const input=root.querySelector('[data-space-links]');if(input)input.value=connections;
const shown=displayedPosition(point);
if(focus&&shown){target=[...shown];panX=panY=0;zoom=Math.min(3,Math.max(1,zoom));}
details();syncTextSelection();
}
function stepToken(direction){
const items=(textView?.points||history).filter(p=>positionMode!=='representations'||representationPoints.has(p.n));
if(!paused||!items.length)return;
let index=items.findIndex(p=>p.n===selected);
if(index<0){const next=direction>0?items.find(p=>p.n>selected):[...items].reverse().find(p=>p.n<selected);if(next)chooseToken(next.n);return;}
index=Math.max(0,Math.min(items.length-1,index+direction));
chooseToken(items[index].n);
}
function syncTextSelection(){
if(!reader||lastHighlighted===selected)return;
lastHighlighted=selected;let first=null;
for(const button of reader.querySelectorAll('[data-flow-indices]')){
const on=button.dataset.flowIndices.split(',').map(Number).includes(selected);
button.classList.toggle('is-selected',on);
button.setAttribute('aria-pressed',String(on));
if(on&&!first)first=button;
}
first?.scrollIntoView({block:'nearest',inline:'nearest'});
}
function inspectText(){
const host=document.querySelector('#page');if(!host)return;
if(!paused||!textView){
host.querySelector('[data-token-reader]')?.remove();host.removeAttribute('data-token-inspection');
reader=null;readerSignature='';lastHighlighted=null;return;
}
const signature=`${stream}:${textView.points.length}:${textView.segments.length}`;
if(readerSignature===signature&&host.querySelector('[data-token-reader]')===reader){syncTextSelection();return;}
host.querySelector('[data-token-reader]')?.remove();
reader=document.createElement('div');reader.setAttribute('data-token-reader','');reader.className='paused-token-reader';
const hint=document.createElement('div');hint.className='token-reader-hint';hint.textContent='PAUSED / Click a token to locate it and inspect its attention.';
const content=document.createElement('div');content.className='paused-token-content';
const choices=document.createElement('div');choices.className='token-piece-choices';
function button(indices,label){
const node=document.createElement('button');node.type='button';node.textContent=label;
node.dataset.flowIndices=indices.join(',');node.className='text-token';
const role=textView.points[indices[0]]?.role;
if(role)node.classList.add(`chat-${role}`);
node.title=indices.map(n=>{const p=textView.points[n];return `Token #${n+1} / ID ${p.id}`;}).join(' / ');
node.addEventListener('click',()=>{
if(!paused||!textView)return;
chooseToken(indices.at(-1));choices.replaceChildren();
if(indices.length>1){
const label=document.createElement('span');label.textContent='This text shares multiple tokens: ';choices.appendChild(label);
for(const n of indices){const point=textView.points[n];choices.appendChild(button([n],`#${n+1} ${JSON.stringify(point.label)} `));}
}
lastHighlighted=null;syncTextSelection();
});return node;
}
if(textView.segments.length){
for(const segment of textView.segments){
content.appendChild(segment.indices.length?button(segment.indices,segment.text):document.createTextNode(segment.text));
}
}else{
const prose=document.createElement('div');prose.textContent=textView.text;content.appendChild(prose);
hint.textContent='PAUSED / Select a token piece below to inspect it in 3D.';
for(const point of textView.points)content.appendChild(button([point.n],JSON.stringify(point.label)+' '));
}
reader.appendChild(hint);reader.appendChild(content);reader.appendChild(choices);host.appendChild(reader);
host.setAttribute('data-token-inspection','true');readerSignature=signature;lastHighlighted=null;syncTextSelection();
}
function resetCamera(){yaw=.35;pitch=-.15;zoom=1;target=[0,0,0];panX=panY=0;}
function pick(e){
const rect=canvas.getBoundingClientRect(),x=e.clientX-rect.left,y=e.clientY-rect.top;
return hits.filter(p=>Math.hypot(p.x-x,p.y-y)<22).sort((a,b)=>Math.hypot(a.x-x,a.y-y)-Math.hypot(b.x-x,b.y-y))[0];
}
function layerRGB(index){
const t=layerCount>1?index/(layerCount-1):1;
const stops=[[113,183,255],[183,155,232],[244,191,103]];
const a=t<.5?stops[0]:stops[1],b=t<.5?stops[1]:stops[2],u=t<.5?t*2:(t-.5)*2;
return a.map((value,i)=>Math.round(value+(b[i]-value)*u)).join(',');
}
function contextPoint(n){return layerTargets.get(n)||textView?.points[n]||history.find(p=>p.n===n);}
function attentionRows(point,includeHidden=false){
if(!point)return [];
const saved=layerRows.get(point.n);
let rows=[];
if(saved&&(layerMode!=='selected'||positionMode==='representations')){
const count=saved.indices.length;
const chosen=positionMode==='representations'?(Math.round(representationStage)>0?[Math.min(count-1,Math.round(representationStage)-1)]:[]):layerMode==='all'?Array.from({length:count},(_,i)=>i):[...new Set([0,Math.floor((count-1)/2),count-1])];
rows=chosen.map(layer=>({query:point.n,layer,head:-1,keys:saved.keys[layer],
links:saved.indices[layer].map((n,i)=>({n,score:saved.scores[layer][i],...contextPoint(n)})).filter(link=>link.n>=-1&&link.score>0)}));
}else if(point.attention&&positionMode!=='representations')rows=[point.attention];
return rows.filter(row=>positionMode==='representations'||includeHidden||!hiddenLayers.has(row.layer)).map(row=>{
const links=row.links.filter(link=>link.score>=minimumWeight).slice(0,layerLimit);
return {...row,links,shown_mass:links.reduce((sum,link)=>sum+link.score,0)};
});
}
function 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`;
}
function details(){
const box=root?.querySelector('.connection-detail');if(!box)return;
const point=history.find(p=>p.n===selected)||externalSelected||(connections==='attention'?sourcePoint():null);
if(positionMode==='representations'&&connections==='attention'&&Math.round(representationStage)===0){
delete box.dataset.attentionSignature;delete box.dataset.connectionSignature;
box.textContent='Input stage: no attention layer has been applied yet. Advance the slider to inspect layers. Attention appears if it was captured; only targets with recorded representations can be drawn.';
return;
}
if(connections!=='attention'){
const signature=JSON.stringify([connections,point?.n,point?.label,point?.links,positionMode]);
if(box.dataset.connectionSignature===signature)return;
delete box.dataset.attentionSignature;box.dataset.connectionSignature=signature;
box.replaceChildren();
function add(parent,tag,className,text){
const node=document.createElement(tag);node.className=className;
if(text!=null)node.textContent=text;parent.appendChild(node);return node;
}
const titles={order:'Generation order',similarity:'Embedding similarity',none:'Tokens only'};
add(box,'h3','attention-title',titles[connections]||'Connections');
if(connections==='order'){
add(box,'p','connection-explanation','Teal lines connect consecutive tokens in the order they were generated. Follow them to trace the stream through the 3D space.');
add(box,'p','connection-note','These lines show sequence, not attention, similarity, or how strongly one token influenced another.');
if(point){
add(box,'p','connection-selected',`Selected: #${point.n+1} ${JSON.stringify(point.label)} / token ID ${point.id}`);
const previous=contextPoint(point.n-1);
add(box,'p','connection-note',point.n===0?'This is the first generated token.':`Previous token: #${point.n}${previous?' '+JSON.stringify(previous.label):''}. A line appears when both tokens are visible.`);
}else add(box,'p','connection-note','Click a token to see its place in the sequence. Faded tokens can leave gaps; use History or pause to inspect earlier tokens.');
}else if(connections==='similarity'){
add(box,'p','connection-explanation','Amber lines connect each token to up to three earlier tokens with the most similar learned input embeddings.');
add(box,'p','connection-note',positionMode==='representations'?'These links still compare input embeddings, even though node positions now show layer representations.':'The matches are calculated from the original embedding vectors, not the distances you see in 3D.');
if(point){
add(box,'p','connection-selected',`Selected: #${point.n+1} ${JSON.stringify(point.label)} / token ID ${point.id}`);
const matches=(point.links||[]).map(link=>({...link,other:contextPoint(link.n)}));
if(matches.length){
add(box,'p','connection-note','Closest saved earlier matches:');
const list=add(box,'div','connection-matches');
for(const link of matches){
const item=add(list,'div','connection-match');
add(item,'span','connection-token',`${link.other?JSON.stringify(link.other.label):'Token'} (#${link.n+1})`);
add(item,'span','connection-score',`cosine ${link.score.toFixed(3)}`);
}
}else add(box,'p','connection-note','No saved similarity matches for this token in the retained history.');
}else add(box,'p','connection-note','Click a token to see its closest saved matches and their similarity scores.');
const help=add(box,'details','attention-help');
add(help,'summary','','How to read similarity');
add(help,'p','','Cosine similarity compares the direction of embedding vectors. Higher scores mean more aligned vectors; only positive matches are drawn. The score is not a probability or an attention weight. We compare distinct token IDs within the preceding 512 tokens. Compressing embeddings to three dimensions can distort apparent distances.');
}else{
add(box,'p','connection-explanation',positionMode==='representations'?'No connection lines are drawn. Nodes show their captured hidden states at the chosen layer, using one shared projection.':'No connection lines are drawn. Token positions still come from the fixed 3D projection of their input embeddings.');
add(box,'p','connection-note','Use this view to explore the token cloud without lines. Changing connection modes only changes the visualisation; it does not change how text is generated.');
if(point)add(box,'p','connection-selected',`Selected: #${point.n+1} ${JSON.stringify(point.label)} / token ID ${point.id}`);
}
return;
}
delete box.dataset.connectionSignature;
let content='Attention weights show which context tokens each layer attended to while predicting the following token. Generate text, then pause and click a token to compare saved layers.';
if(point){
const neighbours=(point.links||[]).map(link=>{
const other=history.find(p=>p.n===link.n);
return other?`${JSON.stringify(other.label)} (#${other.n+1}, cosine ${link.score.toFixed(3)})`:null;
}).filter(Boolean);
content=`Token #${point.n+1} ${JSON.stringify(point.label)} | ID ${point.id}. Earlier neighbours: ${neighbours.join('; ')||'none with positive cosine similarity in the retained window'}.`;
}
if(point && connections==='attention'){
const available=attentionRows(point,true),rows=attentionRows(point);
if(available.length){
const signature=JSON.stringify([point.n,point.label,available,layerMode,layerLimit,minimumWeight,[...hiddenLayers],positionMode,Math.round(representationStage)]);
if(box.dataset.attentionSignature===signature)return;
const explanationOpen=Boolean(box.querySelector('details')?.open),scroll=box.scrollTop||0;
box.dataset.attentionSignature=signature;
function add(parent,tag,className,text){
const node=document.createElement(tag);node.className=className;
if(text!=null)node.textContent=text;parent.appendChild(node);return node;
}
let headingHost=box.querySelector('.attention-header');
if(!headingHost){
box.replaceChildren();
headingHost=add(box,'div','attention-header');
add(box,'div','layer-ui');
add(box,'div','attention-body');
}
const ui=box.querySelector('.layer-ui'),body=box.querySelector('.attention-body');
headingHost.replaceChildren();body.replaceChildren();
add(headingHost,'h3','attention-title',`Attention from #${point.n+1} ${JSON.stringify(point.label)}`);
add(headingHost,'p','attention-intro','What this token attended to while predicting the next token.');
ui.hidden=!layerRows.has(point.n)||positionMode==='representations';
const controlKey=JSON.stringify([layerMode,layerLimit,available.map(row=>row.layer),[...hiddenLayers]]);
if(!ui.hidden&&ui.dataset.controlKey!==controlKey){
const settingsOpen=ui.querySelector('.layer-settings')?.open??(window.innerWidth>640);
ui.replaceChildren();ui.dataset.controlKey=controlKey;
const settings=add(ui,'details','layer-settings');settings.open=settingsOpen;
add(settings,'summary','','Layers & filtering');
const controls=add(settings,'div','layer-controls');
function select(label,choices,value,change){
const field=add(controls,'label','',label),input=add(field,'select','');
for(const [key,text] of choices){const option=add(input,'option','',text);option.value=key;}
input.value=value;input.addEventListener('change',event=>{change(event.target.value);legendFocus=null;details();});
}
select('Layers',[['three','Early / middle / final'],['all','All layers'],['selected','Selected layer / head']],layerMode,value=>{layerMode=value;hiddenLayers.clear();});
select('Links per layer',[1,2,3,5,8].map(n=>[String(n),String(n)]),String(layerLimit),value=>layerLimit=Number(value));
const filter=add(controls,'label','layer-filter','Minimum weight '),readout=add(filter,'span','',`${Math.round(minimumWeight*100)}%`);
const slider=add(filter,'input','');slider.type='range';slider.min=0;slider.max=30;slider.step=1;slider.value=minimumWeight*100;
slider.setAttribute('aria-label','Minimum attention weight');
slider.addEventListener('input',event=>{minimumWeight=Number(event.target.value)/100;readout.textContent=`${Math.round(minimumWeight*100)}%`;});
slider.addEventListener('change',()=>details());
const caption=add(ui,'p','layer-caption');
add(caption,'span','layer-caption-desktop','Colour = layer. Thickness = weight. Click a colour to hide it; Shift-click to isolate it. Hover a colour to highlight it.');
add(caption,'span','layer-caption-mobile','Tap a layer colour to hide/show it.');
const legend=add(ui,'div','layer-legend');
for(const row of available){
const button=add(legend,'button','layer-chip',`L${row.layer}`);button.type='button';
button.style.color=`rgb(${layerRGB(row.layer)})`;button.style.borderColor=`rgb(${layerRGB(row.layer)})`;
button.setAttribute('aria-pressed',String(!hiddenLayers.has(row.layer)));button.title=`Layer ${row.layer}: click to hide/show; Shift-click to isolate`;
button.addEventListener('mouseenter',()=>legendFocus=row.layer);button.addEventListener('mouseleave',()=>legendFocus=null);
button.addEventListener('click',event=>{
if(event.shiftKey){hiddenLayers=new Set(available.filter(other=>other.layer!==row.layer).map(other=>other.layer));}
else if(hiddenLayers.has(row.layer))hiddenLayers.delete(row.layer);else hiddenLayers.add(row.layer);
legendFocus=null;details();
});
}
if(hiddenLayers.size){const restore=add(legend,'button','layer-restore','Restore layers');restore.type='button';restore.addEventListener('click',()=>{hiddenLayers.clear();details();});}
}
if(!rows.length)add(body,'p','attention-meta','All layers are hidden. Restore a layer using the legend.');
for(const row of rows){
const group=add(body,'section','attention-layer');
const heading=add(group,'p','attention-meta',`layer ${row.layer} / ${row.head===-1?'average across attention heads':'head '+row.head}`);
heading.style.borderLeftColor=`rgb(${layerRGB(row.layer)})`;
const list=add(group,'div','attention-list');
for(const link of row.links){
const other=contextPoint(link.n);
const label=link.n===-1?'Start boundary':JSON.stringify(other?.label??link.label??('#'+(link.n+1)));
const item=add(list,'div','attention-item');
const token=add(item,'span','attention-token',label);token.title=link.n===-1?'The special token used to start this stream.':`Token #${link.n+1}`;
const track=add(item,'span','attention-bar');track.setAttribute('aria-hidden','true');
const fill=add(track,'span','attention-bar-fill');fill.style.width=`${Math.max(0,Math.min(100,100*link.score))}%`;fill.style.background=`rgb(${layerRGB(row.layer)})`;
add(item,'span','attention-percent',`${(100*link.score).toFixed(1)}%`);
}
if(!row.links.length)add(group,'p','attention-meta','No saved links meet this minimum weight.');
add(group,'p','attention-coverage',`${row.links.length} strongest connections shown: ${(100*row.shown_mass).toFixed(1)}% of total attention. Others: ${(100*Math.max(0,1-row.shown_mass)).toFixed(1)}%.`);
}
let explanation=box.querySelector('.attention-help');
if(!explanation){
explanation=add(box,'details','attention-help');explanation.open=explanationOpen;
add(explanation,'summary','','How to read this');
add(explanation,'p','','Longer bars mean more attention to that context token, not a higher chance of generating it. Coloured curves compare layers using the same token positions. Multi-layer views average across heads. Start boundary begins the stream. Only the eight strongest links per layer are saved; filters can show fewer. Layer and head indices start at 0. Attention is not a complete explanation of the decision.');
}
box.scrollTop=scroll;
return;
}else content=externalSelected?'This token is outside the retained 512-token attention history. Its embedding is shown; no saved attention row is available.':'No attention captured for this token yet. Enable Capture attention and generate more tokens.';
}
delete box.dataset.attentionSignature;
if(box.textContent!==content)box.textContent=content;
}
function mount(){
const next=document.querySelector('#token-universe'),nextCanvas=next?.querySelector('canvas');
if(!nextCanvas||(next===root&&nextCanvas===canvas))return;
root=next;canvas=nextCanvas;ctx=canvas.getContext('2d');
if(resize)resize.disconnect();
resize=new ResizeObserver(()=>{
const r=canvas.getBoundingClientRect();width=r.width;height=r.height;
const narrow=window.innerWidth<=640;
if(narrow!==lastNarrow){const settings=root.querySelector('.layer-settings');if(settings)settings.open=!narrow;lastNarrow=narrow;}
const dpr=Math.min(window.devicePixelRatio||1,2);
canvas.width=Math.round(width*dpr);canvas.height=Math.round(height*dpr);ctx.setTransform(dpr,0,0,dpr,0,0);
});resize.observe(canvas);
canvas.addEventListener('pointerdown',e=>{
dragging=true;panning=e.shiftKey||e.button===2;moved=false;lastX=e.clientX;lastY=e.clientY;canvas.setPointerCapture(e.pointerId);
});
canvas.addEventListener('pointermove',e=>{
if(!dragging){
const rect=canvas.getBoundingClientRect(),x=e.clientX-rect.left,y=e.clientY-rect.top;
hoverEdge=null;let nearest=7;
for(const edge of edgeHits)for(let i=1;i<edge.path.length;i++){
const a=edge.path[i-1],b=edge.path[i],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<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();});
canvas.addEventListener('dblclick',e=>{
const p=pick(e);if(p){target=[...p.xyz];selected=p.n;panX=panY=0;zoom=Math.max(zoom,3);details();}else resetCamera();
});
canvas.addEventListener('wheel',e=>{e.preventDefault();zoom=Math.max(.15,Math.min(40,zoom*Math.exp(-e.deltaY*.0015)));},{passive:false});
const modeInput=root.querySelector('[data-space-mode]');
if(modeInput){modeInput.value=positionMode==='representations'?'representations':mode;modeInput.addEventListener('change',e=>setPositionView(e.target.value));}
const linksInput=root.querySelector('[data-space-links]');
if(linksInput){linksInput.value=connections;linksInput.addEventListener('change',e=>{connections=e.target.value;details();});}
root.querySelector('[data-representation-layer]')?.addEventListener('input',event=>{
representationPlaying=false;representationStage=Number(event.target.value);representationControls();details();
});
root.querySelector('[data-representation-play]')?.addEventListener('click',()=>{
if(!paused||!representationMeta?.ready)return;
if(representationStage>=representationMeta.stages-1)representationStage=0;
representationPlaying=!representationPlaying;if(!representationPlaying)representationStage=Math.round(representationStage);representationControls();details();
});
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));
details();
}
function receive(){
mount();const node=document.querySelector('[data-flow-frame]');if(!node)return;
const raw=node.getAttribute('data-flow-frame');if(raw===payload)return;
payload=raw;let data;try{data=JSON.parse(raw);}catch{return;}
running=Boolean(data.running);awaitingGPU=Boolean(data.continue_automatically)&&!data.running&&!data.paused&&!data.ended;ended=Boolean(data.ended);togglePending=false;
if(data.continue_automatically&&!data.running&&!data.paused&&!data.ended){
const expectedStream=data.stream,expectedRevision=data.revision;
setTimeout(()=>{
if(stream===expectedStream && JSON.parse(payload).revision===expectedRevision && !running && !paused){
const host=document.querySelector('#generation-auto');
const button=host?.tagName?.toLowerCase()==='button'?host:host?.querySelector('button')||host;
button?.click();
}
},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;}
if(!Array.isArray(p.xyz)||!p.xyz.every(Number.isFinite))continue;
// Recovered old history must not reappear as freshly generated live points.
history.push({...p,born:p.n<=seen?now-lifetime:now,attentionBorn:p.attention?now:0});seen=Math.max(seen,p.n);
}
if(data.text_view)textView=data.text_view;
if(data.attention_layers){
layerCount=data.attention_layers.count;
for(const row of data.attention_layers.rows)layerRows.set(row.query,row);
for(const target of data.attention_layers.targets)layerTargets.set(target.n,target);
const first=Math.max(0,seen-512);
for(const query of layerRows.keys())if(query<first)layerRows.delete(query);
for(const n of layerTargets.keys())if(n>=0&&n<seen-4096)layerTargets.delete(n);
}
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);
}
history.sort((a,b)=>a.n-b.n);history=history.slice(-512);
if(Boolean(data.paused)!==paused){
paused=Boolean(data.paused);
if(paused){previousMode=mode;mode='history';selected=[...history].reverse().find(p=>p.attention)?.n??history.at(-1)?.n??null;connections='attention';}
else{mode=previousMode;positionMode='embeddings';representationPlaying=false;selected=null;externalSelected=null;textView=null;}
const modeInput=root.querySelector('[data-space-mode]');if(modeInput)modeInput.value=positionMode==='representations'?'representations':mode;
const linksInput=root.querySelector('[data-space-links]');if(linksInput)linksInput.value=connections;
}
if(!paused&&mode==='live'&&selected!=null&&!history.some(p=>p.n===selected&&now-p.born<lifetime))selected=null;
representationControls();details();inspectText();
}
function project(v){
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;
const cp=Math.cos(pitch),sp=Math.sin(pitch),ry=y*cp-rz*sp,depth=y*sp+rz*cp,distance=7/zoom;
const denominator=distance+depth,scale=Math.min(width,height)*.91/Math.max(.08,denominator);
return{x:width/2+panX+rx*scale,y:height*(positionMode==='representations'&&width<=640?.4:.5)+panY+ry*scale,z:depth,scale:Math.min(3,7/Math.max(.08,denominator)),visible:denominator>.08};
}
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;
if(positionMode==='representations'){
if(representationPlaying&&paused&&representationMeta?.ready){
representationStage=Math.min(representationMeta.stages-1,representationStage+dt*.002);
if(representationStage>=representationMeta.stages-1)representationPlaying=false;
}
representationControls();
const stage=Math.round(representationStage);
if(stage!==lastRepresentationLayer){lastRepresentationLayer=stage;details();}
}
if(!paused&&!dragging&&mode==='live'&&!matchMedia('(prefers-reduced-motion: reduce)').matches)yaw+=dt*.000025;
ctx.clearRect(0,0,width,height);
const wash=ctx.createRadialGradient(width*.48,height*.48,0,width*.5,height*.5,width*.6);
wash.addColorStop(0,'#142b34');wash.addColorStop(1,'#080f18');ctx.fillStyle=wash;ctx.fillRect(0,0,width,height);
ctx.lineWidth=1;ctx.strokeStyle='#6b9caa19';
for(let i=-4;i<=4;i++)for(const pair of [[[-4,2.8,i],[4,2.8,i]],[[i,2.8,-4],[i,2.8,4]]]){
const 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));
if(paused&&externalSelected)active.push({...externalSelected,born:now});
const activeIndices=new Set(active.map(p=>p.n));
const visibleRows=attentionRows(source);
if(source){
for(const link of visibleRows.flatMap(row=>row.links)){
if(activeIndices.has(link.n))continue;
const old=history.find(p=>p.n===link.n);
if(old||Array.isArray(link.xyz)){active.push({...old,n:link.n,id:link.id??old?.id,label:link.label??old?.label??'[context]',role:link.role??old?.role,xyz:link.xyz??old.xyz,born:now,ghost:true});activeIndices.add(link.n);}
}
}
if(positionMode==='representations')active=active.map(p=>({...p,xyz:displayedPosition(p)})).filter(p=>p.xyz);
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);
const byIndex=new Map(rendered.map(p=>[p.n,p]));
function line(a,b,score){
if(!a||!b)return;const highlight=selected===a.n||selected===b.n;
ctx.strokeStyle=score==null?`rgba(109,207,196,${Math.min(a.alpha,b.alpha)*(highlight?.9:.25)})`:`rgba(244,191,103,${Math.min(a.alpha,b.alpha)*(highlight?1:.12+.4*Math.max(0,score))})`;
ctx.lineWidth=highlight?2:1;ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();
}
if(connections==='order')for(const p of rendered)line(byIndex.get(p.n-1),p,null);
if(connections==='similarity')for(const p of rendered)for(const link of p.links||[])line(p,byIndex.get(link.n),link.score);
edgeHits=[];
if(connections==='attention'){
const start=source?byIndex.get(source.n):null;
if(start)for(const row of visibleRows)for(const link of row.links){
const end=byIndex.get(link.n);if(!end)continue;
const focused=legendFocus==null||legendFocus===row.layer;
const offset=layerCount>1?(row.layer/(layerCount-1)-.5)*70:0;
const dx=end.x-start.x,dy=end.y-start.y,length=Math.hypot(dx,dy)||1;
const control={x:(start.x+end.x)/2-dy/length*offset,y:(start.y+end.y)/2+dx/length*offset};
ctx.strokeStyle=`rgba(${layerRGB(row.layer)},${Math.min(start.alpha,end.alpha)*(.25+.75*link.score)*(focused?1:.08)})`;
ctx.lineWidth=1+8*link.score;ctx.beginPath();ctx.moveTo(start.x,start.y);
const path=[];
if(start.n===end.n){
const radius=14+(layerCount>1?row.layer/(layerCount-1)*24:0);
ctx.arc(start.x,start.y,radius,0,Math.PI*2);
for(let i=0;i<=24;i++){const a=i/24*Math.PI*2;path.push({x:start.x+Math.cos(a)*radius,y:start.y+Math.sin(a)*radius});}
}else{
ctx.quadraticCurveTo(control.x,control.y,end.x,end.y);
for(let i=0;i<=12;i++){const t=i/12,u=1-t;path.push({x:u*u*start.x+2*u*t*control.x+t*t*end.x,y:u*u*start.y+2*u*t*control.y+t*t*end.y});}
}
ctx.stroke();edgeHits.push({layer:row.layer,n:link.n,score:link.score,path});
if(start.n!==end.n){
const angle=Math.atan2(end.y-control.y,end.x-control.x),size=6+5*link.score;
ctx.beginPath();ctx.moveTo(end.x,end.y);ctx.lineTo(end.x-size*Math.cos(angle-.4),end.y-size*Math.sin(angle-.4));
ctx.moveTo(end.x,end.y);ctx.lineTo(end.x-size*Math.cos(angle+.4),end.y-size*Math.sin(angle+.4));ctx.stroke();
}
}
}
if(positionMode==='representations'&&representationTrail&&selected!=null){
const trajectory=representationPoints.get(selected);
if(trajectory){
ctx.setLineDash([4,4]);ctx.lineWidth=1.8;
for(let stage=1;stage<trajectory.length;stage++){
const a=project(trajectory[stage-1]),b=project(trajectory[stage]);if(!a.visible||!b.visible)continue;
ctx.strokeStyle=`rgba(${layerRGB(Math.max(0,stage-1))},.85)`;
ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();
ctx.fillStyle=`rgb(${layerRGB(Math.max(0,stage-1))})`;ctx.beginPath();ctx.arc(b.x,b.y,2,0,Math.PI*2);ctx.fill();
}
ctx.setLineDash([]);
}
}
rendered.sort((a,b)=>b.z-a.z);hits=rendered;
for(const p of rendered){
const highlight=p.n===selected,newest=p.n===seen;ctx.globalAlpha=highlight?1:p.alpha;
const roleColor=p.role==='user'?'#f4bf67':p.role==='assistant'?'#83dfd2':null;
ctx.fillStyle=roleColor||(p.ghost?'#bba2eb':highlight?'#f4bf67':newest?'#faf0bd':'#83dfd2');ctx.shadowColor=ctx.fillStyle;ctx.shadowBlur=newest||highlight?18:8;
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;
ctx.font=`${newest||highlight?600:400} ${Math.max(11,Math.min(19,14*p.scale))}px ui-monospace,monospace`;
let label=p.label.replace(/\n/g,'↵').replace(/\t/g,'⇥').replace(/ /g,'·');
if(!label)label=`[${p.id}]`;if(label.length>32)label=label.slice(0,31)+'…';
if(p.ghost||mode==='live'||highlight||newest||rendered.length<100)ctx.fillText(label,p.x+9,p.y-8-(p.n%3)*5);
}
ctx.globalAlpha=1;ctx.lineWidth=1;
const counter=root.querySelector('.space-count'),empty=root.querySelector('.space-empty');
const count=`${active.length} visible · ${seen+1} chat tokens · zoom ${zoom.toFixed(1)}×`;
if(counter&&counter.textContent!==count)counter.textContent=count;
if(empty){const display=seen<0?'flex':'none';if(empty.style.display!==display)empty.style.display=display;}
const back=root.querySelector('[data-space-back]'),forward=root.querySelector('[data-space-forward]'),step=root.querySelector('[data-space-step]');
const items=(textView?.points||history).filter(p=>positionMode!=='representations'||representationPoints.has(p.n));
if(back)back.disabled=!paused||selected==null||selected<=items[0]?.n;
if(forward)forward.disabled=!paused||selected==null||selected>=items.at(-1)?.n;
const stepText=paused?`Paused ? inspecting token #${selected==null?'?':selected+1}`:'Live';
if(step&&step.textContent!==stepText)step.textContent=stepText;
inspectText();syncTextSelection();
const text=document.querySelector('#page textarea');
if(text&&text.value!==lastText){
const following=lastText===''||text.scrollHeight-text.scrollTop-text.clientHeight<80;
if(following&&document.activeElement!==text)text.scrollTop=text.scrollHeight;
lastText=text.value;
}
}
observer=new MutationObserver(receive);
observer.observe(document.body,{subtree:true,childList:true,attributes:true,attributeFilter:['data-flow-frame']});
receive();tick();timer=setInterval(tick,33);
window.__letItFlowSpace=()=>{disposed=true;observer.disconnect();if(resize)resize.disconnect();clearInterval(timer);toggleButton?.removeEventListener?.('click',generationClick);};
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200"""A fixed three-dimensional PCA projection of input token embeddings."""
import html
import json
import torch
def text_snapshot(tokens, tokenizer, projection):
"""Map displayed text back to actual token occurrences, including byte fragments."""
from tokenizers.decoders import DecodeStream
text = tokenizer.decode(tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False)
points = [{"n": n, "id": token_id, "xyz": projection.point(token_id),
"label": tokenizer.decode([token_id], skip_special_tokens=False,
clean_up_tokenization_spaces=False)}
for n, token_id in enumerate(tokens)]
segments, pending, decoded = [], [], ""
try:
decoder = DecodeStream(skip_special_tokens=True)
special = set(tokenizer.all_special_ids)
for n, token_id in enumerate(tokens):
if token_id not in special:
pending.append(n)
chunk = decoder.step(tokenizer.backend_tokenizer, token_id)
if chunk:
segments.append({"text": chunk, "indices": pending})
pending = []
decoded += chunk
if text.startswith(decoded) and decoded != text:
segments.append({"text": text[len(decoded):], "indices": pending})
decoded = text
if decoded != text:
segments = []
except (AttributeError, TypeError, ValueError):
segments = []
return {"text": text, "segments": segments, "points": points}
class TokenProjection:
def __init__(self, weights):
weights = weights.detach().float().cpu()
self.weights = weights
indices = torch.linspace(0, len(weights) - 1, min(2048, len(weights))).long()
sample = weights[indices]
center = sample.mean(0)
sample = sample - center
dimensions = min(3, *sample.shape)
with torch.random.fork_rng(devices=[]):
torch.manual_seed(42)
_, _, basis = torch.pca_lowrank(sample, q=dimensions, center=False, niter=3)
coords = (weights - center) @ basis
scale = torch.linalg.vector_norm(sample @ basis, dim=1).quantile(.95).clamp_min(1e-6)
coords = coords / scale * 2.4
self.coords = torch.nn.functional.pad(coords, (0, 3 - dimensions)).tolist()
from projection_axes import projected_dimension_axes
padded_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]
def relatives(self, token_id, previous):
"""Closest distinct earlier tokens, scored in the original embedding space."""
latest = {other_id: index for index, other_id in previous if other_id != token_id}
if not latest:
return []
ids = list(latest)
scores = torch.nn.functional.cosine_similarity(self.weights[ids].float(), self.weights[token_id][None].float(), dim=1)
results = []
for position in torch.argsort(scores, descending=True)[:3].tolist():
score = float(scores[position])
if torch.isfinite(scores[position]) and score > 0:
results.append({"n": latest[ids[position]], "score": round(score, 5)})
return results
def frame(flow, store, full=False):
with flow.view_lock:
return _frame(flow, store, full)
def _frame(flow, store, full=False):
flow.view_revision += 1
tokens = flow.tokens.copy()
points = []
if store.projection is not None and flow.model_key == store.key:
first_new = flow.space_history[-1]["n"] + 1 if flow.space_history else 0
for index in range(first_new, len(tokens)):
token_id = tokens[index]
piece = store.tokenizer.decode([token_id], skip_special_tokens=False,
clean_up_tokenization_spaces=False)
previous = list(enumerate(tokens[max(0, index - 512):index], start=max(0, index - 512)))
links = store.projection.relatives(token_id, previous)
flow.space_history.append({"n": index, "id": token_id, "label": piece,
"xyz": store.projection.point(token_id), "links": links,
"role": flow.roles.get(index)})
flow.space_history = flow.space_history[-512:]
for point in flow.space_history:
row = flow.attention_history.get(point["n"])
if row is not None:
point["attention"] = row
for link in point["attention"]["links"]:
if "id" in link and "xyz" not in link:
link["xyz"] = store.projection.point(link["id"])
link["role"] = flow.roles.get(link["n"])
link["label"] = ("[boundary]" if link["n"] == -1 else
store.tokenizer.decode([link["id"]], skip_special_tokens=False,
clean_up_tokenization_spaces=False))
points = 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"]=axes
flow.sent_dimension_axes_key=store.key
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:
queries = queries[-1:]
rows, target_indices = [], set()
for query in queries:
slot = query % 512
packed = flow.layer_rows[slot]
indices = packed[:, :, 0].to(torch.int32).tolist()
rows.append({"query": query, "indices": indices,
"scores": packed[:, :, 1].tolist(), "keys": flow.layer_keys[slot].tolist()})
if not flow.paused:
target_indices.update(n for layer in indices for n in layer if -1 <= n < len(tokens))
from engine import start_id
targets = []
if flow.paused and not flow.messages:
target_indices.add(-1) # other targets are already in the full text snapshot
for n in sorted(target_indices):
token_id = start_id(store.model, store.tokenizer) if n == -1 else tokens[n]
targets.append({"n": n, "id": token_id, "xyz": store.projection.point(token_id),
"role": flow.roles.get(n),
"label": "[boundary]" if n == -1 else store.tokenizer.decode(
[token_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)})
data["attention_layers"] = {"count": flow.layer_rows.shape[1], "rows": rows, "targets": targets}
if flow.paused and store.projection is not None and flow.model_key == store.key:
if flow.text_snapshot_cache is None or flow.text_snapshot_cache[0] != len(tokens):
snapshot = text_snapshot(tokens, store.tokenizer, store.projection)
if flow.messages:
snapshot["segments"] = []
for message, indices in zip(flow.messages, flow.message_tokens):
snapshot["segments"].append({"text": "\n\n" + ("You" if message["role"] == "user" else "Model") + "\n", "indices": []})
first, last = indices
turn = text_snapshot(tokens[first:last], store.tokenizer, store.projection)
for segment in turn["segments"]:
snapshot["segments"].append({"text": segment["text"],
"indices": [first + n for n in segment["indices"]]})
if not turn["segments"]:
snapshot["segments"].extend(
{"text": snapshot["points"][n]["label"], "indices": [n]}
for n in range(first, last) if tokens[n] not in store.tokenizer.all_special_ids)
for point in snapshot["points"]:
point["role"] = flow.roles.get(point["n"])
flow.text_snapshot_cache = (len(tokens), snapshot)
data["text_view"] = flow.text_snapshot_cache[1]
if flow.representations is not None:
data["representations"] = flow.representations.snapshot(len(tokens), full=full or flow.paused)
payload = json.dumps(data, ensure_ascii=True)
return '<div data-flow-frame="' + html.escape(payload, quote=True) + '"></div>'
SCENE = '''<div id="token-universe">
<canvas aria-label="Live 3D projection of chat token embeddings. Drag to orbit; scroll to zoom."></canvas>
<div class="space-top"><span class="space-brand">CHAT VISUALISER / TOKEN SPACE</span><span class="space-count">Waiting for tokens</span></div>
<div class="space-empty">A space for the next thought.<small>Send a message. Tokens appear here, then fade.</small></div>
<div class="space-tools">
<span class="chat-legend"><span class="chat-user">● Prompt</span><span class="chat-assistant">● Reply</span></span>
<label>View <select data-space-mode><option value="live">Live · fade after 6s</option><option value="history">History · last 512 tokens</option><option value="representations">Layer representations</option></select></label>
<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>
<button type="button" data-space-reset>Reset camera</button>
<button type="button" data-space-back disabled>Step back</button>
<button type="button" data-space-forward disabled>Step forward</button>
<span data-space-step>Live</span>
</div>
<section class="dimension-axes-controls" aria-label="Projected dimension axes">
<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>
<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>
<label class="representation-layer-label">Layer <input type="range" data-representation-layer min="0" max="1" step="1" value="0" aria-label="Representation layer"></label>
<p class="representation-stage" data-representation-stage>Input to first layer</p>
<div class="representation-actions"><button type="button" data-representation-play>Play layers</button><label><input type="checkbox" data-representation-trail checked> Selected-token trail</label></div>
<details class="attention-help"><summary>How to read representations</summary><p>Each token shows its hidden states recorded when it was processed to predict the following token. These are historical token recordings, not one full-context snapshot. One shared PCA projection is fitted across the first captured tokens and all layers, then frozen for the stream. These axes differ from the input-embedding view. Only context tokens with saved trajectories can be plotted. Vectors are normalised to compare directions. The input stage may include positional processing; the final stage includes the model's final normalisation. Animation interpolates between recorded stages. Movement is not a direct measure of meaning or importance. Only the most recent 128 processed tokens are retained.</p></details>
</section>
<details class="representation-connection-details" open><summary>Connection details</summary><div class="connection-detail" aria-live="polite">Click a token to inspect its earlier neighbours.</div></details>
</div>
<div class="space-edge-tooltip" role="tooltip" hidden></div>
<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>
</div>'''.gitignoreAdded+6
README.md+17-6
app.pyAdded+313
attention_view.pyAdded+92
brand.cssAdded+293
brand_theme.pyAdded+61
engine.pyAdded+284
english_bias.pyAdded+63
gpu_runtime.pyAdded+9
hf_login.pyAdded+54
hf_login.pyiAdded+44
models.pyAdded+105
projection_axes.pyAdded+22
representations.pyAdded+82
requirements.txtAdded+9
start.ps1Added+9
style.cssAdded+218
token_space.jsAdded+643
token_space.pyAdded+200