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/bench.py ADDED
@@ -0,0 +1,367 @@
1
+ """Offline benchmark of serving modes (no HTTP): latency, throughput, agreement with the first mode, accuracy.
2
+
3
+ basal-bench --model Remek/basal-1.5-4.5B --modes eager-fp32 fast fp8 # bundled examples
4
+ basal-bench --model Remek/basal-1.5-4.5B --modes eager-fp32 fast --questions my_items.jsonl
5
+ basal-bench --identity --model Remek/basal-1.5-4.5B # identity gate of the fast path (basal/identity.py)
6
+ basal-bench --order-check --model Remek/basal-1.5-4.5B # top-pick flips under other option orders (ordercheck.py)
7
+
8
+ Questions file (JSONL): {"state": ..., "question": ..., "options": [...], "gold": <index, optional>}.
9
+ Measured per mode (same definitions as in the technical report):
10
+ lat1_ms median latency of one decision with ONE option order at batch size 1
11
+ lat2_ms median latency of one decision with BOTH option orders at batch size 1 (what the server does by default)
12
+ dec_s two-order decisions per second when 32 option-order passes are processed together
13
+ agree share of decisions whose top option equals the first mode's (default reference: eager-fp32; on Apple
14
+ Silicon bf16 mps, not fp32)
15
+ acc accuracy of the averaged two-order decision (if gold is given)
16
+ """
17
+ import argparse
18
+ import gc
19
+ import json
20
+ import math
21
+ import random
22
+ import statistics
23
+ import time
24
+ from pathlib import Path
25
+
26
+ import torch
27
+
28
+ from . import adapter as adapter_module
29
+ from .cli import positive
30
+ from .engine import (EagerBackend, ExitGraphBackend, GGUFBackend, GraphBackend, LlamaCppBackend, MLXBackend,
31
+ MPSBackend, OllamaBackend, SGLangBackend, VLLMBackend, resolve)
32
+ from .jsonl import records, write_json
33
+ from .prompt import letter_ids, max_options, model_format, render
34
+ from .server import MODES, adapter_refused, adapter_refused_kind, default_mode
35
+
36
+ GGUF_KINDS = ("gguf", "ollama", "llamacpp") # the engine serves GGUF weights: --model gives tokenizer and calibration
37
+ MIN_ITEMS = 6 # the latency runs warm up on the first 5 items and time the ones after them
38
+
39
+
40
+ def build(mode, md, vllm_model=None, gguf=None, ollama_model=None, ollama_url="http://127.0.0.1:11434",
41
+ llamacpp_url="http://127.0.0.1:8080", fmt=1, mlx_packed=False, mlx_forward="mlx-lm", adapter=None):
42
+ """adapter: a LoRA adapter (basal.adapter.read) merged at load / served natively (main refuses it for the
43
+ ADAPTER_REFUSED kinds)."""
44
+ ad = dict(adapter=adapter)
45
+ if mode == "eager-fp32":
46
+ return EagerBackend(md, "float32", **ad)
47
+ if mode.startswith("fast-exit@"):
48
+ return ExitGraphBackend(md, "bfloat16", compile=True, default_policy=mode.split("@")[1])
49
+ if mode == "gguf" or mode.startswith("gguf@"):
50
+ path = mode.split("@", 1)[1] if "@" in mode else gguf
51
+ if not path:
52
+ raise SystemExit("mode gguf needs --gguf <file.gguf> (or gguf@<file.gguf>)")
53
+ return GGUFBackend(md, path)
54
+ if mode in ("tpu", "tpu-fp32"): # Google TPU (basal-engine[tpu]); tpu-fp32: the same engine in fp32 (parity reference)
55
+ from .tpu import TPUBackend
56
+ return TPUBackend(md, "float32" if mode == "tpu-fp32" else "bfloat16", warm=False, **ad)
57
+ if mode.startswith("vllm@"): # vllm@<preset>: basal-serve --mode vllm --vllm-preset <preset>
58
+ return VLLMBackend(vllm_model or md, max_options=max_options(fmt), preset=mode.split("@", 1)[1], **ad)
59
+ kind, quant, comp = MODES[mode]
60
+ if kind == "eager":
61
+ return EagerBackend(md, "bfloat16", **ad)
62
+ if kind == "vllm":
63
+ return VLLMBackend(vllm_model or md, max_options=max_options(fmt), **ad)
64
+ if kind == "sglang":
65
+ return SGLangBackend(md, **ad)
66
+ if kind == "mlx":
67
+ return MLXBackend(md, quant=quant, packed=mlx_packed, forward=mlx_forward, **ad)
68
+ if kind == "mps":
69
+ return MPSBackend(md, "bfloat16", **ad)
70
+ if kind == "ollama":
71
+ return OllamaBackend(md, ollama_url, ollama_model)
72
+ if kind == "llamacpp":
73
+ return LlamaCppBackend(md, llamacpp_url)
74
+ if kind == "strix":
75
+ from .strix import StrixHaloFastBackend
76
+ return StrixHaloFastBackend(md, "bfloat16", **ad)
77
+ if kind == "exit":
78
+ return ExitGraphBackend(md, "bfloat16", quant, compile=comp)
79
+ return GraphBackend(md, "bfloat16", quant, compile=comp, shared=True, **ad)
80
+
81
+
82
+ def default_modes(model=None):
83
+ """A reference that fits the device, then the serving default: eager-fp32 on CUDA and CPU, bf16 mps on Apple
84
+ Silicon (the fp32 4.5B needs about 18 GB); a model with recurrent-state layers (Qwen3.5) gets eager alone there
85
+ (mps refuses it)."""
86
+ mode = default_mode(model)
87
+ if not torch.cuda.is_available() and torch.backends.mps.is_available():
88
+ return [mode] if mode in ("mps", "eager") else ["mps", mode]
89
+ return ["eager-fp32", mode]
90
+
91
+
92
+ def device_name(be=None):
93
+ if hasattr(be, "device_name"): # TPU
94
+ return be.device_name()
95
+ if torch.cuda.is_available():
96
+ return torch.cuda.get_device_name(0)
97
+ import platform
98
+ import subprocess
99
+ try:
100
+ return subprocess.run(["sysctl", "-n", "machdep.cpu.brand_string"], capture_output=True, text=True).stdout.strip()
101
+ except OSError:
102
+ return platform.processor() or "cpu"
103
+
104
+
105
+ def reset_memory():
106
+ if torch.cuda.is_available():
107
+ torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
108
+ elif torch.backends.mps.is_available():
109
+ torch.mps.empty_cache()
110
+ try:
111
+ import mlx.core as mx
112
+ mx.clear_cache(); mx.reset_peak_memory()
113
+ except ImportError:
114
+ pass
115
+
116
+
117
+ def memory_gb(be):
118
+ """Peak allocated memory (CUDA, MLX, TPU); for MPS the memory held by the Metal driver at the end of the run; NaN
119
+ for backends without memory tracking (GGUF, Ollama, llama.cpp server, CPU), written as null by --out."""
120
+ if isinstance(be, MLXBackend):
121
+ return be.mx.get_peak_memory() / 2**30
122
+ if hasattr(be, "memory_gb"): # TPU: the process-wide HBM peak
123
+ return be.memory_gb()
124
+ dev = getattr(be, "dev", None)
125
+ if dev is not None:
126
+ kind = torch.device(dev).type
127
+ if kind == "cuda":
128
+ return torch.cuda.max_memory_allocated() / 2**30
129
+ if kind == "mps":
130
+ return torch.mps.driver_allocated_memory() / 2**30
131
+ if hasattr(be, "llm") and torch.cuda.is_available(): # vLLM / SGLang
132
+ return torch.cuda.max_memory_allocated() / 2**30
133
+ return float("nan")
134
+
135
+
136
+ def sync(be):
137
+ dev = getattr(be, "dev", None)
138
+ if dev is not None:
139
+ kind = torch.device(dev).type
140
+ if kind == "cuda":
141
+ torch.cuda.synchronize()
142
+ elif kind == "mps":
143
+ torch.mps.synchronize()
144
+
145
+
146
+ EXAMPLES = Path(__file__).resolve().parent / "examples" # installed with the package
147
+ DEFAULT_QUESTIONS = [str(EXAMPLES / f) for f in ("questions.jsonl", "choice.jsonl", "noul.jsonl", "score.jsonl")]
148
+
149
+
150
+ def numbered_questions(paths, n, seed=0):
151
+ """load_questions with the place of each item, for a message about it: ("file:line", item) pairs, the same items
152
+ in the same order."""
153
+ if isinstance(paths, (str, Path)):
154
+ paths = [paths]
155
+ qs = []
156
+ for p in paths:
157
+ for i, q in records(p): # a line that is not JSON: a JSONLError (a ValueError) "<p>:<i>: not JSON (...)"
158
+ if isinstance(q, (str, list)): # a text or a list is no question: skipped, as it always was
159
+ continue
160
+ if not isinstance(q, dict):
161
+ raise ValueError(f"{p}:{i}: a line must be a JSON object, not {type(q).__name__}")
162
+ if "options" in q:
163
+ qs.append((f"{p}:{i}", q))
164
+ random.Random(seed).shuffle(qs) # the permutation depends on the length only: the order of load_questions
165
+ return qs[:n]
166
+
167
+
168
+ def load_questions(paths, n, seed=0):
169
+ """Simple-format items {"state", "question", "options", "gold"?} from one or more JSONL files (full-request lines
170
+ with "questions" are skipped). A line that is not JSON, or JSON that is no object, is a ValueError naming its file
171
+ and line."""
172
+ return [q for _, q in numbered_questions(paths, n, seed)]
173
+
174
+
175
+ def questions_or_exit(paths, n, located=False):
176
+ """load_questions (numbered_questions with located) for a command: its ValueError (file:line and what is wrong)
177
+ ends the command with that message, not a traceback."""
178
+ try:
179
+ return (numbered_questions if located else load_questions)(paths, n)
180
+ except ValueError as e:
181
+ raise SystemExit(str(e)) from None
182
+
183
+
184
+ def check_gold(located):
185
+ """basal-bench scores against gold, so a gold that is not an option index stops it (a wrong gold reads as option 0
186
+ and shows an accuracy of 0.9 or 1.0 in silence). located: numbered_questions. Only the bench calls this:
187
+ loadtest and ordercheck never read gold and take such a file as they always did."""
188
+ for where, q in located:
189
+ opts = q.get("options")
190
+ if "gold" not in q:
191
+ continue
192
+ if not isinstance(opts, list):
193
+ raise SystemExit(f"{where}: options must be a list, not {type(opts).__name__}")
194
+ g = q["gold"]
195
+ if not (isinstance(g, int) and not isinstance(g, bool) and 0 <= g < len(opts)):
196
+ raise SystemExit(f"{where}: gold {g!r} of {str(q.get('question', ''))[:40]!r} is not an option index "
197
+ f"0..{len(opts) - 1}")
198
+
199
+
200
+ def groups_for(tok, qs, fmt=1):
201
+ out = []
202
+ for q in qs:
203
+ k = len(q["options"])
204
+ perms = [list(range(k)), list(range(k))[::-1]]
205
+ prompts = [render(tok, q["state"], q["question"], [q["options"][c] for c in p], fmt=fmt) for p in perms]
206
+ ids = letter_ids(tok, prompts[0], k, fmt)
207
+ if ids:
208
+ out.append((q, perms, prompts, [ids, ids]))
209
+ return out
210
+
211
+
212
+ def decisions(groups, res):
213
+ out = []
214
+ for (q, perms, _, _), probs in zip(groups, res):
215
+ canon = [0.0] * len(q["options"])
216
+ for perm, p in zip(perms, probs):
217
+ for k, j in enumerate(perm):
218
+ canon[j] += p[k] / len(perms)
219
+ out.append(canon)
220
+ return out
221
+
222
+
223
+ def cold(be):
224
+ """vLLM keeps finished prompts in its prefix cache; a repeated prompt would be answered almost for free. Clear it so
225
+ that every timed call computes its prompt (the second option order may still reuse the first order's prefix, as in
226
+ real serving)."""
227
+ if hasattr(be, "llm"):
228
+ clear = getattr(be.llm, "reset_prefix_cache", None) or getattr(be.llm, "flush_cache", None) # vLLM / SGLang
229
+ if clear is not None:
230
+ clear()
231
+
232
+
233
+ def fresh(be, prompts):
234
+ """llama-server and Ollama keep the last prompts in a KV / prompt cache that no call of ours can clear, and answer
235
+ a repeated prompt (the warm-up of the same group, the single-order call before the two-order call) almost for free.
236
+ Put a new nonce in front of the prompts of a question in a timed call so that they are computed; both option orders
237
+ of the question get the same nonce, so the second order still reuses the first order's prefix, as in real serving
238
+ (in the throughput call every question has its own nonce, so questions share no prefix). The nonce goes after a
239
+ leading BOS text, which Ollama strips before sending the prompt (it adds BOS itself). The answers of timed calls
240
+ are discarded."""
241
+ if getattr(be, "http", None) is None: # not an HTTP engine: cold() clears what there is to clear
242
+ return prompts
243
+ nonce = f"{random.getrandbits(64):016x}\n"
244
+ bos = getattr(getattr(be, "tok", None), "bos_token", None) or ""
245
+ return [p[:len(bos)] + nonce + p[len(bos):] if bos and p.startswith(bos) else nonce + p for p in prompts]
246
+
247
+
248
+ def timed(fn, reps, be=None):
249
+ lat = []
250
+ for _ in range(reps):
251
+ cold(be)
252
+ sync(be); t = time.perf_counter()
253
+ fn()
254
+ sync(be); lat.append(time.perf_counter() - t)
255
+ return lat
256
+
257
+
258
+ def measure(be, groups, lat_n):
259
+ res = []
260
+ for i in range(0, len(groups), 32):
261
+ res += be.run_shared([(g[2], g[3]) for g in groups[i: i + 32]])
262
+ dec = decisions(groups, res)
263
+ one, two = [], []
264
+ for g in groups[: lat_n + 5]:
265
+ be.run([g[2][0]], [g[3][0]]); be.run_shared([(g[2], g[3])]) # warm-up of the shapes
266
+ one += timed(lambda: be.run(fresh(be, [g[2][0]]), [g[3][0]]), 1, be)
267
+ two += timed(lambda: be.run_shared([(fresh(be, g[2]), g[3])]), 1, be)
268
+ one, two = sorted(one[5:]), sorted(two[5:])
269
+ chunk = groups[: 16 * 8]
270
+ be.run_shared([(g[2], g[3]) for g in chunk[:16]])
271
+ t = sum(timed(lambda: [be.run_shared([(fresh(be, g[2]), g[3]) for g in chunk[i: i + 16]]) for i in range(0, len(chunk), 16)], 1, be))
272
+ return dec, dict(lat1_ms=statistics.median(one) * 1000, lat2_ms=statistics.median(two) * 1000,
273
+ lat2_p95_ms=two[math.ceil(0.95 * len(two)) - 1] * 1000, dec_s=len(chunk) / t)
274
+
275
+
276
+
277
+ def main():
278
+ import sys
279
+ if "--identity" in sys.argv[1:]: # the identity gate of the fast path (basal/identity.py)
280
+ from .identity import main as identity
281
+ rows = identity([x for x in sys.argv[1:] if x != "--identity"])
282
+ return 0 if all(r["gate"] == "pass" for r in rows) else 1 # the exit status of basal-bench --identity
283
+ if "--order-check" in sys.argv[1:]: # option-order flips and --order-average K (basal/ordercheck.py)
284
+ from .ordercheck import main as order_check
285
+ order_check([x for x in sys.argv[1:] if x != "--order-check"])
286
+ return 0
287
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
288
+ ap.add_argument("--model", default="Remek/basal-1.5-4.5B")
289
+ ap.add_argument("--adapter", default=None, help="LoRA adapter directory, as basal-serve --adapter")
290
+ ap.add_argument("--vllm-model", dest="vllm_model", default=None, help="checkpoint for --modes vllm (e.g. the NVFP4 repo)")
291
+ ap.add_argument("--gguf", default=None, help="GGUF weights for --modes gguf (several files: gguf@<file> per mode)")
292
+ ap.add_argument("--ollama-model", dest="ollama_model", default=None, help="Ollama model name for --modes ollama")
293
+ ap.add_argument("--ollama-url", dest="ollama_url", default="http://127.0.0.1:11434")
294
+ ap.add_argument("--llamacpp-url", dest="llamacpp_url", default="http://127.0.0.1:8080")
295
+ ap.add_argument("--modes", nargs="+", default=None,
296
+ help="default: eager-fp32 and the serving default (fast on CUDA); on Apple Silicon bf16 mps and mlx "
297
+ "(--modes eager-fp32 mps mlx for fp32 agreement if memory allows). Modes: eager-fp32, eager, "
298
+ "fast, fast-nocompile, fp8, nvfp4, vllm, vllm@deterministic (--vllm-preset), "
299
+ "sglang, fast-exit@off|0.999|0.995|0.99|0.98; Apple Silicon: mlx, mlx-q8, mps; GGUF: gguf, "
300
+ "gguf@<file.gguf>, ollama, llamacpp; AMD Strix Halo: strix; Google TPU (basal-engine[tpu]): tpu, "
301
+ "tpu-fp32")
302
+ ap.add_argument("--questions", nargs="+", default=DEFAULT_QUESTIONS,
303
+ help="JSONL file(s) with simple items (default: the bundled examples, 44 items)")
304
+ ap.add_argument("--n", type=positive, default=500)
305
+ ap.add_argument("--lat-n", dest="lat_n", type=positive, default=100)
306
+ ap.add_argument("--out", default=None, help="write results as JSON")
307
+ ap.add_argument("--mlx-packed", dest="mlx_packed", action="store_true",
308
+ help="mlx modes: the packed forward of short Llama groups (basal-serve --mlx-packed)")
309
+ ap.add_argument("--mlx-forward", dest="mlx_forward", choices=["mlx-lm", "basal", "metal"], default="mlx-lm",
310
+ help="mlx modes: mlx-lm's forward (default), basal's own, or pure-Metal kernels (3.0.1)")
311
+ a = ap.parse_args()
312
+ a.modes = a.modes or default_modes(a.model)
313
+ adapter = adapter_module.read(a.adapter) if a.adapter else None
314
+ for m in a.modes if adapter else (): # before anything is loaded
315
+ why = adapter_refused_kind(*MODES.get(m.split("@")[0], ("", None))[:2])
316
+ if why:
317
+ raise SystemExit(adapter_refused(adapter.name, f"--modes {m}", why))
318
+ md = resolve(a.model, metadata_only=all(MODES.get(m.split("@")[0], ("",))[0] in GGUF_KINDS for m in a.modes))
319
+ vm = resolve(a.vllm_model) if a.vllm_model else None
320
+ located = questions_or_exit(a.questions, a.n, located=True)
321
+ check_gold(located)
322
+ qs = [q for _, q in located]
323
+ if len(qs) < MIN_ITEMS: # before any engine is loaded
324
+ raise SystemExit(f"basal-bench: {len(qs)} simple items with options in --questions (--n {a.n}); at least "
325
+ f"{MIN_ITEMS} are needed (5 warm up the latency runs)")
326
+ fmt = model_format(md)
327
+ ref, rows = None, []
328
+ for mode in a.modes:
329
+ reset_memory()
330
+ t0 = time.time()
331
+ be = build(mode, md, vm, a.gguf, a.ollama_model, a.ollama_url, a.llamacpp_url, fmt, a.mlx_packed,
332
+ a.mlx_forward, adapter)
333
+ load_s = time.time() - t0
334
+ groups = groups_for(be.tok, qs, fmt)
335
+ if len(groups) < MIN_ITEMS:
336
+ raise SystemExit(f"basal-bench --modes {mode}: {len(groups)} of the {len(qs)} items fit this model's prompt "
337
+ f"format (at most {max_options(fmt)} options); at least {MIN_ITEMS} are needed")
338
+ dec, r = measure(be, groups, min(a.lat_n, len(groups) - 5))
339
+ top = [max(range(len(d)), key=d.__getitem__) for d in dec]
340
+ mem = memory_gb(be)
341
+ r = dict(mode=mode, reference_mode=a.modes[0], gpu=device_name(be), n=len(groups), load_s=round(load_s, 1),
342
+ **r, mem_gb=None if math.isnan(mem) else mem) # null, not NaN (not JSON), when not measured
343
+ if isinstance(getattr(be, "forward", None), str): # MLX: which forward ran
344
+ r["forward"] = be.forward
345
+ if all("gold" in g[0] for g in groups):
346
+ r["acc"] = sum(t == g[0]["gold"] for t, g in zip(top, groups)) / len(groups)
347
+ if ref is None:
348
+ ref = top
349
+ else:
350
+ r["agree"] = sum(x == y for x, y in zip(top, ref)) / len(ref)
351
+ rows.append(r)
352
+ print(json.dumps({k: round(v, 3) if isinstance(v, float) else v for k, v in r.items()}), flush=True)
353
+ if hasattr(be, "llm"):
354
+ del be.llm
355
+ del be; gc.collect(); reset_memory()
356
+ print(f"\n{'mode':<18}{'lat2 ms':>9}{'lat1 ms':>9}{'dec/s':>8}{'agree':>8}{'acc':>7}{'GB':>6}")
357
+ for r in rows:
358
+ print(f"{r['mode']:<18}{r['lat2_ms']:>9.1f}{r['lat1_ms']:>9.1f}{r['dec_s']:>8.1f}"
359
+ f"{r.get('agree', float('nan')):>8.3f}{r.get('acc', float('nan')):>7.3f}"
360
+ f"{float('nan') if r['mem_gb'] is None else r['mem_gb']:>6.1f}")
361
+ if a.out:
362
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
363
+ write_json(a.out, rows, indent=1)
364
+
365
+
366
+ if __name__ == "__main__":
367
+ raise SystemExit(main()) # the status of --identity (python -m basal.bench, as the Makefile runs it)
basal/blockquant.py ADDED
@@ -0,0 +1,227 @@
1
+ """The core of the block-scaled linears of the CUDA graph engine: --mode fp8 --fp8-scaling block (basal/fp8block.py,
2
+ e4m3 values) and --mode int8 (basal/int8block.py, int8 values) are one format each of this module. Weights in 128 x 128
3
+ blocks and activations in 1 x 128 tiles (a token's 128 consecutive input features), each block with its own fp32 scale
4
+ (amax / the format's largest value); the GEMM takes the product of every 128-deep slice of the reduction (FP8: the
5
+ tensor cores' FP8 product; int8: exact in int32), applies both scales to it and adds the slices in fp32.
6
+
7
+ BlockFormat(op, dtype, qmax, rounded, stages) one format: quantize, act_quant, gemm, linear, build
8
+ grid(M, N, config) the GEMM's launch grid (whole BN-wide output tiles)
9
+ BlockLinear a linear layer holding (w, block scales, bias) of a format
10
+ fuse(mods) one weight for the linears of one input, theirs views of it (the
11
+ merged GEMMs of the graph engines; a merged weight's 128 x 128
12
+ blocks are its parts' blocks when every part is a multiple of 128)
13
+
14
+ The GEMM is one Triton kernel for both formats (the product of a slice is the only line that differs), with fixed
15
+ tiles (128 x 128 x 128, no split of the reduction: a row's output does not depend on the other rows), registered as the
16
+ torch op basal::<op> (triton_op: Inductor keeps it inside a compiled layer, a CUDA graph captures it like any kernel).
17
+ On the CPU the GEMM is the same maths dequantised (tests).
18
+ """
19
+ import torch
20
+
21
+ BLOCK = 128
22
+ # the GEMM's tiles and launch: rows x outputs per program (BN = BLOCK: every N here is a multiple of 128, fits), row
23
+ # tiles per group, warps; pipeline stages per format. Fixed for every shape (no autotuning: a CUDA graph replays what
24
+ # warm-up chose, and a row's output must not depend on how many rows there are)
25
+ TILES = dict(BM=128, BN=128, GROUP_M=8, num_warps=8)
26
+
27
+
28
+ def fits(lin):
29
+ """True for a weight a block format can hold: both dimensions multiples of 128 (every Gemma 4 projection)."""
30
+ n, k = lin.weight.shape
31
+ return n % BLOCK == 0 and k % BLOCK == 0
32
+
33
+
34
+ def grid(M, N, config=TILES):
35
+ """The launch grid of the block GEMM for M rows and N outputs: one program per BM x BN tile. N must be a multiple
36
+ of BN: the kernel stores whole BN-wide tiles only, so the outputs past the last one would stay unwritten (fits()
37
+ keeps every weight to multiples of 128)."""
38
+ if N % config["BN"]:
39
+ raise ValueError(f"block GEMM: {N} outputs, not a multiple of {config['BN']}")
40
+ return ((M + config["BM"] - 1) // config["BM"] * (N // config["BN"]),)
41
+
42
+
43
+ def fuse(mods):
44
+ """One weight for several linear layers that read the same input (no bias): their weights concatenated into a new
45
+ tensor, and the layers' own weights become views of it (transformers' forward of the same model still runs, and no
46
+ second copy is kept) -> (weight, output sizes). The Qwen3.5 and Gemma 4 graph engines' merged projections."""
47
+ w = torch.cat([m.weight.detach() for m in mods])
48
+ sizes = [m.weight.shape[0] for m in mods]
49
+ for m, part in zip(mods, w.split(sizes)):
50
+ m.weight = torch.nn.Parameter(part, requires_grad=False)
51
+ return w, sizes
52
+
53
+
54
+ def reference(q, s, w, ws, dtype):
55
+ """The GEMM's maths without the kernel (CPU, tests): both operands dequantised, fp32 products."""
56
+ M, K = q.shape
57
+ N = w.shape[0]
58
+ x = (q.float().view(M, K // BLOCK, BLOCK) * s[..., None]).view(M, K)
59
+ y = (w.float().view(N // BLOCK, BLOCK, K // BLOCK, BLOCK) * ws[:, None, :, None]).view(N, K)
60
+ return (x @ y.t()).to(dtype)
61
+
62
+
63
+ def aligned(K, N, config=TILES):
64
+ """True when the block GEMM can address its rows as multiples of the tiles (K % 128 == 0 and N % BN == 0: every
65
+ weight fits() keeps): its launches then pass ALIGNED, else the kernel takes K and N as they are. A plain bool
66
+ (inside a compiled layer K can be a symbol: the test is then a guard on its divisibility)."""
67
+ return bool(K % BLOCK == 0) and bool(N % config["BN"] == 0)
68
+
69
+
70
+ def _kernel(do_not_specialize=()):
71
+ """The block GEMM's Triton kernel (one for every format; INT: int8 operands, each slice's product exact in
72
+ int32). do_not_specialize: arguments Triton compiles without knowing their divisibility (tests: as Inductor passes
73
+ a size it holds as a symbol)."""
74
+ import triton
75
+ import triton.language as tl
76
+
77
+ @triton.jit(do_not_specialize=do_not_specialize)
78
+ def kernel(a, a_s, b, b_s, c, M, N, K, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr,
79
+ GROUP_M: tl.constexpr, INT: tl.constexpr, ALIGNED: tl.constexpr):
80
+ # a [M, K], a_s [M, K / BK]; b [N, K] (both K-major, as Hopper's FP8 MMA takes them), b_s [N / BK, K / BK];
81
+ # c [M, N]. Programs in groups of GROUP_M row tiles (weight tiles reused from L2); rows past M read row
82
+ # (r mod M) and are not stored.
83
+ pid = tl.program_id(0)
84
+ nm, nn = tl.cdiv(M, BM), N // BN
85
+ width = GROUP_M * nn
86
+ first = (pid // width) * GROUP_M
87
+ gm = tl.minimum(nm - first, GROUP_M)
88
+ pm = first + (pid % width) % gm
89
+ pn = (pid % width) // gm
90
+ rm = pm * BM + tl.arange(0, BM)
91
+ rn = pn * BN + tl.arange(0, BN)
92
+ ra = (rm % M).to(tl.int64)
93
+ rk = tl.arange(0, BK)
94
+ nk = K // BK
95
+ if ALIGNED:
96
+ # K = nk * BK and N = nn * BN (aligned(), on the host): the row strides as multiples of BK and BN, so Triton
97
+ # knows every row starts 16-byte aligned and moves 16 bytes at a time, also where Inductor passes K or N
98
+ # as a symbol of unknown divisibility (with K itself, that variant loaded every operand byte by byte)
99
+ sk, sn = nk * BK, nn * BN
100
+ else:
101
+ sk, sn = K, N
102
+ ap = a + ra[:, None] * sk + rk[None, :]
103
+ bp = b + rn.to(tl.int64)[None, :] * sk + rk[:, None]
104
+ asp = a_s + ra * nk
105
+ bsp = b_s + (rn // BK) * nk
106
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
107
+ for _ in range(nk):
108
+ x = tl.load(ap)
109
+ y = tl.load(bp)
110
+ if INT:
111
+ acc += tl.dot(x, y, out_dtype=tl.int32).to(tl.float32) * tl.load(asp)[:, None] * tl.load(bsp)[None, :]
112
+ else:
113
+ acc += tl.dot(x, y) * tl.load(asp)[:, None] * tl.load(bsp)[None, :]
114
+ ap += BK
115
+ bp += BK
116
+ asp += 1
117
+ bsp += 1
118
+ cp = c + rm.to(tl.int64)[:, None] * sn + rn[None, :]
119
+ tl.store(cp, acc.to(c.dtype.element_ty), mask=(rm < M)[:, None])
120
+
121
+ return kernel
122
+
123
+
124
+ class BlockFormat:
125
+ """One block-scaled format: values of `dtype` within +-qmax (rounded to the nearest integer, ties to even, when
126
+ `rounded`; else saturated and cast), its GEMM the torch op basal::<op> with `stages` pipeline stages (an int, or a
127
+ function of the GPU called when the kernel is built)."""
128
+
129
+ def __init__(self, op, dtype, qmax, rounded, stages):
130
+ self.op, self.dtype, self.qmax, self.rounded, self.stages = op, dtype, qmax, rounded, stages
131
+ self.kernel, self._act = [], []
132
+
133
+ def act_quant_ops(x):
134
+ M, K = x.shape
135
+ b = x.float().view(M, K // BLOCK, BLOCK)
136
+ s = b.abs().amax(-1).clamp(min=1e-12) / qmax
137
+ v = b / s[..., None]
138
+ return (v.round() if rounded else v).clamp(-qmax, qmax).to(dtype).view(M, K), s
139
+ self.act_quant_ops = act_quant_ops
140
+
141
+ @torch.no_grad()
142
+ def quantize(self, w):
143
+ """[N, K] (bf16 / fp32) -> (values [N, K], fp32 scales [N / 128, K / 128]): each 128 x 128 block divided by its
144
+ amax / qmax."""
145
+ N, K = w.shape
146
+ b = w.float().view(N // BLOCK, BLOCK, K // BLOCK, BLOCK)
147
+ s = b.abs().amax((1, 3)).clamp(min=1e-12) / self.qmax
148
+ v = b / s[:, None, :, None]
149
+ q = (v.round() if self.rounded else v).clamp(-self.qmax, self.qmax).to(self.dtype).view(N, K)
150
+ return q, s.contiguous()
151
+
152
+ def act_quant(self, x):
153
+ """[M, K] -> (values [M, K], fp32 scales [M, K / 128]): each token's 128-feature tile by its own amax. Inside a
154
+ compiled forward Inductor fuses it with what precedes it; elsewhere on CUDA one compiled kernel (any shape)."""
155
+ if torch.compiler.is_compiling() or not x.is_cuda:
156
+ return self.act_quant_ops(x)
157
+ if not self._act: # (untimed: nothing Inductor would time at a first launch, engine.compile_untimed)
158
+ from .engine import compile_untimed
159
+ self._act.append(compile_untimed(self.act_quant_ops, dynamic=True))
160
+ return self._act[0](x)
161
+
162
+ def _build(self):
163
+ from torch.library import triton_op, wrap_triton
164
+ kernel, integer = _kernel(), not self.dtype.is_floating_point
165
+ stages = self.stages() if callable(self.stages) else self.stages
166
+
167
+ @triton_op(f"basal::{self.op}", mutates_args=())
168
+ def op(q: torch.Tensor, s: torch.Tensor, w: torch.Tensor, ws: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
169
+ M, K = q.shape
170
+ N = w.shape[0]
171
+ c = torch.empty((M, N), dtype=dtype, device=q.device)
172
+ if M:
173
+ wrap_triton(kernel)[grid(M, N)](q, s, w, ws, c, M, N, K, BK=BLOCK, INT=integer,
174
+ ALIGNED=aligned(K, N), num_stages=stages, **TILES)
175
+ return c
176
+
177
+ return op
178
+
179
+ def build(self):
180
+ """The Triton kernel as the op basal::<op>, built once (before any layer is compiled; CUDA only)."""
181
+ if torch.cuda.is_available() and not self.kernel:
182
+ self.kernel.append(self._build())
183
+
184
+ def gemm(self, q, s, w, ws, dtype):
185
+ """(q, s) [M, K] x (w, ws) [N, K]^T -> [M, N] in dtype."""
186
+ if not q.is_cuda:
187
+ return reference(q, s, w, ws, dtype)
188
+ self.build()
189
+ return getattr(torch.ops.basal, self.op)(q, s.contiguous(), w, ws, dtype)
190
+
191
+ def linear(self, x, w, ws, bias=None):
192
+ """x [..., K] through a block-scaled weight of this format -> [..., N] in x's dtype: act_quant + gemm, the
193
+ bias."""
194
+ shape = x.shape
195
+ q, s = self.act_quant(x.reshape(-1, shape[-1]))
196
+ y = self.gemm(q, s, w, ws, x.dtype)
197
+ if bias is not None:
198
+ y = y + bias.to(y.dtype)
199
+ return y.reshape(*shape[:-1], w.shape[0])
200
+
201
+
202
+ class BlockLinear(torch.nn.Module):
203
+ """A linear layer with a block-scaled weight of a format (the subclass's FORMAT) and an optional bias; part(o, n)
204
+ is a view of output rows o..o + n (multiples of 128): the projections of a merged weight stay modules of their own.
205
+ forward: the subclass's module-level linear (lean.linear runs the same parameters in compiled layers)."""
206
+
207
+ FORMAT = None
208
+
209
+ def __init__(self, weight, scale, bias=None):
210
+ super().__init__()
211
+ self.weight = torch.nn.Parameter(weight, requires_grad=False)
212
+ self.weight_scale = torch.nn.Parameter(scale, requires_grad=False)
213
+ self.bias = bias
214
+ self.out_features, self.in_features = weight.shape
215
+
216
+ @classmethod
217
+ def of(cls, lin):
218
+ """The block-scaled version of a torch.nn.Linear (the bf16 weight is not kept)."""
219
+ q, s = cls.FORMAT.quantize(lin.weight.detach())
220
+ return cls(q, s, None if lin.bias is None else lin.bias.detach())
221
+
222
+ def part(self, o, n):
223
+ return type(self)(self.weight[o: o + n], self.weight_scale[o // BLOCK: (o + n) // BLOCK],
224
+ None if self.bias is None else self.bias[o: o + n])
225
+
226
+ def forward(self, x):
227
+ return self.FORMAT.linear(x, self.weight, self.weight_scale, self.bias)