Spaces:
Running on Zero
Running on Zero
Rename to Automatic Writing; navy start page and collection card
Browse files- README.md +10 -9
- app.py +6 -6
- brand.css +6 -36
- brand_theme.py +4 -19
- token_space.py +181 -181
README.md
CHANGED
|
@@ -1,17 +1,18 @@
|
|
| 1 |
---
|
| 2 |
-
title: Automatic
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 5.49.1
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
python_version: '3.12'
|
| 11 |
hf_oauth: true
|
|
|
|
| 12 |
---
|
| 13 |
|
| 14 |
-
# Automatic
|
| 15 |
|
| 16 |
A prompt-free automatic-writing experiment. Load a public Hugging Face base model,
|
| 17 |
press **Begin**, and watch it generate from a special beginning token alone. No
|
|
@@ -43,15 +44,15 @@ needed for the supported public, ungated models. Start with CPU Basic and a smal
|
|
| 43 |
model; hardware determines the practical model size. This project is prepared for
|
| 44 |
Spaces but does not create or publish a remote Space automatically.
|
| 45 |
|
| 46 |
-
Run `python scripts/prepare_space.py` to create `outputs/
|
| 47 |
Extract the archive and upload its sixteen files to the root of your Gradio Space.
|
| 48 |
`brand.css`, `brand_theme.py` and `hf_login.py` are shared with Automatic Drawing and
|
| 49 |
Token Visualiser, so the three Spaces keep the same start page, workspace and sign-in.
|
| 50 |
|
| 51 |
## Token space
|
| 52 |
|
| 53 |
-
The opening screen shows sign-in (on ZeroGPU) and model selection,
|
| 54 |
-
|
| 55 |
and reveals a viewport-filling 3D token view. The full generated text is retained in a
|
| 56 |
scrollable, resizable top overlay. A combined Start / Pause / Resume button sits in a
|
| 57 |
bottom overlay dock. Expand Settings, model & attention for the remaining controls.
|
|
@@ -289,4 +290,4 @@ The default translates these directions to the PCA mean. Original vector origin
|
|
| 289 |
|
| 290 |
## Sign-in and embedded browsers
|
| 291 |
|
| 292 |
-
The start page has the only sign-in button. It opens the canonical hf.space OAuth route in the same tab (`_top`), leaving the huggingface.co iframe, and returns to the direct app after login. This avoids doing the cookie-based OAuth round trip inside the huggingface.co iframe. Gradio's normal OAuth state validation, callback, expiry checks and logout remain in use. Query strings from the embedding page are not copied into the login URL. If a browser blocks all cookies, users still need to allow site cookies for sign-in to complete. The direct app URL is https://jejunepixels-
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Automatic Writing
|
| 3 |
+
emoji: ✍️
|
| 4 |
+
colorFrom: gray
|
| 5 |
+
colorTo: yellow
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 5.49.1
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
python_version: '3.12'
|
| 11 |
hf_oauth: true
|
| 12 |
+
short_description: Watch a language model write unprompted, token by token
|
| 13 |
---
|
| 14 |
|
| 15 |
+
# Automatic Writing
|
| 16 |
|
| 17 |
A prompt-free automatic-writing experiment. Load a public Hugging Face base model,
|
| 18 |
press **Begin**, and watch it generate from a special beginning token alone. No
|
|
|
|
| 44 |
model; hardware determines the practical model size. This project is prepared for
|
| 45 |
Spaces but does not create or publish a remote Space automatically.
|
| 46 |
|
| 47 |
+
Run `python scripts/prepare_space.py` to create `outputs/automatic-writing-space.zip`.
|
| 48 |
Extract the archive and upload its sixteen files to the root of your Gradio Space.
|
| 49 |
`brand.css`, `brand_theme.py` and `hf_login.py` are shared with Automatic Drawing and
|
| 50 |
Token Visualiser, so the three Spaces keep the same start page, workspace and sign-in.
|
| 51 |
|
| 52 |
## Token space
|
| 53 |
|
| 54 |
+
The opening screen shows sign-in (on ZeroGPU) and model selection, on the same
|
| 55 |
+
midnight background as the token space. Successful loading hides the picker
|
| 56 |
and reveals a viewport-filling 3D token view. The full generated text is retained in a
|
| 57 |
scrollable, resizable top overlay. A combined Start / Pause / Resume button sits in a
|
| 58 |
bottom overlay dock. Expand Settings, model & attention for the remaining controls.
|
|
|
|
| 290 |
|
| 291 |
## Sign-in and embedded browsers
|
| 292 |
|
| 293 |
+
The start page has the only sign-in button. It opens the canonical hf.space OAuth route in the same tab (`_top`), leaving the huggingface.co iframe, and returns to the direct app after login. This avoids doing the cookie-based OAuth round trip inside the huggingface.co iframe. Gradio's normal OAuth state validation, callback, expiry checks and logout remain in use. Query strings from the embedding page are not copied into the login URL. If a browser blocks all cookies, users still need to allow site cookies for sign-in to complete. The direct app URL is https://jejunepixels-automatic-writing.hf.space/.
|
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Automatic
|
| 2 |
from gpu_runtime import ZERO_GPU, spaces
|
| 3 |
import html
|
| 4 |
import secrets
|
|
@@ -223,8 +223,8 @@ def export(flow):
|
|
| 223 |
if not flow.tokens:
|
| 224 |
raise gr.Error("Generate some text first.")
|
| 225 |
import tempfile
|
| 226 |
-
directory = Path(tempfile.mkdtemp(prefix="
|
| 227 |
-
output = directory / "
|
| 228 |
output.write_text(flow.text, encoding="utf-8")
|
| 229 |
return str(output)
|
| 230 |
|
|
@@ -250,12 +250,12 @@ def build_app():
|
|
| 250 |
# Shared look (brand.css, from shared-ui/) first, then this app's layout.
|
| 251 |
css = "".join(Path(__file__).with_name(name).read_text(encoding="utf-8") for name in ("brand.css", "style.css"))
|
| 252 |
js = Path(__file__).with_name("token_space.js").read_text(encoding="utf-8")
|
| 253 |
-
with gr.Blocks(title="Automatic
|
| 254 |
delete_cache=(3600, 3600)) as demo:
|
| 255 |
flow = gr.State(Flow())
|
| 256 |
with gr.Column(elem_id="model-picker", elem_classes=["brand-start"]) as picker:
|
| 257 |
-
gr.HTML('<header class="brand-header"><div class="eyebrow">AN EXPERIMENT IN
|
| 258 |
-
'<h1 class="brand-title">Automatic
|
| 259 |
'<p class="brand-intro">Inspired by the Surrealists\u2019 practice of automatic writing, this experiment lets language unfold without a written prompt. '
|
| 260 |
'A language model uses recent tokens to predict what could come next, then selects the next token by sampling from those probabilities. '
|
| 261 |
'A 3D view tracks attention weights from a selected layer and maps tokens through their embeddings.</p>'
|
|
|
|
| 1 |
+
"""Automatic Writing — a prompt-free Hugging Face Space."""
|
| 2 |
from gpu_runtime import ZERO_GPU, spaces
|
| 3 |
import html
|
| 4 |
import secrets
|
|
|
|
| 223 |
if not flow.tokens:
|
| 224 |
raise gr.Error("Generate some text first.")
|
| 225 |
import tempfile
|
| 226 |
+
directory = Path(tempfile.mkdtemp(prefix="automatic-writing-"))
|
| 227 |
+
output = directory / "automatic-writing.txt"
|
| 228 |
output.write_text(flow.text, encoding="utf-8")
|
| 229 |
return str(output)
|
| 230 |
|
|
|
|
| 250 |
# Shared look (brand.css, from shared-ui/) first, then this app's layout.
|
| 251 |
css = "".join(Path(__file__).with_name(name).read_text(encoding="utf-8") for name in ("brand.css", "style.css"))
|
| 252 |
js = Path(__file__).with_name("token_space.js").read_text(encoding="utf-8")
|
| 253 |
+
with gr.Blocks(title="Automatic Writing", css=css, js=js, theme=brand_theme(),
|
| 254 |
delete_cache=(3600, 3600)) as demo:
|
| 255 |
flow = gr.State(Flow())
|
| 256 |
with gr.Column(elem_id="model-picker", elem_classes=["brand-start"]) as picker:
|
| 257 |
+
gr.HTML('<header class="brand-header"><div class="eyebrow">AN EXPERIMENT IN MACHINE WRITING</div>'
|
| 258 |
+
'<h1 class="brand-title">Automatic Writing<span class="title-stop">.</span></h1>'
|
| 259 |
'<p class="brand-intro">Inspired by the Surrealists\u2019 practice of automatic writing, this experiment lets language unfold without a written prompt. '
|
| 260 |
'A language model uses recent tokens to predict what could come next, then selects the next token by sampling from those probabilities. '
|
| 261 |
'A 3D view tracks attention weights from a selected layer and maps tokens through their embeddings.</p>'
|
brand.css
CHANGED
|
@@ -1,13 +1,14 @@
|
|
| 1 |
/* ==========================================================================
|
| 2 |
Shared look for the Hugging Face Spaces in this folder:
|
| 3 |
-
Automatic Drawing,
|
|
|
|
| 4 |
|
| 5 |
Canonical copy: shared-ui/brand.css. Edit it there, then run
|
| 6 |
`python shared-ui/sync.py` to copy it into each project.
|
| 7 |
|
| 8 |
-
- Start page
|
| 9 |
-
|
| 10 |
-
|
| 11 |
========================================================================== */
|
| 12 |
|
| 13 |
:root {
|
|
@@ -35,23 +36,7 @@
|
|
| 35 |
--brand-serif: Georgia, 'Times New Roman', serif;
|
| 36 |
--brand-sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
| 37 |
|
| 38 |
-
/* Start page,
|
| 39 |
-
--brand-page: #f4f8f6;
|
| 40 |
-
--brand-surface: #ffffff;
|
| 41 |
-
--brand-heading: #17242b;
|
| 42 |
-
--brand-text: #203c3a;
|
| 43 |
-
--brand-subdued: #526b68;
|
| 44 |
-
--brand-eyebrow: #92601c;
|
| 45 |
-
--brand-link: #92601c;
|
| 46 |
-
--brand-line: #b3c7bd;
|
| 47 |
-
--brand-input: #ffffff;
|
| 48 |
-
--brand-input-hover: #f4f8f6;
|
| 49 |
-
--brand-focus: #b77a20;
|
| 50 |
-
}
|
| 51 |
-
|
| 52 |
-
/* Start page, dark browser mode. Gradio puts .dark on an ancestor of the app and
|
| 53 |
-
honours ?__theme=. Streamlit follows the system setting, hence the media query. */
|
| 54 |
-
.dark {
|
| 55 |
--brand-page: #080f18;
|
| 56 |
--brand-surface: #091622;
|
| 57 |
--brand-heading: #eef3f5;
|
|
@@ -64,21 +49,6 @@
|
|
| 64 |
--brand-input-hover: #193442;
|
| 65 |
--brand-focus: #f4bf67;
|
| 66 |
}
|
| 67 |
-
@media (prefers-color-scheme: dark) {
|
| 68 |
-
.stApp {
|
| 69 |
-
--brand-page: #080f18;
|
| 70 |
-
--brand-surface: #091622;
|
| 71 |
-
--brand-heading: #eef3f5;
|
| 72 |
-
--brand-text: #d5e3e6;
|
| 73 |
-
--brand-subdued: #a8bdc4;
|
| 74 |
-
--brand-eyebrow: #f4bf67;
|
| 75 |
-
--brand-link: #f4bf67;
|
| 76 |
-
--brand-line: #577f89;
|
| 77 |
-
--brand-input: #112530;
|
| 78 |
-
--brand-input-hover: #193442;
|
| 79 |
-
--brand-focus: #f4bf67;
|
| 80 |
-
}
|
| 81 |
-
}
|
| 82 |
|
| 83 |
/* ---- Start page --------------------------------------------------------- */
|
| 84 |
/* Order: eyebrow, title, intro, sign-in + note, model, primary action, note. */
|
|
|
|
| 1 |
/* ==========================================================================
|
| 2 |
Shared look for the Hugging Face Spaces in this folder:
|
| 3 |
+
Automatic Drawing, Automatic Writing, Chat Visualiser, Token Visualiser
|
| 4 |
+
(the "Inside the Machine" collection).
|
| 5 |
|
| 6 |
Canonical copy: shared-ui/brand.css. Edit it there, then run
|
| 7 |
`python shared-ui/sync.py` to copy it into each project.
|
| 8 |
|
| 9 |
+
- Start page and workspace share the midnight stage colour, in both
|
| 10 |
+
light and dark browser modes.
|
| 11 |
+
- The workspace's pale mint control panel stays light in both modes.
|
| 12 |
========================================================================== */
|
| 13 |
|
| 14 |
:root {
|
|
|
|
| 36 |
--brand-serif: Georgia, 'Times New Roman', serif;
|
| 37 |
--brand-sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
| 38 |
|
| 39 |
+
/* Start page: the same midnight as the workspace stage, in both browser modes. */
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
--brand-page: #080f18;
|
| 41 |
--brand-surface: #091622;
|
| 42 |
--brand-heading: #eef3f5;
|
|
|
|
| 49 |
--brand-input-hover: #193442;
|
| 50 |
--brand-focus: #f4bf67;
|
| 51 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
/* ---- Start page --------------------------------------------------------- */
|
| 54 |
/* Order: eyebrow, title, intro, sign-in + note, model, primary action, note. */
|
brand_theme.py
CHANGED
|
@@ -3,27 +3,12 @@
|
|
| 3 |
Canonical copy: shared-ui/brand_theme.py. Edit it there, then run
|
| 4 |
`python shared-ui/sync.py` to copy it into each project.
|
| 5 |
|
| 6 |
-
The start page
|
| 7 |
-
|
| 8 |
-
(see brand.css)
|
| 9 |
"""
|
| 10 |
import gradio as gr
|
| 11 |
|
| 12 |
-
LIGHT = {
|
| 13 |
-
"body_background_fill": "#f4f8f6", "body_text_color": "#203c3a",
|
| 14 |
-
"body_text_color_subdued": "#526b68", "background_fill_primary": "#f4f8f6",
|
| 15 |
-
"background_fill_secondary": "#eaf2ef", "block_background_fill": "#ffffff",
|
| 16 |
-
"block_border_color": "#cfdcd6", "block_label_background_fill": "#ffffff",
|
| 17 |
-
"block_label_text_color": "#29433f", "block_title_background_fill": "transparent",
|
| 18 |
-
"block_title_text_color": "#203c3a", "block_info_text_color": "#526b68",
|
| 19 |
-
"panel_background_fill": "#eaf2ef", "input_background_fill": "#ffffff",
|
| 20 |
-
"input_background_fill_hover": "#f4f8f6", "input_background_fill_focus": "#ffffff",
|
| 21 |
-
"input_border_color": "#b3c7bd", "input_placeholder_color": "#6b827e",
|
| 22 |
-
"accordion_text_color": "#203c3a", "border_color_primary": "#b3c7bd",
|
| 23 |
-
"button_secondary_background_fill": "#eaf2ef", "button_secondary_background_fill_hover": "#dce9e1",
|
| 24 |
-
"button_secondary_text_color": "#203c3a", "button_secondary_text_color_hover": "#17242b",
|
| 25 |
-
"link_text_color": "#92601c", "link_text_color_hover": "#b77a20",
|
| 26 |
-
}
|
| 27 |
DARK = {
|
| 28 |
"body_background_fill": "#080f18", "body_text_color": "#eef3f5",
|
| 29 |
"body_text_color_subdued": "#a8bdc4", "background_fill_primary": "#091622",
|
|
@@ -56,6 +41,6 @@ BOTH_MODES = {"input_radius": "10px"}
|
|
| 56 |
|
| 57 |
|
| 58 |
def brand_theme():
|
| 59 |
-
values = {**
|
| 60 |
values.update({key + "_dark": value for key, value in {**DARK, **PRIMARY}.items()})
|
| 61 |
return gr.themes.Soft(primary_hue="amber", neutral_hue="stone", font=FONT).set(**values)
|
|
|
|
| 3 |
Canonical copy: shared-ui/brand_theme.py. Edit it there, then run
|
| 4 |
`python shared-ui/sync.py` to copy it into each project.
|
| 5 |
|
| 6 |
+
The start page uses the workspace's midnight palette in both browser modes, so
|
| 7 |
+
the plain keys and the `*_dark` keys hold the same values. The workspace's mint
|
| 8 |
+
panel sets its own colours (see brand.css).
|
| 9 |
"""
|
| 10 |
import gradio as gr
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
DARK = {
|
| 13 |
"body_background_fill": "#080f18", "body_text_color": "#eef3f5",
|
| 14 |
"body_text_color_subdued": "#a8bdc4", "background_fill_primary": "#091622",
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
def brand_theme():
|
| 44 |
+
values = {**DARK, **PRIMARY, **BOTH_MODES}
|
| 45 |
values.update({key + "_dark": value for key, value in {**DARK, **PRIMARY}.items()})
|
| 46 |
return gr.themes.Soft(primary_hue="amber", neutral_hue="stone", font=FONT).set(**values)
|
token_space.py
CHANGED
|
@@ -1,181 +1,181 @@
|
|
| 1 |
-
"""A fixed three-dimensional PCA projection of input token embeddings."""
|
| 2 |
-
import html
|
| 3 |
-
import json
|
| 4 |
-
|
| 5 |
-
import torch
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
def text_snapshot(tokens, tokenizer, projection):
|
| 9 |
-
"""Map displayed text back to actual token occurrences, including byte fragments."""
|
| 10 |
-
from tokenizers.decoders import DecodeStream
|
| 11 |
-
text = tokenizer.decode(tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 12 |
-
points = [{"n": n, "id": token_id, "xyz": projection.point(token_id),
|
| 13 |
-
"label": tokenizer.decode([token_id], skip_special_tokens=False,
|
| 14 |
-
clean_up_tokenization_spaces=False)}
|
| 15 |
-
for n, token_id in enumerate(tokens)]
|
| 16 |
-
segments, pending, decoded = [], [], ""
|
| 17 |
-
try:
|
| 18 |
-
decoder = DecodeStream(skip_special_tokens=True)
|
| 19 |
-
special = set(tokenizer.all_special_ids)
|
| 20 |
-
for n, token_id in enumerate(tokens):
|
| 21 |
-
if token_id not in special:
|
| 22 |
-
pending.append(n)
|
| 23 |
-
chunk = decoder.step(tokenizer.backend_tokenizer, token_id)
|
| 24 |
-
if chunk:
|
| 25 |
-
segments.append({"text": chunk, "indices": pending})
|
| 26 |
-
pending = []
|
| 27 |
-
decoded += chunk
|
| 28 |
-
if text.startswith(decoded) and decoded != text:
|
| 29 |
-
segments.append({"text": text[len(decoded):], "indices": pending})
|
| 30 |
-
decoded = text
|
| 31 |
-
if decoded != text:
|
| 32 |
-
segments = []
|
| 33 |
-
except (AttributeError, TypeError, ValueError):
|
| 34 |
-
segments = []
|
| 35 |
-
return {"text": text, "segments": segments, "points": points}
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
class TokenProjection:
|
| 39 |
-
def __init__(self, weights):
|
| 40 |
-
weights = weights.detach().float().cpu()
|
| 41 |
-
self.weights = weights
|
| 42 |
-
indices = torch.linspace(0, len(weights) - 1, min(2048, len(weights))).long()
|
| 43 |
-
sample = weights[indices]
|
| 44 |
-
center = sample.mean(0)
|
| 45 |
-
sample = sample - center
|
| 46 |
-
dimensions = min(3, *sample.shape)
|
| 47 |
-
with torch.random.fork_rng(devices=[]):
|
| 48 |
-
torch.manual_seed(42)
|
| 49 |
-
_, _, basis = torch.pca_lowrank(sample, q=dimensions, center=False, niter=3)
|
| 50 |
-
coords = (weights - center) @ basis
|
| 51 |
-
scale = torch.linalg.vector_norm(sample @ basis, dim=1).quantile(.95).clamp_min(1e-6)
|
| 52 |
-
coords = coords / scale * 2.4
|
| 53 |
-
self.coords = torch.nn.functional.pad(coords, (0, 3 - dimensions)).tolist()
|
| 54 |
-
from projection_axes import projected_dimension_axes
|
| 55 |
-
padded_basis=torch.nn.functional.pad(basis,(0,3-dimensions))
|
| 56 |
-
self.dimension_axes=projected_dimension_axes(padded_basis,center,scale,"input_embeddings")
|
| 57 |
-
|
| 58 |
-
def point(self, token_id):
|
| 59 |
-
return self.coords[token_id]
|
| 60 |
-
|
| 61 |
-
def relatives(self, token_id, previous):
|
| 62 |
-
"""Closest distinct earlier tokens, scored in the original embedding space."""
|
| 63 |
-
latest = {other_id: index for index, other_id in previous if other_id != token_id}
|
| 64 |
-
if not latest:
|
| 65 |
-
return []
|
| 66 |
-
ids = list(latest)
|
| 67 |
-
scores = torch.nn.functional.cosine_similarity(self.weights[ids].float(), self.weights[token_id][None].float(), dim=1)
|
| 68 |
-
results = []
|
| 69 |
-
for position in torch.argsort(scores, descending=True)[:3].tolist():
|
| 70 |
-
score = float(scores[position])
|
| 71 |
-
if torch.isfinite(scores[position]) and score > 0:
|
| 72 |
-
results.append({"n": latest[ids[position]], "score": round(score, 5)})
|
| 73 |
-
return results
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
def frame(flow, store, full=False):
|
| 77 |
-
with flow.view_lock:
|
| 78 |
-
return _frame(flow, store, full)
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def _frame(flow, store, full=False):
|
| 82 |
-
flow.view_revision += 1
|
| 83 |
-
tokens = flow.tokens.copy()
|
| 84 |
-
points = []
|
| 85 |
-
if store.projection is not None and flow.model_key == store.key:
|
| 86 |
-
first_new = flow.space_history[-1]["n"] + 1 if flow.space_history else 0
|
| 87 |
-
for index in range(first_new, len(tokens)):
|
| 88 |
-
token_id = tokens[index]
|
| 89 |
-
piece = store.tokenizer.decode([token_id], skip_special_tokens=False,
|
| 90 |
-
clean_up_tokenization_spaces=False)
|
| 91 |
-
previous = list(enumerate(tokens[max(0, index - 512):index], start=max(0, index - 512)))
|
| 92 |
-
links = store.projection.relatives(token_id, previous)
|
| 93 |
-
flow.space_history.append({"n": index, "id": token_id, "label": piece,
|
| 94 |
-
"xyz": store.projection.point(token_id), "links": links})
|
| 95 |
-
flow.space_history = flow.space_history[-512:]
|
| 96 |
-
for point in flow.space_history:
|
| 97 |
-
row = flow.attention_history.get(point["n"])
|
| 98 |
-
if row is not None:
|
| 99 |
-
point["attention"] = row
|
| 100 |
-
for link in point["attention"]["links"]:
|
| 101 |
-
if "id" in link and "xyz" not in link:
|
| 102 |
-
link["xyz"] = store.projection.point(link["id"])
|
| 103 |
-
link["label"] = ("[boundary]" if link["n"] == -1 else
|
| 104 |
-
store.tokenizer.decode([link["id"]], skip_special_tokens=False,
|
| 105 |
-
clean_up_tokenization_spaces=False))
|
| 106 |
-
points = flow.space_history[-512 if full else -48:]
|
| 107 |
-
data = {"continue_automatically": flow.continue_automatically, "stream": flow.stream_id, "revision": flow.view_revision, "paused": flow.paused, "running": flow.running,
|
| 108 |
-
"ended": flow.ended, "points": points}
|
| 109 |
-
axes=getattr(store.projection,"dimension_axes",None)
|
| 110 |
-
if axes is not None and (full or flow.sent_dimension_axes_key != store.key):
|
| 111 |
-
data["dimension_axes"]=axes
|
| 112 |
-
flow.sent_dimension_axes_key=store.key
|
| 113 |
-
if flow.layer_rows is not None and store.projection is not None:
|
| 114 |
-
queries = sorted(q for q in flow.layer_queries if q >= max(0, len(tokens) - 513))
|
| 115 |
-
if not flow.paused:
|
| 116 |
-
queries = queries[-1:]
|
| 117 |
-
rows, target_indices = [], set()
|
| 118 |
-
for query in queries:
|
| 119 |
-
slot = query % 512
|
| 120 |
-
packed = flow.layer_rows[slot]
|
| 121 |
-
indices = packed[:, :, 0].to(torch.int32).tolist()
|
| 122 |
-
rows.append({"query": query, "indices": indices,
|
| 123 |
-
"scores": packed[:, :, 1].tolist(), "keys": flow.layer_keys[slot].tolist()})
|
| 124 |
-
if not flow.paused:
|
| 125 |
-
target_indices.update(n for layer in indices for n in layer if -1 <= n < len(tokens))
|
| 126 |
-
from engine import start_id
|
| 127 |
-
boundary = start_id(store.model, store.tokenizer)
|
| 128 |
-
targets = []
|
| 129 |
-
if flow.paused:
|
| 130 |
-
target_indices.add(-1) # other targets are already in the full text snapshot
|
| 131 |
-
for n in sorted(target_indices):
|
| 132 |
-
token_id = boundary if n == -1 else tokens[n]
|
| 133 |
-
targets.append({"n": n, "id": token_id, "xyz": store.projection.point(token_id),
|
| 134 |
-
"label": "[boundary]" if n == -1 else store.tokenizer.decode(
|
| 135 |
-
[token_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)})
|
| 136 |
-
data["attention_layers"] = {"count": flow.layer_rows.shape[1], "rows": rows, "targets": targets}
|
| 137 |
-
if flow.paused and store.projection is not None and flow.model_key == store.key:
|
| 138 |
-
if flow.text_snapshot_cache is None or flow.text_snapshot_cache[0] != len(tokens):
|
| 139 |
-
flow.text_snapshot_cache = (len(tokens), text_snapshot(tokens, store.tokenizer, store.projection))
|
| 140 |
-
data["text_view"] = flow.text_snapshot_cache[1]
|
| 141 |
-
if flow.representations is not None:
|
| 142 |
-
data["representations"] = flow.representations.snapshot(len(tokens), full=full or flow.paused)
|
| 143 |
-
payload = json.dumps(data, ensure_ascii=True)
|
| 144 |
-
return '<div data-flow-frame="' + html.escape(payload, quote=True) + '"></div>'
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
SCENE = '''<div id="token-universe">
|
| 148 |
-
<canvas aria-label="Live 3D projection of generated token embeddings. Drag to orbit; scroll to zoom."></canvas>
|
| 149 |
-
<div class="space-top"><span class="space-brand">AUTOMATIC
|
| 150 |
-
<div class="space-empty">A space for the next thought.<small>Press Begin. Tokens appear here, then fade.</small></div>
|
| 151 |
-
<div class="space-tools">
|
| 152 |
-
<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>
|
| 153 |
-
<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>
|
| 154 |
-
<button type="button" data-space-reset>Reset camera</button>
|
| 155 |
-
<button type="button" data-space-back disabled>Step back</button>
|
| 156 |
-
<button type="button" data-space-forward disabled>Step forward</button>
|
| 157 |
-
<span data-space-step>Live</span>
|
| 158 |
-
</div>
|
| 159 |
-
<section class="dimension-axes-controls" aria-label="Projected dimension axes">
|
| 160 |
-
<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>
|
| 161 |
-
<div class="dimension-axes-options" hidden>
|
| 162 |
-
<p class="dimension-axis-status" data-dimension-status></p>
|
| 163 |
-
<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>
|
| 164 |
-
<label>Origin <select data-dimension-origin><option value="mean">Projection centre</option><option value="raw">Original vector origin</option></select></label>
|
| 165 |
-
<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>
|
| 166 |
-
</div>
|
| 167 |
-
</section>
|
| 168 |
-
<div class="space-detail">
|
| 169 |
-
<section class="representation-controls" hidden>
|
| 170 |
-
<h3 class="attention-title">Representations through layers</h3>
|
| 171 |
-
<p class="representation-note" data-representation-note></p>
|
| 172 |
-
<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>
|
| 173 |
-
<p class="representation-stage" data-representation-stage>Input to first layer</p>
|
| 174 |
-
<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>
|
| 175 |
-
<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>
|
| 176 |
-
</section>
|
| 177 |
-
<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>
|
| 178 |
-
</div>
|
| 179 |
-
<div class="space-edge-tooltip" role="tooltip" hidden></div>
|
| 180 |
-
<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>
|
| 181 |
-
</div>'''
|
|
|
|
| 1 |
+
"""A fixed three-dimensional PCA projection of input token embeddings."""
|
| 2 |
+
import html
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def text_snapshot(tokens, tokenizer, projection):
|
| 9 |
+
"""Map displayed text back to actual token occurrences, including byte fragments."""
|
| 10 |
+
from tokenizers.decoders import DecodeStream
|
| 11 |
+
text = tokenizer.decode(tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 12 |
+
points = [{"n": n, "id": token_id, "xyz": projection.point(token_id),
|
| 13 |
+
"label": tokenizer.decode([token_id], skip_special_tokens=False,
|
| 14 |
+
clean_up_tokenization_spaces=False)}
|
| 15 |
+
for n, token_id in enumerate(tokens)]
|
| 16 |
+
segments, pending, decoded = [], [], ""
|
| 17 |
+
try:
|
| 18 |
+
decoder = DecodeStream(skip_special_tokens=True)
|
| 19 |
+
special = set(tokenizer.all_special_ids)
|
| 20 |
+
for n, token_id in enumerate(tokens):
|
| 21 |
+
if token_id not in special:
|
| 22 |
+
pending.append(n)
|
| 23 |
+
chunk = decoder.step(tokenizer.backend_tokenizer, token_id)
|
| 24 |
+
if chunk:
|
| 25 |
+
segments.append({"text": chunk, "indices": pending})
|
| 26 |
+
pending = []
|
| 27 |
+
decoded += chunk
|
| 28 |
+
if text.startswith(decoded) and decoded != text:
|
| 29 |
+
segments.append({"text": text[len(decoded):], "indices": pending})
|
| 30 |
+
decoded = text
|
| 31 |
+
if decoded != text:
|
| 32 |
+
segments = []
|
| 33 |
+
except (AttributeError, TypeError, ValueError):
|
| 34 |
+
segments = []
|
| 35 |
+
return {"text": text, "segments": segments, "points": points}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TokenProjection:
|
| 39 |
+
def __init__(self, weights):
|
| 40 |
+
weights = weights.detach().float().cpu()
|
| 41 |
+
self.weights = weights
|
| 42 |
+
indices = torch.linspace(0, len(weights) - 1, min(2048, len(weights))).long()
|
| 43 |
+
sample = weights[indices]
|
| 44 |
+
center = sample.mean(0)
|
| 45 |
+
sample = sample - center
|
| 46 |
+
dimensions = min(3, *sample.shape)
|
| 47 |
+
with torch.random.fork_rng(devices=[]):
|
| 48 |
+
torch.manual_seed(42)
|
| 49 |
+
_, _, basis = torch.pca_lowrank(sample, q=dimensions, center=False, niter=3)
|
| 50 |
+
coords = (weights - center) @ basis
|
| 51 |
+
scale = torch.linalg.vector_norm(sample @ basis, dim=1).quantile(.95).clamp_min(1e-6)
|
| 52 |
+
coords = coords / scale * 2.4
|
| 53 |
+
self.coords = torch.nn.functional.pad(coords, (0, 3 - dimensions)).tolist()
|
| 54 |
+
from projection_axes import projected_dimension_axes
|
| 55 |
+
padded_basis=torch.nn.functional.pad(basis,(0,3-dimensions))
|
| 56 |
+
self.dimension_axes=projected_dimension_axes(padded_basis,center,scale,"input_embeddings")
|
| 57 |
+
|
| 58 |
+
def point(self, token_id):
|
| 59 |
+
return self.coords[token_id]
|
| 60 |
+
|
| 61 |
+
def relatives(self, token_id, previous):
|
| 62 |
+
"""Closest distinct earlier tokens, scored in the original embedding space."""
|
| 63 |
+
latest = {other_id: index for index, other_id in previous if other_id != token_id}
|
| 64 |
+
if not latest:
|
| 65 |
+
return []
|
| 66 |
+
ids = list(latest)
|
| 67 |
+
scores = torch.nn.functional.cosine_similarity(self.weights[ids].float(), self.weights[token_id][None].float(), dim=1)
|
| 68 |
+
results = []
|
| 69 |
+
for position in torch.argsort(scores, descending=True)[:3].tolist():
|
| 70 |
+
score = float(scores[position])
|
| 71 |
+
if torch.isfinite(scores[position]) and score > 0:
|
| 72 |
+
results.append({"n": latest[ids[position]], "score": round(score, 5)})
|
| 73 |
+
return results
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def frame(flow, store, full=False):
|
| 77 |
+
with flow.view_lock:
|
| 78 |
+
return _frame(flow, store, full)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _frame(flow, store, full=False):
|
| 82 |
+
flow.view_revision += 1
|
| 83 |
+
tokens = flow.tokens.copy()
|
| 84 |
+
points = []
|
| 85 |
+
if store.projection is not None and flow.model_key == store.key:
|
| 86 |
+
first_new = flow.space_history[-1]["n"] + 1 if flow.space_history else 0
|
| 87 |
+
for index in range(first_new, len(tokens)):
|
| 88 |
+
token_id = tokens[index]
|
| 89 |
+
piece = store.tokenizer.decode([token_id], skip_special_tokens=False,
|
| 90 |
+
clean_up_tokenization_spaces=False)
|
| 91 |
+
previous = list(enumerate(tokens[max(0, index - 512):index], start=max(0, index - 512)))
|
| 92 |
+
links = store.projection.relatives(token_id, previous)
|
| 93 |
+
flow.space_history.append({"n": index, "id": token_id, "label": piece,
|
| 94 |
+
"xyz": store.projection.point(token_id), "links": links})
|
| 95 |
+
flow.space_history = flow.space_history[-512:]
|
| 96 |
+
for point in flow.space_history:
|
| 97 |
+
row = flow.attention_history.get(point["n"])
|
| 98 |
+
if row is not None:
|
| 99 |
+
point["attention"] = row
|
| 100 |
+
for link in point["attention"]["links"]:
|
| 101 |
+
if "id" in link and "xyz" not in link:
|
| 102 |
+
link["xyz"] = store.projection.point(link["id"])
|
| 103 |
+
link["label"] = ("[boundary]" if link["n"] == -1 else
|
| 104 |
+
store.tokenizer.decode([link["id"]], skip_special_tokens=False,
|
| 105 |
+
clean_up_tokenization_spaces=False))
|
| 106 |
+
points = flow.space_history[-512 if full else -48:]
|
| 107 |
+
data = {"continue_automatically": flow.continue_automatically, "stream": flow.stream_id, "revision": flow.view_revision, "paused": flow.paused, "running": flow.running,
|
| 108 |
+
"ended": flow.ended, "points": points}
|
| 109 |
+
axes=getattr(store.projection,"dimension_axes",None)
|
| 110 |
+
if axes is not None and (full or flow.sent_dimension_axes_key != store.key):
|
| 111 |
+
data["dimension_axes"]=axes
|
| 112 |
+
flow.sent_dimension_axes_key=store.key
|
| 113 |
+
if flow.layer_rows is not None and store.projection is not None:
|
| 114 |
+
queries = sorted(q for q in flow.layer_queries if q >= max(0, len(tokens) - 513))
|
| 115 |
+
if not flow.paused:
|
| 116 |
+
queries = queries[-1:]
|
| 117 |
+
rows, target_indices = [], set()
|
| 118 |
+
for query in queries:
|
| 119 |
+
slot = query % 512
|
| 120 |
+
packed = flow.layer_rows[slot]
|
| 121 |
+
indices = packed[:, :, 0].to(torch.int32).tolist()
|
| 122 |
+
rows.append({"query": query, "indices": indices,
|
| 123 |
+
"scores": packed[:, :, 1].tolist(), "keys": flow.layer_keys[slot].tolist()})
|
| 124 |
+
if not flow.paused:
|
| 125 |
+
target_indices.update(n for layer in indices for n in layer if -1 <= n < len(tokens))
|
| 126 |
+
from engine import start_id
|
| 127 |
+
boundary = start_id(store.model, store.tokenizer)
|
| 128 |
+
targets = []
|
| 129 |
+
if flow.paused:
|
| 130 |
+
target_indices.add(-1) # other targets are already in the full text snapshot
|
| 131 |
+
for n in sorted(target_indices):
|
| 132 |
+
token_id = boundary if n == -1 else tokens[n]
|
| 133 |
+
targets.append({"n": n, "id": token_id, "xyz": store.projection.point(token_id),
|
| 134 |
+
"label": "[boundary]" if n == -1 else store.tokenizer.decode(
|
| 135 |
+
[token_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)})
|
| 136 |
+
data["attention_layers"] = {"count": flow.layer_rows.shape[1], "rows": rows, "targets": targets}
|
| 137 |
+
if flow.paused and store.projection is not None and flow.model_key == store.key:
|
| 138 |
+
if flow.text_snapshot_cache is None or flow.text_snapshot_cache[0] != len(tokens):
|
| 139 |
+
flow.text_snapshot_cache = (len(tokens), text_snapshot(tokens, store.tokenizer, store.projection))
|
| 140 |
+
data["text_view"] = flow.text_snapshot_cache[1]
|
| 141 |
+
if flow.representations is not None:
|
| 142 |
+
data["representations"] = flow.representations.snapshot(len(tokens), full=full or flow.paused)
|
| 143 |
+
payload = json.dumps(data, ensure_ascii=True)
|
| 144 |
+
return '<div data-flow-frame="' + html.escape(payload, quote=True) + '"></div>'
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
SCENE = '''<div id="token-universe">
|
| 148 |
+
<canvas aria-label="Live 3D projection of generated token embeddings. Drag to orbit; scroll to zoom."></canvas>
|
| 149 |
+
<div class="space-top"><span class="space-brand">AUTOMATIC WRITING / TOKEN SPACE</span><span class="space-count">Waiting for tokens</span></div>
|
| 150 |
+
<div class="space-empty">A space for the next thought.<small>Press Begin. Tokens appear here, then fade.</small></div>
|
| 151 |
+
<div class="space-tools">
|
| 152 |
+
<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>
|
| 153 |
+
<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>
|
| 154 |
+
<button type="button" data-space-reset>Reset camera</button>
|
| 155 |
+
<button type="button" data-space-back disabled>Step back</button>
|
| 156 |
+
<button type="button" data-space-forward disabled>Step forward</button>
|
| 157 |
+
<span data-space-step>Live</span>
|
| 158 |
+
</div>
|
| 159 |
+
<section class="dimension-axes-controls" aria-label="Projected dimension axes">
|
| 160 |
+
<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>
|
| 161 |
+
<div class="dimension-axes-options" hidden>
|
| 162 |
+
<p class="dimension-axis-status" data-dimension-status></p>
|
| 163 |
+
<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>
|
| 164 |
+
<label>Origin <select data-dimension-origin><option value="mean">Projection centre</option><option value="raw">Original vector origin</option></select></label>
|
| 165 |
+
<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>
|
| 166 |
+
</div>
|
| 167 |
+
</section>
|
| 168 |
+
<div class="space-detail">
|
| 169 |
+
<section class="representation-controls" hidden>
|
| 170 |
+
<h3 class="attention-title">Representations through layers</h3>
|
| 171 |
+
<p class="representation-note" data-representation-note></p>
|
| 172 |
+
<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>
|
| 173 |
+
<p class="representation-stage" data-representation-stage>Input to first layer</p>
|
| 174 |
+
<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>
|
| 175 |
+
<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>
|
| 176 |
+
</section>
|
| 177 |
+
<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>
|
| 178 |
+
</div>
|
| 179 |
+
<div class="space-edge-tooltip" role="tooltip" hidden></div>
|
| 180 |
+
<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>
|
| 181 |
+
</div>'''
|