jejunepixels commited on
Commit
2ebdc67
·
verified ·
1 Parent(s): 206f86c

Apply slider and inspector changes live during generation

Browse files
Files changed (3) hide show
  1. README.md +13 -6
  2. app.py +33 -8
  3. engine.py +38 -3
README.md CHANGED
@@ -54,14 +54,19 @@ Extract the archive and upload its six files to the root of your Gradio Space.
54
  - **Advanced sampling:** temperature, top-p, sign-aware repetition penalty,
55
  optional seed, memory span, tokens per pass, and a display delay.
56
  Defaults: temperature 1.3, top-p 1.0, repetition penalty 1.1, memory 128 tokens.
57
- Try 64 tokens for more drift; longer memory sustains a subject more easily. Settings are read at the
58
- start of each pass. A seed applies only to a new stream. Results are reproducible
 
 
 
 
 
59
  for the same model revision, settings, hardware/software, and context boundaries;
60
  different hardware or pass boundaries may cause numerical differences.
61
  - **Watch the next token:** show the latest choice, the eight most probable
62
  candidates, and the selected token even if it falls outside those eight. It is
63
- a live snapshot, not a retained history. Turn it off before the next pass to
64
- show only the prose. Spaces and newlines appear using quoted representations.
65
  - **Export:** prepare a UTF-8 text download, or copy directly from the page.
66
 
67
  ## What the probabilities mean
@@ -94,7 +99,8 @@ Space storage may be reset by a restart or rebuild.
94
  A pass generates at most 1,024 tokens. Continue extends it up to 16,384 tokens per
95
  session. The context defaults to the most recent 128 tokens. The Memory span slider
96
  can select 16?2,048 tokens, bounded by the model's smaller advertised context limit.
97
- It applies to the next pass, including Continue; all earlier context and cached
 
98
  activations are excluded once they fall outside the selected window. When full, older text remains on screen but
99
  stops influencing generation. KV cache is rebuilt as needed when the window
100
  slides. This bounds memory but can slow long streams. An emitted end token ends
@@ -111,4 +117,5 @@ model boundaries, EOS, context rollover, and HTML escaping. A real-model smoke
111
  check can be run with `python scripts/smoke.py` after installing dependencies;
112
  it downloads SmolLM2-135M and checks prompt-free generation and continuation.
113
  With the server running, `python scripts/check_server.py` also exercises the
114
- Gradio API, including seeded replay, stopping, exporting, and resetting a session.
 
 
54
  - **Advanced sampling:** temperature, top-p, sign-aware repetition penalty,
55
  optional seed, memory span, tokens per pass, and a display delay.
56
  Defaults: temperature 1.3, top-p 1.0, repetition penalty 1.1, memory 128 tokens.
57
+ Try 64 tokens for more drift; longer memory sustains a subject more easily.
58
+ Sliders update the current stream without restarting it. Changes take effect
59
+ from the next token after the server receives the update; an inference step
60
+ already in progress finishes with its previous settings. The status shows the
61
+ sampling settings actually used for the latest token. Pass length can be raised
62
+ before the pass ends, or lowered to stop at the new limit. Reading delay updates
63
+ for subsequent pauses. A seed applies only to a new stream. Results are reproducible
64
  for the same model revision, settings, hardware/software, and context boundaries;
65
  different hardware or pass boundaries may cause numerical differences.
66
  - **Watch the next token:** show the latest choice, the eight most probable
67
  candidates, and the selected token even if it falls outside those eight. It is
68
+ a live snapshot, not a retained history. Toggle it during generation to show
69
+ or hide the inspector on the next token. Spaces and newlines appear using quoted representations.
70
  - **Export:** prepare a UTF-8 text download, or copy directly from the page.
71
 
72
  ## What the probabilities mean
 
99
  A pass generates at most 1,024 tokens. Continue extends it up to 16,384 tokens per
100
  session. The context defaults to the most recent 128 tokens. The Memory span slider
101
  can select 16?2,048 tokens, bounded by the model's smaller advertised context limit.
102
+ Memory changes apply while generating, including shrinking or expanding the active
103
+ window. Expanding it can bring earlier visible text back into context. All earlier context and cached
104
  activations are excluded once they fall outside the selected window. When full, older text remains on screen but
105
  stops influencing generation. KV cache is rebuilt as needed when the window
