Spaces:
Running on Zero
Running on Zero
Add immersive 3D token space with fading embedding positions
Browse files- README.md +26 -3
- app.py +66 -60
- engine.py +2 -0
- models.py +4 -0
- style.css +34 -17
- token_space.js +91 -0
- token_space.py +46 -0
README.md
CHANGED
|
@@ -35,7 +35,7 @@ GPU are available. Start with SmolLM2-135M; larger models can be slow on CPU.
|
|
| 35 |
## Hugging Face Space
|
| 36 |
|
| 37 |
Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,
|
| 38 |
-
`requirements.txt`, and this `README.md`. The README contains the Space metadata.
|
| 39 |
The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost.
|
| 40 |
`FLOW_HOST` and `PORT` can override these defaults. No API token is
|
| 41 |
needed for the supported public, ungated models. Start with CPU Basic and a small
|
|
@@ -43,7 +43,28 @@ model; hardware determines the practical model size. This project is prepared fo
|
|
| 43 |
Spaces but does not create or publish a remote Space automatically.
|
| 44 |
|
| 45 |
Run `python scripts/prepare_space.py` to create `outputs/let-it-flow-space.zip`.
|
| 46 |
-
Extract the archive and upload its
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
## Controls
|
| 49 |
|
|
@@ -58,7 +79,7 @@ context-rebuilding delays can still occur.
|
|
| 58 |
- **Stop:** request cancellation; the current inference step completes first.
|
| 59 |
- **Continue:** preserve generated token IDs and RNG state, including across a stop.
|
| 60 |
- **Start fresh:** clear the page, then press Begin or Continue to start.
|
| 61 |
-
- **
|
| 62 |
optional seed, memory span, tokens per pass, and a display delay.
|
| 63 |
Defaults: temperature 1.3, top-p 1.0, repetition penalty 1.1, memory 128 tokens.
|
| 64 |
Try 64 tokens for more drift; longer memory sustains a subject more easily.
|
|
@@ -126,3 +147,5 @@ it downloads SmolLM2-135M and checks prompt-free generation and continuation.
|
|
| 126 |
With the server running, `python scripts/check_server.py` also exercises the
|
| 127 |
Gradio API, including seeded replay, live slider/inspector updates while generation
|
| 128 |
is running, stopping, exporting, and resetting a session.
|
|
|
|
|
|
|
|
|
| 35 |
## Hugging Face Space
|
| 36 |
|
| 37 |
Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,
|
| 38 |
+
`token_space.py`, `token_space.js`, `requirements.txt`, and this `README.md`. The README contains the Space metadata.
|
| 39 |
The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost.
|
| 40 |
`FLOW_HOST` and `PORT` can override these defaults. No API token is
|
| 41 |
needed for the supported public, ungated models. Start with CPU Basic and a small
|
|
|
|
| 43 |
Spaces but does not create or publish a remote Space automatically.
|
| 44 |
|
| 45 |
Run `python scripts/prepare_space.py` to create `outputs/let-it-flow-space.zip`.
|
| 46 |
+
Extract the archive and upload its eight files to the root of your Gradio Space.
|
| 47 |
+
|
| 48 |
+
## Token space
|
| 49 |
+
|
| 50 |
+
The opening screen shows only model selection. Successful loading hides the picker
|
| 51 |
+
and reveals the 3D token view with the generated text below it. **Change model**
|
| 52 |
+
returns to the picker and requests Stop if generation is running.
|
| 53 |
+
|
| 54 |
+
Each generated token appears at a fixed position derived from its input embedding.
|
| 55 |
+
A deterministic PCA is fitted to up to 2,048 evenly sampled vocabulary embeddings;
|
| 56 |
+
all vocabulary tokens use that same centered projection and scale. These are
|
| 57 |
+
stored token embeddings, not contextual activations or a map of thoughts. The
|
| 58 |
+
three projected axes have no named semantic meaning and lose information.
|
| 59 |
+
|
| 60 |
+
Drag the canvas to orbit, scroll to zoom, and double-click to reset the camera.
|
| 61 |
+
Tokens and connecting trails fade over six seconds using browser animation,
|
| 62 |
+
including while generation is stopped. Repeated tokens share a position. Visible
|
| 63 |
+
points are bounded to 240 occurrences; the text retains the complete session.
|
| 64 |
+
The viewer uses a perspective 3D projection rendered on a local canvas, with no
|
| 65 |
+
external script or graphics-service dependency. Reduced-motion preferences disable
|
| 66 |
+
idle camera rotation. The stream text below the canvas remains available to copy
|
| 67 |
+
or export; probability details and secondary controls are in the lower accordion.
|
| 68 |
|
| 69 |
## Controls
|
| 70 |
|
|
|
|
| 79 |
- **Stop:** request cancellation; the current inference step completes first.
|
| 80 |
- **Continue:** preserve generated token IDs and RNG state, including across a stop.
|
| 81 |
- **Start fresh:** clear the page, then press Begin or Continue to start.
|
| 82 |
+
- **Live sampling controls:** temperature, top-p, sign-aware repetition penalty,
|
| 83 |
optional seed, memory span, tokens per pass, and a display delay.
|
| 84 |
Defaults: temperature 1.3, top-p 1.0, repetition penalty 1.1, memory 128 tokens.
|
| 85 |
Try 64 tokens for more drift; longer memory sustains a subject more easily.
|
|
|
|
| 147 |
With the server running, `python scripts/check_server.py` also exercises the
|
| 148 |
Gradio API, including seeded replay, live slider/inspector updates while generation
|
| 149 |
is running, stopping, exporting, and resetting a session.
|
| 150 |
+
|
| 151 |
+
Frontend behavior checks: `node tests/check_token_space.cjs` (arrival, fading while paused, reset, orbit and zoom).
|
app.py
CHANGED
|
@@ -7,6 +7,7 @@ import gradio as gr
|
|
| 7 |
|
| 8 |
from engine import Flow, generate
|
| 9 |
from models import ModelStore, PRESETS
|
|
|
|
| 10 |
|
| 11 |
STORE = ModelStore()
|
| 12 |
|
|
@@ -36,6 +37,8 @@ EMPTY = '<div class="inspector"><div class="eyebrow">WATCH THE NEXT TOKEN</div><
|
|
| 36 |
|
| 37 |
|
| 38 |
def clear(flow):
|
|
|
|
|
|
|
| 39 |
flow.tokens.clear()
|
| 40 |
flow.text = ""
|
| 41 |
flow.model_key = ""
|
|
@@ -49,7 +52,7 @@ def load_model(repo, flow):
|
|
| 49 |
try:
|
| 50 |
description = STORE.load(repo)
|
| 51 |
text, panel, status = clear(flow)
|
| 52 |
-
return description, text, panel, status
|
| 53 |
except Exception as error:
|
| 54 |
raise gr.Error(f"Could not load model: {error}") from error
|
| 55 |
|
|
@@ -84,7 +87,7 @@ def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128
|
|
| 84 |
clean_up_tokenization_spaces=False)
|
| 85 |
trimmed = False
|
| 86 |
try:
|
| 87 |
-
yield last_text, panel, "Generating…"
|
| 88 |
for step in generate(STORE.model, STORE.tokenizer, flow, STORE.key,
|
| 89 |
count, temperature, top_p, penalty, seed, context_limit=memory,
|
| 90 |
live_settings=flow.controls):
|
|
@@ -103,7 +106,7 @@ def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128
|
|
| 103 |
status += " · automatic continuation on"
|
| 104 |
if trimmed:
|
| 105 |
status += f" · Only the latest {step['context_limit']} tokens inform the next choice."
|
| 106 |
-
yield last_text, panel if watching else "", status
|
| 107 |
delay = flow.controls()["delay"]
|
| 108 |
if delay and flow.stop.wait(float(delay)):
|
| 109 |
break
|
|
@@ -118,7 +121,7 @@ def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128
|
|
| 118 |
if trimmed:
|
| 119 |
reason += " Earlier text remains visible but is outside the model’s context."
|
| 120 |
controls = flow.controls()
|
| 121 |
-
yield last_text, panel if controls["watch"] else "", f"{reason} · {len(flow.tokens)} tokens · seed {flow.seed} · requested memory {int(controls['memory'])} tokens"
|
| 122 |
except Exception as error:
|
| 123 |
# Preserve already-generated text and RNG state so a failed pass can be retried.
|
| 124 |
raise gr.Error(str(error)) from error
|
|
@@ -138,68 +141,70 @@ def export(flow):
|
|
| 138 |
return str(output)
|
| 139 |
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
def build_app():
|
| 142 |
css = Path(__file__).with_name("style.css").read_text(encoding="utf-8")
|
| 143 |
-
|
|
|
|
| 144 |
primary_hue="teal", neutral_hue="stone"), delete_cache=(3600, 3600)) as demo:
|
| 145 |
flow = gr.State(Flow())
|
| 146 |
-
gr.
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
info="Used when Automatically continue is off. Changes apply live.")
|
| 178 |
-
delay = gr.Slider(0, .5, value=.06, step=.02, label="Reading delay per token (seconds)",
|
| 179 |
-
info="Slows the display, without changing the sampling distribution.")
|
| 180 |
-
with gr.Row():
|
| 181 |
-
with gr.Column(scale=3):
|
| 182 |
with gr.Row():
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
status = gr.Textbox(label="Stream status", value="Load a model to begin.", interactive=False)
|
| 191 |
with gr.Row():
|
| 192 |
save = gr.Button("Prepare text download", size="sm")
|
| 193 |
download = gr.File(label="Text export", interactive=False)
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
"the current inference step completes first. Seed applies on Begin, which replaces the current stream.")
|
| 202 |
-
outputs = [page, panel, status]
|
| 203 |
inputs = [flow, temperature, top_p, penalty, seed, count, watch, delay, memory, auto_continue]
|
| 204 |
common = dict(concurrency_id="model", concurrency_limit=1)
|
| 205 |
for component, name in [(temperature, "temperature"), (top_p, "top_p"),
|
|
@@ -207,11 +212,12 @@ def build_app():
|
|
| 207 |
(delay, "delay"), (watch, "watch"), (auto_continue, "auto_continue")]:
|
| 208 |
component.input(control_handler(name), [component, flow], [], queue=False,
|
| 209 |
trigger_mode="always_last", api_name=f"update_{name}", show_progress="hidden")
|
| 210 |
-
load.click(load_model, [repo, flow], [model_status, *outputs], **common)
|
|
|
|
| 211 |
start.click(begin, inputs, outputs, **common)
|
| 212 |
resume.click(run, inputs, outputs, **common)
|
| 213 |
halt.click(stop, [flow], [], queue=False)
|
| 214 |
-
reset.click(
|
| 215 |
save.click(export, [flow], download, **common)
|
| 216 |
return demo.queue(max_size=16, default_concurrency_limit=1)
|
| 217 |
|
|
|
|
| 7 |
|
| 8 |
from engine import Flow, generate
|
| 9 |
from models import ModelStore, PRESETS
|
| 10 |
+
from token_space import SCENE, frame
|
| 11 |
|
| 12 |
STORE = ModelStore()
|
| 13 |
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def clear(flow):
|
| 40 |
+
import uuid
|
| 41 |
+
flow.stream_id = uuid.uuid4().hex
|
| 42 |
flow.tokens.clear()
|
| 43 |
flow.text = ""
|
| 44 |
flow.model_key = ""
|
|
|
|
| 52 |
try:
|
| 53 |
description = STORE.load(repo)
|
| 54 |
text, panel, status = clear(flow)
|
| 55 |
+
return description, text, panel, status, frame(flow, STORE), gr.update(visible=False), gr.update(visible=True)
|
| 56 |
except Exception as error:
|
| 57 |
raise gr.Error(f"Could not load model: {error}") from error
|
| 58 |
|
|
|
|
| 87 |
clean_up_tokenization_spaces=False)
|
| 88 |
trimmed = False
|
| 89 |
try:
|
| 90 |
+
yield last_text, panel, "Generating…", frame(flow, STORE)
|
| 91 |
for step in generate(STORE.model, STORE.tokenizer, flow, STORE.key,
|
| 92 |
count, temperature, top_p, penalty, seed, context_limit=memory,
|
| 93 |
live_settings=flow.controls):
|
|
|
|
| 106 |
status += " · automatic continuation on"
|
| 107 |
if trimmed:
|
| 108 |
status += f" · Only the latest {step['context_limit']} tokens inform the next choice."
|
| 109 |
+
yield last_text, panel if watching else "", status, frame(flow, STORE)
|
| 110 |
delay = flow.controls()["delay"]
|
| 111 |
if delay and flow.stop.wait(float(delay)):
|
| 112 |
break
|
|
|
|
| 121 |
if trimmed:
|
| 122 |
reason += " Earlier text remains visible but is outside the model’s context."
|
| 123 |
controls = flow.controls()
|
| 124 |
+
yield last_text, panel if controls["watch"] else "", f"{reason} · {len(flow.tokens)} tokens · seed {flow.seed} · requested memory {int(controls['memory'])} tokens", frame(flow, STORE)
|
| 125 |
except Exception as error:
|
| 126 |
# Preserve already-generated text and RNG state so a failed pass can be retried.
|
| 127 |
raise gr.Error(str(error)) from error
|
|
|
|
| 141 |
return str(output)
|
| 142 |
|
| 143 |
|
| 144 |
+
def reset_view(flow):
|
| 145 |
+
return *clear(flow), frame(flow, STORE)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def choose_model(flow):
|
| 149 |
+
flow.stop.set()
|
| 150 |
+
return gr.update(visible=True), gr.update(visible=False)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
def build_app():
|
| 154 |
css = Path(__file__).with_name("style.css").read_text(encoding="utf-8")
|
| 155 |
+
js = Path(__file__).with_name("token_space.js").read_text(encoding="utf-8")
|
| 156 |
+
with gr.Blocks(title="Let it flow", css=css, js=js, theme=gr.themes.Soft(
|
| 157 |
primary_hue="teal", neutral_hue="stone"), delete_cache=(3600, 3600)) as demo:
|
| 158 |
flow = gr.State(Flow())
|
| 159 |
+
with gr.Column(elem_id="model-picker") as picker:
|
| 160 |
+
gr.HTML('<header><div class="eyebrow">AN EXPERIMENT IN AUTOMATIC WRITING</div>'
|
| 161 |
+
'<h1>Let it flow<span>.</span></h1><p>Choose a model. Enter its token space.</p></header>')
|
| 162 |
+
repo = gr.Dropdown(PRESETS, value=PRESETS[0], allow_custom_value=True,
|
| 163 |
+
label="Public model repository or Hugging Face URL")
|
| 164 |
+
load = gr.Button("Load model & enter space", variant="primary")
|
| 165 |
+
gr.Markdown("Small **base models** work best. Public safetensors models only; "
|
| 166 |
+
"2 GB download limit. One model is shared by visitors. "
|
| 167 |
+
"Loading includes preparing a fixed 3D embedding projection.")
|
| 168 |
+
with gr.Column(visible=False, elem_id="flow-workspace") as workspace:
|
| 169 |
+
with gr.Row(elem_id="workspace-top"):
|
| 170 |
+
model_status = gr.Textbox(label="Loaded model", interactive=False, scale=8)
|
| 171 |
+
change_model = gr.Button("Change model", scale=1, size="sm")
|
| 172 |
+
with gr.Row(elem_id="sampling-controls"):
|
| 173 |
+
temperature = gr.Slider(.05, 2, value=1.3, step=.05, label="Temperature")
|
| 174 |
+
top_p = gr.Slider(.05, 1, value=1, step=.01, label="Top-p")
|
| 175 |
+
penalty = gr.Slider(1, 2, value=1.1, step=.01, label="Repetition penalty")
|
| 176 |
+
memory = gr.Slider(16, 2048, value=128, step=1, label="Memory span (tokens)")
|
| 177 |
+
with gr.Row(elem_id="stream-buttons"):
|
| 178 |
+
start = gr.Button("Begin", variant="primary")
|
| 179 |
+
resume = gr.Button("Continue")
|
| 180 |
+
halt = gr.Button("Stop", variant="stop")
|
| 181 |
+
reset = gr.Button("Start fresh")
|
| 182 |
+
gr.HTML(SCENE, elem_id="space-scene")
|
| 183 |
+
page = gr.Textbox(label="The stream", lines=4, max_lines=6,
|
| 184 |
+
placeholder="No written prompt. Just the next token.",
|
| 185 |
+
interactive=False, show_copy_button=True, elem_id="page")
|
| 186 |
+
status = gr.Textbox(label="Stream status", value="Press Begin to let it flow.", interactive=False)
|
| 187 |
+
with gr.Accordion("More controls, probabilities & export", open=False):
|
| 188 |
+
auto_continue = gr.Checkbox(label="Automatically continue", value=True,
|
| 189 |
+
info="Flow until Stop, an end token, or 16,384 tokens.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
with gr.Row():
|
| 191 |
+
seed = gr.Number(value=None, precision=0, label="Random seed (optional)",
|
| 192 |
+
info="Applies on Begin; Continue keeps the random sequence.")
|
| 193 |
+
count = gr.Slider(1, 1024, value=256, step=1, label="Tokens per pass",
|
| 194 |
+
info="Used when automatic continuation is off.")
|
| 195 |
+
delay = gr.Slider(0, .5, value=.06, step=.02, label="Reading delay per token (seconds)")
|
| 196 |
+
watch = gr.Checkbox(label="Watch the next token", value=True)
|
| 197 |
+
panel = gr.HTML(EMPTY)
|
|
|
|
| 198 |
with gr.Row():
|
| 199 |
save = gr.Button("Prepare text download", size="sm")
|
| 200 |
download = gr.File(label="Text export", interactive=False)
|
| 201 |
+
gr.Markdown("Positions are a fixed PCA projection of the model's input token embeddings, "
|
| 202 |
+
"fitted to up to 2,048 vocabulary samples. The same token returns to the same position. "
|
| 203 |
+
"Axes have no named meaning, and projection loses information. "
|
| 204 |
+
"Tokens fade after six seconds, including while paused. "
|
| 205 |
+
"Sliders apply live; no written prompt or chat template is added.")
|
| 206 |
+
transport = gr.HTML('', elem_id="space-transport", elem_classes=["space-transport"])
|
| 207 |
+
outputs = [page, panel, status, transport]
|
|
|
|
|
|
|
| 208 |
inputs = [flow, temperature, top_p, penalty, seed, count, watch, delay, memory, auto_continue]
|
| 209 |
common = dict(concurrency_id="model", concurrency_limit=1)
|
| 210 |
for component, name in [(temperature, "temperature"), (top_p, "top_p"),
|
|
|
|
| 212 |
(delay, "delay"), (watch, "watch"), (auto_continue, "auto_continue")]:
|
| 213 |
component.input(control_handler(name), [component, flow], [], queue=False,
|
| 214 |
trigger_mode="always_last", api_name=f"update_{name}", show_progress="hidden")
|
| 215 |
+
load.click(load_model, [repo, flow], [model_status, *outputs, picker, workspace], **common)
|
| 216 |
+
change_model.click(choose_model, [flow], [picker, workspace], queue=False)
|
| 217 |
start.click(begin, inputs, outputs, **common)
|
| 218 |
resume.click(run, inputs, outputs, **common)
|
| 219 |
halt.click(stop, [flow], [], queue=False)
|
| 220 |
+
reset.click(reset_view, [flow], outputs, api_name="clear", **common)
|
| 221 |
save.click(export, [flow], download, **common)
|
| 222 |
return demo.queue(max_size=16, default_concurrency_limit=1)
|
| 223 |
|
engine.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""Prompt-free causal sampling. The inspector uses the actual sampled distribution."""
|
| 2 |
import secrets
|
| 3 |
import threading
|
|
|
|
| 4 |
|
| 5 |
import torch
|
| 6 |
|
|
@@ -8,6 +9,7 @@ import torch
|
|
| 8 |
class Flow:
|
| 9 |
def __init__(self, tokens=None, text="", model_key="", seed=None, ended=False):
|
| 10 |
self.tokens = list(tokens or [])
|
|
|
|
| 11 |
self.text = text
|
| 12 |
self.model_key = model_key
|
| 13 |
self.seed = seed
|
|
|
|
| 1 |
"""Prompt-free causal sampling. The inspector uses the actual sampled distribution."""
|
| 2 |
import secrets
|
| 3 |
import threading
|
| 4 |
+
import uuid
|
| 5 |
|
| 6 |
import torch
|
| 7 |
|
|
|
|
| 9 |
class Flow:
|
| 10 |
def __init__(self, tokens=None, text="", model_key="", seed=None, ended=False):
|
| 11 |
self.tokens = list(tokens or [])
|
| 12 |
+
self.stream_id = uuid.uuid4().hex
|
| 13 |
self.text = text
|
| 14 |
self.model_key = model_key
|
| 15 |
self.seed = seed
|
models.py
CHANGED
|
@@ -32,6 +32,7 @@ class ModelStore:
|
|
| 32 |
def __init__(self):
|
| 33 |
self.model = self.tokenizer = None
|
| 34 |
self.key = ""
|
|
|
|
| 35 |
self.description = "No model loaded."
|
| 36 |
|
| 37 |
def load(self, value):
|
|
@@ -60,6 +61,7 @@ class ModelStore:
|
|
| 60 |
raise ValueError("Choose a decoder-only text-generation model.")
|
| 61 |
# Release the previous model before allocating the next one.
|
| 62 |
self.model = self.tokenizer = None
|
|
|
|
| 63 |
self.key = ""
|
| 64 |
gc.collect()
|
| 65 |
if torch.cuda.is_available():
|
|
@@ -74,6 +76,8 @@ class ModelStore:
|
|
| 74 |
model.eval()
|
| 75 |
from engine import start_id
|
| 76 |
initial = start_id(model, tokenizer)
|
|
|
|
|
|
|
| 77 |
self.model, self.tokenizer = model, tokenizer
|
| 78 |
self.key = f"{repo}@{info.sha}"
|
| 79 |
device = "GPU" if torch.cuda.is_available() else "CPU"
|
|
|
|
| 32 |
def __init__(self):
|
| 33 |
self.model = self.tokenizer = None
|
| 34 |
self.key = ""
|
| 35 |
+
self.projection = None
|
| 36 |
self.description = "No model loaded."
|
| 37 |
|
| 38 |
def load(self, value):
|
|
|
|
| 61 |
raise ValueError("Choose a decoder-only text-generation model.")
|
| 62 |
# Release the previous model before allocating the next one.
|
| 63 |
self.model = self.tokenizer = None
|
| 64 |
+
self.projection = None
|
| 65 |
self.key = ""
|
| 66 |
gc.collect()
|
| 67 |
if torch.cuda.is_available():
|
|
|
|
| 76 |
model.eval()
|
| 77 |
from engine import start_id
|
| 78 |
initial = start_id(model, tokenizer)
|
| 79 |
+
from token_space import TokenProjection
|
| 80 |
+
self.projection = TokenProjection(model.get_input_embeddings().weight)
|
| 81 |
self.model, self.tokenizer = model, tokenizer
|
| 82 |
self.key = f"{repo}@{info.sha}"
|
| 83 |
device = "GPU" if torch.cuda.is_available() else "CPU"
|
style.css
CHANGED
|
@@ -1,17 +1,34 @@
|
|
| 1 |
-
.gradio-container { max-width:
|
| 2 |
-
header { padding: 36px 8px 28px; }
|
| 3 |
-
.eyebrow { font: 600 11px/1.5 system-ui, sans-serif; letter-spacing: .18em; color: #497b71; }
|
| 4 |
-
header h1 { font: 400 clamp(44px, 6vw, 74px)/1.1 Georgia, serif; letter-spacing: -.04em; margin: 12px 0; }
|
| 5 |
-
header h1 span { color: #568f7e; }
|
| 6 |
-
header p { font: 18px/1.6 Georgia, serif; color: #777; }
|
| 7 |
-
#page textarea { font:
|
| 8 |
-
.inspector { padding: 22px; border: 1px solid #82968b40; border-radius: 14px; min-height: 230px; }
|
| 9 |
-
.inspector h3 { font: 26px/1.2 Georgia, serif; margin: 12px 0; }
|
| 10 |
-
.inspector p, .inspector small { opacity: .75; line-height: 1.6; }
|
| 11 |
-
.candidate { padding: 8px 10px; margin: 6px 0; border-radius: 8px; }
|
| 12 |
-
.candidate.selected { background: #48887518; outline: 1px solid #48887580; }
|
| 13 |
-
.candidate-label { display: flex; justify-content: space-between; gap: 12px; font-size: 12px; }
|
| 14 |
-
.candidate-label code { white-space: pre-wrap; overflow-wrap: anywhere; }
|
| 15 |
-
.candidate small { font-size: 10px; }
|
| 16 |
-
.track { height: 5px; background: #82968b20; border-radius: 8px; margin: 7px 0 3px; overflow: hidden; }
|
| 17 |
-
.track div { height: 100%; background: #629b89; border-radius: 8px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.gradio-container { max-width: 1600px !important; margin: auto; }
|
| 2 |
+
header { padding: 36px 8px 28px; }
|
| 3 |
+
.eyebrow { font: 600 11px/1.5 system-ui, sans-serif; letter-spacing: .18em; color: #497b71; }
|
| 4 |
+
header h1 { font: 400 clamp(44px, 6vw, 74px)/1.1 Georgia, serif; letter-spacing: -.04em; margin: 12px 0; }
|
| 5 |
+
header h1 span { color: #568f7e; }
|
| 6 |
+
header p { font: 18px/1.6 Georgia, serif; color: #777; }
|
| 7 |
+
#page textarea { font: 18px/1.65 Georgia, 'Times New Roman', serif !important; padding: 14px 20px !important; }
|
| 8 |
+
.inspector { padding: 22px; border: 1px solid #82968b40; border-radius: 14px; min-height: 230px; }
|
| 9 |
+
.inspector h3 { font: 26px/1.2 Georgia, serif; margin: 12px 0; }
|
| 10 |
+
.inspector p, .inspector small { opacity: .75; line-height: 1.6; }
|
| 11 |
+
.candidate { padding: 8px 10px; margin: 6px 0; border-radius: 8px; }
|
| 12 |
+
.candidate.selected { background: #48887518; outline: 1px solid #48887580; }
|
| 13 |
+
.candidate-label { display: flex; justify-content: space-between; gap: 12px; font-size: 12px; }
|
| 14 |
+
.candidate-label code { white-space: pre-wrap; overflow-wrap: anywhere; }
|
| 15 |
+
.candidate small { font-size: 10px; }
|
| 16 |
+
.track { height: 5px; background: #82968b20; border-radius: 8px; margin: 7px 0 3px; overflow: hidden; }
|
| 17 |
+
.track div { height: 100%; background: #629b89; border-radius: 8px; }
|
| 18 |
+
|
| 19 |
+
#model-picker { max-width:680px; margin:8vh auto; padding:24px; }
|
| 20 |
+
#flow-workspace { gap:10px; }
|
| 21 |
+
#workspace-top textarea { font-size:11px; }
|
| 22 |
+
#sampling-controls { gap:8px; }
|
| 23 |
+
#space-scene { padding:0 !important; border:0 !important; }
|
| 24 |
+
#token-universe { position:relative; height:clamp(340px,55vh,800px); overflow:hidden; border-radius:16px; background:#080f18; color:#bdd8dd; }
|
| 25 |
+
#token-universe canvas { width:100%; height:100%; display:block; cursor:grab; touch-action:none; }
|
| 26 |
+
#token-universe canvas:active { cursor:grabbing; }
|
| 27 |
+
.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; }
|
| 28 |
+
.space-top { top:18px; letter-spacing:.12em; }
|
| 29 |
+
.space-bottom { bottom:16px; opacity:.6; }
|
| 30 |
+
.space-brand { color:#95d7cc; }
|
| 31 |
+
.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; }
|
| 32 |
+
.space-empty small { font:13px/1.5 system-ui,sans-serif; opacity:.65; }
|
| 33 |
+
.space-transport { display:none !important; }
|
| 34 |
+
@media(max-width:640px) { .space-bottom { font-size:9px;left:12px;right:12px; } .space-top { left:12px;right:12px;font-size:9px; } #model-picker { margin:3vh auto; } }
|
token_space.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
() => {
|
| 2 |
+
if (window.__letItFlowSpace) window.__letItFlowSpace();
|
| 3 |
+
let root, canvas, ctx, observer, raf, resize, stream=null, seen=-1;
|
| 4 |
+
let points=[], yaw=.35, pitch=-.15, zoom=1, dragging=false;
|
| 5 |
+
let lastX=0,lastY=0,lastTime=performance.now(),width=0,height=0,payload='',disposed=false;
|
| 6 |
+
const lifetime=6000;
|
| 7 |
+
function mount() {
|
| 8 |
+
const next=document.querySelector('#token-universe');
|
| 9 |
+
if(!next || next===root) return;
|
| 10 |
+
root=next;canvas=root.querySelector('canvas');ctx=canvas.getContext('2d');
|
| 11 |
+
if(resize)resize.disconnect();
|
| 12 |
+
resize=new ResizeObserver(()=>{
|
| 13 |
+
const rect=canvas.getBoundingClientRect();width=rect.width;height=rect.height;
|
| 14 |
+
const dpr=Math.min(window.devicePixelRatio||1,2);
|
| 15 |
+
canvas.width=Math.round(width*dpr);canvas.height=Math.round(height*dpr);
|
| 16 |
+
ctx.setTransform(dpr,0,0,dpr,0,0);
|
| 17 |
+
});
|
| 18 |
+
resize.observe(canvas);
|
| 19 |
+
canvas.addEventListener('pointerdown',e=>{dragging=true;lastX=e.clientX;lastY=e.clientY;canvas.setPointerCapture(e.pointerId);});
|
| 20 |
+
canvas.addEventListener('pointermove',e=>{
|
| 21 |
+
if(!dragging)return;
|
| 22 |
+
yaw+=(e.clientX-lastX)*.006;pitch=Math.max(-1.3,Math.min(1.3,pitch+(e.clientY-lastY)*.006));
|
| 23 |
+
lastX=e.clientX;lastY=e.clientY;
|
| 24 |
+
});
|
| 25 |
+
canvas.addEventListener('pointerup',()=>dragging=false);
|
| 26 |
+
canvas.addEventListener('pointercancel',()=>dragging=false);
|
| 27 |
+
canvas.addEventListener('wheel',e=>{e.preventDefault();zoom=Math.max(.4,Math.min(3,zoom*Math.exp(-e.deltaY*.001)));},{passive:false});
|
| 28 |
+
canvas.addEventListener('dblclick',()=>{yaw=.35;pitch=-.15;zoom=1;});
|
| 29 |
+
}
|
| 30 |
+
function receive() {
|
| 31 |
+
mount();
|
| 32 |
+
const node=document.querySelector('[data-flow-frame]');if(!node)return;
|
| 33 |
+
const raw=node.getAttribute('data-flow-frame');if(raw===payload)return;
|
| 34 |
+
payload=raw;let data;try{data=JSON.parse(raw);}catch{return;}
|
| 35 |
+
if(data.stream!==stream){stream=data.stream;seen=-1;points=[];}
|
| 36 |
+
const now=performance.now();
|
| 37 |
+
for(const p of data.points||[]){
|
| 38 |
+
if(p.n<=seen||!Array.isArray(p.xyz)||!p.xyz.every(Number.isFinite))continue;
|
| 39 |
+
points.push({...p,born:now});seen=p.n;
|
| 40 |
+
}
|
| 41 |
+
points=points.slice(-240);
|
| 42 |
+
}
|
| 43 |
+
function project(v){
|
| 44 |
+
const[x,y,z]=v,cy=Math.cos(yaw),sy=Math.sin(yaw),rx=x*cy+z*sy,rz=-x*sy+z*cy;
|
| 45 |
+
const cp=Math.cos(pitch),sp=Math.sin(pitch),ry=y*cp-rz*sp,depth=y*sp+rz*cp;
|
| 46 |
+
const perspective=7/Math.max(1,7+depth),scale=Math.min(width,height)*.13*zoom*perspective;
|
| 47 |
+
return{x:width/2+rx*scale,y:height/2+ry*scale,z:depth,scale:perspective};
|
| 48 |
+
}
|
| 49 |
+
function tick(now){
|
| 50 |
+
if(disposed)return;
|
| 51 |
+
const dt=Math.min(now-lastTime,100);lastTime=now;
|
| 52 |
+
if(!dragging&&!matchMedia('(prefers-reduced-motion: reduce)').matches)yaw+=dt*.000025;
|
| 53 |
+
if(ctx&&width&&height){
|
| 54 |
+
ctx.clearRect(0,0,width,height);
|
| 55 |
+
const wash=ctx.createRadialGradient(width*.48,height*.48,0,width*.5,height*.5,width*.6);
|
| 56 |
+
wash.addColorStop(0,'#142b34');wash.addColorStop(1,'#080f18');ctx.fillStyle=wash;ctx.fillRect(0,0,width,height);
|
| 57 |
+
ctx.lineWidth=1;ctx.strokeStyle='#6b9caa19';
|
| 58 |
+
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]]]){
|
| 59 |
+
const a=project(pair[0]),b=project(pair[1]);ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();
|
| 60 |
+
}
|
| 61 |
+
points=points.filter(p=>now-p.born<lifetime);
|
| 62 |
+
const rendered=points.map(p=>({...p,...project(p.xyz),age:(now-p.born)/lifetime}));
|
| 63 |
+
const recent=[...rendered].sort((a,b)=>a.n-b.n);
|
| 64 |
+
for(let i=1;i<recent.length;i++){
|
| 65 |
+
const a=recent[i-1],b=recent[i];if(b.n-a.n!==1)continue;
|
| 66 |
+
ctx.strokeStyle=`rgba(109,207,196,${(1-Math.max(a.age,b.age))*.17})`;
|
| 67 |
+
ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();
|
| 68 |
+
}
|
| 69 |
+
rendered.sort((a,b)=>b.z-a.z);
|
| 70 |
+
for(const p of rendered){
|
| 71 |
+
const alpha=Math.pow(1-p.age,1.5),newest=p.n===seen;ctx.globalAlpha=alpha;
|
| 72 |
+
ctx.fillStyle=newest?'#faf0bd':'#83dfd2';ctx.shadowColor=ctx.fillStyle;ctx.shadowBlur=newest?18:8;
|
| 73 |
+
ctx.beginPath();ctx.arc(p.x,p.y,Math.max(2,(newest?5:3)*p.scale),0,Math.PI*2);ctx.fill();ctx.shadowBlur=0;
|
| 74 |
+
ctx.font=`${newest?600:400} ${Math.max(11,Math.min(19,14*p.scale))}px ui-monospace,monospace`;
|
| 75 |
+
let label=p.label.replace(/\n/g,'↵').replace(/\t/g,'⇥').replace(/ /g,'·');
|
| 76 |
+
if(!label)label=`[${p.id}]`;if(label.length>32)label=label.slice(0,31)+'…';
|
| 77 |
+
ctx.fillText(label,p.x+9,p.y-8-(p.n%3)*5);
|
| 78 |
+
}
|
| 79 |
+
ctx.globalAlpha=1;
|
| 80 |
+
const counter=root.querySelector('.space-count'),empty=root.querySelector('.space-empty');
|
| 81 |
+
if(counter)counter.textContent=`${points.length} visible · ${seen+1} generated`;
|
| 82 |
+
if(empty)empty.style.display=seen<0?'flex':'none';
|
| 83 |
+
const text=document.querySelector('#page textarea');if(text&&document.activeElement!==text)text.scrollTop=text.scrollHeight;
|
| 84 |
+
}
|
| 85 |
+
raf=requestAnimationFrame(tick);
|
| 86 |
+
}
|
| 87 |
+
observer=new MutationObserver(receive);
|
| 88 |
+
observer.observe(document.body,{subtree:true,childList:true,attributes:true,attributeFilter:['data-flow-frame']});
|
| 89 |
+
receive();raf=requestAnimationFrame(tick);
|
| 90 |
+
window.__letItFlowSpace=()=>{disposed=true;observer.disconnect();if(resize)resize.disconnect();cancelAnimationFrame(raf);};
|
| 91 |
+
}
|
token_space.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A fixed three-dimensional PCA projection of input token embeddings."""
|
| 2 |
+
import html
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TokenProjection:
|
| 9 |
+
def __init__(self, weights):
|
| 10 |
+
weights = weights.detach().float().cpu()
|
| 11 |
+
indices = torch.linspace(0, len(weights) - 1, min(2048, len(weights))).long()
|
| 12 |
+
sample = weights[indices]
|
| 13 |
+
center = sample.mean(0)
|
| 14 |
+
sample = sample - center
|
| 15 |
+
dimensions = min(3, *sample.shape)
|
| 16 |
+
with torch.random.fork_rng(devices=[]):
|
| 17 |
+
torch.manual_seed(42)
|
| 18 |
+
_, _, basis = torch.pca_lowrank(sample, q=dimensions, center=False, niter=3)
|
| 19 |
+
coords = (weights - center) @ basis
|
| 20 |
+
scale = torch.linalg.vector_norm(sample @ basis, dim=1).quantile(.95).clamp_min(1e-6)
|
| 21 |
+
coords = coords / scale * 2.4
|
| 22 |
+
self.coords = torch.nn.functional.pad(coords, (0, 3 - dimensions)).tolist()
|
| 23 |
+
|
| 24 |
+
def point(self, token_id):
|
| 25 |
+
return self.coords[token_id]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def frame(flow, store):
|
| 29 |
+
points = []
|
| 30 |
+
if store.projection is not None and flow.model_key == store.key:
|
| 31 |
+
for index in range(max(0, len(flow.tokens) - 48), len(flow.tokens)):
|
| 32 |
+
token_id = flow.tokens[index]
|
| 33 |
+
piece = store.tokenizer.decode([token_id], skip_special_tokens=False,
|
| 34 |
+
clean_up_tokenization_spaces=False)
|
| 35 |
+
points.append({"n": index, "id": token_id, "label": piece,
|
| 36 |
+
"xyz": store.projection.point(token_id)})
|
| 37 |
+
payload = json.dumps({"stream": flow.stream_id, "points": points}, ensure_ascii=True)
|
| 38 |
+
return '<div data-flow-frame="' + html.escape(payload, quote=True) + '"></div>'
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
SCENE = '''<div id="token-universe">
|
| 42 |
+
<canvas aria-label="Live 3D projection of generated token embeddings. Drag to orbit; scroll to zoom."></canvas>
|
| 43 |
+
<div class="space-top"><span class="space-brand">LET IT FLOW / TOKEN SPACE</span><span class="space-count">Waiting for tokens</span></div>
|
| 44 |
+
<div class="space-empty">A space for the next thought.<small>Press Begin. Tokens appear here, then fade.</small></div>
|
| 45 |
+
<div class="space-bottom"><span>Drag to orbit · Scroll to zoom</span><span>Embedding PCA · 6-second trails</span></div>
|
| 46 |
+
</div>'''
|