jejunepixels commited on
Commit
17374eb
·
verified ·
1 Parent(s): ae55e6a

Fill the app viewport with token space and overlay text and expandable controls

Browse files
Files changed (4) hide show
  1. README.md +12 -2
  2. app.py +48 -54
  3. style.css +22 -0
  4. token_space.js +7 -1
README.md CHANGED
@@ -48,7 +48,10 @@ Extract the archive and upload its nine files to the root of your Gradio Space.
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.
@@ -77,7 +80,7 @@ causal influence. History labels are reduced for dense views; click to inspect.
77
  Retained history is bounded to 512 occurrences; the text retains the complete session.
78
  The viewer uses a perspective 3D projection rendered on a local canvas, with no
79
  external script or graphics-service dependency. Reduced-motion preferences disable
80
- idle camera rotation. The stream text below the canvas remains available to copy
81
  or export; probability details and secondary controls are in the lower accordion.
82
 
83
  ## Attention view
@@ -119,6 +122,13 @@ fading behavior. Pausing also works after a pass has completed.
119
 
120
  ## Controls
121
 
 
 
 
 
 
 
 
122
  **Automatically continue** is on by default. Generation keeps flowing past the
123
  pass limit without restarting the model cache or random sequence. Stop, an emitted
124
  end token, and the 16,384-token session limit still end the stream. Toggle it off
 
48
  ## Token space
49
 
50
  The opening screen shows only model selection. Successful loading hides the picker
51
+ and reveals a viewport-filling 3D token view. The full generated text is retained in a
52
+ scrollable, resizable top overlay. Start / Resume and Pause generation sit in a
53
+ bottom overlay dock. Expand Settings, model & attention for the remaining controls.
54
+ The overlay fills the app viewport, including when embedded in the Space page. **Change model**
55
  returns to the picker and requests Stop if generation is running.
56
 
57
  Each generated token appears at a fixed position derived from its input embedding.
 
80
  Retained history is bounded to 512 occurrences; the text retains the complete session.
81
  The viewer uses a perspective 3D projection rendered on a local canvas, with no
82
  external script or graphics-service dependency. Reduced-motion preferences disable
83
+ idle camera rotation. The full stream text in the top overlay remains available to copy
84
  or export; probability details and secondary controls are in the lower accordion.
85
 
86
  ## Attention view
 
122
 
123
  ## Controls
124
 
125
+ Each successful model load draws a fresh 32-bit random seed and replaces any
126
+ previous manual seed in the settings field. Start / Resume uses that seed for a
127
+ new stream; resuming preserves the existing RNG state. You can still enter a seed
128
+ manually, or clear the field to request a random seed on the next new stream.
129
+ New stream begins again with the selected seed; Clear stream clears the text.
130
+ The bottom Settings drawer is collapsed by default and scrolls when expanded.
131
+
132
  **Automatically continue** is on by default. Generation keeps flowing past the
133
  pass limit without restarting the model cache or random sequence. Stop, an emitted
134
  end token, and the 16,384-token session limit still end the stream. Toggle it off
app.py CHANGED
@@ -1,5 +1,6 @@
1
  """Let it flow — a prompt-free Hugging Face Space."""
2
  import html
 
3
  from pathlib import Path
4
  import time
5
 
@@ -55,7 +56,7 @@ def load_model(repo, flow):
55
  try:
56
  description = STORE.load(repo)
57
  text, panel, status = clear(flow)
58
- return description, text, panel, status, frame(flow, STORE), gr.update(visible=False), gr.update(visible=True)
59
  except Exception as error:
60
  raise gr.Error(f"Could not load model: {error}") from error
61
 
@@ -182,58 +183,51 @@ def build_app():
182
  "2 GB download limit. One model is shared by visitors. "
183
  "Loading includes preparing a fixed 3D embedding projection.")
184
  with gr.Column(visible=False, elem_id="flow-workspace") as workspace:
185
- with gr.Row(elem_id="workspace-top"):
186
- model_status = gr.Textbox(label="Loaded model", interactive=False, scale=8)
187
- change_model = gr.Button("Change model", scale=1, size="sm")
188
- with gr.Row(elem_id="sampling-controls"):
189
- temperature = gr.Slider(.05, 2, value=1.3, step=.05, label="Temperature")
190
- top_p = gr.Slider(.05, 1, value=1, step=.01, label="Top-p")
191
- penalty = gr.Slider(1, 2, value=1.1, step=.01, label="Repetition penalty")
192
- memory = gr.Slider(16, 2048, value=128, step=1, label="Memory span (tokens)")
193
- with gr.Row():
194
- attention = gr.Checkbox(label="Capture attention", value=True,
195
- info="Select Attention weights in Connections. Capturing can slow generation.")
196
- attention_layer = gr.Number(value=-1, precision=0, label="Attention layer",
197
- info="-1 = last layer; otherwise a layer index starting at 0.")
198
- attention_head = gr.Number(value=-1, precision=0, label="Attention head",
199
- info="-1 = average heads; otherwise a head index starting at 0.")
200
- with gr.Row(elem_id="stream-buttons"):
201
- start = gr.Button("Begin", variant="primary")
202
- resume = gr.Button("Resume generation")
203
- pause = gr.Button("Pause generation")
204
- halt = gr.Button("Stop", variant="stop")
205
- reset = gr.Button("Start fresh")
206
  gr.HTML(SCENE, elem_id="space-scene")
207
- page = gr.Textbox(label="The stream", lines=4, max_lines=6,
208
- placeholder="No written prompt. Just the next token.",
209
  interactive=False, show_copy_button=True, elem_id="page")
210
- status = gr.Textbox(label="Stream status", value="Press Begin to let it flow.", interactive=False)
211
- with gr.Accordion("More controls, probabilities & export", open=False):
212
- auto_continue = gr.Checkbox(label="Automatically continue", value=True,
213
- info="Flow until Stop, an end token, or 16,384 tokens.")
214
- with gr.Row():
215
- seed = gr.Number(value=None, precision=0, label="Random seed (optional)",
216
- info="Applies on Begin; Continue keeps the random sequence.")
217
- count = gr.Slider(1, 1024, value=256, step=1, label="Tokens per pass",
218
- info="Used when automatic continuation is off.")
219
- delay = gr.Slider(0, .5, value=.06, step=.02, label="Reading delay per token (seconds)")
220
- watch = gr.Checkbox(label="Watch the next token", value=True)
221
- panel = gr.HTML(EMPTY)
222
- with gr.Row():
223
- save = gr.Button("Prepare text download", size="sm")
224
- download = gr.File(label="Text export", interactive=False)
225
- gr.Markdown("Positions are a fixed PCA projection of the model's input token embeddings, "
226
- "fitted to up to 2,048 vocabulary samples. The same token returns to the same position. "
227
- "Axes have no named meaning, and projection loses information. "
228
- "Live mode fades tokens after six seconds, including while stopped. "
229
- "History keeps the last 512 tokens. Choose generation-order links or embedding-similarity links. "
230
- "Similarity scores use full-dimensional cosine similarity to up to three distinct earlier tokens "
231
- "within the preceding 512 occurrences; these are not causal attention links. "
232
- "Attention mode instead displays measured attention weights from the selected layer/head. "
233
- "It shows the last input token attending to its active context while predicting the following token. "
234
- "Only the eight largest weights are drawn, without renormalizing; boundary-token and self-attention "
235
- "can account for weight too. Click tokens to inspect. These weights are not a complete explanation of a prediction. "
236
- "Sliders apply live; no written prompt or chat template is added.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  transport = gr.HTML('', elem_id="space-transport", elem_classes=["space-transport"])
238
  outputs = [page, panel, status, transport]
239
  inputs = [flow, temperature, top_p, penalty, seed, count, watch, delay, memory, auto_continue,
@@ -246,10 +240,10 @@ def build_app():
246
  (attention_head, "attention_head")]:
247
  component.input(control_handler(name), [component, flow], [], queue=False,
248
  trigger_mode="always_last", api_name=f"update_{name}", show_progress="hidden")
249
- load.click(load_model, [repo, flow], [model_status, *outputs, picker, workspace], **common)
250
  change_model.click(choose_model, [flow], [picker, workspace], queue=False)
251
- start.click(begin, inputs, outputs, **common)
252
- resume.click(run, inputs, outputs, **common)
253
  halt.click(stop, [flow], transport, queue=False)
254
  pause.click(pause_generation, [flow], [status, transport], queue=False)
255
  reset.click(reset_view, [flow], outputs, api_name="clear", **common)
 
1
  """Let it flow — a prompt-free Hugging Face Space."""
2
  import html
3
+ import secrets
4
  from pathlib import Path
5
  import time
6
 
 
56
  try:
57
  description = STORE.load(repo)
58
  text, panel, status = clear(flow)
59
+ return description, text, panel, status, frame(flow, STORE), secrets.randbits(32), gr.update(visible=False), gr.update(visible=True)
60
  except Exception as error:
61
  raise gr.Error(f"Could not load model: {error}") from error
62
 
 
183
  "2 GB download limit. One model is shared by visitors. "
184
  "Loading includes preparing a fixed 3D embedding projection.")