106
  slides. This bounds memory but can slow long streams. An emitted end token ends
 
117
  check can be run with `python scripts/smoke.py` after installing dependencies;
118
  it downloads SmolLM2-135M and checks prompt-free generation and continuation.
119
  With the server running, `python scripts/check_server.py` also exercises the
120
+ Gradio API, including seeded replay, live slider/inspector updates while generation
121
+ is running, stopping, exporting, and resetting a session.
app.py CHANGED
@@ -58,11 +58,22 @@ def stop(flow):
58
  flow.stop.set()
59
 
60
 
 
 
 
 
 
 
 
 
 
61
  def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128, 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()
@@ -73,17 +84,23 @@ def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128
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, context_limit=memory):
 
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
- f" · memory {step['context_limit']} tokens")
 
 
84
  if trimmed:
85
  status += f" · Only the latest {step['context_limit']} tokens inform the next choice."
86
- yield last_text, panel if watch else "", status
 
87
  if delay and flow.stop.wait(float(delay)):
88
  break
89
  if flow.ended:
@@ -96,7 +113,8 @@ def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128
96
  reason = "Pass complete. Continue to let it flow further."
97
  if trimmed:
98
  reason += " Earlier text remains visible but is outside the model’s context."
99
- yield last_text, panel if watch else "", f"{reason} · {len(flow.tokens)} tokens · seed {flow.seed} · requested memory {int(memory)} tokens"
 
100
  except Exception as error:
101
  # Preserve already-generated text and RNG state so a failed pass can be retried.
102
  raise gr.Error(str(error)) from error
@@ -160,20 +178,27 @@ def build_app():
160
  info="1 leaves repetition unchanged; higher values discourage seen tokens.")
161
  memory = gr.Slider(16, 2048, value=128, step=1, label="Memory span (tokens)",
162
  info="Only this many recent tokens inform each choice. Try 64 for more drift; "
163
- "2048 keeps a longer thread. Earlier text stays visible. Applies on the next pass.")
164
  with gr.Row():
165
  seed = gr.Number(value=None, precision=0, label="Random seed (optional)",
166
  info="Blank chooses a seed. Applied on Begin; Continue keeps the RNG sequence.")
167
- count = gr.Slider(1, 1024, value=256, step=1, label="Tokens per pass")
 
168
  delay = gr.Slider(0, .5, value=.06, step=.02, label="Reading delay per token (seconds)",
169
  info="Slows the display, without changing the sampling distribution.")
170
  gr.Markdown("Starts from the model’s beginning token (or its end token when no beginning token exists). "
171
  "No written prompt or chat template is added. Each token becomes context for the next. "
172
  "The inspector displays sampling choices, not private thoughts or consciousness. "
173
- "Model output may take any form. Settings apply to the next pass; Begin replaces the current stream.")
 
174
  outputs = [page, panel, status]
175
  inputs = [flow, temperature, top_p, penalty, seed, count, watch, delay, memory]
176
  common = dict(concurrency_id="model", concurrency_limit=1)
 
 
 
 
 
177
  load.click(load_model, [repo, flow], [model_status, *outputs], **common)
178
  start.click(begin, inputs, outputs, **common)
179
  resume.click(run, inputs, outputs, **common)
 
58
  flow.stop.set()
59
 
60
 
61
+ def control_handler(name):
62
+ def update(value, flow):
63
+ try:
64
+ flow.update_controls(**{name: value})
65
+ except (ValueError, TypeError) as error:
66
+ raise gr.Error(str(error)) from error
67
+ return update
68
+
69
+
70
  def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128, fresh=False):
71
  if STORE.model is None:
72
  raise gr.Error("Load a model first.")
73
  if fresh:
74
  clear(flow)
75
+ flow.update_controls(temperature=temperature, top_p=top_p, penalty=penalty,
76
+ count=count, watch=watch, delay=delay, memory=memory)
77
  flow.stop.clear()
78
  panel = EMPTY
79
  started = time.monotonic()
 
84
  try:
85
  yield last_text, panel, "Generating…"
86
  for step in generate(STORE.model, STORE.tokenizer, flow, STORE.key,
87
+ count, temperature, top_p, penalty, seed, context_limit=memory,
88
+ live_settings=flow.controls):
89
  last_text = step["text"]
90
  trimmed = step["context_trimmed"]
