basal-engine 3.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. basal/__init__.py +7 -0
  2. basal/adapter.py +420 -0
  3. basal/adapters.py +8 -0
  4. basal/agree.py +393 -0
  5. basal/attach.py +160 -0
  6. basal/attn512.py +132 -0
  7. basal/auth.py +194 -0
  8. basal/bench.py +367 -0
  9. basal/blockquant.py +227 -0
  10. basal/calibrate.py +2198 -0
  11. basal/chat.py +175 -0
  12. basal/cli.py +70 -0
  13. basal/client.py +8 -0
  14. basal/decision_log.py +189 -0
  15. basal/decision_rules.py +569 -0
  16. basal/decisions.py +158 -0
  17. basal/derive.py +98 -0
  18. basal/disconnect.py +85 -0
  19. basal/engine.py +6023 -0
  20. basal/evidence.py +133 -0
  21. basal/examples/choice.jsonl +8 -0
  22. basal/examples/complex.jsonl +5 -0
  23. basal/examples/labelled_tickets.jsonl +500 -0
  24. basal/examples/local_backend.py +34 -0
  25. basal/examples/noul.jsonl +8 -0
  26. basal/examples/questions.jsonl +20 -0
  27. basal/examples/score.jsonl +8 -0
  28. basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
  29. basal/examples/selfcheck_basal-omni-pico.json +1 -0
  30. basal/examples/types_demo.py +74 -0
  31. basal/facts.py +497 -0
  32. basal/feedback.py +234 -0
  33. basal/file_identity.py +39 -0
  34. basal/finetune.py +321 -0
  35. basal/fit_decisions.py +944 -0
  36. basal/fla_configs.json +1822 -0
  37. basal/fold.py +206 -0
  38. basal/fonts/OFL-DMSans.txt +93 -0
  39. basal/fonts/OFL-SpaceGrotesk.txt +93 -0
  40. basal/fonts/dm-sans-latin-ext.woff2 +0 -0
  41. basal/fonts/dm-sans-latin.woff2 +0 -0
  42. basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
  43. basal/fonts/space-grotesk-latin.woff2 +0 -0
  44. basal/fp8block.py +100 -0
  45. basal/gdn_graph.py +1792 -0
  46. basal/gemma4.py +726 -0
  47. basal/gemma4_graph.py +931 -0
  48. basal/gguf_export.py +497 -0
  49. basal/identity.py +217 -0
  50. basal/int8block.py +50 -0
  51. basal/interpolate.py +330 -0
  52. basal/jsonl.py +172 -0
  53. basal/lean.py +204 -0
  54. basal/llama_attn.py +252 -0
  55. basal/llama_attn_kernels.py +266 -0
  56. basal/llama_graph.py +587 -0
  57. basal/llama_kernels.py +593 -0
  58. basal/loadtest.py +189 -0
  59. basal/mcp_server.py +432 -0
  60. basal/media.py +138 -0
  61. basal/metrics.py +16 -0
  62. basal/mlx_attn_kernels.py +1057 -0
  63. basal/mlx_forward.py +326 -0
  64. basal/mlx_kernels.py +543 -0
  65. basal/mlx_metal.py +510 -0
  66. basal/navcut.py +283 -0
  67. basal/navigate.py +646 -0
  68. basal/navtree.py +397 -0
  69. basal/nvfp4.py +245 -0
  70. basal/ordercheck.py +165 -0
  71. basal/pdf.py +183 -0
  72. basal/prepared.py +355 -0
  73. basal/presets.py +8 -0
  74. basal/prompt.py +462 -0
  75. basal/rank.py +373 -0
  76. basal/readout.py +121 -0
  77. basal/request.py +327 -0
  78. basal/response_cache.py +105 -0
  79. basal/router.py +1551 -0
  80. basal/router_ui.html +902 -0
  81. basal/router_ui.py +277 -0
  82. basal/run.py +376 -0
  83. basal/selfcheck.py +215 -0
  84. basal/server.py +5279 -0
  85. basal/sets.py +214 -0
  86. basal/signals.py +28 -0
  87. basal/state_disk.py +942 -0
  88. basal/strix.py +505 -0
  89. basal/synth.py +92 -0
  90. basal/tasks.py +848 -0
  91. basal/textio.py +21 -0
  92. basal/think.py +390 -0
  93. basal/tools.py +171 -0
  94. basal/tpu.py +336 -0
  95. basal/tpu_kernels.py +129 -0
  96. basal/trace.py +125 -0
  97. basal/ui.html +861 -0
  98. basal/ui.py +526 -0
  99. basal/varloop.py +813 -0
  100. basal/varloop_graph.py +1377 -0
  101. basal/varloop_kernels.py +907 -0
  102. basal/viz.html +660 -0
  103. basal/viz.py +375 -0
  104. basal/vllm_unified.py +100 -0
  105. basal_engine-3.0.3.dist-info/METADATA +416 -0
  106. basal_engine-3.0.3.dist-info/RECORD +111 -0
  107. basal_engine-3.0.3.dist-info/WHEEL +5 -0
  108. basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
  109. basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
  110. basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
  111. basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/viz.py ADDED