185
  with gr.Column(visible=False, elem_id="flow-workspace") as workspace:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  gr.HTML(SCENE, elem_id="space-scene")
187
+ page = gr.Textbox(label="The stream", lines=5, max_lines=8,
188
+ placeholder="No written prompt. Just the next token.", show_label=False,
189
  interactive=False, show_copy_button=True, elem_id="page")
190
+ with gr.Column(elem_id="control-dock"):
191
+ with gr.Row(elem_id="stream-buttons"):
192
+ start = gr.Button("Start / Resume", variant="primary")
193
+ pause = gr.Button("Pause generation")
194
+ with gr.Accordion("Settings, model & attention", open=False, elem_id="settings-drawer"):
195
+ with gr.Row(elem_id="sampling-controls"):
196
+ temperature = gr.Slider(.05, 2, value=1.3, step=.05, label="Temperature")
197
+ top_p = gr.Slider(.05, 1, value=1, step=.01, label="Top-p")
198
+ penalty = gr.Slider(1, 2, value=1.1, step=.01, label="Repetition penalty")
199
+ memory = gr.Slider(16, 2048, value=128, step=1, label="Memory span (tokens)")
200
+ with gr.Row():
201
+ attention = gr.Checkbox(label="Capture attention", value=True,
202
+ info="Use Attention weights in Connections. Capture can slow generation.")
203
+ attention_layer = gr.Number(value=-1, precision=0, label="Attention layer",
204
+ info="-1 = last layer; otherwise a zero-based index.")
205
+ attention_head = gr.Number(value=-1, precision=0, label="Attention head",
206
+ info="-1 = average heads; otherwise a zero-based index.")
207
+ auto_continue = gr.Checkbox(label="Automatically continue", value=True,
208
+ info="Flow until Pause, Stop, an end token, or 16,384 tokens.")
209
+ with gr.Row():
210
+ seed = gr.Number(value=None, precision=0, label="Random seed",
211
+ info="A fresh random seed is selected on every model load. Clear for a random seed on the next new stream.")
212
+ count = gr.Slider(1, 1024, value=256, step=1, label="Tokens per pass",
213
+ info="Used when automatic continuation is off.")
214
+ delay = gr.Slider(0, .5, value=.06, step=.02, label="Reading delay per token (seconds)")
215
+ with gr.Row():
216
+ new_stream = gr.Button("New stream")
217
+ halt = gr.Button("Stop", variant="stop")
218
+ reset = gr.Button("Clear stream")
219
+ status = gr.Textbox(label="Stream status", value="Press Start to let it flow.", interactive=False)
220
+ model_status = gr.Textbox(label="Loaded model", interactive=False)
221
+ change_model = gr.Button("Change model", size="sm")
222
+ watch = gr.Checkbox(label="Watch the next token", value=True)
223
+ panel = gr.HTML(EMPTY)
224
+ with gr.Row():
225
+ save = gr.Button("Prepare text download", size="sm")
226
+ download = gr.File(label="Text export", interactive=False)
227
+ gr.Markdown("Drag to orbit, Shift-drag to pan, scroll to zoom. Pause to step through the last 512 tokens. "
228
+ "Positions are projected input embeddings. Attention arrows show measured weights from the "
229
+ "selected layer/head while predicting the following token; they are not a complete explanation. "
230
+ "Sliders apply live. The top overlay retains the full generated text; scroll it to read earlier passages.")
231
  transport = gr.HTML('', elem_id="space-transport", elem_classes=["space-transport"])