91
+ controls = flow.controls()
92
+ watching = controls["watch"]
93
+ if watching:
94
  panel = inspector(STORE.tokenizer, step, len(flow.tokens))
95
  status = (f"{len(flow.tokens)} tokens · seed {flow.seed} · "
96
  f"{(len(flow.tokens) - before) / max(.001, time.monotonic() - started):.1f} tokens/s"
97
+ f" · memory {step['context_limit']} tokens"
98
+ f" · temperature {step['temperature']:g} · top-p {step['top_p']:g}"
99
+ f" · repetition {step['penalty']:g}")
100
  if trimmed:
101
  status += f" · Only the latest {step['context_limit']} tokens inform the next choice."
102
+ yield last_text, panel if watching else "", status
103
+ delay = flow.controls()["delay"]
104
  if delay and flow.stop.wait(float(delay)):
105
  break
106
  if flow.ended:
 
113
  reason = "Pass complete. Continue to let it flow further."
114
  if trimmed:
115
  reason += " Earlier text remains visible but is outside the model’s context."
116
+ controls = flow.controls()
117
+ yield last_text, panel if controls["watch"] else "", f"{reason} · {len(flow.tokens)} tokens · seed {flow.seed} · requested memory {int(controls['memory'])} tokens"
118
  except Exception as error:
119
  # Preserve already-generated text and RNG state so a failed pass can be retried.
120
  raise gr.Error(str(error)) from error
 
178
  info="1 leaves repetition unchanged; higher values discourage seen tokens.")
179
  memory = gr.Slider(16, 2048, value=128, step=1, label="Memory span (tokens)",
180
  info="Only this many recent tokens inform each choice. Try 64 for more drift; "
181
+ "2048 keeps a longer thread. Earlier text stays visible. Changes apply live.")
182
  with gr.Row():
183
  seed = gr.Number(value=None, precision=0, label="Random seed (optional)",
184
  info="Blank chooses a seed. Applied on Begin; Continue keeps the RNG sequence.")
185
+ count = gr.Slider(1, 1024, value=256, step=1, label="Tokens per pass",
186
+ info="Changes the current pass limit live. Increase it before the pass ends to extend it.")
187
  delay = gr.Slider(0, .5, value=.06, step=.02, label="Reading delay per token (seconds)",
188
  info="Slows the display, without changing the sampling distribution.")
189
  gr.Markdown("Starts from the model’s beginning token (or its end token when no beginning token exists). "
190
  "No written prompt or chat template is added. Each token becomes context for the next. "
191
  "The inspector displays sampling choices, not private thoughts or consciousness. "
192
+ "Model output may take any form. Sliders apply live from the next token after the update arrives; "
193
+ "the current inference step completes first. Seed applies on Begin, which replaces the current stream.")
194
  outputs = [page, panel, status]
195
  inputs = [flow, temperature, top_p, penalty, seed, count, watch, delay, memory]
196
  common = dict(concurrency_id="model", concurrency_limit=1)
197
+ for component, name in [(temperature, "temperature"), (top_p, "top_p"),
198
+ (penalty, "penalty"), (memory, "memory"), (count, "count"),
199
+ (delay, "delay"), (watch, "watch")]:
200
+ component.input(control_handler(name), [component, flow], [], queue=False,
201
+ trigger_mode="always_last", api_name=f"update_{name}", show_progress="hidden")
202
  load.click(load_model, [repo, flow], [model_status, *outputs], **common)
203
  start.click(begin, inputs, outputs, **common)
204
  resume.click(run, inputs, outputs, **common)
engine.py CHANGED
@@ -14,6 +14,26 @@ class Flow:
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.
@@ -50,7 +70,7 @@ def start_id(model, tokenizer):
50
 
51
 
52
  def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, seed,
53
- context_limit=128):
54
  if int(context_limit) != context_limit or not 1 <= context_limit <= 2048:
55
  raise ValueError("Memory span must be an integer from 1 to 2048 tokens.")
56
  context_limit = int(context_limit)
@@ -76,8 +96,20 @@ def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, se
76
  limit = min(context_limit, int(getattr(model.config, "max_position_embeddings", context_limit)))
77
  cache = None
78
  consumed = 0
 
79
  with torch.inference_mode():
80
- for _ in range(int(count)):
 
 
 
 
 
 
 
 
 
 
 
