jejunepixels commited on
Commit
bb4dacd
·
verified ·
1 Parent(s): 55b2a40

Add adjustable live English-biased sampling without a prompt

Browse files
Files changed (6) hide show
  1. README.md +6 -2
  2. app.py +14 -10
  3. engine.py +13 -5
  4. english_bias.py +63 -0
  5. models.py +3 -0
  6. requirements.txt +2 -0
README.md CHANGED
@@ -36,7 +36,7 @@ GPU are available. Start with SmolLM2-135M; larger models can be slow on CPU.
36
  ## Hugging Face Space
37
 
38
  Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,
39
- `gpu_runtime.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
@@ -44,7 +44,7 @@ model; hardware determines the practical model size. This project is prepared fo
44
  Spaces but does not create or publish a remote Space automatically.
45
 
46
  Run `python scripts/prepare_space.py` to create `outputs/let-it-flow-space.zip`.
47
- Extract the archive and upload its ten files to the root of your Gradio Space.
48
 
49
  ## Token space
50
 
@@ -258,3 +258,7 @@ Frontend behavior checks: `node tests/check_token_space.cjs` (arrival, fading wh
258
  ## Public ZeroGPU deployment
259
 
260
  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.
 
 
 
 
 
36
  ## Hugging Face Space
37
 
38
  Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,
39
+ `gpu_runtime.py`, `english_bias.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
 
44
  Spaces but does not create or publish a remote Space automatically.
45
 
46
  Run `python scripts/prepare_space.py` to create `outputs/let-it-flow-space.zip`.
47
+ Extract the archive and upload its eleven files to the root of your Gradio Space.
48
 
49
  ## Token space
50
 
 
258
  ## Public ZeroGPU deployment
259
 
260
  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.
261
+
262
+ ## English-biased sampling
263
+
264
+ 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
app.py CHANGED
@@ -42,7 +42,7 @@ def inspector(tokenizer, step, number):
42
  '<h3>What could come next?</h3><p>Probabilities immediately before the latest token was selected.</p>'
43
  + "".join(rows) + f'<p>Other tokens: {step["other"]:.2%}</p>'
44
  f'<small>Top-p retained {step["retained_mass"]:.2%} of the distribution after '
45
- 'temperature and repetition penalty. Bars show probabilities renormalized over that set. '
46
  'The selected token may be outside the eight leading candidates.</small></div>')
47
 
48
 
@@ -111,7 +111,7 @@ def control_handler(name):
111
 
112
 
113
  def _run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
114
- auto_continue=True, attention=True, attention_layer=-1, attention_head=-1, fresh=False):
115
  if flow.reset_requested:
116
  return
117
  store = session_store(flow)
@@ -124,7 +124,7 @@ def _run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=12
124
  flow.update_controls(temperature=temperature, top_p=top_p, penalty=penalty,
125
  count=count, watch=watch, delay=delay, memory=memory,
126
  auto_continue=auto_continue, attention=attention,
127
- attention_layer=attention_layer, attention_head=attention_head)
128
  flow.continue_automatically = False
129
  flow.stop.clear()
130
  flow.paused = False
@@ -139,7 +139,8 @@ def _run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=12
139
  yield last_text, panel, "Generating…", frame(flow, session_store(flow), full=True)
140
  for step in generate(store.model, store.tokenizer, flow, store.key,
141
  count, temperature, top_p, penalty, seed, context_limit=memory,
142
- live_settings=flow.controls, attention_modules=store.attention_modules):
 
143
  last_text = step["text"]
144
  trimmed = step["context_trimmed"]
145
  controls = flow.controls()
@@ -151,6 +152,7 @@ def _run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=12
151
  f" · memory {step['context_limit']} tokens"
152
  f" · temperature {step['temperature']:g} · top-p {step['top_p']:g}"
153
  f" · repetition {step['penalty']:g}")
 
154
  if controls["auto_continue"]:
155
  status += " · automatic continuation on"
156
  if trimmed:
@@ -193,18 +195,18 @@ def _run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=12
193
 
194
  @spaces.GPU(duration=30)
195
  def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
196
- auto_continue=True, attention=True, attention_layer=-1, attention_head=-1, automatic=False):
197
  if automatic and (flow.paused or flow.reset_requested or not flow.continue_automatically):
198
  return