232
  outputs = [page, panel, status, transport]
233
  inputs = [flow, temperature, top_p, penalty, seed, count, watch, delay, memory, auto_continue,
 
240
  (attention_head, "attention_head")]:
241
  component.input(control_handler(name), [component, flow], [], queue=False,
242
  trigger_mode="always_last", api_name=f"update_{name}", show_progress="hidden")
243
+ load.click(load_model, [repo, flow], [model_status, *outputs, seed, picker, workspace], **common)
244
  change_model.click(choose_model, [flow], [picker, workspace], queue=False)
245
+ start.click(run, inputs, outputs, api_name="run", **common)
246
+ new_stream.click(begin, inputs, outputs, api_name="begin", **common)
247
  halt.click(stop, [flow], transport, queue=False)
248
  pause.click(pause_generation, [flow], [status, transport], queue=False)
249
  reset.click(reset_view, [flow], outputs, api_name="clear", **common)
style.css CHANGED
@@ -37,3 +37,25 @@ header p { font: 18px/1.6 Georgia, serif; color: #777; }
37
  .space-tools select,.space-tools button { border:1px solid #577f89; border-radius:7px; padding:6px 8px; background:#112530; color:#d6e9e9; cursor:pointer; font:inherit; }
38
  .space-detail { position:absolute; left:22px; bottom:44px; max-width:min(650px,85%); padding:8px 12px; border-radius:7px; background:#0a1726d9; color:#c4d8da; font:11px/1.5 system-ui,sans-serif; pointer-events:none; }
39
  @media(max-width:640px){ .space-tools{top:43px;left:12px;right:12px;gap:7px;font-size:10px;} .space-detail{left:12px;bottom:55px;font-size:10px;} .space-bottom{flex-wrap:wrap;} }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  .space-tools select,.space-tools button { border:1px solid #577f89; border-radius:7px; padding:6px 8px; background:#112530; color:#d6e9e9; cursor:pointer; font:inherit; }
38
  .space-detail { position:absolute; left:22px; bottom:44px; max-width:min(650px,85%); padding:8px 12px; border-radius:7px; background:#0a1726d9; color:#c4d8da; font:11px/1.5 system-ui,sans-serif; pointer-events:none; }
39
  @media(max-width:640px){ .space-tools{top:43px;left:12px;right:12px;gap:7px;font-size:10px;} .space-detail{left:12px;bottom:55px;font-size:10px;} .space-bottom{flex-wrap:wrap;} }
40
+ /* Loaded experience: a viewport-sized canvas with text and controls above it. */
41
+ .gradio-container { max-width:none !important; min-height:100dvh !important; }
42
+ #flow-workspace { position:fixed !important; inset:0 !important; width:100vw !important; height:100dvh !important; margin:0 !important; padding:0 !important; gap:0 !important; overflow:hidden !important; background:#080f18; z-index:50; }
43
+ #space-scene { position:absolute !important; inset:0 !important; width:100% !important; height:100% !important; z-index:0; }
44
+ #token-universe { width:100%; height:100% !important; border-radius:0 !important; }
45
+ #page { position:absolute !important; top:max(18px,env(safe-area-inset-top)); left:clamp(16px,4vw,72px); right:clamp(16px,4vw,72px); width:auto !important; z-index:2; padding:0 !important; border:1px solid #b4dad52b !important; border-radius:16px !important; background:linear-gradient(180deg,#091622ed,#091622b0) !important; backdrop-filter:blur(10px); box-shadow:0 10px 40px #0003; }
46
+ #page textarea { height:clamp(110px,22vh,240px) !important; min-height:110px !important; max-height:45vh !important; overflow-y:auto !important; resize:vertical !important; color:#e0eeeb !important; background:transparent !important; border:none !important; font:clamp(16px,1.5vw,21px)/1.7 Georgia,serif !important; padding:20px 24px !important; scrollbar-color:#668c8b #10232d; }
47
+ #page > div { background:transparent !important; }
48
+ #control-dock { position:absolute !important; bottom:max(16px,env(safe-area-inset-bottom)); left:50%; transform:translateX(-50%); width:min(940px,calc(100vw - 32px)) !important; max-height:65dvh; overflow-y:auto; z-index:4; padding:12px !important; border:1px solid #6d9f9b66; border-radius:18px; background:#eaf2eff2; backdrop-filter:blur(18px); box-shadow:0 12px 50px #0006; gap:8px !important; }
49
+ #stream-buttons { gap:10px !important; flex-wrap:nowrap !important; }
50
+ #stream-buttons button { min-height:44px; min-width:0 !important; }
51
+ #settings-drawer { border:0 !important; background:transparent !important; }
52
+ #sampling-controls { flex-wrap:wrap; }
53
+ #sampling-controls > div { min-width:180px !important; }
54
+ .space-top { top:auto !important; bottom:8px; left:18px; right:18px; font-size:9px; opacity:.5; }
55
+ .space-tools { top:auto !important; bottom:150px; left:24px; right:24px; justify-content:center; gap:10px; z-index:1; }
56
+ .space-detail { bottom:203px; left:24px; max-width:min(720px,calc(100vw - 48px)); z-index:1; }
57
+ .space-bottom { display:none !important; }
58
+ @media(max-width:640px) { #page { left:12px;right:12px;top:12px; } #page textarea { height:20vh !important; font-size:16px !important; padding:12px 16px !important; } #control-dock { bottom:12px;width:calc(100vw - 24px) !important;padding:8px !important;max-height:60dvh; } .space-tools { bottom:145px;left:12px;right:12px;font-size:10px;gap:6px; } .space-detail { bottom:228px;left:12px;max-width:calc(100vw - 24px);font-size:10px; } }
59
+ #token-universe { position:fixed !important; inset:0 !important; width:100vw !important; height:100dvh !important; }
60
+ #stream-buttons { position:sticky; top:0; z-index:6; background:#eaf2eff2; }
61
+ #control-dock { --body-text-color:#203c3a; --body-text-color-subdued:#526b68; --input-text-color:#1c3536; --input-background-fill:#fff; --block-background-fill:#f4f8f6; --block-label-text-color:#29433f; --block-info-text-color:#526b68; color:#203c3a; }
token_space.js CHANGED
@@ -5,6 +5,7 @@
5
  let dragging=false,panning=false,moved=false,lastX=0,lastY=0,width=0,height=0;
6
  let lastTime=Date.now(),mode='live',connections='attention';
7
  const lifetime=6000;
 
8
  let paused=false, previousMode='live';
9
  function sourcePoint(){
10
  const pinned=history.find(p=>p.n===selected);
@@ -186,7 +187,12 @@
186
  if(forward)forward.disabled=!paused||selected==null||selected>=history.at(-1)?.n;
187
  const stepText=paused?`Paused ? inspecting token #${selected==null?'?':selected+1}`:'Live';
188
  if(step&&step.textContent!==stepText)step.textContent=stepText;
189
- const text=document.querySelector('#page textarea');if(text&&document.activeElement!==text)text.scrollTop=text.scrollHeight;
 
 
 
 
 
190
  }
191
  observer=new MutationObserver(receive);
192
  observer.observe(document.body,{subtree:true,childList:true,attributes:true,attributeFilter:['data-flow-frame']});
 
5
  let dragging=false,panning=false,moved=false,lastX=0,lastY=0,width=0,height=0;
6
  let lastTime=Date.now(),mode='live',connections='attention';
7
  const lifetime=6000;
8
+ let lastText='';
9
  let paused=false, previousMode='live';
10
  function sourcePoint(){
11
  const pinned=history.find(p=>p.n===selected);
 
187
  if(forward)forward.disabled=!paused||selected==null||selected>=history.at(-1)?.n;
188
  const stepText=paused?`Paused ? inspecting token #${selected==null?'?':selected+1}`:'Live';
189
  if(step&&step.textContent!==stepText)step.textContent=stepText;
190
+ const text=document.querySelector('#page textarea');
191
+ if(text&&text.value!==lastText){
192
+ const following=lastText===''||text.scrollHeight-text.scrollTop-text.clientHeight<80;
193
+ if(following&&document.activeElement!==text)text.scrollTop=text.scrollHeight;
194
+ lastText=text.value;
195
+ }
196
  }
197
  observer=new MutationObserver(receive);
198
  observer.observe(document.body,{subtree:true,childList:true,attributes:true,attributeFilter:['data-flow-frame']});