@@ -0,0 +1,375 @@
1
+ """Local visualiser: every step of a typed decision, from the rendered prompt to the calibrated answer.
2
+
3
+ basal-viz --model Remek/basal-2.0-mini --port 8080 then open http://127.0.0.1:8080
4
+
5
+ basal-viz --model Remek/basal-2.0-mini-MLX-8bit --mode mlx Apple Silicon: the MLX engine (mlx-q8 too)
6
+
7
+ The page runs a basal-serve Server in this process (--mode mps on Apple Silicon, eager elsewhere, or --mode mlx /
8
+ mlx-q8) and reads the layers of the model it serves.
9
+ POST /api/explain takes a /v1/basal request body and returns, per question (per label for multi): the prompt of each
10
+ option order the server asks (split into template / state / question / options / prefill; prompt format and option
11
+ codes from the model's basal.json, one order by default for format-2 models), the shared-prefix packing of the orders,
12
+ the code probabilities of each order, the per-layer readout ("logit lens": each layer's hidden state at the answer
13
+ position through the final norm and the output head, restricted to the option codes), the order average, the
14
+ calibrated distribution and the decision against the certified thresholds of the calibration file basal-serve loads.
15
+ The request is also answered by the server itself (Server.decide), to show that the page explains the served answer.
16
+ """
17
+ import argparse
18
+ import asyncio
19
+ import json
20
+ import os
21
+ import threading
22
+ import time
23
+ from pathlib import Path
24
+
25
+ import torch
26
+
27
+ from .engine import EagerBackend, default_device
28
+ from .facts import inject as inject_facts
29
+ from .gemma4 import is_gemma4, text_model
30
+ from .jsonl import read_lines
31
+ from .prompt import FORMATS, PREFILL, RequestError
32
+ from .run import to_request
33
+ from .server import Server, certified, http_status, temperature, to_items
34
+ from .server import parser as serve_parser
35
+
36
+ HERE = Path(__file__).resolve().parent
37
+ EXAMPLES = HERE / "examples"
38
+ TARGETS = ("0.01", "0.05") # max_error targets the page compares the confidence with
39
+
40
+
41
+ def segments(prompt, state, question, options, fmt=1):
42
+ """Split a rendered prompt into labelled pieces (the template text between them is "template")."""
43
+ codes = FORMATS[fmt]["codes"]
44
+ marks, at = [], 0
45
+ for kind, text in [("state", state), ("question", question)] + [
46
+ ("option", f"{codes[k]}. {o}") for k, o in enumerate(options)]:
47
+ i = prompt.find(text, at) if text else -1
48
+ if i < 0:
49
+ continue
50
+ marks.append((i, i + len(text), kind))
51
+ at = i + len(text)
52
+ out, at = [], 0
53
+ for a, b, kind in marks:
54
+ if a > at:
55
+ out.append({"kind": "template", "text": prompt[at:a]})
56
+ out.append({"kind": kind, "text": prompt[a:b]})
57
+ at = b
58
+ tail = prompt[at:]
59
+ if tail.endswith(PREFILL):
60
+ if tail[: -len(PREFILL)]:
61
+ out.append({"kind": "template", "text": tail[: -len(PREFILL)]})
62
+ out.append({"kind": "prefill", "text": PREFILL})
63
+ elif tail:
64
+ out.append({"kind": "template", "text": tail})
65
+ return out
66
+
67
+
68
+ MLX_MODES = ("mlx", "mlx-q8")
69
+
70
+
71
+ def lens_parts(model):
72
+ """(decoder, output head, final logit softcap) the PyTorch lens reads: the Llama model, or the text decoder of a
73
+ Gemma 4 basal-omni model with its head (bias) and softcap."""
74
+ if not is_gemma4(model):
75
+ return model.model, model.lm_head, None
76
+ tm = text_model(model)
77
+ return tm, model.get_output_embeddings(), getattr(tm.config, "final_logit_softcapping", None)
78
+
79
+
80
+ @torch.no_grad()
81
+ def torch_lens(model, dev, ids, codes, parts=None):
82
+ """Forward with a hook on every decoder layer -> code distribution after each layer (fp32 code logits, as the
83
+ engines read them; the head's bias and the final logit softcap where the model has them) and the top 5 tokens
84
+ (ids, probabilities) of the full vocabulary at the last layer. parts: lens_parts(model)."""
85
+ mm, head, softcap = parts or lens_parts(model)
86
+ caught = []
87
+ hooks = [layer.register_forward_hook(
88
+ lambda _m, _i, o: caught.append((o[0] if isinstance(o, tuple) else o)[0, -1].clone()))
89
+ for layer in mm.layers]
90
+ try:
91
+ final = mm(input_ids=torch.tensor([ids], device=dev), use_cache=False,
92
+ output_hidden_states=False).last_hidden_state[0, -1]
93
+ finally:
94
+ for h in hooks:
95
+ h.remove()
96
+ H = torch.stack([mm.norm(h[None])[0] for h in caught[:-1]] + [final])
97
+ W = head.weight
98
+ logits = H.float() @ W[codes].float().T
99
+ top_logits = H[-1] @ W.T
100
+ if head.bias is not None:
101
+ logits = logits + head.bias[codes].float()
102
+ top_logits = top_logits + head.bias.float()
103
+ if softcap:
104
+ logits = torch.tanh(logits / softcap) * softcap
105
+ top_logits = torch.tanh(top_logits.float() / softcap) * softcap
106
+ per_layer = torch.softmax(logits, -1)
107
+ top = torch.log_softmax(top_logits.float(), -1).topk(5) # what the model would write without the codes
108
+ return per_layer.tolist(), [(int(i), float(p.exp())) for p, i in zip(top.values, top.indices)]
109
+
110
+
111
+ class _Catch:
112
+ """An MLX decoder layer that also keeps its output at the last position (attributes pass through to the layer)."""
113
+
114
+ def __init__(self, layer, out):
115
+ self.layer, self.out = layer, out
116
+
117
+ def __getattr__(self, name):
118
+ return getattr(self.layer, name)
119
+
120
+ def __call__(self, *args, **kw):
121
+ h = self.layer(*args, **kw)
122
+ self.out.append(h[0, -1])
123
+ return h
124
+
125
+
126
+ def mlx_lens(be, ids, codes):
127
+ """torch_lens on the MLX backend that serves (--mode mlx / mlx-q8), on its thread: each decoder layer's output at
128
+ the answer position through the final norm, read as the backend reads the codes (MLXBackend._letters: fp32 code
129
+ rows, or the quantised head itself)."""
130
+ def run():
131
+ mx, mm, caught = be.mx, be.lm.model, []
132
+ layers = mm.layers
133
+ mm.layers = [_Catch(layer, caught) for layer in layers]
134
+ try:
135
+ final = mm(mx.array([ids]))[0, -1]
136
+ finally:
137
+ mm.layers = layers
138
+ H = mx.stack([mm.norm(h) for h in caught[:-1]] + [final])
139
+ per_layer = be._letters(H, [codes] * len(caught))
140
+ z = be._head(H[-1:])[0].astype(mx.float32)
141
+ if be.softcap:
142
+ z = mx.tanh(z / be.softcap) * be.softcap
143
+ top = mx.argsort(-z)[:5]
144
+ p = mx.exp(z[top] - mx.logsumexp(z))
145
+ return per_layer, list(zip(top.tolist(), p.tolist()))
146
+ return be.pool.submit(run).result()
147
+
148
+
149
+ def packing(toks):
150
+ """Tokens of the option orders' prompts: shared prefix (computed once in the packed row), each order's own tail,
151
+ and the tokens of separate prompts."""
152
+ prefix = len(os.path.commonprefix(toks)) if len(toks) > 1 else 0
153
+ return dict(prefix=prefix, tails=[len(t) - prefix for t in toks], separate=sum(map(len, toks)))
154
+
155
+
156
+ class Explainer:
157
+ mlx = False # --mode mlx / mlx-q8: the MLX engine's layers (mlx_lens), else the PyTorch model's (torch_lens)
158
+
159
+ def __init__(self, a):
160
+ mode = getattr(a, "mode", None)
161
+ if mode in MLX_MODES: # the MLX engine of basal-serve: the page reads its layers
162
+ if a.device:
163
+ raise SystemExit(f"--device is for the PyTorch modes; --mode {mode} runs on the Mac's GPU")
164
+ args = ["--model", a.model, "--mode", mode]
165
+ else:
166
+ dev = a.device or default_device()
167
+ # the in-process PyTorch engines: the page reads the model's layers
168
+ mode = "mps" if dev == "mps" else "eager"
169
+ args = ["--model", a.model, "--mode", mode, "--dtype", a.dtype]
170
+ args += ["--device", dev] if mode == "eager" else []
171
+ args += ["--orders", str(a.orders)] if a.orders else []
172
+ args += ["--calibration", a.calibration] if a.calibration else []
173
+ self.srv = Server(serve_parser().parse_args(args))
174
+ be = self.srv.backend
175
+ self.mlx = mode in MLX_MODES
176
+ self.tok, self.fmt = be.tok, self.srv.fmt
177
+ if self.mlx:
178
+ q = be.quantization
179
+ self.model, self.dev, self.gemma4 = None, "mlx", False
180
+ arch, n_layers = be.config.get("model_type"), len(be.lm.model.layers)
181
+ # "8-bit"; "4-bit nvfp4" for an -MLX-fp4 export (quantisation mode other than affine); bf16 weights
182
+ dtype = (f"{q['bits']}-bit" + (f" {q['mode']}" if q.get("mode", "affine") != "affine" else "") if q
183
+ else str(be.lm.model.embed_tokens.weight.dtype).rsplit(".", 1)[-1])
184
+ if arch != "llama":
185
+ raise SystemExit(f"basal-viz --mode {mode} reads the layers of the Llama-architecture models (basal-1.0, "
186
+ f"basal-1.5, basal-2.0); {a.model} is {arch!r} (Gemma 4 basal-omni: the PyTorch "
187
+ "modes)")
188
+ else:
189
+ self.model, self.dev, dtype = be.model, be.dev, a.dtype
190
+ self.gemma4 = is_gemma4(self.model)
191
+ if not self.gemma4 and getattr(self.model.config, "model_type", None) != "llama":
192
+ raise SystemExit(f"basal-viz reads the layers of the Llama-architecture models (basal-1.0, basal-1.5, "
193
+ f"basal-2.0) and Gemma 4 basal-omni; {a.model} is {self.model.config.model_type!r}")
194
+ self.text_model, self.head, self.softcap = lens_parts(self.model)
195
+ n_layers = len(self.text_model.layers)
196
+ self.name = self.srv.name
197
+ self.lock = threading.Lock()
198
+ cal = self.srv.cal
199
+ self.thresholds = {t: {q: certified(cal, float(t), q) for q in ("choice", "noul", "score")} for t in TARGETS}
200
+ self.info = {"model": self.name, "device": str(self.dev), "dtype": dtype, "mode": mode,
201
+ "layers": n_layers, "prompt_format": self.fmt, "orders": self.srv.orders,
202
+ "thresholds": self.thresholds, "temperatures": cal.get("temperature_per_prim", {}),
203
+ "temperature_per_bucket": cal.get("temperature_per_bucket", {})}
204
+
205
+ def lens(self, ids, codes):
206
+ """Code distribution after each layer and the top tokens of the full vocabulary at the last layer."""
207
+ if self.mlx:
208
+ per_layer, top = mlx_lens(self.srv.backend, ids, codes)
209
+ else:
210
+ # shortcut: full-sequence Gemma lens is limited to one eager chunk; use chunked capture for longer prompts.
211
+ if self.gemma4 and len(ids) > EagerBackend.CHUNK:
212
+ raise RequestError(f"Gemma 4 inspection supports at most {EagerBackend.CHUNK} prompt tokens; "
213
+ "shorten the state or question")
214
+ per_layer, top = torch_lens(self.model, self.dev, ids, codes, (self.text_model, self.head, self.softcap))
215
+ return per_layer, [(self.tok.decode([i]), p) for i, p in top]
216
+
217
+ def explain_branch(self, q, bi):
218
+ question, options = q["branches"][bi]
219
+ k = len(options)
220
+ t = "noul" if q["type"] == "multi" or q.get("multi") else q.get("base", q["type"])
221
+ t0 = time.perf_counter()
222
+ jobs = self.srv.jobs_for(q, question, options) # (perm, prompt, code ids) per option order, as served
223
+ if any(ids is None for _, _, ids in jobs):
224
+ raise ValueError("option codes are not single tokens for this tokenizer")
225
+ codes = FORMATS[self.fmt]["codes"]
226
+ orders, toks = [], []
227
+ for perm, prompt, cids in jobs:
228
+ ids = self.tok(prompt, add_special_tokens=False).input_ids
229
+ toks.append(ids)
230
+ opts = [options[c] for c in perm]
231
+ orders.append(dict(perm=perm, prompt=prompt, segments=segments(prompt, q["state"], question, opts, self.fmt),
232
+ n_tokens=len(ids), letters=list(codes[:k]), letter_ids=cids))
233
+ t_tok = time.perf_counter() - t0
234
+ # the lens runs the whole prompt without truncation: a prompt over the context (the model's, or the engine's
235
+ # own limit, as basal-serve checks it) is refused before any forward
236
+ limit, n = getattr(self.srv, "context", None), max(map(len, toks))
237
+ if limit and n > limit[0]:
238
+ raise RequestError(f"basal-viz explains prompts within {limit[1]} ({limit[0]} tokens); this prompt has "
239
+ f"{n} (basal-serve would truncate its state)")
240
+
241
+ t0 = time.perf_counter()
242
+ for o, ids in zip(orders, toks):
243
+ layers, top = self.lens(ids, o["letter_ids"])
244
+ o["letter_probs"], o["top_tokens"] = layers[-1], top
245
+ canon = lambda p, perm=o["perm"]: [p[perm.index(j)] for j in range(k)] # position -> option index
246
+ o["canon"] = canon(o["letter_probs"])
247
+ o["layers_canon"] = [canon(p) for p in layers]
248
+ t_sep = time.perf_counter() - t0
249
+
250
+ t0 = time.perf_counter()
251
+ packed = self.srv.backend.run_shared([(toks, [o["letter_ids"] for o in orders])])[0]
252
+ t_packed = time.perf_counter() - t0
253
+ diff = max(abs(a - b) for o, p in zip(orders, packed) for a, b in zip(o["letter_probs"], p))
254
+
255
+ mean = [sum(o["canon"][j] for o in orders) / len(orders) for j in range(k)]
256
+ T = temperature(self.srv.cal, t, k)
257
+ cal = self.srv.canonical(t, [o["perm"] for o in orders], [o["letter_probs"] for o in orders])
258
+ conf = max(cal)
259
+ best = cal.index(conf)
260
+ multi = q["type"] == "multi" or q.get("multi")
261
+ keys = ["true", "false"] if multi else q["keys"]
262
+ answer = {"index": best, "key": keys[best], "confidence": conf}
263
+ if t == "noul":
264
+ answer["noul"] = cal[0]
265
+ elif t == "score":
266
+ answer["score"] = sum(i * v for i, v in enumerate(cal))
267
+ n_layers = len(orders[0]["layers_canon"])
268
+ label = q["labels"][bi] if multi and q.get("labels") else None
269
+ return dict(
270
+ name=q["name"] + (f" · {label}" if label else ""), qname=q["name"], label_key=q["keys"][bi] if multi else None,
271
+ type=t, kind=q["type"], lang=q["lang"], keys=keys, options=list(options), question=question, orders=orders,
272
+ packing=packing(toks),
273
+ layers=[[sum(o["layers_canon"][L][j] for o in orders) / len(orders) for j in range(k)] for L in range(n_layers)],
274
+ mean=mean, temperature=T, calibrated=cal, answer=answer,
275
+ thresholds={target: self.thresholds[target].get(t) for target in TARGETS}, packed_max_diff=diff,
276
+ timing_ms=dict(tokenize=t_tok * 1000, separate_with_lens=t_sep * 1000, packed=t_packed * 1000))
277
+
278
+ def explain(self, body):
279
+ """The page's steps for every question of a request (one entry per label of a multi question); with
280
+ "facts": "auto" the state carries the computed facts, as basal-serve reads it. Text only: a request with media
281
+ is refused."""
282
+ if body.get("facts", "off") not in ("off", "auto"):
283
+ raise RequestError('facts must be "off" or "auto"')
284
+ if body.get("media"):
285
+ raise ValueError("basal-viz reads text only: remove the media to inspect this request")
286
+ with self.lock:
287
+ t0 = time.perf_counter()
288
+ state = body["state"]
289
+ if body.get("facts") == "auto":
290
+ state = inject_facts(state if isinstance(state, str) else json.dumps(state, ensure_ascii=False))
291
+ items = to_items(state, body["questions"], self.srv.max_options, force_lang=body.get("lang"))
292
+ qs = [self.explain_branch(q, bi) for q in items for bi in range(len(q["branches"]))]
293
+ return {"model": self.name, "questions": qs, "total_ms": (time.perf_counter() - t0) * 1000}
294
+
295
+
296
+ def compare_served(res, served):
297
+ """Largest difference between each explained distribution and the probabilities basal-serve returns."""
298
+ for q in res["questions"]:
299
+ a = served["answers"].get(q["qname"], {}).get("probabilities") or {}
300
+ if q["label_key"] is not None:
301
+ ours = {q["label_key"]: q["calibrated"][0]} # multi: P(yes) per label
302
+ else:
303
+ ours = dict(zip(q["keys"], q["calibrated"]))
304
+ q["served_max_diff"] = max((abs(v - a[k]) for k, v in ours.items() if k in a), default=None)
305
+ res["served"] = served["answers"]
306
+ return res
307
+
308
+
309
+ def examples():
310
+ out = []
311
+ for f in sorted(EXAMPLES.glob("*.jsonl")):
312
+ for n, line in enumerate(read_lines(f)):
313
+ if not line.strip():
314
+ continue
315
+ item = json.loads(line)
316
+ ex = {"file": f.stem, "id": item.get("id") or f"{f.stem}-{n + 1}", "request": to_request(item)}
317
+ if "gold" in item and "questions" not in item:
318
+ ex["gold"] = {"q": ["true", "false"][item["gold"]] if item.get("type") == "noul" else str(item["gold"])}
319
+ out.append(ex)
320
+ return out
321
+
322
+
323
+ def main():
324
+ ap = argparse.ArgumentParser(description="basal decision visualiser (local web page)")
325
+ ap.add_argument("--model", default="Remek/basal-2.0-mini", help="local directory or Hugging Face repo id")
326
+ ap.add_argument("--mode", default=None, choices=MLX_MODES,
327
+ help="Apple Silicon: the MLX engine of basal-serve (the -MLX-8bit / -MLX-fp4 exports or bf16 "
328
+ "weights; mlx-q8: 8-bit weights made at load time); default: the PyTorch engine of --device")
329
+ ap.add_argument("--dtype", default="bfloat16", help="the PyTorch modes")
330
+ ap.add_argument("--device", default=None, choices=["cuda", "mps", "cpu"],
331
+ help=f"default here: {default_device()} (mps runs --mode mps, cuda and cpu --mode eager)")
332
+ ap.add_argument("--orders", type=int, choices=[1, 2], default=None,
333
+ help="option orders per question (default: the model's, 1 for prompt-format-2 models)")
334
+ ap.add_argument("--calibration", default=None, help="a calibration file instead of the model's (as basal-serve)")
335
+ ap.add_argument("--host", default="127.0.0.1")
336
+ ap.add_argument("--port", type=int, default=8080)
337
+ a = ap.parse_args()
338
+
339
+ import uvicorn
340
+ from starlette.applications import Starlette
341
+ from starlette.responses import FileResponse, JSONResponse
342
+ from starlette.routing import Route
343
+
344
+ t0 = time.time()
345
+ ex = Explainer(a)
346
+ exs = examples()
347
+ # The lens hooks and served comparison share one model, including on the MPS backend.
348
+ inspection_lock = asyncio.Lock()
349
+
350
+ async def explain(request):
351
+ try:
352
+ body = await request.json()
353
+ async with inspection_lock:
354
+ res = await asyncio.get_running_loop().run_in_executor(None, ex.explain, body)
355
+ return JSONResponse(compare_served(res, await ex.srv.decide(body)))
356
+ except Exception as e: # noqa: BLE001
357
+ return JSONResponse({"error": str(e)}, status_code=http_status(e))
358
+
359
+ async def lifespan(_app):
360
+ task = asyncio.get_running_loop().create_task(ex.srv.worker()) # the batching loop of basal-serve
361
+ yield
362
+ task.cancel()
363
+
364
+ app = Starlette(routes=[
365
+ Route("/", lambda _: FileResponse(HERE / "viz.html")),
366
+ Route("/api/info", lambda _: JSONResponse(ex.info)),
367
+ Route("/api/examples", lambda _: JSONResponse(exs)),
368
+ Route("/api/explain", explain, methods=["POST"]),
369
+ ], lifespan=lifespan)
370
+ print(f"basal-viz: {ex.name} on {ex.dev} ready in {time.time() - t0:.0f}s -> http://{a.host}:{a.port}", flush=True)
371
+ uvicorn.run(app, host=a.host, port=a.port, log_level="warning")
372
+
373
+
374
+ if __name__ == "__main__":
375
+ main()
basal/vllm_unified.py ADDED
@@ -0,0 +1,100 @@
1
+ """Images and audio of Gemma 4 Unified models (basal-omni-1.1-max) through vLLM (`--mode vllm --media on`).
2
+
3
+ vLLM 0.31 serves Gemma4UnifiedForConditionalGeneration with two rules of the Gemma 4 models with encoders (31B) that
4
+ the unified models do not follow (transformers' Gemma4UnifiedModel and `--mode eager`):
5
+
6
+ - **Image attention.** The soft tokens of one image attend to each other in every layer, OR-ed after the sliding
7
+ window (create_masks_for_generate). vLLM keeps that block in the sliding-window layers only, clamped to the window,
8
+ and makes the global layers causal: through vLLM 1.1-max's images got the eager answer on 94.2% only.
9
+ - **Audio token counts.** The processor gives one soft token per audio_samples_per_token (640) samples:
10
+ ceil(samples / 640). vLLM counts the mel frames and the two stride-2 convolutions of the encoder models, which
11
+ differs on some clip lengths (19 of 285 clips).
12
+
13
+ patch() changes both in the process that runs it, once: the prompt processor (the process that calls vLLM) and the
14
+ model. The model is built in vLLM's worker, which imports this module as its worker extension (WORKER_EXTENSION,
15
+ vLLM's worker_extension_cls) before it builds the model and patches on import when ENV is set (vllm_args sets both);
16
+ check() reads the flags of the loaded model back, so a server whose worker missed the patch refuses to start instead of
17
+ reading images the encoder models' way.
18
+ """
19
+ import math
20
+ import os
21
+
22
+ WORKER_EXTENSION = "basal.vllm_unified.UnifiedWorker"
23
+ ENV = "BASAL_VLLM_UNIFIED"
24
+ ARCH = "Gemma4UnifiedForConditionalGeneration"
25
+
26
+
27
+ def is_unified(cfg):
28
+ """A Gemma 4 Unified model by its config.json."""
29
+ return ARCH in (cfg.get("architectures") or ())
30
+
31
+
32
+ def audio_tokens(samples, samples_per_token=640, cap=None):
33
+ """Soft tokens of an audio clip of `samples` samples, as the unified processor counts them (ceil), at most cap."""
34
+ n = math.ceil(samples / samples_per_token)
35
+ return n if cap is None else min(n, cap)
36
+
37
+
38
+ def _unify(model):
39
+ """A built Gemma4UnifiedForConditionalGeneration: image blocks in the global layers too, past the window."""
40
+ model._full_attn_layer_idxs = frozenset() # vLLM clears the image ranges of these layers at every forward
41
+ for m in model.language_model.modules():
42
+ if hasattr(m, "mm_prefix_clamp_sliding_window"):
43
+ m.mm_prefix_clamp_sliding_window = False # (causal AND window) OR image block
44
+
45
+
46
+ def patch():
47
+ """Patch vLLM's Gemma4 Unified model and prompt processor in this process (idempotent)."""
48
+ try:
49
+ from vllm.model_executor.models import gemma4_unified as gu
50
+ from vllm.model_executor.models.gemma4_mm import PromptUpdateDetails
51
+ except ImportError as e:
52
+ raise SystemExit(f"--media on with --mode vllm for Gemma 4 Unified models needs vLLM's gemma4_unified ({e})")
53
+ model, info = gu.Gemma4UnifiedForConditionalGeneration, gu.Gemma4UnifiedProcessingInfo
54
+ if getattr(model, "_basal_unified", False):
55
+ return
56
+ if not hasattr(model, "_clear_mm_prefix_for_full_attn_layers") or not hasattr(info, "get_audio_repl"):
57
+ raise SystemExit("--media on with --mode vllm for Gemma 4 Unified models: this vLLM's Gemma 4 code is not the "
58
+ "one checked (vLLM 0.31); use --mode eager --media on")
59
+ init = model.__init__
60
+
61
+ def __init__(self, *, vllm_config, prefix=""): # vLLM builds a model by these parameter names (inspect.signature)
62
+ init(self, vllm_config=vllm_config, prefix=prefix)
63
+ _unify(self)
64
+
65
+ def get_audio_repl(self, *, audio_len, processor=None):
66
+ processor = processor or self.get_hf_processor()
67
+ cfg = self.get_hf_config()
68
+ n = audio_tokens(audio_len, getattr(processor.feature_extractor, "audio_samples_per_token", 640),
69
+ processor.audio_seq_length)
70
+ eoa = cfg.eoa_token_id if hasattr(cfg, "eoa_token_id") else cfg.eoa_token_index
71
+ ids = [cfg.boa_token_id] + [processor.audio_token_id] * n + [eoa]
72
+ return PromptUpdateDetails.select_token_id(ids, processor.audio_token_id)
73
+
74
+ model.__init__, info.get_audio_repl = __init__, get_audio_repl
75
+ model._basal_unified = True
76
+
77
+
78
+ def flags(model):
79
+ """(global layers whose image ranges vLLM clears, attention layers that clamp an image to the window)."""
80
+ clamped = sum(bool(getattr(m, "mm_prefix_clamp_sliding_window", False)) for m in model.language_model.modules())
81
+ return len(model._full_attn_layer_idxs), clamped
82
+
83
+
84
+ def check(llm):
85
+ """Refuse a server whose worker built the model without the patch (SystemExit)."""
86
+ got = llm.collective_rpc("basal_unified_flags")
87
+ if any(tuple(f) != (0, 0) for f in got):
88
+ raise SystemExit(f"--media on with --mode vllm: vLLM's worker did not take the Gemma 4 Unified attention rule "
89
+ f"(global layers cleared, layers clamped: {got}); use --mode eager --media on")
90
+
91
+
92
+ class UnifiedWorker:
93
+ """vLLM worker extension: importing this module in the worker patched it; basal_unified_flags reports the model."""
94
+
95
+ def basal_unified_flags(self):
96
+ return flags(self.get_model())
97
+
98
+
99
+ if os.environ.get(ENV) == "1": # vLLM's worker imports this module by WORKER_EXTENSION before it builds the model
100
+ patch()