199
  for update in _run(flow, temperature, top_p, penalty, seed, count, watch, delay,
200
- memory, auto_continue, attention, attention_layer, attention_head):
201
  yield (*update, flow)
202
 
203
  @spaces.GPU(duration=30)
204
  def begin(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
205
- auto_continue=True, attention=True, attention_layer=-1, attention_head=-1):
206
  for update in _run(flow, temperature, top_p, penalty, seed, count, watch, delay,
207
- memory, auto_continue, attention, attention_layer, attention_head, fresh=True):
208
  yield (*update, flow)
209
 
210
 
@@ -281,6 +283,8 @@ def build_app():
281
  top_p = gr.Slider(.05, 1, value=1, step=.01, label="Top-p")
282
  penalty = gr.Slider(1, 2, value=1.1, step=.01, label="Repetition penalty")
283
  memory = gr.Slider(16, 2048, value=128, step=1, label="Memory span (tokens)")
 
 
284
  with gr.Row():
285
  attention = gr.Checkbox(label="Capture attention", value=True,
286
  info="Use Attention weights in Connections. Capture can slow generation.")
@@ -318,13 +322,13 @@ def build_app():
318
  pause = gr.Button("Pause generation", elem_id="generation-pause", elem_classes=["generation-proxy"])
319
  outputs = [page, panel, status, transport]
320
  inputs = [flow, temperature, top_p, penalty, seed, count, watch, delay, memory, auto_continue,
321
- attention, attention_layer, attention_head]
322
  common = dict(concurrency_id="model", concurrency_limit=1)
323
  for component, name in [(temperature, "temperature"), (top_p, "top_p"),
324
  (penalty, "penalty"), (memory, "memory"), (count, "count"),
325
  (delay, "delay"), (watch, "watch"), (auto_continue, "auto_continue"),
326
  (attention, "attention"), (attention_layer, "attention_layer"),
327
- (attention_head, "attention_head")]:
328
  component.input(control_handler(name), [component, flow], [], queue=False,
329
  trigger_mode="always_last", api_name=f"update_{name}", show_progress="hidden")
330
  load.click(load_model, [repo, flow], [model_status, *outputs, seed, model_badge, picker, workspace], **common)
 
42
  '<h3>What could come next?</h3><p>Probabilities immediately before the latest token was selected.</p>'
43
  + "".join(rows) + f'<p>Other tokens: {step["other"]:.2%}</p>'
44
  f'<small>Top-p retained {step["retained_mass"]:.2%} of the distribution after '
45
+ 'temperature, repetition penalty and English bias. Bars show probabilities renormalized over that set. '
46
  'The selected token may be outside the eight leading candidates.</small></div>')
47
 
48
 
 
111
 
112
 
113
  def _run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
114
+ auto_continue=True, attention=True, attention_layer=-1, attention_head=-1, fresh=False, english_bias=2):
115
  if flow.reset_requested:
116
  return
117
  store = session_store(flow)
 
124
  flow.update_controls(temperature=temperature, top_p=top_p, penalty=penalty,
125
  count=count, watch=watch, delay=delay, memory=memory,
126
  auto_continue=auto_continue, attention=attention,
127
+ attention_layer=attention_layer, attention_head=attention_head, english_bias=english_bias)
128
  flow.continue_automatically = False
129
  flow.stop.clear()
130
  flow.paused = False
 
139
  yield last_text, panel, "Generating…", frame(flow, session_store(flow), full=True)
140
  for step in generate(store.model, store.tokenizer, flow, store.key,
141
  count, temperature, top_p, penalty, seed, context_limit=memory,
142
+ live_settings=flow.controls, attention_modules=store.attention_modules,
143
+ english_prior=store.english_prior):
144
  last_text = step["text"]
145
  trimmed = step["context_trimmed"]
146
  controls = flow.controls()
 
152
  f" · memory {step['context_limit']} tokens"
153
  f" · temperature {step['temperature']:g} · top-p {step['top_p']:g}"
154
  f" · repetition {step['penalty']:g}")
155
+ status += f" / English bias {step['english_bias']:g}"
156
  if controls["auto_continue"]:
157
  status += " · automatic continuation on"
158
  if trimmed:
 
195
 
196
  @spaces.GPU(duration=30)