81
  if flow.stop.is_set():
82
  break
83
  if len(flow.tokens) >= 16384:
@@ -94,9 +126,10 @@ def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, se
94
  result = model(input_ids=input_ids, past_key_values=cache, use_cache=True)
95
  cache = result.past_key_values
96
  probs, before_nucleus = distribution(result.logits[0, -1], window,
97
- temperature, top_p, penalty)
98
  chosen = int(torch.multinomial(probs, 1, generator=rng))
99
  flow.tokens.append(chosen)
 
100
  flow.rng_state = rng.get_state()
101
  flow.ended = chosen in eos_ids
102
  flow.text = tokenizer.decode(flow.tokens, skip_special_tokens=True,
@@ -113,6 +146,8 @@ def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, se
113
  "other": max(0., 1. - sum(p for _, p in candidates)),
114
  "context_trimmed": len(all_ids) > limit,
115
  "context_limit": limit,
 
 
116
  }
117
  if flow.ended:
118
  break
 
14
  self.rng_state = None
15
  self.ended = ended
16
  self.stop = threading.Event()
17
+ self._control_lock = threading.Lock()
18
+ self._controls = {}
19
+
20
+ def update_controls(self, **changes):
21
+ bounds = {"temperature": (.05, 2), "top_p": (.05, 1), "penalty": (1, 2),
22
+ "memory": (16, 2048), "count": (1, 1024), "delay": (0, .5)}
23
+ for name, value in changes.items():
24
+ if name == "watch":
25
+ if not isinstance(value, bool):
26
+ raise ValueError("Watch must be true or false.")
27
+ elif name not in bounds or not bounds[name][0] <= value <= bounds[name][1]:
28
+ raise ValueError(f"Invalid live setting: {name}.")
29
+ elif name in ("memory", "count") and int(value) != value:
30
+ raise ValueError(f"{name} must be an integer.")
31
+ with self._control_lock:
32
+ self._controls = {**self._controls, **changes}
33
+
34
+ def controls(self):
35
+ with self._control_lock:
36
+ return self._controls.copy()
37
 
38
  def __deepcopy__(self, memo):
39
  return Flow() # Gradio creates an independent state for each visitor.
 
70
 
71
 
72
  def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, seed,
73
+ context_limit=128, live_settings=None):
74
  if int(context_limit) != context_limit or not 1 <= context_limit <= 2048:
75
  raise ValueError("Memory span must be an integer from 1 to 2048 tokens.")
76
  context_limit = int(context_limit)
 
96
  limit = min(context_limit, int(getattr(model.config, "max_position_embeddings", context_limit)))
97
  cache = None
98
  consumed = 0
99
+ emitted = 0
100
  with torch.inference_mode():
101
+ while True:
102
+ settings = live_settings() if live_settings is not None else {}
103
+ if emitted >= int(settings.get("count", count)):
104
+ break
105
+ next_limit = min(int(settings.get("memory", context_limit)),
106
+ int(getattr(model.config, "max_position_embeddings", context_limit)))
107
+ if next_limit != limit:
108
+ cache = None # Old cached activations must not leak forgotten context.
109
+ limit = next_limit
110
+ current_temperature = settings.get("temperature", temperature)
111
+ current_top_p = settings.get("top_p", top_p)
112
+ current_penalty = settings.get("penalty", penalty)
113
  if flow.stop.is_set():
114
  break
115
  if len(flow.tokens) >= 16384:
 
126
  result = model(input_ids=input_ids, past_key_values=cache, use_cache=True)
127
  cache = result.past_key_values
128
  probs, before_nucleus = distribution(result.logits[0, -1], window,
129
+ current_temperature, current_top_p, current_penalty)
130
  chosen = int(torch.multinomial(probs, 1, generator=rng))
131
  flow.tokens.append(chosen)
132
+ emitted += 1
133
  flow.rng_state = rng.get_state()
134
  flow.ended = chosen in eos_ids
135
  flow.text = tokenizer.decode(flow.tokens, skip_special_tokens=True,
 
146
  "other": max(0., 1. - sum(p for _, p in candidates)),
147
  "context_trimmed": len(all_ids) > limit,
148
  "context_limit": limit,
149
+ "temperature": current_temperature, "top_p": current_top_p,
150
+ "penalty": current_penalty,
151
  }
152
  if flow.ended:
153
  break