Spaces:
Running on Zero
Running on Zero
Add Hugging Face login and ZeroGPU generation with real attention
Browse files- README.md +6 -1
- app.py +66 -24
- engine.py +235 -179
- gpu_runtime.py +9 -0
- models.py +109 -105
- requirements.txt +7 -4
- token_space.js +10 -0
- token_space.py +128 -128
README.md
CHANGED
|
@@ -7,7 +7,8 @@ sdk: gradio
|
|
| 7 |
sdk_version: 5.49.1
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
-
python_version: '3.
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
# Let it flow
|
|
@@ -251,3 +252,7 @@ Gradio API, including seeded replay, live slider/inspector updates while generat
|
|
| 251 |
is running, stopping, exporting, and resetting a session.
|
| 252 |
|
| 253 |
Frontend behavior checks: `node tests/check_token_space.cjs` (arrival, fading while paused, reset, orbit and zoom).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
# Let it flow
|
|
|
|
| 252 |
is running, stopping, exporting, and resetting a session.
|
| 253 |
|
| 254 |
Frontend behavior checks: `node tests/check_token_space.cjs` (arrival, fading while paused, reset, orbit and zoom).
|
| 255 |
+
|
| 256 |
+
## Public ZeroGPU deployment
|
| 257 |
+
|
| 258 |
+
Sign in with Hugging Face to use your personal ZeroGPU quota. Curated models are preloaded in half precision, including GPT-2 XL (1.5B). Actual eager attention is captured on the GPU. Generation yields session state back to Gradio and automatically requests another short GPU session while automatic continuation is enabled. GPU queue delays can occur between sessions. Pausing releases the GPU. Local CPU mode retains custom public model loading with a 2 GB download cap.
|
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
"""Let it flow — a prompt-free Hugging Face Space."""
|
|
|
|
| 2 |
import html
|
| 3 |
import secrets
|
| 4 |
from pathlib import Path
|
|
@@ -7,10 +8,21 @@ import time
|
|
| 7 |
import gradio as gr
|
| 8 |
|
| 9 |
from engine import Flow, generate
|
| 10 |
-
from models import ModelStore, PRESETS, MODEL_LABELS
|
| 11 |
from token_space import SCENE, frame
|
| 12 |
|
| 13 |
STORE = ModelStore()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
def inspector(tokenizer, step, number):
|
|
@@ -44,6 +56,7 @@ def clear(flow):
|
|
| 44 |
flow.space_history.clear()
|
| 45 |
flow.attention_history.clear()
|
| 46 |
flow.text_snapshot_cache = None
|
|
|
|
| 47 |
flow.paused = False
|
| 48 |
flow.running = False
|
| 49 |
flow.reset_requested = False
|
|
@@ -57,24 +70,33 @@ def clear(flow):
|
|
| 57 |
|
| 58 |
def load_model(repo, flow):
|
| 59 |
try:
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
text, panel, status = clear(flow)
|
| 62 |
-
return description, text, panel, status, frame(flow,
|
| 63 |
except Exception as error:
|
| 64 |
raise gr.Error(f"Could not load model: {error}") from error
|
| 65 |
|
| 66 |
|
| 67 |
def stop(flow):
|
|
|
|
| 68 |
flow.paused = False
|
| 69 |
flow.stop.set()
|
| 70 |
-
return frame(flow,
|
| 71 |
|
| 72 |
|
| 73 |
def pause_generation(flow):
|
|
|
|
| 74 |
flow.paused = True
|
| 75 |
flow.stop.set()
|
| 76 |
return ("Pausing after the current token. Use Step back / Step forward in the 3D view, then Resume generation.",
|
| 77 |
-
frame(flow,
|
| 78 |
|
| 79 |
|
| 80 |
def control_handler(name):
|
|
@@ -86,11 +108,12 @@ def control_handler(name):
|
|
| 86 |
return update
|
| 87 |
|
| 88 |
|
| 89 |
-
def
|
| 90 |
auto_continue=True, attention=True, attention_layer=-1, attention_head=-1, fresh=False):
|
| 91 |
if flow.reset_requested:
|
| 92 |
return
|
| 93 |
-
|
|
|
|
| 94 |
raise gr.Error("Load a model first.")
|
| 95 |
if fresh:
|
| 96 |
clear(flow)
|
|
@@ -98,26 +121,27 @@ def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128
|
|
| 98 |
count=count, watch=watch, delay=delay, memory=memory,
|
| 99 |
auto_continue=auto_continue, attention=attention,
|
| 100 |
attention_layer=attention_layer, attention_head=attention_head)
|
|
|
|
| 101 |
flow.stop.clear()
|
| 102 |
flow.paused = False
|
| 103 |
panel = EMPTY
|
| 104 |
started = time.monotonic()
|
| 105 |
before = len(flow.tokens)
|
| 106 |
-
last_text =
|
| 107 |
clean_up_tokenization_spaces=False)
|
| 108 |
trimmed = False
|
| 109 |
flow.running = True
|
| 110 |
try:
|
| 111 |
-
yield last_text, panel, "Generating…", frame(flow,
|
| 112 |
-
for step in generate(
|
| 113 |
count, temperature, top_p, penalty, seed, context_limit=memory,
|
| 114 |
-
live_settings=flow.controls, attention_modules=
|
| 115 |
last_text = step["text"]
|
| 116 |
trimmed = step["context_trimmed"]
|
| 117 |
controls = flow.controls()
|
| 118 |
watching = controls["watch"]
|
| 119 |
if watching:
|
| 120 |
-
panel = inspector(
|
| 121 |
status = (f"{len(flow.tokens)} tokens · seed {flow.seed} · "
|
| 122 |
f"{(len(flow.tokens) - before) / max(.001, time.monotonic() - started):.1f} tokens/s"
|
| 123 |
f" · memory {step['context_limit']} tokens"
|
|
@@ -127,10 +151,13 @@ def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128
|
|
| 127 |
status += " · automatic continuation on"
|
| 128 |
if trimmed:
|
| 129 |
status += f" · Only the latest {step['context_limit']} tokens inform the next choice."
|
| 130 |
-
yield last_text, panel if watching else "", status, frame(flow,
|
| 131 |
delay = flow.controls()["delay"]
|
| 132 |
if delay and flow.stop.wait(float(delay)):
|
| 133 |
break
|
|
|
|
|
|
|
|
|
|
| 134 |
flow.running = False
|
| 135 |
if flow.ended:
|
| 136 |
reason = "The model emitted an end token. Start fresh to begin another stream."
|
|
@@ -145,7 +172,7 @@ def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128
|
|
| 145 |
if trimmed:
|
| 146 |
reason += " Earlier text remains visible but is outside the model’s context."
|
| 147 |
controls = flow.controls()
|
| 148 |
-
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,
|
| 149 |
except Exception as error:
|
| 150 |
flow.running = False
|
| 151 |
# Preserve already-generated text and RNG state so a failed pass can be retried.
|
|
@@ -154,8 +181,19 @@ def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128
|
|
| 154 |
flow.running = False
|
| 155 |
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
|
| 161 |
def export(flow):
|
|
@@ -169,11 +207,12 @@ def export(flow):
|
|
| 169 |
|
| 170 |
|
| 171 |
def reset_view(flow):
|
| 172 |
-
return *clear(flow), frame(flow,
|
| 173 |
|
| 174 |
|
| 175 |
def choose_model(flow):
|
| 176 |
flow.reset_requested = True
|
|
|
|
| 177 |
flow.paused = False
|
| 178 |
flow.stop.set()
|
| 179 |
return gr.update(visible=True), gr.update(visible=False)
|
|
@@ -181,7 +220,7 @@ def choose_model(flow):
|
|
| 181 |
|
| 182 |
def refresh_view(flow):
|
| 183 |
flow.running = False
|
| 184 |
-
return frame(flow,
|
| 185 |
|
| 186 |
|
| 187 |
def build_app():
|
|
@@ -193,14 +232,17 @@ def build_app():
|
|
| 193 |
with gr.Column(elem_id="model-picker") as picker:
|
| 194 |
gr.HTML('<header><div class="eyebrow">AN EXPERIMENT IN AUTOMATIC WRITING</div>'
|
| 195 |
'<h1>Let it flow<span>.</span></h1><p>Choose a model. Enter its token space.</p></header>')
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
| 197 |
label="Public model repository or Hugging Face URL")
|
| 198 |
model_note = gr.Textbox(value=MODEL_LABELS[PRESETS[0]], label="Model description", interactive=False)
|
| 199 |
repo.change(lambda value: MODEL_LABELS.get(value, "Custom public model repository or URL"),
|
| 200 |
[repo], model_note, queue=False, api_name="model_description")
|
| 201 |
load = gr.Button("Load model & enter space", variant="primary")
|
| 202 |
-
gr.Markdown("Small **base models** work best. Public safetensors models only; "
|
| 203 |
-
"2 GB download limit. One model is shared by visitors. "
|
| 204 |
"Loading includes preparing a fixed 3D embedding projection.")
|
| 205 |
gr.Markdown("Gemma 3 1B downloads about 2 GB and is slower on CPU. Qwen3 0.6B downloads "
|
| 206 |
"about 1.2–1.5 GB. Base models are the closest fit for prompt-free continuation. "
|
|
@@ -236,7 +278,7 @@ def build_app():
|
|
| 236 |
info="A fresh random seed is selected on every model load. Clear for a random seed on the next new stream.")
|
| 237 |
count = gr.Slider(1, 1024, value=256, step=1, label="Tokens per pass",
|
| 238 |
info="Used when automatic continuation is off.")
|
| 239 |
-
delay = gr.Slider(0, .5, value=.06, step=.02, label="Reading delay per token (seconds)")
|
| 240 |
with gr.Row():
|
| 241 |
new_stream = gr.Button("New stream", elem_id="generation-new")
|
| 242 |
halt = gr.Button("Stop", variant="stop")
|
|
@@ -269,9 +311,9 @@ def build_app():
|
|
| 269 |
load.click(load_model, [repo, flow], [model_status, *outputs, seed, picker, workspace], **common)
|
| 270 |
reset_model.click(choose_model, [flow], [picker, workspace], queue=False).then(
|
| 271 |
reset_view, [flow], outputs, api_name="reset_model_state", **common)
|
| 272 |
-
start.click(run, inputs, outputs, api_name="run", **common).failure(
|
| 273 |
refresh_view, [flow], transport, queue=False)
|
| 274 |
-
new_stream.click(begin, inputs, outputs, api_name="begin", **common).failure(
|
| 275 |
refresh_view, [flow], transport, queue=False)
|
| 276 |
halt.click(stop, [flow], transport, queue=False)
|
| 277 |
pause.click(pause_generation, [flow], [status, transport], queue=False)
|
|
|
|
| 1 |
"""Let it flow — a prompt-free Hugging Face Space."""
|
| 2 |
+
from gpu_runtime import ZERO_GPU, spaces
|
| 3 |
import html
|
| 4 |
import secrets
|
| 5 |
from pathlib import Path
|
|
|
|
| 8 |
import gradio as gr
|
| 9 |
|
| 10 |
from engine import Flow, generate
|
| 11 |
+
from models import ModelStore, PRESETS, MODEL_LABELS, repository
|
| 12 |
from token_space import SCENE, frame
|
| 13 |
|
| 14 |
STORE = ModelStore()
|
| 15 |
+
POOL = {}
|
| 16 |
+
if ZERO_GPU:
|
| 17 |
+
for model_id in PRESETS:
|
| 18 |
+
print(f"Preloading {model_id}", flush=True)
|
| 19 |
+
entry = ModelStore()
|
| 20 |
+
entry.load(model_id)
|
| 21 |
+
POOL[model_id] = entry
|
| 22 |
+
|
| 23 |
+
def session_store(flow):
|
| 24 |
+
return POOL.get(flow.selected_repo, STORE) if ZERO_GPU else STORE
|
| 25 |
+
|
| 26 |
|
| 27 |
|
| 28 |
def inspector(tokenizer, step, number):
|
|
|
|
| 56 |
flow.space_history.clear()
|
| 57 |
flow.attention_history.clear()
|
| 58 |
flow.text_snapshot_cache = None
|
| 59 |
+
flow.continue_automatically = False
|
| 60 |
flow.paused = False
|
| 61 |
flow.running = False
|
| 62 |
flow.reset_requested = False
|
|
|
|
| 70 |
|
| 71 |
def load_model(repo, flow):
|
| 72 |
try:
|
| 73 |
+
if ZERO_GPU:
|
| 74 |
+
selected = repository(repo)
|
| 75 |
+
if selected not in POOL:
|
| 76 |
+
raise ValueError("Choose a preloaded model from the list.")
|
| 77 |
+
flow.selected_repo = selected
|
| 78 |
+
description = POOL[selected].description
|
| 79 |
+
else:
|
| 80 |
+
description = STORE.load(repo)
|
| 81 |
text, panel, status = clear(flow)
|
| 82 |
+
return description, text, panel, status, frame(flow, session_store(flow)), secrets.randbits(32), gr.update(visible=False), gr.update(visible=True)
|
| 83 |
except Exception as error:
|
| 84 |
raise gr.Error(f"Could not load model: {error}") from error
|
| 85 |
|
| 86 |
|
| 87 |
def stop(flow):
|
| 88 |
+
flow.continue_automatically = False
|
| 89 |
flow.paused = False
|
| 90 |
flow.stop.set()
|
| 91 |
+
return frame(flow, session_store(flow), full=True)
|
| 92 |
|
| 93 |
|
| 94 |
def pause_generation(flow):
|
| 95 |
+
flow.continue_automatically = False
|
| 96 |
flow.paused = True
|
| 97 |
flow.stop.set()
|
| 98 |
return ("Pausing after the current token. Use Step back / Step forward in the 3D view, then Resume generation.",
|
| 99 |
+
frame(flow, session_store(flow), full=True))
|
| 100 |
|
| 101 |
|
| 102 |
def control_handler(name):
|
|
|
|
| 108 |
return update
|
| 109 |
|
| 110 |
|
| 111 |
+
def _run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
|
| 112 |
auto_continue=True, attention=True, attention_layer=-1, attention_head=-1, fresh=False):
|
| 113 |
if flow.reset_requested:
|
| 114 |
return
|
| 115 |
+
store = session_store(flow)
|
| 116 |
+
if store.model is None:
|
| 117 |
raise gr.Error("Load a model first.")
|
| 118 |
if fresh:
|
| 119 |
clear(flow)
|
|
|
|
| 121 |
count=count, watch=watch, delay=delay, memory=memory,
|
| 122 |
auto_continue=auto_continue, attention=attention,
|
| 123 |
attention_layer=attention_layer, attention_head=attention_head)
|
| 124 |
+
flow.continue_automatically = False
|
| 125 |
flow.stop.clear()
|
| 126 |
flow.paused = False
|
| 127 |
panel = EMPTY
|
| 128 |
started = time.monotonic()
|
| 129 |
before = len(flow.tokens)
|
| 130 |
+
last_text = store.tokenizer.decode(flow.tokens, skip_special_tokens=True,
|
| 131 |
clean_up_tokenization_spaces=False)
|
| 132 |
trimmed = False
|
| 133 |
flow.running = True
|
| 134 |
try:
|
| 135 |
+
yield last_text, panel, "Generating…", frame(flow, session_store(flow), full=True)
|
| 136 |
+
for step in generate(store.model, store.tokenizer, flow, store.key,
|
| 137 |
count, temperature, top_p, penalty, seed, context_limit=memory,
|
| 138 |
+
live_settings=flow.controls, attention_modules=store.attention_modules):
|
| 139 |
last_text = step["text"]
|
| 140 |
trimmed = step["context_trimmed"]
|
| 141 |
controls = flow.controls()
|
| 142 |
watching = controls["watch"]
|
| 143 |
if watching:
|
| 144 |
+
panel = inspector(store.tokenizer, step, len(flow.tokens))
|
| 145 |
status = (f"{len(flow.tokens)} tokens · seed {flow.seed} · "
|
| 146 |
f"{(len(flow.tokens) - before) / max(.001, time.monotonic() - started):.1f} tokens/s"
|
| 147 |
f" · memory {step['context_limit']} tokens"
|
|
|
|
| 151 |
status += " · automatic continuation on"
|
| 152 |
if trimmed:
|
| 153 |
status += f" · Only the latest {step['context_limit']} tokens inform the next choice."
|
| 154 |
+
yield last_text, panel if watching else "", status, frame(flow, session_store(flow))
|
| 155 |
delay = flow.controls()["delay"]
|
| 156 |
if delay and flow.stop.wait(float(delay)):
|
| 157 |
break
|
| 158 |
+
if ZERO_GPU and (time.monotonic() - started >= 18 or len(flow.tokens) - before >= 256):
|
| 159 |
+
flow.continue_automatically = bool(flow.controls()["auto_continue"] and not flow.stop.is_set() and not flow.ended and len(flow.tokens) < 16384)
|
| 160 |
+
break
|
| 161 |
flow.running = False
|
| 162 |
if flow.ended:
|
| 163 |
reason = "The model emitted an end token. Start fresh to begin another stream."
|
|
|
|
| 172 |
if trimmed:
|
| 173 |
reason += " Earlier text remains visible but is outside the model’s context."
|
| 174 |
controls = flow.controls()
|
| 175 |
+
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, session_store(flow), full=True)
|
| 176 |
except Exception as error:
|
| 177 |
flow.running = False
|
| 178 |
# Preserve already-generated text and RNG state so a failed pass can be retried.
|
|
|
|
| 181 |
flow.running = False
|
| 182 |
|
| 183 |
|
| 184 |
+
@spaces.GPU(duration=30)
|
| 185 |
+
def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
|
| 186 |
+
auto_continue=True, attention=True, attention_layer=-1, attention_head=-1):
|
| 187 |
+
for update in _run(flow, temperature, top_p, penalty, seed, count, watch, delay,
|
| 188 |
+
memory, auto_continue, attention, attention_layer, attention_head):
|
| 189 |
+
yield (*update, flow)
|
| 190 |
+
|
| 191 |
+
@spaces.GPU(duration=30)
|
| 192 |
+
def begin(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
|
| 193 |
+
auto_continue=True, attention=True, attention_layer=-1, attention_head=-1):
|
| 194 |
+
for update in _run(flow, temperature, top_p, penalty, seed, count, watch, delay,
|
| 195 |
+
memory, auto_continue, attention, attention_layer, attention_head, fresh=True):
|
| 196 |
+
yield (*update, flow)
|
| 197 |
|
| 198 |
|
| 199 |
def export(flow):
|
|
|
|
| 207 |
|
| 208 |
|
| 209 |
def reset_view(flow):
|
| 210 |
+
return *clear(flow), frame(flow, session_store(flow))
|
| 211 |
|
| 212 |
|
| 213 |
def choose_model(flow):
|
| 214 |
flow.reset_requested = True
|
| 215 |
+
flow.continue_automatically = False
|
| 216 |
flow.paused = False
|
| 217 |
flow.stop.set()
|
| 218 |
return gr.update(visible=True), gr.update(visible=False)
|
|
|
|
| 220 |
|
| 221 |
def refresh_view(flow):
|
| 222 |
flow.running = False
|
| 223 |
+
return frame(flow, session_store(flow), full=True)
|
| 224 |
|
| 225 |
|
| 226 |
def build_app():
|
|
|
|
| 232 |
with gr.Column(elem_id="model-picker") as picker:
|
| 233 |
gr.HTML('<header><div class="eyebrow">AN EXPERIMENT IN AUTOMATIC WRITING</div>'
|
| 234 |
'<h1>Let it flow<span>.</span></h1><p>Choose a model. Enter its token space.</p></header>')
|
| 235 |
+
if ZERO_GPU:
|
| 236 |
+
gr.LoginButton()
|
| 237 |
+
gr.Markdown("Sign in to use your Hugging Face ZeroGPU quota. Generation uses short GPU sessions; Pause releases the GPU.")
|
| 238 |
+
repo = gr.Dropdown(PRESETS, value=PRESETS[0], allow_custom_value=not ZERO_GPU,
|
| 239 |
label="Public model repository or Hugging Face URL")
|
| 240 |
model_note = gr.Textbox(value=MODEL_LABELS[PRESETS[0]], label="Model description", interactive=False)
|
| 241 |
repo.change(lambda value: MODEL_LABELS.get(value, "Custom public model repository or URL"),
|
| 242 |
[repo], model_note, queue=False, api_name="model_description")
|
| 243 |
load = gr.Button("Load model & enter space", variant="primary")
|
| 244 |
+
gr.Markdown("Small **base models** work best. Public safetensors models only; " +
|
| 245 |
+
("Preloaded models up to 8 GB; each visitor has a separate stream. " if ZERO_GPU else "2 GB download limit. One model is shared by visitors. ") +
|
| 246 |
"Loading includes preparing a fixed 3D embedding projection.")
|
| 247 |
gr.Markdown("Gemma 3 1B downloads about 2 GB and is slower on CPU. Qwen3 0.6B downloads "
|
| 248 |
"about 1.2–1.5 GB. Base models are the closest fit for prompt-free continuation. "
|
|
|
|
| 278 |
info="A fresh random seed is selected on every model load. Clear for a random seed on the next new stream.")
|
| 279 |
count = gr.Slider(1, 1024, value=256, step=1, label="Tokens per pass",
|
| 280 |
info="Used when automatic continuation is off.")
|
| 281 |
+
delay = gr.Slider(0, .5, value=0 if ZERO_GPU else .06, step=.02, label="Reading delay per token (seconds)")
|
| 282 |
with gr.Row():
|
| 283 |
new_stream = gr.Button("New stream", elem_id="generation-new")
|
| 284 |
halt = gr.Button("Stop", variant="stop")
|
|
|
|
| 311 |
load.click(load_model, [repo, flow], [model_status, *outputs, seed, picker, workspace], **common)
|
| 312 |
reset_model.click(choose_model, [flow], [picker, workspace], queue=False).then(
|
| 313 |
reset_view, [flow], outputs, api_name="reset_model_state", **common)
|
| 314 |
+
start.click(run, inputs, [*outputs, flow], api_name="run", **common).failure(
|
| 315 |
refresh_view, [flow], transport, queue=False)
|
| 316 |
+
new_stream.click(begin, inputs, [*outputs, flow], api_name="begin", **common).failure(
|
| 317 |
refresh_view, [flow], transport, queue=False)
|
| 318 |
halt.click(stop, [flow], transport, queue=False)
|
| 319 |
pause.click(pause_generation, [flow], [status, transport], queue=False)
|
engine.py
CHANGED
|
@@ -1,179 +1,235 @@
|
|
| 1 |
-
"""Prompt-free causal sampling. The inspector uses the actual sampled distribution."""
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
self.
|
| 15 |
-
self.
|
| 16 |
-
self.
|
| 17 |
-
self.
|
| 18 |
-
self.
|
| 19 |
-
self.
|
| 20 |
-
self.
|
| 21 |
-
self.
|
| 22 |
-
self.
|
| 23 |
-
self.
|
| 24 |
-
self.
|
| 25 |
-
self.
|
| 26 |
-
self.
|
| 27 |
-
self.
|
| 28 |
-
self.
|
| 29 |
-
self.
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
def
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
if
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 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 |
-
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prompt-free causal sampling. The inspector uses the actual sampled distribution."""
|
| 2 |
+
from gpu_runtime import manager
|
| 3 |
+
import secrets
|
| 4 |
+
import threading
|
| 5 |
+
import uuid
|
| 6 |
+
from contextlib import nullcontext
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Flow:
|
| 12 |
+
def __init__(self, tokens=None, text="", model_key="", seed=None, ended=False):
|
| 13 |
+
shared = manager()
|
| 14 |
+
self._shared = shared is not None
|
| 15 |
+
self._status = shared.dict() if shared else {}
|
| 16 |
+
self.selected_repo = ""
|
| 17 |
+
self.continue_automatically = False
|
| 18 |
+
self.tokens = list(tokens or [])
|
| 19 |
+
self.stream_id = uuid.uuid4().hex
|
| 20 |
+
self.space_history = []
|
| 21 |
+
self.attention_history = {}
|
| 22 |
+
self.paused = False
|
| 23 |
+
self.running = False
|
| 24 |
+
self.reset_requested = False
|
| 25 |
+
self.view_revision = 0
|
| 26 |
+
self.view_lock = threading.RLock()
|
| 27 |
+
self.text_snapshot_cache = None
|
| 28 |
+
self.text = text
|
| 29 |
+
self.model_key = model_key
|
| 30 |
+
self.seed = seed
|
| 31 |
+
self.rng_state = None
|
| 32 |
+
self.ended = ended
|
| 33 |
+
self.stop = shared.Event() if shared else threading.Event()
|
| 34 |
+
self._control_lock = shared.RLock() if shared else threading.Lock()
|
| 35 |
+
self._controls = shared.dict() if shared else {}
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def paused(self):
|
| 39 |
+
return self._status.get("paused", False)
|
| 40 |
+
|
| 41 |
+
@paused.setter
|
| 42 |
+
def paused(self, value):
|
| 43 |
+
self._status["paused"] = value
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def running(self):
|
| 47 |
+
return self._status.get("running", False)
|
| 48 |
+
|
| 49 |
+
@running.setter
|
| 50 |
+
def running(self, value):
|
| 51 |
+
self._status["running"] = value
|
| 52 |
+
|
| 53 |
+
@property
|
| 54 |
+
def reset_requested(self):
|
| 55 |
+
return self._status.get("reset_requested", False)
|
| 56 |
+
|
| 57 |
+
@reset_requested.setter
|
| 58 |
+
def reset_requested(self, value):
|
| 59 |
+
self._status["reset_requested"] = value
|
| 60 |
+
|
| 61 |
+
@property
|
| 62 |
+
def continue_automatically(self):
|
| 63 |
+
return self._status.get("continue_automatically", False)
|
| 64 |
+
|
| 65 |
+
@continue_automatically.setter
|
| 66 |
+
def continue_automatically(self, value):
|
| 67 |
+
self._status["continue_automatically"] = value
|
| 68 |
+
|
| 69 |
+
def __getstate__(self):
|
| 70 |
+
state = self.__dict__.copy()
|
| 71 |
+
state.pop("view_lock", None)
|
| 72 |
+
if not self._shared:
|
| 73 |
+
state["_stopped"] = self.stop.is_set()
|
| 74 |
+
state.pop("stop", None)
|
| 75 |
+
state.pop("_control_lock", None)
|
| 76 |
+
return state
|
| 77 |
+
|
| 78 |
+
def __setstate__(self, state):
|
| 79 |
+
self.__dict__.update(state)
|
| 80 |
+
self.view_lock = threading.RLock()
|
| 81 |
+
if not self._shared:
|
| 82 |
+
self.stop = threading.Event()
|
| 83 |
+
if self.__dict__.pop("_stopped", False):
|
| 84 |
+
self.stop.set()
|
| 85 |
+
self._control_lock = threading.Lock()
|
| 86 |
+
|
| 87 |
+
def update_controls(self, **changes):
|
| 88 |
+
bounds = {"temperature": (.05, 2), "top_p": (.05, 1), "penalty": (1, 2),
|
| 89 |
+
"memory": (16, 2048), "count": (1, 1024), "delay": (0, .5)}
|
| 90 |
+
for name, value in changes.items():
|
| 91 |
+
if name in ("watch", "auto_continue", "attention"):
|
| 92 |
+
if not isinstance(value, bool):
|
| 93 |
+
raise ValueError("Watch must be true or false.")
|
| 94 |
+
elif name in ("attention_layer", "attention_head"):
|
| 95 |
+
if int(value) != value or value < -1:
|
| 96 |
+
raise ValueError(f"{name} must be -1 or a nonnegative integer.")
|
| 97 |
+
elif name not in bounds or not bounds[name][0] <= value <= bounds[name][1]:
|
| 98 |
+
raise ValueError(f"Invalid live setting: {name}.")
|
| 99 |
+
elif name in ("memory", "count") and int(value) != value:
|
| 100 |
+
raise ValueError(f"{name} must be an integer.")
|
| 101 |
+
with self._control_lock:
|
| 102 |
+
self._controls.update(changes)
|
| 103 |
+
|
| 104 |
+
def controls(self):
|
| 105 |
+
with self._control_lock:
|
| 106 |
+
return self._controls.copy()
|
| 107 |
+
|
| 108 |
+
def __deepcopy__(self, memo):
|
| 109 |
+
return Flow() # Gradio creates an independent state for each visitor.
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def distribution(logits, history, temperature, top_p, repetition_penalty):
|
| 113 |
+
"""Standard sign-aware repetition penalty, temperature, then nucleus filtering."""
|
| 114 |
+
if not 0.05 <= temperature <= 2 or not 0 < top_p <= 1 or not 1 <= repetition_penalty <= 2:
|
| 115 |
+
raise ValueError("Sampling settings are outside the supported range.")
|
| 116 |
+
scores = logits.detach().float().cpu().clone()
|
| 117 |
+
if history and repetition_penalty != 1:
|
| 118 |
+
ids = torch.tensor(sorted(set(history)), dtype=torch.long)
|
| 119 |
+
values = scores[ids]
|
| 120 |
+
scores[ids] = torch.where(values < 0, values * repetition_penalty, values / repetition_penalty)
|
| 121 |
+
scores /= temperature
|
| 122 |
+
raw = torch.softmax(scores, dim=-1)
|
| 123 |
+
ordered, indices = torch.sort(raw, descending=True)
|
| 124 |
+
# Keep the first token that crosses p, including the highest-probability token.
|
| 125 |
+
remove = ordered.cumsum(0) - ordered >= top_p
|
| 126 |
+
filtered = raw.clone()
|
| 127 |
+
filtered[indices[remove]] = 0
|
| 128 |
+
filtered /= filtered.sum()
|
| 129 |
+
if not torch.isfinite(filtered).all():
|
| 130 |
+
raise ValueError("The model returned invalid probabilities.")
|
| 131 |
+
return filtered, raw
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def start_id(model, tokenizer):
|
| 135 |
+
for value in (tokenizer.bos_token_id, model.config.bos_token_id,
|
| 136 |
+
tokenizer.eos_token_id, model.config.eos_token_id):
|
| 137 |
+
if value is not None:
|
| 138 |
+
return int(value[0] if isinstance(value, (tuple, list)) else value)
|
| 139 |
+
raise ValueError("This model has no BOS or EOS token. Prompt-free startup is unavailable.")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, seed,
|
| 143 |
+
context_limit=128, live_settings=None, attention_modules=None):
|
| 144 |
+
if int(context_limit) != context_limit or not 1 <= context_limit <= 2048:
|
| 145 |
+
raise ValueError("Memory span must be an integer from 1 to 2048 tokens.")
|
| 146 |
+
context_limit = int(context_limit)
|
| 147 |
+
if flow.model_key and flow.model_key != key:
|
| 148 |
+
raise ValueError("The loaded model changed. Choose Start fresh before continuing.")
|
| 149 |
+
if flow.ended:
|
| 150 |
+
raise ValueError("The model ended this stream. Choose Start fresh for another.")
|
| 151 |
+
fresh = not flow.model_key
|
| 152 |
+
if fresh:
|
| 153 |
+
if seed is not None and (int(seed) != seed or not 0 <= seed <= 2**32 - 1):
|
| 154 |
+
raise ValueError("Seed must be an integer from 0 to 4294967295, or blank.")
|
| 155 |
+
flow.seed = int(seed) if seed is not None else secrets.randbits(32)
|
| 156 |
+
flow.model_key = key
|
| 157 |
+
rng = torch.Generator(device="cpu")
|
| 158 |
+
if flow.rng_state is not None:
|
| 159 |
+
rng.set_state(flow.rng_state)
|
| 160 |
+
else:
|
| 161 |
+
rng.manual_seed(flow.seed)
|
| 162 |
+
prefix = [start_id(model, tokenizer)]
|
| 163 |
+
eos = model.generation_config.eos_token_id
|
| 164 |
+
eos_ids = set(eos if isinstance(eos, (list, tuple)) else [eos]) if eos is not None else set()
|
| 165 |
+
eos_ids.update([tokenizer.eos_token_id] if tokenizer.eos_token_id is not None else [])
|
| 166 |
+
limit = min(context_limit, int(getattr(model.config, "max_position_embeddings", context_limit)))
|
| 167 |
+
cache = None
|
| 168 |
+
consumed = 0
|
| 169 |
+
emitted = 0
|
| 170 |
+
with torch.inference_mode():
|
| 171 |
+
while True:
|
| 172 |
+
settings = live_settings() if live_settings is not None else {}
|
| 173 |
+
if not settings.get("auto_continue", False) and emitted >= int(settings.get("count", count)):
|
| 174 |
+
break
|
| 175 |
+
next_limit = min(int(settings.get("memory", context_limit)),
|
| 176 |
+
int(getattr(model.config, "max_position_embeddings", context_limit)))
|
| 177 |
+
if next_limit != limit:
|
| 178 |
+
cache = None # Old cached activations must not leak forgotten context.
|
| 179 |
+
limit = next_limit
|
| 180 |
+
current_temperature = settings.get("temperature", temperature)
|
| 181 |
+
current_top_p = settings.get("top_p", top_p)
|
| 182 |
+
current_penalty = settings.get("penalty", penalty)
|
| 183 |
+
if flow.stop.is_set():
|
| 184 |
+
break
|
| 185 |
+
if len(flow.tokens) >= 16384:
|
| 186 |
+
break
|
| 187 |
+
all_ids = prefix + flow.tokens
|
| 188 |
+
window = all_ids[-limit:]
|
| 189 |
+
if cache is None or consumed >= limit:
|
| 190 |
+
cache = None
|
| 191 |
+
input_ids = torch.tensor([window], device=model.device)
|
| 192 |
+
consumed = len(window)
|
| 193 |
+
else:
|
| 194 |
+
input_ids = torch.tensor([[flow.tokens[-1]]], device=model.device)
|
| 195 |
+
consumed += 1
|
| 196 |
+
probe = None
|
| 197 |
+
if settings.get("attention", False):
|
| 198 |
+
from attention_view import AttentionProbe
|
| 199 |
+
probe = AttentionProbe(attention_modules or [], settings.get("attention_layer", -1),
|
| 200 |
+
settings.get("attention_head", -1))
|
| 201 |
+
with probe if probe is not None else nullcontext():
|
| 202 |
+
result = model(input_ids=input_ids, past_key_values=cache, use_cache=True)
|
| 203 |
+
if probe is not None and flow.tokens:
|
| 204 |
+
query = len(flow.tokens) - 1
|
| 205 |
+
flow.attention_history[query] = probe.record(len(all_ids) - len(probe.row), query)
|
| 206 |
+
for link in flow.attention_history[query]["links"]:
|
| 207 |
+
link["id"] = all_ids[link["n"] + 1]
|
| 208 |
+
flow.attention_history = {i: row for i, row in flow.attention_history.items() if i >= query - 511}
|
| 209 |
+
cache = result.past_key_values
|
| 210 |
+
probs, before_nucleus = distribution(result.logits[0, -1], window,
|
| 211 |
+
current_temperature, current_top_p, current_penalty)
|
| 212 |
+
chosen = int(torch.multinomial(probs, 1, generator=rng))
|
| 213 |
+
flow.tokens.append(chosen)
|
| 214 |
+
emitted += 1
|
| 215 |
+
flow.rng_state = rng.get_state()
|
| 216 |
+
flow.ended = chosen in eos_ids
|
| 217 |
+
flow.text = tokenizer.decode(flow.tokens, skip_special_tokens=True,
|
| 218 |
+
clean_up_tokenization_spaces=False)
|
| 219 |
+
values, ids = torch.topk(probs, min(8, len(probs)))
|
| 220 |
+
candidates = [(int(i), float(p)) for i, p in zip(ids, values) if p > 0]
|
| 221 |
+
if chosen not in [i for i, _ in candidates]:
|
| 222 |
+
candidates.append((chosen, float(probs[chosen])))
|
| 223 |
+
yield {
|
| 224 |
+
"text": flow.text,
|
| 225 |
+
"candidates": candidates, "chosen": chosen,
|
| 226 |
+
"chosen_probability": float(probs[chosen]),
|
| 227 |
+
"retained_mass": float(before_nucleus[probs > 0].sum()),
|
| 228 |
+
"other": max(0., 1. - sum(p for _, p in candidates)),
|
| 229 |
+
"context_trimmed": len(all_ids) > limit,
|
| 230 |
+
"context_limit": limit,
|
| 231 |
+
"temperature": current_temperature, "top_p": current_top_p,
|
| 232 |
+
"penalty": current_penalty,
|
| 233 |
+
}
|
| 234 |
+
if flow.ended:
|
| 235 |
+
break
|
gpu_runtime.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ZeroGPU setup must precede model and CUDA imports."""
|
| 2 |
+
import spaces
|
| 3 |
+
import os
|
| 4 |
+
import multiprocessing
|
| 5 |
+
ZERO_GPU = os.environ.get("SPACES_ZERO_GPU", "").lower() in ("1", "true")
|
| 6 |
+
_MANAGER = multiprocessing.get_context("fork").Manager() if ZERO_GPU else None
|
| 7 |
+
|
| 8 |
+
def manager():
|
| 9 |
+
return _MANAGER
|
models.py
CHANGED
|
@@ -1,105 +1,109 @@
|
|
| 1 |
-
"""Public Hub model loading with pinned downloads and bounded resource use."""
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
from huggingface_hub
|
| 10 |
-
import
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
"HuggingFaceTB/SmolLM2-
|
| 17 |
-
"
|
| 18 |
-
"
|
| 19 |
-
"Qwen/Qwen3-0.6B": "Qwen3 0.6B /
|
| 20 |
-
"Qwen/
|
| 21 |
-
"
|
| 22 |
-
"unsloth/gemma-3-1b-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
if
|
| 37 |
-
raise ValueError("
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
self.
|
| 49 |
-
self.
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
if any(f.
|
| 64 |
-
raise ValueError("
|
| 65 |
-
|
| 66 |
-
if size
|
| 67 |
-
raise ValueError(
|
| 68 |
-
|
| 69 |
-
if
|
| 70 |
-
raise ValueError("
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
self.
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
self.
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public Hub model loading with pinned downloads and bounded resource use."""
|
| 2 |
+
from gpu_runtime import ZERO_GPU
|
| 3 |
+
import gc
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import shutil
|
| 7 |
+
from urllib.parse import urlsplit
|
| 8 |
+
|
| 9 |
+
from huggingface_hub import HfApi, snapshot_download
|
| 10 |
+
from huggingface_hub.utils import validate_repo_id
|
| 11 |
+
import torch
|
| 12 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 13 |
+
|
| 14 |
+
CACHE = Path(__file__).parent / ".model-cache"
|
| 15 |
+
MODEL_LABELS = {
|
| 16 |
+
"HuggingFaceTB/SmolLM2-135M": "SmolLM2 135M / base / quick CPU start",
|
| 17 |
+
"HuggingFaceTB/SmolLM2-360M": "SmolLM2 360M / base",
|
| 18 |
+
"openai-community/gpt2": "GPT-2 / classic base model",
|
| 19 |
+
"Qwen/Qwen3-0.6B-Base": "Qwen3 0.6B / base / multilingual",
|
| 20 |
+
"Qwen/Qwen3-0.6B": "Qwen3 0.6B / instruction tuned / Token Visualiser option",
|
| 21 |
+
"Qwen/Qwen2.5-0.5B": "Qwen2.5 0.5B / base / multilingual",
|
| 22 |
+
"unsloth/gemma-3-1b-pt": "Gemma 3 1B / base / larger CPU model",
|
| 23 |
+
"unsloth/gemma-3-1b-it": "Gemma 3 1B / instruction tuned / safetensors",
|
| 24 |
+
}
|
| 25 |
+
if ZERO_GPU:
|
| 26 |
+
MODEL_LABELS["openai-community/gpt2-xl"] = "GPT-2 XL / 1.5B / larger prose base model"
|
| 27 |
+
PRESETS = list(MODEL_LABELS)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def repository(value):
|
| 31 |
+
value = value.strip()
|
| 32 |
+
# Accept labels from older/cached dropdown UIs as well as canonical IDs.
|
| 33 |
+
value = {label: repo for repo, label in MODEL_LABELS.items()}.get(value, value)
|
| 34 |
+
if "://" in value:
|
| 35 |
+
url = urlsplit(value)
|
| 36 |
+
if url.scheme != "https" or url.netloc != "huggingface.co":
|
| 37 |
+
raise ValueError("Enter a Hugging Face model repository URL or owner/model.")
|
| 38 |
+
parts = url.path.strip("/").split("/")
|
| 39 |
+
if parts[0] in ("spaces", "datasets") or len(parts) != 2:
|
| 40 |
+
raise ValueError("Use the model's main repository URL, without a file path.")
|
| 41 |
+
value = "/".join(parts)
|
| 42 |
+
validate_repo_id(value)
|
| 43 |
+
return value
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class ModelStore:
|
| 47 |
+
def __init__(self):
|
| 48 |
+
self.model = self.tokenizer = None
|
| 49 |
+
self.key = ""
|
| 50 |
+
self.projection = None
|
| 51 |
+
self.attention_modules = []
|
| 52 |
+
self.description = "No model loaded."
|
| 53 |
+
|
| 54 |
+
def load(self, value):
|
| 55 |
+
repo = repository(value)
|
| 56 |
+
info = HfApi().model_info(repo, files_metadata=True, token=False)
|
| 57 |
+
if info.private or info.gated:
|
| 58 |
+
raise ValueError("This version supports public, ungated models.")
|
| 59 |
+
patterns = ["*.json", "*.safetensors", "*.model", "*.txt", "*.tiktoken"]
|
| 60 |
+
import fnmatch
|
| 61 |
+
files = [f for f in info.siblings if any(fnmatch.fnmatch(f.rfilename, p) for p in patterns)
|
| 62 |
+
and "/" not in f.rfilename]
|
| 63 |
+
if not any(f.rfilename.endswith(".safetensors") for f in files):
|
| 64 |
+
raise ValueError("Choose a model with safetensors weights. GGUF is not supported yet.")
|
| 65 |
+
size = sum(f.size or 0 for f in files)
|
| 66 |
+
if any(f.size is None for f in files):
|
| 67 |
+
raise ValueError("Cannot determine the model download size.")
|
| 68 |
+
max_bytes = float(os.environ.get("FLOW_MAX_DOWNLOAD_GB", "8" if ZERO_GPU else "2")) * 1024**3
|
| 69 |
+
if size > max_bytes:
|
| 70 |
+
raise ValueError(f"Download is {size / 1024**3:.2f} GB; the limit is {max_bytes / 1024**3:g} GB.")
|
| 71 |
+
CACHE.mkdir(exist_ok=True)
|
| 72 |
+
if shutil.disk_usage(CACHE).free < size + 1024**3:
|
| 73 |
+
raise ValueError("Insufficient disk space; leave at least 1 GB free after download.")
|
| 74 |
+
config = AutoConfig.from_pretrained(repo, revision=info.sha, token=False,
|
| 75 |
+
trust_remote_code=False, cache_dir=CACHE)
|
| 76 |
+
if getattr(config, "is_encoder_decoder", False):
|
| 77 |
+
raise ValueError("Choose a decoder-only text-generation model.")
|
| 78 |
+
# Release the previous model before allocating the next one.
|
| 79 |
+
self.model = self.tokenizer = None
|
| 80 |
+
self.projection = None
|
| 81 |
+
self.attention_modules = []
|
| 82 |
+
self.key = ""
|
| 83 |
+
gc.collect()
|
| 84 |
+
if torch.cuda.is_available():
|
| 85 |
+
torch.cuda.empty_cache()
|
| 86 |
+
path = snapshot_download(repo, revision=info.sha, token=False, cache_dir=CACHE,
|
| 87 |
+
allow_patterns=[f.rfilename for f in files])
|
| 88 |
+
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=False)
|
| 89 |
+
model = AutoModelForCausalLM.from_pretrained(path, config=config, use_safetensors=True,
|
| 90 |
+
trust_remote_code=False, torch_dtype=torch.float16 if ZERO_GPU else torch.float32,
|
| 91 |
+
attn_implementation="eager")
|
| 92 |
+
model.eval()
|
| 93 |
+
from engine import start_id
|
| 94 |
+
initial = start_id(model, tokenizer)
|
| 95 |
+
from token_space import TokenProjection
|
| 96 |
+
self.projection = TokenProjection(model.get_input_embeddings().weight)
|
| 97 |
+
if ZERO_GPU or torch.cuda.is_available():
|
| 98 |
+
model = model.to(device="cuda", dtype=torch.float16)
|
| 99 |
+
self.projection.weights = model.get_input_embeddings().weight
|
| 100 |
+
self.model, self.tokenizer = model, tokenizer
|
| 101 |
+
from attention_view import attention_modules
|
| 102 |
+
self.attention_modules = attention_modules(model)
|
| 103 |
+
self.key = f"{repo}@{info.sha}"
|
| 104 |
+
device = "GPU" if torch.cuda.is_available() else "CPU"
|
| 105 |
+
self.description = (f"{repo} · {info.sha[:8]} · {device} · "
|
| 106 |
+
f"{size / 1024**2:.0f} MB download · starting token ID {initial} · "
|
| 107 |
+
f"{len(self.attention_modules)} attention layers · "
|
| 108 |
+
f"{getattr(config, 'num_attention_heads', '?')} heads")
|
| 109 |
+
return self.description
|
requirements.txt
CHANGED
|
@@ -1,4 +1,7 @@
|
|
| 1 |
-
gradio==5.49.1
|
| 2 |
-
transformers==4.57.3
|
| 3 |
-
torch==2.
|
| 4 |
-
huggingface-hub==0.36.0
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.49.1
|
| 2 |
+
transformers==4.57.3
|
| 3 |
+
torch==2.8.0
|
| 4 |
+
huggingface-hub==0.36.0
|
| 5 |
+
|
| 6 |
+
spaces==0.52.0
|
| 7 |
+
authlib==1.6.5
|
token_space.js
CHANGED
|
@@ -171,6 +171,16 @@
|
|
| 171 |
const raw=node.getAttribute('data-flow-frame');if(raw===payload)return;
|
| 172 |
payload=raw;let data;try{data=JSON.parse(raw);}catch{return;}
|
| 173 |
running=Boolean(data.running);ended=Boolean(data.ended);togglePending=false;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
if(data.stream!==stream){stream=data.stream;seen=-1;history=[];selected=null;paused=false;textView=null;externalSelected=null;details();}
|
| 175 |
const now=Date.now(),existing=new Set(history.map(p=>p.n));
|
| 176 |
for(const p of data.points||[]){
|
|
|
|
| 171 |
const raw=node.getAttribute('data-flow-frame');if(raw===payload)return;
|
| 172 |
payload=raw;let data;try{data=JSON.parse(raw);}catch{return;}
|
| 173 |
running=Boolean(data.running);ended=Boolean(data.ended);togglePending=false;
|
| 174 |
+
if(data.continue_automatically&&!data.running&&!data.paused&&!data.ended){
|
| 175 |
+
const expectedStream=data.stream,expectedRevision=data.revision;
|
| 176 |
+
setTimeout(()=>{
|
| 177 |
+
if(stream===expectedStream && !running && !paused){
|
| 178 |
+
const host=document.querySelector('#generation-run');
|
| 179 |
+
const button=host?.matches?.('button')?host:host?.querySelector('button');
|
| 180 |
+
button?.click();
|
| 181 |
+
}
|
| 182 |
+
},700);
|
| 183 |
+
}
|
| 184 |
if(data.stream!==stream){stream=data.stream;seen=-1;history=[];selected=null;paused=false;textView=null;externalSelected=null;details();}
|
| 185 |
const now=Date.now(),existing=new Set(history.map(p=>p.n));
|
| 186 |
for(const p of data.points||[]){
|
token_space.py
CHANGED
|
@@ -1,128 +1,128 @@
|
|
| 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 |
-
|
| 55 |
-
def point(self, token_id):
|
| 56 |
-
return self.coords[token_id]
|
| 57 |
-
|
| 58 |
-
def relatives(self, token_id, previous):
|
| 59 |
-
"""Closest distinct earlier tokens, scored in the original embedding space."""
|
| 60 |
-
latest = {other_id: index for index, other_id in previous if other_id != token_id}
|
| 61 |
-
if not latest:
|
| 62 |
-
return []
|
| 63 |
-
ids = list(latest)
|
| 64 |
-
scores = torch.nn.functional.cosine_similarity(self.weights[ids], self.weights[token_id][None], dim=1)
|
| 65 |
-
results = []
|
| 66 |
-
for position in torch.argsort(scores, descending=True)[:3].tolist():
|
| 67 |
-
score = float(scores[position])
|
| 68 |
-
if torch.isfinite(scores[position]) and score > 0:
|
| 69 |
-
results.append({"n": latest[ids[position]], "score": round(score, 5)})
|
| 70 |
-
return results
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def frame(flow, store, full=False):
|
| 74 |
-
with flow.view_lock:
|
| 75 |
-
return _frame(flow, store, full)
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
def _frame(flow, store, full=False):
|
| 79 |
-
flow.view_revision += 1
|
| 80 |
-
tokens = flow.tokens.copy()
|
| 81 |
-
points = []
|
| 82 |
-
if store.projection is not None and flow.model_key == store.key:
|
| 83 |
-
first_new = flow.space_history[-1]["n"] + 1 if flow.space_history else 0
|
| 84 |
-
for index in range(first_new, len(tokens)):
|
| 85 |
-
token_id = tokens[index]
|
| 86 |
-
piece = store.tokenizer.decode([token_id], skip_special_tokens=False,
|
| 87 |
-
clean_up_tokenization_spaces=False)
|
| 88 |
-
previous = list(enumerate(tokens[max(0, index - 512):index], start=max(0, index - 512)))
|
| 89 |
-
links = store.projection.relatives(token_id, previous)
|
| 90 |
-
flow.space_history.append({"n": index, "id": token_id, "label": piece,
|
| 91 |
-
"xyz": store.projection.point(token_id), "links": links})
|
| 92 |
-
flow.space_history = flow.space_history[-512:]
|
| 93 |
-
for point in flow.space_history:
|
| 94 |
-
row = flow.attention_history.get(point["n"])
|
| 95 |
-
if row is not None:
|
| 96 |
-
point["attention"] = row
|
| 97 |
-
for link in point["attention"]["links"]:
|
| 98 |
-
if "id" in link and "xyz" not in link:
|
| 99 |
-
link["xyz"] = store.projection.point(link["id"])
|
| 100 |
-
link["label"] = ("[boundary]" if link["n"] == -1 else
|
| 101 |
-
store.tokenizer.decode([link["id"]], skip_special_tokens=False,
|
| 102 |
-
clean_up_tokenization_spaces=False))
|
| 103 |
-
points = flow.space_history[-512 if full else -48:]
|
| 104 |
-
data = {"stream": flow.stream_id, "revision": flow.view_revision, "paused": flow.paused, "running": flow.running,
|
| 105 |
-
"ended": flow.ended, "points": points}
|
| 106 |
-
if flow.paused and store.projection is not None and flow.model_key == store.key:
|
| 107 |
-
if flow.text_snapshot_cache is None or flow.text_snapshot_cache[0] != len(tokens):
|
| 108 |
-
flow.text_snapshot_cache = (len(tokens), text_snapshot(tokens, store.tokenizer, store.projection))
|
| 109 |
-
data["text_view"] = flow.text_snapshot_cache[1]
|
| 110 |
-
payload = json.dumps(data, ensure_ascii=True)
|
| 111 |
-
return '<div data-flow-frame="' + html.escape(payload, quote=True) + '"></div>'
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
SCENE = '''<div id="token-universe">
|
| 115 |
-
<canvas aria-label="Live 3D projection of generated token embeddings. Drag to orbit; scroll to zoom."></canvas>
|
| 116 |
-
<div class="space-top"><span class="space-brand">LET IT FLOW / TOKEN SPACE</span><span class="space-count">Waiting for tokens</span></div>
|
| 117 |
-
<div class="space-empty">A space for the next thought.<small>Press Begin. Tokens appear here, then fade.</small></div>
|
| 118 |
-
<div class="space-tools">
|
| 119 |
-
<label>View <select data-space-mode><option value="live">Live · fade after 6s</option><option value="history">History · last 512 tokens</option></select></label>
|
| 120 |
-
<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>
|
| 121 |
-
<button type="button" data-space-reset>Reset camera</button>
|
| 122 |
-
<button type="button" data-space-back disabled>Step back</button>
|
| 123 |
-
<button type="button" data-space-forward disabled>Step forward</button>
|
| 124 |
-
<span data-space-step>Live</span>
|
| 125 |
-
</div>
|
| 126 |
-
<div class="space-detail" aria-live="polite">Click a token to inspect its earlier neighbours.</div>
|
| 127 |
-
<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>
|
| 128 |
-
</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 |
+
|
| 55 |
+
def point(self, token_id):
|
| 56 |
+
return self.coords[token_id]
|
| 57 |
+
|
| 58 |
+
def relatives(self, token_id, previous):
|
| 59 |
+
"""Closest distinct earlier tokens, scored in the original embedding space."""
|
| 60 |
+
latest = {other_id: index for index, other_id in previous if other_id != token_id}
|
| 61 |
+
if not latest:
|
| 62 |
+
return []
|
| 63 |
+
ids = list(latest)
|
| 64 |
+
scores = torch.nn.functional.cosine_similarity(self.weights[ids].float(), self.weights[token_id][None].float(), dim=1)
|
| 65 |
+
results = []
|
| 66 |
+
for position in torch.argsort(scores, descending=True)[:3].tolist():
|
| 67 |
+
score = float(scores[position])
|
| 68 |
+
if torch.isfinite(scores[position]) and score > 0:
|
| 69 |
+
results.append({"n": latest[ids[position]], "score": round(score, 5)})
|
| 70 |
+
return results
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def frame(flow, store, full=False):
|
| 74 |
+
with flow.view_lock:
|
| 75 |
+
return _frame(flow, store, full)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _frame(flow, store, full=False):
|
| 79 |
+
flow.view_revision += 1
|
| 80 |
+
tokens = flow.tokens.copy()
|
| 81 |
+
points = []
|
| 82 |
+
if store.projection is not None and flow.model_key == store.key:
|
| 83 |
+
first_new = flow.space_history[-1]["n"] + 1 if flow.space_history else 0
|
| 84 |
+
for index in range(first_new, len(tokens)):
|
| 85 |
+
token_id = tokens[index]
|
| 86 |
+
piece = store.tokenizer.decode([token_id], skip_special_tokens=False,
|
| 87 |
+
clean_up_tokenization_spaces=False)
|
| 88 |
+
previous = list(enumerate(tokens[max(0, index - 512):index], start=max(0, index - 512)))
|
| 89 |
+
links = store.projection.relatives(token_id, previous)
|
| 90 |
+
flow.space_history.append({"n": index, "id": token_id, "label": piece,
|
| 91 |
+
"xyz": store.projection.point(token_id), "links": links})
|
| 92 |
+
flow.space_history = flow.space_history[-512:]
|
| 93 |
+
for point in flow.space_history:
|
| 94 |
+
row = flow.attention_history.get(point["n"])
|
| 95 |
+
if row is not None:
|
| 96 |
+
point["attention"] = row
|
| 97 |
+
for link in point["attention"]["links"]:
|
| 98 |
+
if "id" in link and "xyz" not in link:
|
| 99 |
+
link["xyz"] = store.projection.point(link["id"])
|
| 100 |
+
link["label"] = ("[boundary]" if link["n"] == -1 else
|
| 101 |
+
store.tokenizer.decode([link["id"]], skip_special_tokens=False,
|
| 102 |
+
clean_up_tokenization_spaces=False))
|
| 103 |
+
points = flow.space_history[-512 if full else -48:]
|
| 104 |
+
data = {"continue_automatically": flow.continue_automatically, "stream": flow.stream_id, "revision": flow.view_revision, "paused": flow.paused, "running": flow.running,
|
| 105 |
+
"ended": flow.ended, "points": points}
|
| 106 |
+
if flow.paused and store.projection is not None and flow.model_key == store.key:
|
| 107 |
+
if flow.text_snapshot_cache is None or flow.text_snapshot_cache[0] != len(tokens):
|
| 108 |
+
flow.text_snapshot_cache = (len(tokens), text_snapshot(tokens, store.tokenizer, store.projection))
|
| 109 |
+
data["text_view"] = flow.text_snapshot_cache[1]
|
| 110 |
+
payload = json.dumps(data, ensure_ascii=True)
|
| 111 |
+
return '<div data-flow-frame="' + html.escape(payload, quote=True) + '"></div>'
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
SCENE = '''<div id="token-universe">
|
| 115 |
+
<canvas aria-label="Live 3D projection of generated token embeddings. Drag to orbit; scroll to zoom."></canvas>
|
| 116 |
+
<div class="space-top"><span class="space-brand">LET IT FLOW / TOKEN SPACE</span><span class="space-count">Waiting for tokens</span></div>
|
| 117 |
+
<div class="space-empty">A space for the next thought.<small>Press Begin. Tokens appear here, then fade.</small></div>
|
| 118 |
+
<div class="space-tools">
|
| 119 |
+
<label>View <select data-space-mode><option value="live">Live · fade after 6s</option><option value="history">History · last 512 tokens</option></select></label>
|
| 120 |
+
<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>
|
| 121 |
+
<button type="button" data-space-reset>Reset camera</button>
|
| 122 |
+
<button type="button" data-space-back disabled>Step back</button>
|
| 123 |
+
<button type="button" data-space-forward disabled>Step forward</button>
|
| 124 |
+
<span data-space-step>Live</span>
|
| 125 |
+
</div>
|
| 126 |
+
<div class="space-detail" aria-live="polite">Click a token to inspect its earlier neighbours.</div>
|
| 127 |
+
<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>
|
| 128 |
+
</div>'''
|