Spaces:
Running on Zero
Running on Zero
Add prompt-free Let it flow app
Browse files
README.md
CHANGED
|
@@ -1,13 +1,110 @@
|
|
| 1 |
---
|
| 2 |
-
title: Let
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version: '3.13'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Let it flow
|
| 3 |
+
emoji: 🌊
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.49.1
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
python_version: '3.11'
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# Let it flow
|
| 14 |
+
|
| 15 |
+
A prompt-free automatic-writing experiment. Load a public Hugging Face base model,
|
| 16 |
+
press **Begin**, and watch it generate from a special beginning token alone. No
|
| 17 |
+
written prompt, hidden literary instruction, or chat template is inserted. For
|
| 18 |
+
models without BOS, EOS is used as the initial document boundary. The initial
|
| 19 |
+
boundary is not displayed; generated special tokens are hidden in the prose but
|
| 20 |
+
remain visible in the inspector and count toward the token total.
|
| 21 |
+
|
| 22 |
+
## Run locally
|
| 23 |
+
|
| 24 |
+
Use Python 3.11–3.13. On Windows:
|
| 25 |
+
|
| 26 |
+
```powershell
|
| 27 |
+
powershell -ExecutionPolicy Bypass -File .\start.ps1
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Open http://localhost:7860. The first model load requires internet access.
|
| 31 |
+
Dependencies and weights stay in `.venv` and `.model-cache` respectively.
|
| 32 |
+
CPU is supported; CUDA is used automatically when a compatible PyTorch build and
|
| 33 |
+
GPU are available. Start with SmolLM2-135M; larger models can be slow on CPU.
|
| 34 |
+
|
| 35 |
+
## Hugging Face Space
|
| 36 |
+
|
| 37 |
+
Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,
|
| 38 |
+
`requirements.txt`, and this `README.md`. The README contains the Space metadata.
|
| 39 |
+
The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost.
|
| 40 |
+
`FLOW_HOST` and `PORT` can override these defaults. No API token is
|
| 41 |
+
needed for the supported public, ungated models. Start with CPU Basic and a small
|
| 42 |
+
model; hardware determines the practical model size. This project is prepared for
|
| 43 |
+
Spaces but does not create or publish a remote Space automatically.
|
| 44 |
+
|
| 45 |
+
Run `python scripts/prepare_space.py` to create `outputs/let-it-flow-space.zip`.
|
| 46 |
+
Extract the archive and upload its six files to the root of your Gradio Space.
|
| 47 |
+
|
| 48 |
+
## Controls
|
| 49 |
+
|
| 50 |
+
- **Begin:** replace the stream and initialize a new random sequence.
|
| 51 |
+
- **Stop:** request cancellation; the current inference step completes first.
|
| 52 |
+
- **Continue:** preserve generated token IDs and RNG state, including across a stop.
|
| 53 |
+
- **Start fresh:** clear the page, then press Begin or Continue to start.
|
| 54 |
+
- **Advanced sampling:** temperature, top-p, sign-aware repetition penalty,
|
| 55 |
+
optional seed, tokens per pass, and a display delay. Settings are read at the
|
| 56 |
+
start of each pass. A seed applies only to a new stream. Results are reproducible
|
| 57 |
+
for the same model revision, settings, hardware/software, and context boundaries;
|
| 58 |
+
different hardware or pass boundaries may cause numerical differences.
|
| 59 |
+
- **Watch the next token:** show the latest choice, the eight most probable
|
| 60 |
+
candidates, and the selected token even if it falls outside those eight. It is
|
| 61 |
+
a live snapshot, not a retained history. Turn it off before the next pass to
|
| 62 |
+
show only the prose. Spaces and newlines appear using quoted representations.
|
| 63 |
+
- **Export:** prepare a UTF-8 text download, or copy directly from the page.
|
| 64 |
+
|
| 65 |
+
## What the probabilities mean
|
| 66 |
+
|
| 67 |
+
Each step takes the model's logits, applies repetition penalty over the active
|
| 68 |
+
context (including the initial boundary while present), then temperature. Top-p
|
| 69 |
+
keeps the smallest leading set reaching the requested probability mass. The
|
| 70 |
+
inspector shows the resulting **renormalized sampling distribution**, not the
|
| 71 |
+
unmodified model probabilities. The selected token is sampled from exactly that
|
| 72 |
+
distribution. Other tokens reports the probability mass outside the shown rows.
|
| 73 |
+
No fabricated reasoning or token alternatives are used. The text is generated
|
| 74 |
+
output, not evidence of consciousness or a view of private reasoning.
|
| 75 |
+
|
| 76 |
+
## Limits and shared hosting
|
| 77 |
+
|
| 78 |
+
One model is held in memory for the process. Loading and generation share a queue
|
| 79 |
+
to avoid simultaneous model allocation. Loading another model affects all
|
| 80 |
+
visitors; previous streams cannot continue under a different model revision.
|
| 81 |
+
Text and random state are per browser session. Clear or copy/export your text
|
| 82 |
+
before switching models. Browser refresh discards the session.
|
| 83 |
+
|
| 84 |
+
Only public, ungated, decoder-only safetensors models supported by standard
|
| 85 |
+
Transformers code are accepted. Remote model Python code is disabled. GGUF,
|
| 86 |
+
custom-code architectures, and gated/private access are outside this version.
|
| 87 |
+
Downloads are pinned to a resolved commit and cached. The default total download
|
| 88 |
+
cap is 2 GB (`FLOW_MAX_DOWNLOAD_GB` can change it); this is not a RAM guarantee.
|
| 89 |
+
Use compatible small models. Cached files persist until manually removed; ephemeral
|
| 90 |
+
Space storage may be reset by a restart or rebuild.
|
| 91 |
+
|
| 92 |
+
A pass generates at most 1,024 tokens. Continue extends it up to 16,384 tokens per
|
| 93 |
+
session. The context is limited to the most recent 2,048 tokens or the model's
|
| 94 |
+
smaller advertised context limit. When full, older text remains on screen but
|
| 95 |
+
stops influencing generation. KV cache is rebuilt as needed when the window
|
| 96 |
+
slides. This bounds memory but can slow long streams. An emitted end token ends
|
| 97 |
+
the stream naturally; it is not suppressed to force more prose.
|
| 98 |
+
|
| 99 |
+
## Verification
|
| 100 |
+
|
| 101 |
+
```powershell
|
| 102 |
+
.\.venv\Scripts\python.exe -m unittest discover -s tests -v
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
The automated tests cover real sampling math, seeded continuation, stopping,
|
| 106 |
+
model boundaries, EOS, context rollover, and HTML escaping. A real-model smoke
|
| 107 |
+
check can be run with `python scripts/smoke.py` after installing dependencies;
|
| 108 |
+
it downloads SmolLM2-135M and checks prompt-free generation and continuation.
|
| 109 |
+
With the server running, `python scripts/check_server.py` also exercises the
|
| 110 |
+
Gradio API, including seeded replay, stopping, exporting, and resetting a session.
|
app.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Let it flow — a prompt-free Hugging Face Space."""
|
| 2 |
+
import html
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
|
| 8 |
+
from engine import Flow, generate
|
| 9 |
+
from models import ModelStore, PRESETS
|
| 10 |
+
|
| 11 |
+
STORE = ModelStore()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def inspector(tokenizer, step, number):
|
| 15 |
+
rows = []
|
| 16 |
+
for token_id, probability in step["candidates"]:
|
| 17 |
+
piece = tokenizer.decode([token_id], skip_special_tokens=False,
|
| 18 |
+
clean_up_tokenization_spaces=False)
|
| 19 |
+
# repr makes spaces and linebreaks visible; escaping prevents generated HTML execution.
|
| 20 |
+
label = html.escape(repr(piece))
|
| 21 |
+
selected = token_id == step["chosen"]
|
| 22 |
+
rows.append(f'<div class="candidate {"selected" if selected else ""}">'
|
| 23 |
+
f'<div class="candidate-label"><code>{label}</code>'
|
| 24 |
+
f'<span>{probability:.2%}{" · selected" if selected else ""}</span></div>'
|
| 25 |
+
f'<div class="track"><div style="width:{probability * 100:.4f}%"></div></div>'
|
| 26 |
+
f'<small>token {token_id}</small></div>')
|
| 27 |
+
return (f'<div class="inspector"><div class="eyebrow">CHOICE {number}</div>'
|
| 28 |
+
'<h3>What could come next?</h3><p>Probabilities immediately before the latest token was selected.</p>'
|
| 29 |
+
+ "".join(rows) + f'<p>Other tokens: {step["other"]:.2%}</p>'
|
| 30 |
+
f'<small>Top-p retained {step["retained_mass"]:.2%} of the distribution after '
|
| 31 |
+
'temperature and repetition penalty. Bars show probabilities renormalized over that set. '
|
| 32 |
+
'The selected token may be outside the eight leading candidates.</small></div>')
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
EMPTY = '<div class="inspector"><div class="eyebrow">WATCH THE NEXT TOKEN</div><h3>A field of possibilities.</h3><p>Enable the inspector and begin. Each choice will show candidate tokens, their sampling probabilities, and the selected token.</p></div>'
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def clear(flow):
|
| 39 |
+
flow.tokens.clear()
|
| 40 |
+
flow.text = ""
|
| 41 |
+
flow.model_key = ""
|
| 42 |
+
flow.seed = flow.rng_state = None
|
| 43 |
+
flow.ended = False
|
| 44 |
+
flow.stop.clear()
|
| 45 |
+
return "", EMPTY, "A blank page. Press Begin when you’re ready."
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_model(repo, flow):
|
| 49 |
+
try:
|
| 50 |
+
description = STORE.load(repo)
|
| 51 |
+
text, panel, status = clear(flow)
|
| 52 |
+
return description, text, panel, status
|
| 53 |
+
except Exception as error:
|
| 54 |
+
raise gr.Error(f"Could not load model: {error}") from error
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def stop(flow):
|
| 58 |
+
flow.stop.set()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def run(flow, temperature, top_p, penalty, seed, count, watch, delay, fresh=False):
|
| 62 |
+
if STORE.model is None:
|
| 63 |
+
raise gr.Error("Load a model first.")
|
| 64 |
+
if fresh:
|
| 65 |
+
clear(flow)
|
| 66 |
+
flow.stop.clear()
|
| 67 |
+
panel = EMPTY
|
| 68 |
+
started = time.monotonic()
|
| 69 |
+
before = len(flow.tokens)
|
| 70 |
+
last_text = STORE.tokenizer.decode(flow.tokens, skip_special_tokens=True,
|
| 71 |
+
clean_up_tokenization_spaces=False)
|
| 72 |
+
trimmed = False
|
| 73 |
+
try:
|
| 74 |
+
yield last_text, panel, "Generating…"
|
| 75 |
+
for step in generate(STORE.model, STORE.tokenizer, flow, STORE.key,
|
| 76 |
+
count, temperature, top_p, penalty, seed):
|
| 77 |
+
last_text = step["text"]
|
| 78 |
+
trimmed = step["context_trimmed"]
|
| 79 |
+
if watch:
|
| 80 |
+
panel = inspector(STORE.tokenizer, step, len(flow.tokens))
|
| 81 |
+
status = (f"{len(flow.tokens)} tokens · seed {flow.seed} · "
|
| 82 |
+
f"{(len(flow.tokens) - before) / max(.001, time.monotonic() - started):.1f} tokens/s")
|
| 83 |
+
if trimmed:
|
| 84 |
+
status += " · Context window full: only the latest 2,048 tokens (or model limit) inform the next choice."
|
| 85 |
+
yield last_text, panel if watch else "", status
|
| 86 |
+
if delay and flow.stop.wait(float(delay)):
|
| 87 |
+
break
|
| 88 |
+
if flow.ended:
|
| 89 |
+
reason = "The model emitted an end token. Start fresh to begin another stream."
|
| 90 |
+
elif len(flow.tokens) >= 16384:
|
| 91 |
+
reason = "Session limit of 16,384 tokens reached. Download your text and start fresh."
|
| 92 |
+
elif flow.stop.is_set():
|
| 93 |
+
reason = "Stopped. Continue preserves the text and random sequence."
|
| 94 |
+
else:
|
| 95 |
+
reason = "Pass complete. Continue to let it flow further."
|
| 96 |
+
if trimmed:
|
| 97 |
+
reason += " Earlier text remains visible but is outside the model’s context."
|
| 98 |
+
yield last_text, panel if watch else "", f"{reason} · {len(flow.tokens)} tokens · seed {flow.seed}"
|
| 99 |
+
except Exception as error:
|
| 100 |
+
# Preserve already-generated text and RNG state so a failed pass can be retried.
|
| 101 |
+
raise gr.Error(str(error)) from error
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def begin(*args):
|
| 105 |
+
yield from run(*args, fresh=True)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def export(flow):
|
| 109 |
+
if not flow.tokens:
|
| 110 |
+
raise gr.Error("Generate some text first.")
|
| 111 |
+
import tempfile
|
| 112 |
+
directory = Path(tempfile.mkdtemp(prefix="let-it-flow-"))
|
| 113 |
+
output = directory / "let-it-flow.txt"
|
| 114 |
+
output.write_text(flow.text, encoding="utf-8")
|
| 115 |
+
return str(output)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def build_app():
|
| 119 |
+
css = Path(__file__).with_name("style.css").read_text(encoding="utf-8")
|
| 120 |
+
with gr.Blocks(title="Let it flow", css=css, theme=gr.themes.Soft(
|
| 121 |
+
primary_hue="teal", neutral_hue="stone"), delete_cache=(3600, 3600)) as demo:
|
| 122 |
+
flow = gr.State(Flow())
|
| 123 |
+
gr.HTML('<header><div class="eyebrow">AN EXPERIMENT IN AUTOMATIC WRITING</div>'
|
| 124 |
+
'<h1>Let it flow<span>.</span></h1><p>No subject. No instructions. Just the next token.</p></header>')
|
| 125 |
+
with gr.Accordion("01 / Load a model", open=True):
|
| 126 |
+
with gr.Row():
|
| 127 |
+
repo = gr.Dropdown(PRESETS, value=PRESETS[0], allow_custom_value=True,
|
| 128 |
+
label="Public model repository or Hugging Face URL", scale=4)
|
| 129 |
+
load = gr.Button("Load model", variant="primary", scale=1)
|
| 130 |
+
model_status = gr.Textbox(label="Model", value="No model loaded.", interactive=False)
|
| 131 |
+
gr.Markdown("Small **base models** work best for this experiment. Public safetensors models only; "
|
| 132 |
+
"2 GB download limit by default. One model is shared by visitors; loading another replaces it.")
|
| 133 |
+
with gr.Row():
|
| 134 |
+
with gr.Column(scale=3):
|
| 135 |
+
with gr.Row():
|
| 136 |
+
start = gr.Button("Begin", variant="primary")
|
| 137 |
+
resume = gr.Button("Continue")
|
| 138 |
+
halt = gr.Button("Stop", variant="stop")
|
| 139 |
+
reset = gr.Button("Start fresh")
|
| 140 |
+
page = gr.Textbox(label="The stream", lines=19, max_lines=30,
|
| 141 |
+
placeholder="A blank page. Let something emerge.",
|
| 142 |
+
interactive=False, show_copy_button=True, elem_id="page")
|
| 143 |
+
status = gr.Textbox(label="Stream status", value="Load a model to begin.", interactive=False)
|
| 144 |
+
with gr.Row():
|
| 145 |
+
save = gr.Button("Prepare text download", size="sm")
|
| 146 |
+
download = gr.File(label="Text export", interactive=False)
|
| 147 |
+
with gr.Column(scale=2):
|
| 148 |
+
watch = gr.Checkbox(label="Watch the next token", value=True)
|
| 149 |
+
panel = gr.HTML(EMPTY)
|
| 150 |
+
with gr.Accordion("02 / Advanced sampling", open=False):
|
| 151 |
+
with gr.Row():
|
| 152 |
+
temperature = gr.Slider(.05, 2, value=1, step=.05, label="Temperature",
|
| 153 |
+
info="Higher values spread probability across more choices.")
|
| 154 |
+
top_p = gr.Slider(.05, 1, value=.95, step=.01, label="Top-p",
|
| 155 |
+
info="Sample from the smallest leading set reaching this probability mass.")
|
| 156 |
+
penalty = gr.Slider(1, 2, value=1, step=.01, label="Repetition penalty",
|
| 157 |
+
info="1 leaves repetition unchanged; higher values discourage seen tokens.")
|
| 158 |
+
with gr.Row():
|
| 159 |
+
seed = gr.Number(value=None, precision=0, label="Random seed (optional)",
|
| 160 |
+
info="Blank chooses a seed. Applied on Begin; Continue keeps the RNG sequence.")
|
| 161 |
+
count = gr.Slider(1, 1024, value=256, step=1, label="Tokens per pass")
|
| 162 |
+
delay = gr.Slider(0, .5, value=.06, step=.02, label="Reading delay per token (seconds)",
|
| 163 |
+
info="Slows the display, without changing the sampling distribution.")
|
| 164 |
+
gr.Markdown("Starts from the model’s beginning token (or its end token when no beginning token exists). "
|
| 165 |
+
"No written prompt or chat template is added. Each token becomes context for the next. "
|
| 166 |
+
"The inspector displays sampling choices, not private thoughts or consciousness. "
|
| 167 |
+
"Model output may take any form. Settings apply to the next pass; Begin replaces the current stream.")
|
| 168 |
+
outputs = [page, panel, status]
|
| 169 |
+
inputs = [flow, temperature, top_p, penalty, seed, count, watch, delay]
|
| 170 |
+
common = dict(concurrency_id="model", concurrency_limit=1)
|
| 171 |
+
load.click(load_model, [repo, flow], [model_status, *outputs], **common)
|
| 172 |
+
start.click(begin, inputs, outputs, **common)
|
| 173 |
+
resume.click(run, inputs, outputs, **common)
|
| 174 |
+
halt.click(stop, [flow], [], queue=False)
|
| 175 |
+
reset.click(clear, [flow], outputs, **common)
|
| 176 |
+
save.click(export, [flow], download, **common)
|
| 177 |
+
return demo.queue(max_size=16, default_concurrency_limit=1)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
import os
|
| 182 |
+
default_host = "0.0.0.0" if os.environ.get("SPACE_ID") else "127.0.0.1"
|
| 183 |
+
build_app().launch(server_name=os.environ.get("FLOW_HOST", default_host),
|
| 184 |
+
server_port=int(os.environ.get("PORT", "7860")), show_error=True)
|
engine.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prompt-free causal sampling. The inspector uses the actual sampled distribution."""
|
| 2 |
+
import secrets
|
| 3 |
+
import threading
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Flow:
|
| 9 |
+
def __init__(self, tokens=None, text="", model_key="", seed=None, ended=False):
|
| 10 |
+
self.tokens = list(tokens or [])
|
| 11 |
+
self.text = text
|
| 12 |
+
self.model_key = model_key
|
| 13 |
+
self.seed = seed
|
| 14 |
+
self.rng_state = None
|
| 15 |
+
self.ended = ended
|
| 16 |
+
self.stop = threading.Event()
|
| 17 |
+
|
| 18 |
+
def __deepcopy__(self, memo):
|
| 19 |
+
return Flow() # Gradio creates an independent state for each visitor.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def distribution(logits, history, temperature, top_p, repetition_penalty):
|
| 23 |
+
"""Standard sign-aware repetition penalty, temperature, then nucleus filtering."""
|
| 24 |
+
if not 0.05 <= temperature <= 2 or not 0 < top_p <= 1 or not 1 <= repetition_penalty <= 2:
|
| 25 |
+
raise ValueError("Sampling settings are outside the supported range.")
|
| 26 |
+
scores = logits.detach().float().cpu().clone()
|
| 27 |
+
if history and repetition_penalty != 1:
|
| 28 |
+
ids = torch.tensor(sorted(set(history)), dtype=torch.long)
|
| 29 |
+
values = scores[ids]
|
| 30 |
+
scores[ids] = torch.where(values < 0, values * repetition_penalty, values / repetition_penalty)
|
| 31 |
+
scores /= temperature
|
| 32 |
+
raw = torch.softmax(scores, dim=-1)
|
| 33 |
+
ordered, indices = torch.sort(raw, descending=True)
|
| 34 |
+
# Keep the first token that crosses p, including the highest-probability token.
|
| 35 |
+
remove = ordered.cumsum(0) - ordered >= top_p
|
| 36 |
+
filtered = raw.clone()
|
| 37 |
+
filtered[indices[remove]] = 0
|
| 38 |
+
filtered /= filtered.sum()
|
| 39 |
+
if not torch.isfinite(filtered).all():
|
| 40 |
+
raise ValueError("The model returned invalid probabilities.")
|
| 41 |
+
return filtered, raw
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def start_id(model, tokenizer):
|
| 45 |
+
for value in (tokenizer.bos_token_id, model.config.bos_token_id,
|
| 46 |
+
tokenizer.eos_token_id, model.config.eos_token_id):
|
| 47 |
+
if value is not None:
|
| 48 |
+
return int(value[0] if isinstance(value, (tuple, list)) else value)
|
| 49 |
+
raise ValueError("This model has no BOS or EOS token. Prompt-free startup is unavailable.")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, seed,
|
| 53 |
+
context_limit=2048):
|
| 54 |
+
if flow.model_key and flow.model_key != key:
|
| 55 |
+
raise ValueError("The loaded model changed. Choose Start fresh before continuing.")
|
| 56 |
+
if flow.ended:
|
| 57 |
+
raise ValueError("The model ended this stream. Choose Start fresh for another.")
|
| 58 |
+
fresh = not flow.model_key
|
| 59 |
+
if fresh:
|
| 60 |
+
if seed is not None and (int(seed) != seed or not 0 <= seed <= 2**32 - 1):
|
| 61 |
+
raise ValueError("Seed must be an integer from 0 to 4294967295, or blank.")
|
| 62 |
+
flow.seed = int(seed) if seed is not None else secrets.randbits(32)
|
| 63 |
+
flow.model_key = key
|
| 64 |
+
rng = torch.Generator(device="cpu")
|
| 65 |
+
if flow.rng_state is not None:
|
| 66 |
+
rng.set_state(flow.rng_state)
|
| 67 |
+
else:
|
| 68 |
+
rng.manual_seed(flow.seed)
|
| 69 |
+
prefix = [start_id(model, tokenizer)]
|
| 70 |
+
eos = model.generation_config.eos_token_id
|
| 71 |
+
eos_ids = set(eos if isinstance(eos, (list, tuple)) else [eos]) if eos is not None else set()
|
| 72 |
+
eos_ids.update([tokenizer.eos_token_id] if tokenizer.eos_token_id is not None else [])
|
| 73 |
+
limit = min(context_limit, int(getattr(model.config, "max_position_embeddings", context_limit)))
|
| 74 |
+
cache = None
|
| 75 |
+
consumed = 0
|
| 76 |
+
with torch.inference_mode():
|
| 77 |
+
for _ in range(int(count)):
|
| 78 |
+
if flow.stop.is_set():
|
| 79 |
+
break
|
| 80 |
+
if len(flow.tokens) >= 16384:
|
| 81 |
+
break
|
| 82 |
+
all_ids = prefix + flow.tokens
|
| 83 |
+
window = all_ids[-limit:]
|
| 84 |
+
if cache is None or consumed >= limit:
|
| 85 |
+
cache = None
|
| 86 |
+
input_ids = torch.tensor([window], device=model.device)
|
| 87 |
+
consumed = len(window)
|
| 88 |
+
else:
|
| 89 |
+
input_ids = torch.tensor([[flow.tokens[-1]]], device=model.device)
|
| 90 |
+
consumed += 1
|
| 91 |
+
result = model(input_ids=input_ids, past_key_values=cache, use_cache=True)
|
| 92 |
+
cache = result.past_key_values
|
| 93 |
+
probs, before_nucleus = distribution(result.logits[0, -1], window,
|
| 94 |
+
temperature, top_p, penalty)
|
| 95 |
+
chosen = int(torch.multinomial(probs, 1, generator=rng))
|
| 96 |
+
flow.tokens.append(chosen)
|
| 97 |
+
flow.rng_state = rng.get_state()
|
| 98 |
+
flow.ended = chosen in eos_ids
|
| 99 |
+
flow.text = tokenizer.decode(flow.tokens, skip_special_tokens=True,
|
| 100 |
+
clean_up_tokenization_spaces=False)
|
| 101 |
+
values, ids = torch.topk(probs, min(8, len(probs)))
|
| 102 |
+
candidates = [(int(i), float(p)) for i, p in zip(ids, values) if p > 0]
|
| 103 |
+
if chosen not in [i for i, _ in candidates]:
|
| 104 |
+
candidates.append((chosen, float(probs[chosen])))
|
| 105 |
+
yield {
|
| 106 |
+
"text": flow.text,
|
| 107 |
+
"candidates": candidates, "chosen": chosen,
|
| 108 |
+
"chosen_probability": float(probs[chosen]),
|
| 109 |
+
"retained_mass": float(before_nucleus[probs > 0].sum()),
|
| 110 |
+
"other": max(0., 1. - sum(p for _, p in candidates)),
|
| 111 |
+
"context_trimmed": len(all_ids) > limit,
|
| 112 |
+
}
|
| 113 |
+
if flow.ended:
|
| 114 |
+
break
|
models.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public Hub model loading with pinned downloads and bounded resource use."""
|
| 2 |
+
import gc
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import shutil
|
| 6 |
+
from urllib.parse import urlsplit
|
| 7 |
+
|
| 8 |
+
from huggingface_hub import HfApi, snapshot_download
|
| 9 |
+
from huggingface_hub.utils import validate_repo_id
|
| 10 |
+
import torch
|
| 11 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 12 |
+
|
| 13 |
+
CACHE = Path(__file__).parent / ".model-cache"
|
| 14 |
+
PRESETS = ["HuggingFaceTB/SmolLM2-135M", "HuggingFaceTB/SmolLM2-360M", "openai-community/gpt2"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def repository(value):
|
| 18 |
+
value = value.strip()
|
| 19 |
+
if "://" in value:
|
| 20 |
+
url = urlsplit(value)
|
| 21 |
+
if url.scheme != "https" or url.netloc != "huggingface.co":
|
| 22 |
+
raise ValueError("Enter a Hugging Face model repository URL or owner/model.")
|
| 23 |
+
parts = url.path.strip("/").split("/")
|
| 24 |
+
if parts[0] in ("spaces", "datasets") or len(parts) != 2:
|
| 25 |
+
raise ValueError("Use the model's main repository URL, without a file path.")
|
| 26 |
+
value = "/".join(parts)
|
| 27 |
+
validate_repo_id(value)
|
| 28 |
+
return value
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ModelStore:
|
| 32 |
+
def __init__(self):
|
| 33 |
+
self.model = self.tokenizer = None
|
| 34 |
+
self.key = ""
|
| 35 |
+
self.description = "No model loaded."
|
| 36 |
+
|
| 37 |
+
def load(self, value):
|
| 38 |
+
repo = repository(value)
|
| 39 |
+
info = HfApi().model_info(repo, files_metadata=True, token=False)
|
| 40 |
+
if info.private or info.gated:
|
| 41 |
+
raise ValueError("This version supports public, ungated models.")
|
| 42 |
+
patterns = ["*.json", "*.safetensors", "*.model", "*.txt", "*.tiktoken"]
|
| 43 |
+
import fnmatch
|
| 44 |
+
files = [f for f in info.siblings if any(fnmatch.fnmatch(f.rfilename, p) for p in patterns)
|
| 45 |
+
and "/" not in f.rfilename]
|
| 46 |
+
if not any(f.rfilename.endswith(".safetensors") for f in files):
|
| 47 |
+
raise ValueError("Choose a model with safetensors weights. GGUF is not supported yet.")
|
| 48 |
+
size = sum(f.size or 0 for f in files)
|
| 49 |
+
if any(f.size is None for f in files):
|
| 50 |
+
raise ValueError("Cannot determine the model download size.")
|
| 51 |
+
max_bytes = float(os.environ.get("FLOW_MAX_DOWNLOAD_GB", "2")) * 1024**3
|
| 52 |
+
if size > max_bytes:
|
| 53 |
+
raise ValueError(f"Download is {size / 1024**3:.2f} GB; the limit is {max_bytes / 1024**3:g} GB.")
|
| 54 |
+
CACHE.mkdir(exist_ok=True)
|
| 55 |
+
if shutil.disk_usage(CACHE).free < size + 1024**3:
|
| 56 |
+
raise ValueError("Insufficient disk space; leave at least 1 GB free after download.")
|
| 57 |
+
config = AutoConfig.from_pretrained(repo, revision=info.sha, token=False,
|
| 58 |
+
trust_remote_code=False, cache_dir=CACHE)
|
| 59 |
+
if getattr(config, "is_encoder_decoder", False):
|
| 60 |
+
raise ValueError("Choose a decoder-only text-generation model.")
|
| 61 |
+
# Release the previous model before allocating the next one.
|
| 62 |
+
self.model = self.tokenizer = None
|
| 63 |
+
self.key = ""
|
| 64 |
+
gc.collect()
|
| 65 |
+
if torch.cuda.is_available():
|
| 66 |
+
torch.cuda.empty_cache()
|
| 67 |
+
path = snapshot_download(repo, revision=info.sha, token=False, cache_dir=CACHE,
|
| 68 |
+
allow_patterns=[f.rfilename for f in files])
|
| 69 |
+
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=False)
|
| 70 |
+
model = AutoModelForCausalLM.from_pretrained(path, config=config, use_safetensors=True,
|
| 71 |
+
trust_remote_code=False, torch_dtype=torch.float32)
|
| 72 |
+
if torch.cuda.is_available():
|
| 73 |
+
model = model.to(device="cuda", dtype=torch.float16)
|
| 74 |
+
model.eval()
|
| 75 |
+
from engine import start_id
|
| 76 |
+
initial = start_id(model, tokenizer)
|
| 77 |
+
self.model, self.tokenizer = model, tokenizer
|
| 78 |
+
self.key = f"{repo}@{info.sha}"
|
| 79 |
+
device = "GPU" if torch.cuda.is_available() else "CPU"
|
| 80 |
+
self.description = (f"{repo} · {info.sha[:8]} · {device} · "
|
| 81 |
+
f"{size / 1024**2:.0f} MB download · starting token ID {initial}")
|
| 82 |
+
return self.description
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.49.1
|
| 2 |
+
transformers==4.57.3
|
| 3 |
+
torch==2.6.0
|
| 4 |
+
huggingface-hub==0.36.0
|
style.css
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.gradio-container { max-width: 1240px !important; margin: auto; }
|
| 2 |
+
header { padding: 36px 8px 28px; }
|
| 3 |
+
.eyebrow { font: 600 11px/1.5 system-ui, sans-serif; letter-spacing: .18em; color: #497b71; }
|
| 4 |
+
header h1 { font: 400 clamp(44px, 6vw, 74px)/1.1 Georgia, serif; letter-spacing: -.04em; margin: 12px 0; }
|
| 5 |
+
header h1 span { color: #568f7e; }
|
| 6 |
+
header p { font: 18px/1.6 Georgia, serif; color: #777; }
|
| 7 |
+
#page textarea { font: 19px/1.85 Georgia, 'Times New Roman', serif !important; padding: 24px !important; }
|
| 8 |
+
.inspector { padding: 22px; border: 1px solid #82968b40; border-radius: 14px; min-height: 230px; }
|
| 9 |
+
.inspector h3 { font: 26px/1.2 Georgia, serif; margin: 12px 0; }
|
| 10 |
+
.inspector p, .inspector small { opacity: .75; line-height: 1.6; }
|
| 11 |
+
.candidate { padding: 8px 10px; margin: 6px 0; border-radius: 8px; }
|
| 12 |
+
.candidate.selected { background: #48887518; outline: 1px solid #48887580; }
|
| 13 |
+
.candidate-label { display: flex; justify-content: space-between; gap: 12px; font-size: 12px; }
|
| 14 |
+
.candidate-label code { white-space: pre-wrap; overflow-wrap: anywhere; }
|
| 15 |
+
.candidate small { font-size: 10px; }
|
| 16 |
+
.track { height: 5px; background: #82968b20; border-radius: 8px; margin: 7px 0 3px; overflow: hidden; }
|
| 17 |
+
.track div { height: 100%; background: #629b89; border-radius: 8px; }
|