jejunepixels commited on
Commit
a31b411
·
verified ·
1 Parent(s): 15639bf

Remove in-app sign-in; explain the GPU allowance on the intro page

Browse files
Files changed (5) hide show
  1. README.md +8 -9
  2. app.py +3 -15
  3. gpu_note.py +37 -0
  4. hf_login.py +0 -83
  5. style.css +1 -1
README.md CHANGED
@@ -8,7 +8,6 @@ sdk_version: 5.49.1
8
  app_file: app.py
9
  pinned: false
10
  python_version: '3.12'
11
- hf_oauth: true
12
  short_description: Watch a language model write unprompted, token by token
13
  ---
14
 
@@ -37,7 +36,7 @@ GPU are available. Start with SmolLM2-135M; larger models can be slow on CPU.
37
  ## Hugging Face Space
38
 
39
  Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,
40
- `brand.css`, `brand_theme.py`, `gpu_runtime.py`, `hf_login.py`, `english_bias.py`, `representations.py`, `projection_axes.py`, `token_space.py`, `token_space.js`, `attention_view.py`, `requirements.txt`, and this `README.md`. The README contains the Space metadata.
41
  The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost.
42
  `FLOW_HOST` and `PORT` can override these defaults. No API token is
43
  needed for the supported public, ungated models. Start with CPU Basic and a small
@@ -46,18 +45,18 @@ Spaces but does not create or publish a remote Space automatically.
46
 
47
  Run `python scripts/prepare_space.py` to create `outputs/automatic-writing-space.zip`.
48
  Extract the archive and upload its sixteen files to the root of your Gradio Space.
49
- `brand.css`, `brand_theme.py` and `hf_login.py` are shared with Automatic Drawing and
50
- Token Visualiser, so the three Spaces keep the same start page, workspace and sign-in.
51
 
52
  ## Token space
53
 
54
- The opening screen shows sign-in (on ZeroGPU) and model selection, on the same
55
  midnight background as the token space. Successful loading hides the picker
56
  and reveals a viewport-filling 3D token view. The full generated text is retained in a
57
  scrollable, resizable top overlay. A combined Start / Pause / Resume button sits in a
58
  bottom overlay dock. Expand Settings, model & attention for the remaining controls.
59
  The overlay fills the app viewport, including when embedded in the Space page. The round
60
- ↺ button at the bottom right (**Change model / sign in**) requests Stop if generation is
61
  running and returns to the start page.
62
 
63
  Each generated token appears at a fixed position derived from its input embedding.
