Spaces:
Running on Zero
Running on Zero
|
Download README.md from jejunepixels/automatic-writing: direct link, hf CLI and curl.
- Browser
- Download file 21.7 kB
-
https://huggingface.co/spaces/jejunepixels/automatic-writing/resolve/main/README.md
- Command line
-
hf download hf://spaces/jejunepixels/automatic-writing/README.md
-
curl -L -o README.md https://huggingface.co/spaces/jejunepixels/automatic-writing/resolve/main/README.md
21.7 kB
| title: Automatic Writing | |
| emoji: ✍️ | |
| colorFrom: gray | |
| colorTo: yellow | |
| sdk: gradio | |
| sdk_version: 5.49.1 | |
| app_file: app.py | |
| pinned: false | |
| python_version: '3.12' | |
| short_description: Watch a language model write unprompted, token by token | |
| # Automatic Writing | |
| A prompt-free automatic-writing experiment. Load a public Hugging Face base model, | |
| press **Begin**, and watch it generate from a special beginning token alone. No | |
| written prompt, hidden literary instruction, or chat template is inserted. For | |
| models without BOS, EOS is used as the initial document boundary. The initial | |
| boundary is not displayed; generated special tokens are hidden in the prose but | |
| remain visible in the inspector and count toward the token total. | |
| ## Run locally | |
| Use Python 3.11–3.13. On Windows: | |
| ```powershell | |
| powershell -ExecutionPolicy Bypass -File .\start.ps1 | |
| ``` | |
| Open http://localhost:7860. The first model load requires internet access. | |
| Dependencies and weights stay in `.venv` and `.model-cache` respectively. | |
| CPU is supported; CUDA is used automatically when a compatible PyTorch build and | |
| GPU are available. Start with SmolLM2-135M; larger models can be slow on CPU. | |
| ## Hugging Face Space | |
| Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`, | |
| `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. | |
| The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost. | |
| `FLOW_HOST` and `PORT` can override these defaults. No API token is | |
| needed for the supported public, ungated models. Start with CPU Basic and a small | |
| model; hardware determines the practical model size. This project is prepared for | |
| Spaces but does not create or publish a remote Space automatically. | |
| Run `python scripts/prepare_space.py` to create `outputs/automatic-writing-space.zip`. | |
| Extract the archive and upload its sixteen files to the root of your Gradio Space. | |
| `brand.css`, `brand_theme.py` and `gpu_note.py` are shared with Automatic Drawing and | |
| Token Visualiser, so the Spaces keep the same start page and workspace. | |
| ## Token space | |
| The opening screen shows the overview and model selection, on the same | |
| midnight background as the token space. Successful loading hides the picker | |
| and reveals a viewport-filling 3D token view. The full generated text is retained in a | |
| scrollable, resizable top overlay. A combined Start / Pause / Resume button sits in a | |
| bottom overlay dock. Expand Settings, model & attention for the remaining controls. | |
| The overlay fills the app viewport, including when embedded in the Space page. The round | |
| ↺ button at the bottom right (**Change model**) requests Stop if generation is | |
| running and returns to the start page. | |
| Each generated token appears at a fixed position derived from its input embedding. | |
| A deterministic PCA is fitted to up to 2,048 evenly sampled vocabulary embeddings; | |
| all vocabulary tokens use that same centered projection and scale. These are | |
| stored token embeddings, not contextual activations or a map of thoughts. The | |
| three projected axes have no named semantic meaning and lose information. | |
| Drag to orbit, Shift-drag (or right-drag) to pan, and scroll to zoom from 0.15x | |
| to 40x. Double-click a token to focus the camera on it; double-click the background | |
| or use Reset camera to return to the overview. Click a token to inspect its ID, | |
| generation position, and earlier embedding neighbours. | |
| The View selector switches between Live (six-second fading trails) and History | |
| (the last 512 token occurrences, retained even after Stop). Fading uses an independent | |
| browser timer and wall-clock time; the renderer reconnects if the page replaces | |
| the canvas. Repeated token snapshots never reset their fade timestamps. | |
| Connections can show generation order (teal), embedding similarity (amber), or no | |
| lines. Each token links to up to three distinct earlier token IDs with the highest | |
| positive cosine similarity among the preceding 512 occurrences. Repeated IDs | |
| are excluded from similarity links and the latest earlier occurrence represents | |
| each ID. Similarity is computed in the full original embedding space, not from | |
| the 3D projection. These are stored embedding relationships, not attention or | |
| causal influence. History labels are reduced for dense views; click to inspect. | |
| Retained history is bounded to 512 occurrences; the text retains the complete session. | |
| The viewer uses a perspective 3D projection rendered on a local canvas, with no | |
| external script or graphics-service dependency. Reduced-motion preferences disable | |
| idle camera rotation. The full stream text in the top overlay remains available to copy | |
| or export; probability details and secondary controls are in the lower accordion. | |
| ## Attention view | |
| Capture attention is enabled by default. Choose Attention weights under Connections | |
| (the default), then Begin. Purple directed lines show the eight highest measured | |
| attention weights from the latest query token, or from a token you click in History. | |
| Thicker lines indicate larger weights. Self-attention is drawn as a loop. | |
| Click a token to see actual percentages, including any boundary-token weight. | |
| Top-eight values are not renormalized; the detail shows their total probability mass. | |
| Attention targets that have faded or fallen outside retained history reappear as faint context nodes, including the boundary token. Their weights are unchanged. Expired selections no longer block the latest attention row. | |
| Layer -1 selects the last attention layer; head -1 averages across heads. Otherwise | |
| use zero-based indices. Model status reports the layer/head counts. Changes apply | |
| while generating; stored historical rows retain the settings used when captured. | |
| A query's attention is captured while it predicts the following token, not from the | |
| new token before that new token has been fed through the model. The final generated | |
| token therefore has no attention row until generation continues. | |
| The model uses its eager attention implementation. A forward hook copies only the | |
| last query row from the selected layer, avoiding retention of all layers' complete | |
| attention matrices. This can be slower than optimized attention, especially with | |
| long memory. Capture may be disabled. Unsupported custom attention architectures | |
| can generate with capture disabled. Attention weights describe one operation in the | |
| network and are not a complete causal explanation or access to private reasoning. | |
| ## Clickable paused text | |
| While generation is paused, the top text overlay becomes a token-aware reader. | |
| Click a token occurrence to highlight it in the text, focus its position in 3D, | |
| and show its captured attention. Step back and Step forward stay synchronized with | |
| the text highlight. Resume restores the normal full-text overlay. Repeated token | |
| IDs remain separate occurrences. All generated tokens can be located in 3D from | |
| the text; only the last 512 token occurrences retain attention rows. | |
| The reader uses the tokenizer's streaming decoder to preserve the exact text. | |
| When several byte-level tokens jointly produce one Unicode character, clicking | |
| that text exposes individual token choices. For unsupported streaming decoders, | |
| the exact prose is retained with selectable token pieces below it. Model text is | |
| inserted using textContent, not interpreted as HTML. Clickable text does not change | |
| sampling, token IDs, the generated passage, or RNG state. | |
| ## Pause and token stepping | |
| Pause generation finishes the current inference step and stops sampling. It switches | |
| the viewer to a non-fading attention inspection mode. Step back and Step forward | |
| move through generated token occurrences. Only the last 512 occurrences retain attention; older tokens can still be located by their embeddings. The | |
| view hides future tokens relative to the selected query and shows that query's | |
| recorded attention, including faint older targets. Rows that were not captured | |
| are labelled as unavailable; the final token has no row until it predicts another. | |
| Stepping does not generate text, delete tokens, change the random state, or recompute | |
| attention with different layer/head settings. Resume generation continues the same | |
| text and RNG sequence and restores the prior viewer mode. Stop keeps its normal | |
| fading behavior. Pausing also works after a pass has completed. | |
| ## Model presets | |
| Eight presets are available: SmolLM2 135M and 360M, GPT-2, Qwen3 0.6B Base, | |
| Qwen3 0.6B instruction tuned, Qwen2.5 0.5B Base, and Gemma 3 1B in base and | |
| instruction-tuned versions. These include the model families in Token Visualiser. | |
| Gemma uses public safetensors repositories (`unsloth/gemma-3-1b-pt` and | |
| `unsloth/gemma-3-1b-it`) instead of the Visualiser's GGUF file. Public repository | |
| metadata, download sizes, tokenizers, and attention-compatible model architectures | |
| were checked; full pretrained inference was smoke-tested with the default SmolLM2. | |
| The added model architectures were checked using reduced test configurations. | |
| Gemma downloads about 2 GB and is slower on CPU; the Qwen models download about | |
| 1?1.5 GB. Base models are labelled separately from instruction-tuned models. | |
| Custom public model repository IDs and main repository URLs remain supported. | |
| The dropdown sends canonical repository IDs; descriptions are shown separately. | |
| Older display labels are also resolved on the backend for cached browser pages. | |
| Prompt-free output is not restricted to prose: code and other learned document | |
| formats may emerge, and temperature controls randomness rather than genre. | |
| ## Controls | |
| The main button starts as Start, changes to Pause during generation, and becomes | |
| Resume after pausing. It waits for the current inference step before enabling | |
| Resume. After a model end token, Start begins a new stream. The round ↺ button at | |
| the bottom right returns to the start page immediately, stopping the | |
| current generation before clearing the session. The selected model remains in the | |
| shared process until another model is loaded; other visitors' sessions are not reset. | |
| Each successful model load draws a fresh 32-bit random seed and replaces any | |
| previous manual seed in the settings field. Start / Resume uses that seed for a | |
| new stream; resuming preserves the existing RNG state. You can still enter a seed | |
| manually, or clear the field to request a random seed on the next new stream. | |
| New stream begins again with the selected seed; Clear stream clears the text. | |
| The bottom Settings drawer is collapsed by default and scrolls when expanded. | |
| **Automatically continue** is on by default. Generation keeps flowing past the | |
| pass limit without restarting the model cache or random sequence. Stop, an emitted | |
| end token, and the 16,384-token session limit still end the stream. Toggle it off | |
| live to use Tokens per pass; if that limit has already been passed, generation | |
| stops after the current token. This removes manual continuation pauses; CPU and | |
| context-rebuilding delays can still occur. | |
| - **Begin:** replace the stream and initialize a new random sequence. | |
| - **Stop:** request cancellation; the current inference step completes first. | |
| - **Continue:** preserve generated token IDs and RNG state, including across a stop. | |
| - **Start fresh:** clear the page, then press Begin or Continue to start. | |
| - **Live sampling controls:** temperature, top-p, sign-aware repetition penalty, | |
| optional seed, memory span, tokens per pass, and a display delay. | |
| Defaults: temperature 1.3, top-p 1.0, repetition penalty 1.1, memory 128 tokens. | |
| Try 64 tokens for more drift; longer memory sustains a subject more easily. | |
| Sliders update the current stream without restarting it. Changes take effect | |
| from the next token after the server receives the update; an inference step | |
| already in progress finishes with its previous settings. The status shows the | |
| sampling settings actually used for the latest token. Pass length can be raised | |
| before the pass ends, or lowered to stop at the new limit. Reading delay updates | |
| for subsequent pauses. A seed applies only to a new stream. Results are reproducible | |
| for the same model revision, settings, hardware/software, and context boundaries; | |
| different hardware or pass boundaries may cause numerical differences. | |
| - **Watch the next token:** show the latest choice, the eight most probable | |
| candidates, and the selected token even if it falls outside those eight. It is | |
| a live snapshot, not a retained history. Toggle it during generation to show | |
| or hide the inspector on the next token. Spaces and newlines appear using quoted representations. | |
| - **Export:** prepare a UTF-8 text download, or copy directly from the page. | |
| ## What the probabilities mean | |
| Each step takes the model's logits, applies repetition penalty over the active | |
| context (including the initial boundary while present), then temperature. Top-p | |
| keeps the smallest leading set reaching the requested probability mass. The | |
| inspector shows the resulting **renormalized sampling distribution**, not the | |
| unmodified model probabilities. The selected token is sampled from exactly that | |
| distribution. Other tokens reports the probability mass outside the shown rows. | |
| No fabricated reasoning or token alternatives are used. The text is generated | |
| output, not evidence of consciousness or a view of private reasoning. | |
| ## Limits and shared hosting | |
| The public ZeroGPU Space preloads the curated catalog in half precision at startup. Each visitor selects a model independently; changing a selection does not replace another visitor's model. GPU generation is queued in short sessions, with state returned to Gradio after each token. Live controls and pause signals are shared safely with the GPU worker. Attention and text history stay with the visitor's session. | |
| In local CPU mode, one model is held in memory for the process. Loading and generation share a queue | |
| to avoid simultaneous model allocation. Loading another model affects all | |
| visitors; previous streams cannot continue under a different model revision. | |
| Text and random state are per browser session. Clear or copy/export your text | |
| before switching models. Browser refresh discards the session. | |
| Only public, ungated, decoder-only safetensors models supported by standard | |
| Transformers code are accepted. Remote model Python code is disabled. GGUF, | |
| custom-code architectures, and gated/private access are outside this version. | |
| Downloads are pinned to a resolved commit and cached. The default total download | |
| cap is 2 GB (`FLOW_MAX_DOWNLOAD_GB` can change it); this is not a RAM guarantee. | |
| Use compatible small models. Cached files persist until manually removed; ephemeral | |
| Space storage may be reset by a restart or rebuild. | |
| With automatic continuation off, a pass generates at most 1,024 tokens. Continue extends it up to 16,384 tokens per | |
| session. The context defaults to the most recent 128 tokens. The Memory span slider | |
| can select 16?2,048 tokens, bounded by the model's smaller advertised context limit. | |
| Memory changes apply while generating, including shrinking or expanding the active | |
| window. Expanding it can bring earlier visible text back into context. All earlier context and cached | |
| activations are excluded once they fall outside the selected window. When full, older text remains on screen but | |
| stops influencing generation. KV cache is rebuilt as needed when the window | |
| slides. This bounds memory but can slow long streams. An emitted end token ends | |
| the stream naturally; it is not suppressed to force more prose. | |
| ## Verification | |
| ```powershell | |
| .\.venv\Scripts\python.exe -m unittest discover -s tests -v | |
| ``` | |
| The automated tests cover real sampling math, seeded continuation, stopping, | |
| model boundaries, EOS, context rollover, and HTML escaping. A real-model smoke | |
| check can be run with `python scripts/smoke.py` after installing dependencies; | |
| it downloads SmolLM2-135M and checks prompt-free generation and continuation. | |
| With the server running, `python scripts/check_server.py` also exercises the | |
| Gradio API, including seeded replay, live slider/inspector updates while generation | |
| is running, stopping, exporting, and resetting a session. | |
| Frontend behavior checks: `node tests/check_token_space.cjs` (arrival, fading while paused, reset, orbit and zoom). | |
| ## Public ZeroGPU deployment | |
| 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. | |
| ## English-biased sampling | |
| English bias (default 2; 0 disables it) adds a soft token prior before temperature and top-p filtering. The prior uses wordfreq English word frequencies compared with eight other Latin-script languages, English subword fragments, and Unicode script information. Punctuation, digits, special tokens, and incomplete byte tokens remain neutral. No prompt or chat template is added. Shared words, names, and subword ambiguity mean English is not guaranteed. The next-token inspector displays the actual distribution after this adjustment. The slider applies live and persists across GPU chunks. wordfreq data attribution and licensing: https://github.com/rspeer/wordfreq/blob/master/NOTICE.md | |
| ## Coloured layer overlays | |
| The attention panel defaults to early, middle and final layers. All layers uses a continuous cyan/violet/amber palette; Selected layer/head preserves the original inspection controls. Each layer overlay averages its attention heads. Curves separate overlapping connections; thickness encodes raw attention weight. Hover a curve for its layer, target and weight. Legend buttons hide/show layers, Shift-click isolates one, and hover highlights one. The links-per-layer selector and minimum-weight filter affect the display only. | |
| During generation, all layer means are captured, keeping the eight strongest targets for each query in a compact 512-slot CPU tensor ring. Full attention matrices are not retained. Live transport sends the latest query; pausing sends retained layer records for token-by-token replay. Positions stay in the same embedding projection. Layer comparisons are measurements of attention, not explanations of all model computations. The chosen layer/head is also saved separately. | |
| ## Representations through layers | |
| Capture layer representations is optional and enabled initially for this experiment. Pause and select Layer representations in View. The layer slider shows the input to the first block, successive hidden states, and the final normalised output. Play layers interpolates between recorded positions; the selected-token trail joins the recorded stages. Attention, when available, follows the nearest displayed layer, averaged across heads. Input stage has no attention overlay. | |
| Only the last-position hidden states from the original generation calls are retained for capture. Each token trajectory belongs to the moment that occurrence was processed to predict the following token; the cloud is not a single full-context snapshot. The latest generated token has no trajectory until it is processed in another forward pass. Recording is bounded to the latest 128 processed token positions, plus the initial boundary when captured. | |
| Vectors are unit-normalised. One shared PCA basis and scale are fitted jointly across all stages of the first eight captured tokens, or fewer when a pass/pause ends early, then frozen for that stream. Calibration vectors are discarded after fitting; only the basis and 3D coordinates persist. This compares directions in a fixed compressed space, not semantic distance or importance. Input may include positional processing depending on architecture. Switching back to Live or History restores the original input-embedding view. No extra model calls, prompt tokens or random draws are introduced by layer playback. | |
| ## Experimental original-dimension axes | |
| All projected dimensions is off initially. Enable the checkbox above the connection panel for faint white guides, with opacity and origin options. Every original feature coordinate direction is transformed by the active PCA basis. A single common extent makes the guides visible while preserving their relative projected lengths. Axes may overlap or collapse when compressed into 3D; these are not attention links, model layers, semantic labels or individual learned parameters. Hover identifies a zero-based dimension index. | |
| 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. | |
| ## GPU allowance | |
| 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`). | |