197
  def run(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
198
+ auto_continue=True, attention=True, attention_layer=-1, attention_head=-1, english_bias=2, automatic=False):
199
  if automatic and (flow.paused or flow.reset_requested or not flow.continue_automatically):
200
  return
201
  for update in _run(flow, temperature, top_p, penalty, seed, count, watch, delay,
202
+ memory, auto_continue, attention, attention_layer, attention_head, english_bias=english_bias):
203
  yield (*update, flow)
204
 
205
  @spaces.GPU(duration=30)
206
  def begin(flow, temperature, top_p, penalty, seed, count, watch, delay, memory=128,
207
+ auto_continue=True, attention=True, attention_layer=-1, attention_head=-1, english_bias=2):
208
  for update in _run(flow, temperature, top_p, penalty, seed, count, watch, delay,
209
+ memory, auto_continue, attention, attention_layer, attention_head, fresh=True, english_bias=english_bias):
210
  yield (*update, flow)
211
 
212
 
 
283
  top_p = gr.Slider(.05, 1, value=1, step=.01, label="Top-p")
284
  penalty = gr.Slider(1, 2, value=1.1, step=.01, label="Repetition penalty")
285
  memory = gr.Slider(16, 2048, value=128, step=1, label="Memory span (tokens)")
286
+ english_bias = gr.Slider(0, 4, value=2, step=.25, label="English bias",
287
+ info="Favour English without a prompt. 0 = off. Applies live; languages can still mix.")
288
  with gr.Row():
289
  attention = gr.Checkbox(label="Capture attention", value=True,
290
  info="Use Attention weights in Connections. Capture can slow generation.")
 
322
  pause = gr.Button("Pause generation", elem_id="generation-pause", elem_classes=["generation-proxy"])
323
  outputs = [page, panel, status, transport]
324
  inputs = [flow, temperature, top_p, penalty, seed, count, watch, delay, memory, auto_continue,
325
+ attention, attention_layer, attention_head, english_bias]
326
  common = dict(concurrency_id="model", concurrency_limit=1)
327
  for component, name in [(temperature, "temperature"), (top_p, "top_p"),
328
  (penalty, "penalty"), (memory, "memory"), (count, "count"),
329
  (delay, "delay"), (watch, "watch"), (auto_continue, "auto_continue"),
330
  (attention, "attention"), (attention_layer, "attention_layer"),
331
+ (attention_head, "attention_head"), (english_bias, "english_bias")]:
332
  component.input(control_handler(name), [component, flow], [], queue=False,
333
  trigger_mode="always_last", api_name=f"update_{name}", show_progress="hidden")
334
  load.click(load_model, [repo, flow], [model_status, *outputs, seed, model_badge, picker, workspace], **common)
engine.py CHANGED
@@ -86,7 +86,7 @@ class Flow:
86
 
87
  def update_controls(self, **changes):
88
  bounds = {"temperature": (.05, 2), "top_p": (.05, 1), "penalty": (1, 2),
89
- "memory": (16, 2048), "count": (1, 1024), "delay": (0, .5)}
90
  for name, value in changes.items():
91
  if name in ("watch", "auto_continue", "attention"):
92
  if not isinstance(value, bool):
@@ -109,8 +109,8 @@ class Flow:
109
  return Flow() # Gradio creates an independent state for each visitor.
110
 
111
 
112
- def distribution(logits, history, temperature, top_p, repetition_penalty):
113
- """Standard sign-aware repetition penalty, temperature, then nucleus filtering."""
114
  if not 0.05 <= temperature <= 2 or not 0 < top_p <= 1 or not 1 <= repetition_penalty <= 2:
115
  raise ValueError("Sampling settings are outside the supported range.")
116
  scores = logits.detach().float().cpu().clone()
@@ -118,6 +118,12 @@ def distribution(logits, history, temperature, top_p, repetition_penalty):
118
  ids = torch.tensor(sorted(set(history)), dtype=torch.long)
119
  values = scores[ids]
120
  scores[ids] = torch.where(values < 0, values * repetition_penalty, values / repetition_penalty)
 
 
 
 
 
 
121
  scores /= temperature
122
  raw = torch.softmax(scores, dim=-1)
123
  ordered, indices = torch.sort(raw, descending=True)
@@ -140,7 +146,7 @@ def start_id(model, tokenizer):
140
 
141
 