@@ -262,7 +261,7 @@ Frontend behavior checks: `node tests/check_token_space.cjs` (arrival, fading wh
262
 
263
  ## Public ZeroGPU deployment
264
 
265
- 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.
266
 
267
  ## English-biased sampling
268
 
@@ -288,6 +287,6 @@ All projected dimensions is off initially. Enable the checkbox above the connect
288
 
289
  The default translates these directions to the PCA mean. Original vector origin instead uses the affine projection of the zero vector. In Layer representations, the basis belongs to the frozen, unit-normalised hidden-state projection, so axes stay fixed during layer playback. Embedding and representation geometry are sent only when first available or with full snapshots, rather than on every generated token. Controls are local to the visualisation and do not change generation.
290
 
291
- ## Sign-in and embedded browsers
292
 
293
- The start page has the only sign-in button, with a note that says whether you are signed in. On the direct app it opens the canonical hf.space OAuth route in the same tab. On the huggingface.co Space page the app runs in a sandboxed iframe that may open pop-ups but not navigate the whole tab, so sign-in opens the app in a new tab instead. Either way it returns to the direct app after login. This avoids doing the cookie-based OAuth round trip inside the huggingface.co iframe. Gradio's normal OAuth state validation, callback, expiry checks and logout remain in use. Query strings from the embedding page are not copied into the login URL. If a browser blocks all cookies, users still need to allow site cookies for sign-in to complete. The direct app URL is https://jejunepixels-automatic-writing.hf.space/.
 
8
  app_file: app.py
9
  pinned: false
10
  python_version: '3.12'
 
11
  short_description: Watch a language model write unprompted, token by token
12
  ---
13
 
 
36
  ## Hugging Face Space
37
 
38
  Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,
39
+ `brand.css`, `brand_theme.py`, `gpu_note.py`, `gpu_runtime.py`, `english_bias.py`, `representations.py`, `projection_axes.py`, `token_space.py`, `token_space.js`, `attention_view.py`, `requirements.txt`, and this `README.md`. The README contains the Space metadata.
40
  The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost.
41
  `FLOW_HOST` and `PORT` can override these defaults. No API token is
42
  needed for the supported public, ungated models. Start with CPU Basic and a small
 
45
 
46
  Run `python scripts/prepare_space.py` to create `outputs/automatic-writing-space.zip`.
47
  Extract the archive and upload its sixteen files to the root of your Gradio Space.
48
+ `brand.css`, `brand_theme.py` and `gpu_note.py` are shared with Automatic Drawing and
49
+ Token Visualiser, so the Spaces keep the same start page and workspace.
50
 
51
  ## Token space
52
 
53
+ The opening screen shows the overview and model selection, on the same
54
  midnight background as the token space. Successful loading hides the picker
55
  and reveals a viewport-filling 3D token view. The full generated text is retained in a
56
  scrollable, resizable top overlay. A combined Start / Pause / Resume button sits in a
57
  bottom overlay dock. Expand Settings, model & attention for the remaining controls.
58
  The overlay fills the app viewport, including when embedded in the Space page. The round
59
+ ↺ button at the bottom right (**Change model**) requests Stop if generation is
60
  running and returns to the start page.
61
 
62
  Each generated token appears at a fixed position derived from its input embedding.
 
261
 
262
  ## Public ZeroGPU deployment
263
 
264
+ No account is needed. On the Space page, signed-in huggingface.co visitors use their own ZeroGPU allowance; everyone else uses a short guest allowance. 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.
265
 
266
  ## English-biased sampling
267
 
 
287
 
288
  The default translates these directions to the PCA mean. Original vector origin instead uses the affine projection of the zero vector. In Layer representations, the basis belongs to the frozen, unit-normalised hidden-state projection, so axes stay fixed during layer playback. Embedding and representation geometry are sent only when first available or with full snapshots, rather than on every generated token. Controls are local to the visualisation and do not change generation.
289
 
290
+ ## GPU allowance
291
 
292
+ There is no sign-in button. ZeroGPU charges GPU time to the visitor's own daily allowance when they open the Space on huggingface.co while signed in there (the Space page passes their identity to the embedded app), and to a short guest allowance otherwise, including on the direct app URL https://jejunepixels-automatic-writing.hf.space/. The intro page shows the matching wording (`gpu_note.py`).
app.py CHANGED
@@ -10,7 +10,7 @@ import gradio as gr
10
  from engine import Flow, generate
11
  from models import ModelStore, PRESETS, MODEL_LABELS, repository
12
  from token_space import SCENE, frame
13
- from hf_login import TopLevelLoginButton, signin_status
14
  from brand_theme import brand_theme
15
 
16
  STORE = ModelStore()
@@ -263,25 +263,13 @@ def build_app():
263
  'through learned patterns, attention, and probabilistic sampling within a limited context window.</p></header>',
264
  padding=False)
265
  if ZERO_GPU:
266
- TopLevelLoginButton(elem_id="hf-login-picker")
267
- signin_status()
268
  # Labels describe each preset; the values sent are canonical repository IDs.
269
  repo = gr.Dropdown([(MODEL_LABELS[preset].replace(" / ", " · "), preset) for preset in PRESETS],
270
  value=PRESETS[0], allow_custom_value=not ZERO_GPU, label="Model",
271
  info=None if ZERO_GPU else "Or paste a public model repository ID or Hugging Face URL.")
272
  load = gr.Button("Load model & enter space", variant="primary", elem_id="load-model",
273
  elem_classes=["brand-primary"])
