"""Automatic Writing — a prompt-free Hugging Face Space."""
from gpu_runtime import ZERO_GPU, spaces
import html
import secrets
from pathlib import Path
import time
import gradio as gr
from engine import Flow, generate
from models import ModelStore, PRESETS, MODEL_LABELS, repository
from token_space import SCENE, frame
from gpu_note import gpu_note
from brand_theme import brand_theme
STORE = ModelStore()
POOL = {}
if ZERO_GPU:
for model_id in PRESETS:
print(f"Preloading {model_id}", flush=True)
entry = ModelStore()
entry.load(model_id)
POOL[model_id] = entry
def session_store(flow):
return POOL.get(flow.selected_repo, STORE) if ZERO_GPU else STORE
def inspector(tokenizer, step, number):
rows = []
for token_id, probability in step["candidates"]:
piece = tokenizer.decode([token_id], skip_special_tokens=False,
clean_up_tokenization_spaces=False)
# repr makes spaces and linebreaks visible; escaping prevents generated HTML execution.
label = html.escape(repr(piece))
selected = token_id == step["chosen"]
rows.append(f'
'
f'
{label}'
f'{probability:.2%}{" · selected" if selected else ""}
'
f'
'
f'token {token_id}
')
return (f'
CHOICE {number}
'
'
What could come next?
Probabilities immediately before the latest token was selected.
'
+ "".join(rows) + f'
Other tokens: {step["other"]:.2%}
'
f'Top-p retained {step["retained_mass"]:.2%} of the distribution after '
'temperature, repetition penalty and English bias. Bars show probabilities renormalized over that set. '
'The selected token may be outside the eight leading candidates.
')
EMPTY = '
WATCH THE NEXT TOKEN
A field of possibilities.
Enable the inspector and begin. Each choice will show candidate tokens, their sampling probabilities, and the selected token.
'
def clear(flow):
import uuid
flow.stream_id = uuid.uuid4().hex
flow.tokens.clear()
flow.space_history.clear()
flow.attention_history.clear()
flow.layer_rows = flow.layer_keys = None
flow.layer_queries = [-1] * 512
flow.representations = None
flow.sent_dimension_axes_key = ""
flow.text_snapshot_cache = None
flow.continue_automatically = False
flow.pass_remaining = None
flow.paused = False
flow.running = False
flow.reset_requested = False
flow.text = ""
flow.model_key = ""
flow.seed = flow.rng_state = None
flow.ended = False
flow.stop.clear()
return "", EMPTY, "A blank page. Press Begin when you’re ready."
def load_model(repo, flow):
try:
if ZERO_GPU:
selected = repository(repo)
if selected not in POOL:
raise ValueError("Choose a preloaded model from the list.")
flow.selected_repo = selected
description = POOL[selected].description
else:
description = STORE.load(repo)
text, panel, status = clear(flow)
badge = "" + html.escape(repository(repo)) + ""
return description, text, panel, status, frame(flow, session_store(flow)), secrets.randbits(32), badge, gr.update(visible=False), gr.update(visible=True)
except Exception as error:
raise gr.Error(f"Could not load model: {error}") from error
def stop(flow):
flow.continue_automatically = False
flow.paused = False
flow.stop.set()
return frame(flow, session_store(flow), full=True)
def pause_generation(flow):
flow.continue_automatically = False
flow.paused = True
flow.stop.set()
return ("Pausing after the current token. Use Step back / Step forward in the 3D view, then Resume generation.",
frame(flow, session_store(flow), full=True))
def control_handler(name):
def update(value, flow):
try:
flow.update_controls(**{name: value})
except (ValueError, TypeError) as error:
raise gr.Error(str(error)) from error
return update
def _run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
auto_continue=True, attention=True, attention_layer=-1, attention_head=-1, fresh=False, english_bias=2, capture_representations=True):
if flow.reset_requested:
return
store = session_store(flow)
if store.model is None:
raise gr.Error("Load a model first.")
if fresh:
clear(flow)
if ZERO_GPU and flow.continue_automatically and not auto_continue:
count = getattr(flow, "pass_remaining", None) or count
flow.update_controls(temperature=temperature, top_p=top_p, penalty=penalty,
count=count, watch=watch, delay=delay, memory=memory,
auto_continue=auto_continue, attention=attention,
attention_layer=attention_layer, attention_head=attention_head, english_bias=english_bias,
capture_representations=capture_representations)
flow.continue_automatically = False
flow.stop.clear()
flow.paused = False
panel = EMPTY
started = time.monotonic()
before = len(flow.tokens)
last_text = store.tokenizer.decode(flow.tokens, skip_special_tokens=True,
clean_up_tokenization_spaces=False)
trimmed = False
flow.running = True
try:
yield last_text, panel, "Generating…", frame(flow, session_store(flow), full=True)
for step in generate(store.model, store.tokenizer, flow, store.key,
count, temperature, top_p, penalty, seed, context_limit=memory,
live_settings=flow.controls, attention_modules=store.attention_modules,
english_prior=store.english_prior):
last_text = step["text"]
trimmed = step["context_trimmed"]
controls = flow.controls()
watching = controls["watch"]
if watching:
panel = inspector(store.tokenizer, step, len(flow.tokens))
status = (f"{len(flow.tokens)} tokens · seed {flow.seed} · "
f"{(len(flow.tokens) - before) / max(.001, time.monotonic() - started):.1f} tokens/s"
f" · memory {step['context_limit']} tokens"
f" · temperature {step['temperature']:g} · top-p {step['top_p']:g}"
f" · repetition {step['penalty']:g}")
status += f" / English bias {step['english_bias']:g}"
if controls["auto_continue"]:
status += " · automatic continuation on"
if trimmed:
status += f" · Only the latest {step['context_limit']} tokens inform the next choice."
yield last_text, panel if watching else "", status, frame(flow, session_store(flow))
delay = flow.controls()["delay"]
if delay and flow.stop.wait(float(delay)):
break
if ZERO_GPU and (time.monotonic() - started >= 18 or len(flow.tokens) - before >= 256):
flow.pass_remaining = max(0, int(flow.controls()["count"]) - (len(flow.tokens) - before))
flow.continue_automatically = bool((flow.controls()["auto_continue"] or flow.pass_remaining) and not flow.stop.is_set() and not flow.ended and len(flow.tokens) < 16384)
break
if flow.representations is not None:
flow.representations.finalize()
flow.running = False
if ZERO_GPU:
import torch
print(f"GPU validation {flow.selected_repo}: {torch.cuda.get_device_name()} / peak allocated {torch.cuda.max_memory_allocated() / 1024**3:.2f} GiB", flush=True)
if flow.continue_automatically:
reason = "GPU session complete. Requesting the next GPU session automatically."
elif flow.ended:
reason = "The model emitted an end token. Start fresh to begin another stream."
elif len(flow.tokens) >= 16384:
reason = "Session limit of 16,384 tokens reached. Download your text and start fresh."
elif flow.paused:
reason = "Paused. Step back / Step forward inspect saved attention; Resume generation continues the same stream."
elif flow.stop.is_set():
reason = "Stopped. Continue preserves the text and random sequence."
else:
reason = "Pass complete. Continue to let it flow further."
if trimmed:
reason += " Earlier text remains visible but is outside the model’s context."
controls = flow.controls()
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)
except Exception as error:
flow.running = False
# Preserve already-generated text and RNG state so a failed pass can be retried.
raise gr.Error(str(error)) from error
finally:
flow.running = False
@spaces.GPU(duration=30)
def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
auto_continue=True, attention=True, attention_layer=-1, attention_head=-1, english_bias=2, capture_representations=True, automatic=False):
if automatic and (flow.paused or flow.reset_requested or not flow.continue_automatically):
return
for update in _run(flow, temperature, top_p, penalty, seed, count, watch, delay,
memory, auto_continue, attention, attention_layer, attention_head, english_bias=english_bias, capture_representations=capture_representations):
yield (*update, flow)
@spaces.GPU(duration=30)
def begin(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
auto_continue=True, attention=True, attention_layer=-1, attention_head=-1, english_bias=2, capture_representations=True):
for update in _run(flow, temperature, top_p, penalty, seed, count, watch, delay,
memory, auto_continue, attention, attention_layer, attention_head, fresh=True, english_bias=english_bias, capture_representations=capture_representations):
yield (*update, flow)
def export(flow):
if not flow.tokens:
raise gr.Error("Generate some text first.")
import tempfile
directory = Path(tempfile.mkdtemp(prefix="automatic-writing-"))
output = directory / "automatic-writing.txt"
output.write_text(flow.text, encoding="utf-8")
return str(output)
def reset_view(flow):
return *clear(flow), frame(flow, session_store(flow))
def choose_model(flow):
flow.reset_requested = True
flow.continue_automatically = False
flow.paused = False
flow.stop.set()
return gr.update(visible=True), gr.update(visible=False)
def refresh_view(flow):
flow.running = False
return frame(flow, session_store(flow), full=True)
def build_app():
# Shared look (brand.css, from shared-ui/) first, then this app's layout.
css = "".join(Path(__file__).with_name(name).read_text(encoding="utf-8") for name in ("brand.css", "style.css"))
js = Path(__file__).with_name("token_space.js").read_text(encoding="utf-8")
with gr.Blocks(title="Automatic Writing", css=css, js=js, theme=brand_theme(),
delete_cache=(3600, 3600)) as demo:
flow = gr.State(Flow())
with gr.Column(elem_id="model-picker", elem_classes=["brand-start"]) as picker:
gr.HTML('
AN EXPERIMENT IN MACHINE WRITING
'
'
Automatic Writing.
'
'
Inspired by the Surrealists\u2019 practice of automatic writing, this experiment lets language unfold without a written prompt. '
'A language model uses recent tokens to predict what could come next, then selects the next token by sampling from those probabilities. '
'A 3D view tracks attention weights from a selected layer and maps tokens through their embeddings.
'
'
The model has no unconscious mind to uncover. This demo offers a look under the hood of how large language models generate text '
'through learned patterns, attention, and probabilistic sampling within a limited context window.
',
padding=False)
if ZERO_GPU:
gpu_note(demo, "Writing", "Automatic Writing", "jejunepixels/automatic-writing")
# Labels describe each preset; the values sent are canonical repository IDs.
repo = gr.Dropdown([(MODEL_LABELS[preset].replace(" / ", " · "), preset) for preset in PRESETS],
value=PRESETS[0], allow_custom_value=not ZERO_GPU, label="Model",
info=None if ZERO_GPU else "Or paste a public model repository ID or Hugging Face URL.")
load = gr.Button("Load model & enter space", variant="primary", elem_id="load-model",
elem_classes=["brand-primary"])
with gr.Column(visible=False, elem_id="flow-workspace") as workspace:
gr.HTML(SCENE, elem_id="space-scene")
with gr.Column(elem_id="text-overlay"):
model_badge = gr.HTML('', elem_id="model-name", elem_classes=["brand-caption"])
page = gr.Textbox(label="The stream", lines=5, max_lines=8,
placeholder="No written prompt. Just the next token.", show_label=False,
interactive=False, show_copy_button=True, elem_id="page")
# Round ↺ button, outside the dock: returns to the start page (model choice and sign-in).
reset_model = gr.Button("Change model", elem_id="reset-model", elem_classes=["return-home"],
size="sm", min_width=0)
with gr.Column(elem_id="control-dock", elem_classes=["brand-dock"]):
with gr.Row(elem_id="stream-buttons"):
gr.HTML('',
elem_id="generation-toggle")
with gr.Accordion("Settings, model & attention", open=False, elem_id="settings-drawer"):
with gr.Row(elem_id="sampling-controls"):
temperature = gr.Slider(.05, 2, value=1.3, step=.05, label="Temperature")
top_p = gr.Slider(.05, 1, value=1, step=.01, label="Top-p")
penalty = gr.Slider(1, 2, value=1.1, step=.01, label="Repetition penalty")
memory = gr.Slider(16, 2048, value=128, step=1, label="Memory span (tokens)")
english_bias = gr.Slider(0, 4, value=2, step=.25, label="English bias",
info="Favour English without a prompt. 0 = off. Applies live; languages can still mix.")
with gr.Row():
attention = gr.Checkbox(label="Capture attention", value=True,
info="Record layer averages for the coloured overlay, plus the selected layer/head.")
attention_layer = gr.Number(value=-1, precision=0, label="Selected attention layer",
info="-1 = last layer; otherwise a zero-based index.")
attention_head = gr.Number(value=-1, precision=0, label="Selected attention head",
info="-1 = average heads; otherwise a zero-based index.")
capture_representations = gr.Checkbox(value=True, label="Capture layer representations",
info="Record up to 128 recent token trajectories. Pause, then choose Layer representations in View. Optional; disabling reduces overhead.")
auto_continue = gr.Checkbox(label="Automatically continue", value=True,
info="Flow until Pause, Stop, an end token, or 16,384 tokens.")
with gr.Row():
seed = gr.Number(value=None, precision=0, label="Random seed",
info="A fresh random seed is selected on every model load. Clear for a random seed on the next new stream.")
count = gr.Slider(1, 1024, value=256, step=1, label="Tokens per pass",
info="Used when automatic continuation is off.")
delay = gr.Slider(0, .5, value=0 if ZERO_GPU else .06, step=.02, label="Reading delay per token (seconds)")
with gr.Row():
new_stream = gr.Button("New stream", elem_id="generation-new")
halt = gr.Button("Stop", variant="stop")
reset = gr.Button("Clear stream")
status = gr.Textbox(label="Stream status", value="Press Start to let it flow.", interactive=False)
model_status = gr.Textbox(label="Loaded model", interactive=False)
watch = gr.Checkbox(label="Watch the next token", value=True)
panel = gr.HTML(EMPTY)
with gr.Row():
save = gr.Button("Prepare text download", size="sm")
download = gr.File(label="Text export", interactive=False)
gr.Markdown("Drag to orbit, Shift-drag to pan, scroll to zoom. Pause to step through the last 512 tokens. "
"Positions are projected input embeddings. Attention arrows show measured weights from the "
"selected layer/head while predicting the following token; they are not a complete explanation. "
"Sliders apply live. The top overlay retains the full generated text; scroll it to read earlier passages.")
transport = gr.HTML('', elem_id="space-transport", elem_classes=["space-transport"])
start = gr.Button("Start generation", elem_id="generation-run", elem_classes=["generation-proxy"])
automatic_start = gr.Button("Continue GPU session", elem_id="generation-auto", elem_classes=["generation-proxy"])
automatic_request = gr.State(True)
pause = gr.Button("Pause generation", elem_id="generation-pause", elem_classes=["generation-proxy"])
outputs = [page, panel, status, transport]
inputs = [flow, temperature, top_p, penalty, seed, count, watch, delay, memory, auto_continue,
attention, attention_layer, attention_head, english_bias, capture_representations]
common = dict(concurrency_id="model", concurrency_limit=1)
for component, name in [(temperature, "temperature"), (top_p, "top_p"),
(penalty, "penalty"), (memory, "memory"), (count, "count"),
(delay, "delay"), (watch, "watch"), (auto_continue, "auto_continue"),
(attention, "attention"), (attention_layer, "attention_layer"),
(attention_head, "attention_head"), (english_bias, "english_bias"),
(capture_representations, "capture_representations")]:
component.input(control_handler(name), [component, flow], [], queue=False,
trigger_mode="always_last", api_name=f"update_{name}", show_progress="hidden")
load.click(load_model, [repo, flow], [model_status, *outputs, seed, model_badge, picker, workspace], **common)
reset_model.click(choose_model, [flow], [picker, workspace], queue=False).then(
reset_view, [flow], outputs, api_name="reset_model_state", **common)
start.click(run, inputs, [*outputs, flow], api_name="run", **common).failure(
refresh_view, [flow], transport, queue=False)
automatic_start.click(run, [*inputs, automatic_request], [*outputs, flow], api_name=False, **common).failure(
refresh_view, [flow], transport, queue=False)
new_stream.click(begin, inputs, [*outputs, flow], api_name="begin", **common).failure(
refresh_view, [flow], transport, queue=False)
halt.click(stop, [flow], transport, queue=False)
pause.click(pause_generation, [flow], [status, transport], queue=False)
reset.click(reset_view, [flow], outputs, api_name="clear", **common)
save.click(export, [flow], download, **common)
return demo.queue(max_size=16, default_concurrency_limit=1)
if __name__ == "__main__":
import os
default_host = "0.0.0.0" if os.environ.get("SPACE_ID") else "127.0.0.1"
build_app().launch(server_name=os.environ.get("FLOW_HOST", default_host),
server_port=int(os.environ.get("PORT", "7860")), show_error=True)