142
  def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, seed,
143
- context_limit=128, live_settings=None, attention_modules=None):
144
  if int(context_limit) != context_limit or not 1 <= context_limit <= 2048:
145
  raise ValueError("Memory span must be an integer from 1 to 2048 tokens.")
146
  context_limit = int(context_limit)
@@ -208,7 +214,8 @@ def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, se
208
  flow.attention_history = {i: row for i, row in flow.attention_history.items() if i >= query - 511}
209
  cache = result.past_key_values
210
  probs, before_nucleus = distribution(result.logits[0, -1], window,
211
- current_temperature, current_top_p, current_penalty)
 
212
  chosen = int(torch.multinomial(probs, 1, generator=rng))
213
  flow.tokens.append(chosen)
214
  emitted += 1
@@ -230,6 +237,7 @@ def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, se
230
  "context_limit": limit,
231
  "temperature": current_temperature, "top_p": current_top_p,
232
  "penalty": current_penalty,
 
233
  }
234
  if flow.ended:
235
  break
 
86
 
87
  def update_controls(self, **changes):
88
  bounds = {"temperature": (.05, 2), "top_p": (.05, 1), "penalty": (1, 2),
89
+ "memory": (16, 2048), "count": (1, 1024), "delay": (0, .5), "english_bias": (0, 4)}
90
  for name, value in changes.items():
91
  if name in ("watch", "auto_continue", "attention"):
92
  if not isinstance(value, bool):
 
109
  return Flow() # Gradio creates an independent state for each visitor.
110
 
111
 
112
+ def distribution(logits, history, temperature, top_p, repetition_penalty, english_prior=None, english_bias=0):
113
+ """Repetition penalty, optional language prior, temperature, then nucleus filtering."""
114
  if not 0.05 <= temperature <= 2 or not 0 < top_p <= 1 or not 1 <= repetition_penalty <= 2:
115
  raise ValueError("Sampling settings are outside the supported range.")
116
  scores = logits.detach().float().cpu().clone()
 
118
  ids = torch.tensor(sorted(set(history)), dtype=torch.long)
119
  values = scores[ids]
120
  scores[ids] = torch.where(values < 0, values * repetition_penalty, values / repetition_penalty)
121
+ if not 0 <= english_bias <= 4:
122
+ raise ValueError("English bias must be between 0 and 4.")
123
+ if english_bias and english_prior is not None:
124
+ if english_prior.shape != scores.shape:
125
+ raise ValueError("Language prior does not match model vocabulary.")
126
+ scores += english_prior * english_bias
127
  scores /= temperature
128
  raw = torch.softmax(scores, dim=-1)
129
  ordered, indices = torch.sort(raw, descending=True)
 
146
 
147
 
148
  def generate(model, tokenizer, flow, key, count, temperature, top_p, penalty, seed,
149
+ context_limit=128, live_settings=None, attention_modules=None, english_prior=None):
150
  if int(context_limit) != context_limit or not 1 <= context_limit <= 2048:
151
  raise ValueError("Memory span must be an integer from 1 to 2048 tokens.")
152
  context_limit = int(context_limit)
 
214
  flow.attention_history = {i: row for i, row in flow.attention_history.items() if i >= query - 511}
215
  cache = result.past_key_values
216
  probs, before_nucleus = distribution(result.logits[0, -1], window,
217
+ current_temperature, current_top_p, current_penalty,
218
+ english_prior, settings.get("english_bias", 0))
219
  chosen = int(torch.multinomial(probs, 1, generator=rng))
220
  flow.tokens.append(chosen)
221
  emitted += 1
 
237
  "context_limit": limit,
238
  "temperature": current_temperature, "top_p": current_top_p,
239
  "penalty": current_penalty,
240
+ "english_bias": settings.get("english_bias", 0),
241
  }
242
  if flow.ended:
243
  break