274
- gr.Markdown(elem_classes=["brand-note"], value=(
275
- "**What you will see:** tokens appear in a 3D space as the model writes, with the probabilities and "
276
- "attention behind each choice. Small **base models** work best. Loading includes preparing a fixed "
277
- "3D embedding projection. " +
278
- ("Models are preloaded in 16-bit precision (Gemma in BF16 to keep generation numerically stable), up to "
279
- "8 GB; each visitor has a separate stream. Generation uses short GPU sessions; Pause releases the GPU."
280
- if ZERO_GPU else
281
- "Public safetensors models only; 2 GB download limit. One model is shared by visitors. Gemma 3 1B "
282
- "downloads about 2 GB and is slower on CPU; Qwen3 0.6B downloads about 1.2–1.5 GB. GGUF files are not "
283
- "supported by this backend. Without a written prompt, output can be prose, code, lists, or other "
284
- "training-data patterns.")))
285
  with gr.Column(visible=False, elem_id="flow-workspace") as workspace:
286
  gr.HTML(SCENE, elem_id="space-scene")
287
  with gr.Column(elem_id="text-overlay"):
@@ -290,7 +278,7 @@ def build_app():
290
  placeholder="No written prompt. Just the next token.", show_label=False,
291
  interactive=False, show_copy_button=True, elem_id="page")
292
  # Round ↺ button, outside the dock: returns to the start page (model choice and sign-in).
293
- reset_model = gr.Button("Change model / sign in", elem_id="reset-model", elem_classes=["return-home"],
294
  size="sm", min_width=0)
295
  with gr.Column(elem_id="control-dock", elem_classes=["brand-dock"]):
296
  with gr.Row(elem_id="stream-buttons"):
 
10
  from engine import Flow, generate
11
  from models import ModelStore, PRESETS, MODEL_LABELS, repository
12
  from token_space import SCENE, frame
13
+ from gpu_note import gpu_note
14
  from brand_theme import brand_theme
15
 
16
  STORE = ModelStore()
 
263
  'through learned patterns, attention, and probabilistic sampling within a limited context window.</p></header>',
264
  padding=False)
265
  if ZERO_GPU:
266
+ gpu_note(demo, "Writing", "Automatic Writing", "jejunepixels/automatic-writing")
 
267
  # Labels describe each preset; the values sent are canonical repository IDs.
268
  repo = gr.Dropdown([(MODEL_LABELS[preset].replace(" / ", " · "), preset) for preset in PRESETS],
269
  value=PRESETS[0], allow_custom_value=not ZERO_GPU, label="Model",
270
  info=None if ZERO_GPU else "Or paste a public model repository ID or Hugging Face URL.")
271
  load = gr.Button("Load model & enter space", variant="primary", elem_id="load-model",
272
  elem_classes=["brand-primary"])
 
 
 
 
 
 
 
 
 
 
 
273
  with gr.Column(visible=False, elem_id="flow-workspace") as workspace:
274
  gr.HTML(SCENE, elem_id="space-scene")
275
  with gr.Column(elem_id="text-overlay"):
 
278
  placeholder="No written prompt. Just the next token.", show_label=False,
279
  interactive=False, show_copy_button=True, elem_id="page")
280
  # Round ↺ button, outside the dock: returns to the start page (model choice and sign-in).
281
+ reset_model = gr.Button("Change model", elem_id="reset-model", elem_classes=["return-home"],
282
  size="sm", min_width=0)
283
  with gr.Column(elem_id="control-dock", elem_classes=["brand-dock"]):
284
  with gr.Row(elem_id="stream-buttons"):
gpu_note.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GPU-allowance line for the ZeroGPU Spaces in this folder.
2
+
3
+ Canonical copy: shared-ui/gpu_note.py. Edit it there, then run
4
+ `python shared-ui/sync.py` to copy it into each project.
5
+
6
+ ZeroGPU charges GPU time to the visitor's own daily allowance when they open the
7
+ Space on huggingface.co while signed in there: the Space page passes their
8
+ identity to the embedded app. Everyone else uses a short guest allowance. The
9
+ apps need no sign-in of their own, so the intro page explains this instead.
10
+ """
11
+ import html
12
+
13
+ import gradio as gr
14
+
15
+ EMBEDDED = ("No account needed. {action} uses a little GPU time from a short daily guest allowance; "
16
+ "if you’re signed in to huggingface.co, your account’s larger allowance is used instead.")
17
+ DIRECT = ("No account needed. Here GPU time uses the short daily guest allowance; "
18
+ "{link} to use your account’s allowance.")
19
+
20
+ # Show the Space-page wording inside the huggingface.co frame, the own-address wording otherwise.
21
+ SHOW_FOR_CONTEXT = """() => {
22
+ const direct = window.self === window.top;
23
+ document.querySelectorAll('.gpu-note-embedded').forEach(el => { el.hidden = direct; });
24
+ document.querySelectorAll('.gpu-note-direct').forEach(el => { el.hidden = !direct; });
25
+ }"""
26
+
27
+
28
+ def gpu_note(demo, action, name, space_id):
29
+ """Add the line inside `demo`'s Blocks; `action` is e.g. "Each reply", `space_id` e.g. "owner/name"."""
30
+ url = f"https://huggingface.co/spaces/{space_id}"
31
+ link = f'<a href="{html.escape(url)}" target="_blank" rel="noopener"><strong>open {html.escape(name)} on Hugging Face</strong></a>'
32
+ note = gr.HTML(
33
+ f'<p class="signin-note gpu-note-embedded">{html.escape(EMBEDDED.format(action=action))}</p>'
34
+ f'<p class="signin-note gpu-note-direct" hidden>{DIRECT.format(link=link)}</p>',
35
+ padding=False, elem_classes=["gpu-note"])
36
+ demo.load(None, None, None, js=SHOW_FOR_CONTEXT)
37
+ return note
hf_login.py DELETED
@@ -1,83 +0,0 @@
1
- """Hugging Face sign-in shared by the Gradio Spaces in this folder.
2
-
3
- Canonical copy: shared-ui/hf_login.py. Edit it there, then run
4
- `python shared-ui/sync.py` to copy it into each project.
5
-
6
- The button opens the OAuth route of the Space's canonical *.hf.space origin:
7
- - on the direct app (top-level page), in the same tab;
8
- - on the huggingface.co Space page, in a new tab. That page embeds the app in a
9
- sandboxed iframe that may open pop-ups but may not navigate the whole tab.
10
- Either way the cookie-based round trip happens outside the iframe and returns
11
- to the direct app. Gradio's own OAuth state validation, callback, expiry checks
12
- and logout stay in use. Only basic profile identity is requested.
13
-
14
- signin_status() adds the note under the button, which says whether this
15
- visitor is signed in.
16
- """
17
- import html
18
- import json
19
- import os
20
- import re
21
-
22
- import gradio as gr
23
-
24
- HOST_PATTERN = re.compile(r"[a-z0-9][a-z0-9-]*\.hf\.space")
25
-
26
-
27
- def canonical_space_origin():
28
- """The Space's canonical https origin, or None when not running on Spaces."""
29
- host = os.environ.get("SPACE_HOST", "").split(",", 1)[0].strip().lower()
30
- if not host:
31
- return None
32
- if not HOST_PATTERN.fullmatch(host):
33
- raise ValueError("Expected the canonical hf.space hostname for OAuth.")
34
- return "https://" + host
35
-
36
-
37
- def login_redirect_js(default_value):
38
- # Outside Spaces (local runs) the page's own origin is used, which reaches
39
- # Gradio's local mocked sign-in.
40
- return """(buttonValue) => {
41
- const origin = ORIGIN || window.location.origin;
42
- const route = buttonValue === DEFAULT ? '/login/huggingface' : '/logout';
43
- const url = new URL(route, origin);
44
- url.searchParams.set('_target_url', '/');
45
- // Embedded on huggingface.co: the sandbox blocks navigating the whole tab, but allows pop-ups.
46
- if (window.self !== window.top) window.open(url.href, '_blank', 'noopener');
47
- else window.open(url.href, '_top');
48
- }""".replace("ORIGIN", json.dumps(canonical_space_origin())).replace("DEFAULT", json.dumps(default_value))
49
-
50
-
51
- class TopLevelLoginButton(gr.LoginButton):
52
- """Gradio's LoginButton as a normal button; signs in outside the huggingface.co iframe."""
53
-
54
- def get_block_name(self):
55
- return "button"
56
-
57
- def get_block_class(self):
58
- return "button"
59
-
60
- def activate(self):
61
- self.click(fn=None, inputs=[self], outputs=None, js=login_redirect_js(self.value))
62
- self.attach_load_event(self._check_login_status, None)
63
-
64
-
65
- def signin_status(quota=True):
66
- """Add the note under the sign-in button and keep it saying whether this visitor is signed in.
67
-
68
- Call it inside the Blocks, right after TopLevelLoginButton. On the huggingface.co
69
- Space page the embedded app may not see a sign-in made in another tab, so the
70
- signed-out wording says where sign-in continues.
71
- """
72
- uses = "Hugging Face ZeroGPU quota" if quota else "Hugging Face account"
73
- signed_out = (f"Not signed in. Sign in to use your {uses}. On the Space page, sign-in opens "
74
- "the app in its own tab, where you stay signed in.")
75
-
76
- def update(profile: gr.OAuthProfile | None):
77
- if profile is None:
78
- return signed_out
79
- return f"Signed in as **{html.escape(profile.username)}**." + (" GPU time uses your ZeroGPU quota." if quota else "")
80
-
81
- note = gr.Markdown(signed_out, elem_classes=["signin-note"])
82
- note.attach_load_event(update, None)
83
- return note
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
style.css CHANGED
@@ -75,7 +75,7 @@
75
  #text-overlay { position:absolute !important; top:max(18px,env(safe-area-inset-top)); left:clamp(16px,4vw,72px); right:clamp(16px,4vw,72px); width:auto !important; gap:7px !important; z-index:2; }