english_bias.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Soft token priors from word frequencies, never a hidden text prompt."""
2
+ from functools import lru_cache
3
+ import math
4
+ import re
5
+ import unicodedata
6
+ import torch
7
+ from wordfreq import get_frequency_dict
8
+
9
+ WORDS = re.compile(r"[^\W\d_]+", re.UNICODE)
10
+
11
+ @lru_cache(maxsize=1)
12
+ def lexicon():
13
+ english = get_frequency_dict("en", wordlist="small")
14
+ others = {}
15
+ for lang in ("es", "fr", "de", "it", "pt", "nl", "pl", "tr"):
16
+ for word, frequency in get_frequency_dict(lang, wordlist="small").items():
17
+ others[word] = max(others.get(word, 0), frequency)
18
+ fragments = set()
19
+ for word in english:
20
+ if word.isascii() and word.isalpha():
21
+ for length in range(2, min(len(word), 10)):
22
+ fragments.add(word[:length])
23
+ fragments.add(word[-length:])
24
+ return english, others, fragments
25
+
26
+ @lru_cache(maxsize=150000)
27
+ def piece_score(piece):
28
+ # Incomplete byte tokens remain neutral, preserving UTF-8 continuations.
29
+ if "\ufffd" in piece:
30
+ return 0.0
31
+ words = WORDS.findall(unicodedata.normalize("NFC", piece).casefold())
32
+ if not words:
33
+ return 0.0
34
+ english, others, fragments = lexicon()
35
+ values = []
36
+ for word in words:
37
+ en, other = english.get(word, 0), others.get(word, 0)
38
+ if en >= 1e-5:
39
+ value = 0.5 + min(0.5, max(0, math.log((en + 1e-8) / (other + 1e-8)) * 0.2))
40
+ elif en:
41
+ value = max(-0.5, min(0.75, math.log((en + 1e-8) / (other + 1e-8)) * 0.35))
42
+ elif any("LATIN" not in unicodedata.name(char, "") for char in word if char.isalpha()):
43
+ value = -2.0
44
+ elif other:
45
+ value = -1.5
46
+ elif len(word) <= 2 or word in fragments:
47
+ value = 0.15
48
+ else:
49
+ value = -0.35
50
+ values.append(value)
51
+ return sum(values) / len(values)
52
+
53
+ def build_prior(tokenizer, vocab_size):
54
+ prior = torch.zeros(vocab_size, dtype=torch.float32)
55
+ special = set(tokenizer.all_special_ids)
56
+ limit = min(len(tokenizer), vocab_size)
57
+ for start in range(0, limit, 4096):
58
+ ids = list(range(start, min(limit, start + 4096)))
59
+ pieces = tokenizer.batch_decode([[i] for i in ids], skip_special_tokens=False,
60
+ clean_up_tokenization_spaces=False)
61
+ prior[start:start + len(ids)] = torch.tensor([
62
+ 0.0 if i in special else piece_score(piece) for i, piece in zip(ids, pieces)])
63
+ return prior
models.py CHANGED
@@ -50,6 +50,7 @@ class ModelStore:
50
  self.projection = None
51
  self.attention_modules = []
52
  self.description = "No model loaded."
 
53
 
54
  def load(self, value):
55
  repo = repository(value)
@@ -98,6 +99,8 @@ class ModelStore:
98
  if ZERO_GPU or torch.cuda.is_available():
99
  model = model.to(device="cuda", dtype=compute_dtype if ZERO_GPU else torch.float16)
100
  self.projection.weights = model.get_input_embeddings().weight
 
 
101
  self.model, self.tokenizer = model, tokenizer
102
  from attention_view import attention_modules
103
  self.attention_modules = attention_modules(model)
 
50
  self.projection = None
51
  self.attention_modules = []
52
  self.description = "No model loaded."
53
+ self.english_prior = None
54
 
55
  def load(self, value):
56
  repo = repository(value)
 
99
  if ZERO_GPU or torch.cuda.is_available():
100
  model = model.to(device="cuda", dtype=compute_dtype if ZERO_GPU else torch.float16)
101
  self.projection.weights = model.get_input_embeddings().weight
102
+ from english_bias import build_prior
103
+ self.english_prior = build_prior(tokenizer, model.get_output_embeddings().weight.shape[0])
104
  self.model, self.tokenizer = model, tokenizer
105
  from attention_view import attention_modules
106
  self.attention_modules = attention_modules(model)
requirements.txt CHANGED
@@ -5,3 +5,5 @@ huggingface-hub==0.36.0
5
 
6
  spaces>=0.51.3,<0.53
7
  authlib==1.6.5
 
 
 
5
 
6
  spaces>=0.51.3,<0.53
7
  authlib==1.6.5
8
+
9
+ wordfreq==3.1.1