76
  #model-name { padding:0 24px !important; border:0 !important; min-height:18px !important; background:transparent !important; color:#c5e2dd; text-align:left; font:600 13px/1.5 system-ui,sans-serif; overflow-wrap:anywhere; }
77
  #page { position:relative !important; top:auto !important; left:auto !important; right:auto !important; width:100% !important; }
78
- #flow-workspace { --brand-return-label:"Change model / sign in"; }
79
  #control-dock { width:min(940px,calc(100vw - 120px)) !important; }
80
  @media(max-width:640px) { #text-overlay { top:12px;left:12px;right:12px;gap:5px !important; } #model-name { font-size:12px;padding:0 16px !important; } #control-dock { left:12px;transform:none;width:calc(100vw - 72px) !important; } }
81
 
 
75
  #text-overlay { position:absolute !important; top:max(18px,env(safe-area-inset-top)); left:clamp(16px,4vw,72px); right:clamp(16px,4vw,72px); width:auto !important; gap:7px !important; z-index:2; }
76
  #model-name { padding:0 24px !important; border:0 !important; min-height:18px !important; background:transparent !important; color:#c5e2dd; text-align:left; font:600 13px/1.5 system-ui,sans-serif; overflow-wrap:anywhere; }
77
  #page { position:relative !important; top:auto !important; left:auto !important; right:auto !important; width:100% !important; }
78
+ #flow-workspace { --brand-return-label:"Change model"; }
79
  #control-dock { width:min(940px,calc(100vw - 120px)) !important; }
80
  @media(max-width:640px) { #text-overlay { top:12px;left:12px;right:12px;gap:5px !important; } #model-name { font-size:12px;padding:0 16px !important; } #control-dock { left:12px;transform:none;width:calc(100vw - 72px) !important; } }
81