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/tpu.py ADDED
@@ -0,0 +1,336 @@
1
+ """Google TPU backend
2
+ """
3
+ import json
4
+ import math
5
+ import os
6
+ import struct
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ from transformers import AutoTokenizer
12
+
13
+ from .engine import GraphBackend, modelopt_refused
14
+ from .prompt import PREFILL
15
+
16
+ _ST_DTYPES = {"F32": np.float32, "F16": np.float16, "I64": np.int64, "I32": np.int32}
17
+ DTYPES = ("bfloat16", "float32") # weight / activation dtypes of the TPU backend
18
+
19
+
20
+ def load_safetensors(path):
21
+ """Memory-map a .safetensors file into numpy arrays without torch (the safetensors numpy API cannot read BF16)."""
22
+ from ml_dtypes import bfloat16
23
+ mm = np.memmap(path, dtype=np.uint8, mode="r")
24
+ n = struct.unpack("<Q", mm[:8].tobytes())[0]
25
+ header = json.loads(mm[8: 8 + n].tobytes())
26
+ out = {}
27
+ for name, meta in header.items():
28
+ if name == "__metadata__":
29
+ continue
30
+ dt = bfloat16 if meta["dtype"] == "BF16" else _ST_DTYPES.get(meta["dtype"])
31
+ if dt is None:
32
+ raise ValueError(f"{path}: unsupported safetensors dtype {meta['dtype']} ({name})")
33
+ a, b = meta["data_offsets"]
34
+ out[name] = mm[8 + n + a: 8 + n + b].view(dt).reshape(meta["shape"])
35
+ return out
36
+
37
+
38
+ def model_config(model_dir):
39
+ cfg = json.loads((Path(model_dir) / "config.json").read_text(encoding="utf-8"))
40
+ if cfg.get("model_type") != "llama":
41
+ raise ValueError(f"TPU backend supports Llama-architecture checkpoints, got {cfg.get('model_type')!r}")
42
+ rope = cfg.get("rope_parameters") or {}
43
+ if rope.get("rope_type", "default") != "default" or cfg.get("rope_scaling"):
44
+ raise ValueError(f"TPU backend supports default RoPE only, got {rope or cfg.get('rope_scaling')}")
45
+ nh = cfg["num_attention_heads"]
46
+ return dict(layers=cfg["num_hidden_layers"], hidden=cfg["hidden_size"], ffn=cfg["intermediate_size"], heads=nh,
47
+ kv_heads=cfg.get("num_key_value_heads", nh), head_dim=cfg.get("head_dim") or cfg["hidden_size"] // nh,
48
+ eps=cfg.get("rms_norm_eps", 1e-6), theta=float(rope.get("rope_theta", cfg.get("rope_theta", 10000.0))),
49
+ max_pos=cfg.get("max_position_embeddings"))
50
+
51
+
52
+ def stack_params(w, c, dtype="bfloat16"):
53
+ """HF-named weights -> host pytree with the decoder layers stacked on axis 0, q / k / v fused, linear weights
54
+ [in, out]. Biases are always present (zeros when the checkpoint has none), so the compiled program does not depend
55
+ on the checkpoint."""
56
+ from ml_dtypes import bfloat16
57
+ if dtype not in DTYPES:
58
+ raise ValueError(f"--mode tpu supports --dtype {' / '.join(DTYPES)}, got {dtype!r}")
59
+ dt = {"bfloat16": bfloat16, "float32": np.float32}[dtype]
60
+ L, H, F = c["layers"], c["hidden"], c["ffn"]
61
+ Q, KV = c["heads"] * c["head_dim"], c["kv_heads"] * c["head_dim"]
62
+ shapes = dict(ln1=(H,), wqkv=(H, Q + 2 * KV), bqkv=(Q + 2 * KV,), wo=(Q, H), bo=(H,), ln2=(H,),
63
+ wg=(H, F), bg=(F,), wu=(H, F), bu=(F,), wd=(F, H), bd=(H,))
64
+ lay = {k: np.zeros((L, *s), dt) for k, s in shapes.items()}
65
+
66
+ def get(name):
67
+ return np.asarray(w[name]).astype(dt)
68
+
69
+ def bias(name, out, sl=slice(None)):
70
+ if name in w:
71
+ out[sl] = get(name)
72
+
73
+ def fill(i):
74
+ p = f"model.layers.{i}"
75
+ lay["ln1"][i], lay["ln2"][i] = get(f"{p}.input_layernorm.weight"), get(f"{p}.post_attention_layernorm.weight")
76
+ for name, sl in (("q", slice(0, Q)), ("k", slice(Q, Q + KV)), ("v", slice(Q + KV, None))):
77
+ lay["wqkv"][i, :, sl] = get(f"{p}.self_attn.{name}_proj.weight").T
78
+ bias(f"{p}.self_attn.{name}_proj.bias", lay["bqkv"][i], sl)
79
+ lay["wo"][i] = get(f"{p}.self_attn.o_proj.weight").T
80
+ bias(f"{p}.self_attn.o_proj.bias", lay["bo"][i])
81
+ for name, wk, bk in (("gate", "wg", "bg"), ("up", "wu", "bu"), ("down", "wd", "bd")):
82
+ lay[wk][i] = get(f"{p}.mlp.{name}_proj.weight").T
83
+ bias(f"{p}.mlp.{name}_proj.bias", lay[bk][i])
84
+
85
+ with ThreadPoolExecutor(min(16, os.cpu_count() or 1)) as ex: # numpy copies release the GIL: ~5x faster load
86
+ list(ex.map(fill, range(L)))
87
+ embed = get("model.embed_tokens.weight")
88
+ head = get("lm_head.weight") if "lm_head.weight" in w else embed # tied embeddings
89
+ return dict(embed=embed, norm=get("model.norm.weight"), lm_head=head, layers=lay)
90
+
91
+
92
+ def load_params(model_dir, dtype="bfloat16", device=None, adapter=None):
93
+ """Checkpoint directory -> (config, parameter pytree on `device`, default: JAX's default device). adapter: a LoRA
94
+ adapter (basal.adapter) merged into the checkpoint's weights before they are stacked."""
95
+ import jax
96
+
97
+ from .adapter import merge_numpy
98
+ c = model_config(model_dir)
99
+ w = {}
100
+ for f in sorted(Path(model_dir).glob("*.safetensors")):
101
+ w.update(load_safetensors(f))
102
+ if adapter:
103
+ merge_numpy(w, adapter)
104
+ return c, jax.device_put(stack_params(w, c, dtype), device)
105
+
106
+
107
+ def forward(params, ids, pos, end, *, c, q_block=None, kv_block=None):
108
+ """ids / pos / end (b, L) int32 (end: see tpu_kernels.tree_mask) -> last-layer hidden states (b, L, H), before the
109
+ final norm. Stays on the device; `readout` reads the letter logits. q_block / kv_block: blocked attention for long
110
+ prompts (see tpu_kernels.attention)."""
111
+ import jax
112
+
113
+ from . import tpu_kernels as K
114
+ b, L = ids.shape
115
+ nh, nkv, hd, H = c["heads"], c["kv_heads"], c["head_dim"], c["hidden"]
116
+ Q, KV = nh * hd, nkv * hd
117
+ cos, sin = K.rope_cache(L, hd, c["theta"]) # positions never exceed the row length
118
+ scale = 1.0 / math.sqrt(hd)
119
+
120
+ def layer(h, lp):
121
+ x = K.rms_norm(h.reshape(b * L, H), lp["ln1"], c["eps"])
122
+ qkv = K.linear(x, lp["wqkv"], lp["bqkv"])
123
+ q = K.rope(qkv[:, :Q].reshape(b, L, nh, hd), pos, cos, sin)
124
+ k = K.rope(qkv[:, Q: Q + KV].reshape(b, L, nkv, hd), pos, cos, sin)
125
+ v = qkv[:, Q + KV:].reshape(b, L, nkv, hd)
126
+ o = K.attention(q.transpose(0, 2, 1, 3), k.transpose(0, 2, 1, 3), v.transpose(0, 2, 1, 3), end, scale,
127
+ q_block, kv_block)
128
+ h = h + K.linear(o.transpose(0, 2, 1, 3).reshape(b * L, Q), lp["wo"], lp["bo"]).reshape(b, L, H)
129
+ x = K.rms_norm(h.reshape(b * L, H), lp["ln2"], c["eps"])
130
+ f = K.swiglu(x, lp["wg"], lp["bg"], lp["wu"], lp["bu"])
131
+ return h + K.linear(f, lp["wd"], lp["bd"]).reshape(b, L, H), None
132
+
133
+ h, _ = jax.lax.scan(layer, params["embed"][ids], params["layers"])
134
+ return h
135
+
136
+
137
+ def readout(params, h, rows, cols, lids, *, c):
138
+ """h (b, L, H), rows / cols (n,) int32 readout positions, lids (S,) int32 output-head rows -> fp32 logits (n, S)
139
+ of the next token. Only the letter rows of the head: the full-vocabulary normaliser cancels in the letter
140
+ softmax."""
141
+ import jax
142
+ import jax.numpy as jnp
143
+
144
+ from . import tpu_kernels as K
145
+ hr = K.rms_norm(h[rows, cols], params["norm"], c["eps"])
146
+ return jnp.einsum("nh,sh->ns", hr.astype(jnp.float32), params["lm_head"][lids].astype(jnp.float32),
147
+ precision=jax.lax.Precision.HIGHEST)
148
+
149
+
150
+ def subtree_ends(seg, parent):
151
+ """Packed row (block id per token, parent block per block; GraphBackend._pack) -> per token, the end of its block's
152
+ subtree. _pack flattens the trie depth-first, so a block and its descendants are one contiguous run of tokens."""
153
+ end = [0] * len(parent)
154
+ for t, k in enumerate(seg):
155
+ end[k] = t + 1
156
+ for k in range(len(parent) - 1, 0, -1): # children come after their parent
157
+ if parent[k] >= 0:
158
+ end[parent[k]] = max(end[parent[k]], end[k])
159
+ return [end[k] for k in seg]
160
+
161
+
162
+ def tpu_available():
163
+ """True when JAX and libtpu (basal-engine[tpu]) are installed and JAX sees a TPU. Only the default-mode probe: without
164
+ libtpu JAX is not imported (a CPU or GPU JAX installed for something else never selects or slows another mode),
165
+ and a JAX that fails to import or to initialise counts as no TPU (an explicit --mode tpu shows the error,
166
+ TPUBackend)."""
167
+ import importlib.util
168
+ if importlib.util.find_spec("jax") is None or importlib.util.find_spec("libtpu") is None:
169
+ return False
170
+ try:
171
+ import jax
172
+ return bool(jax.devices("tpu"))
173
+ except Exception:
174
+ return False
175
+
176
+
177
+ def _softmax(x):
178
+ e = np.exp(x - x.max())
179
+ return (e / e.sum()).tolist()
180
+
181
+
182
+ class TPUBackend(GraphBackend):
183
+ """Google TPU through JAX / XLA (plain-JAX kernels, bf16 or fp32), experimental and community-maintained.
184
+ GraphBackend's units (every group -- all option orders of a question, or every branch of a request: SOAM -- is
185
+ the compressed prefix trie of its prompts) packed as ONE row each: the attention mask comes from the trie, so a
186
+ unit runs whole whatever its branches. Units are batched by length into forwards of at most TOKEN_BUDGET padded
187
+ tokens. The forward and the small readout (always READOUTS positions, more in several calls) compile once per
188
+ (rows, length) bucket; with warm=True all of them compile at start-up.
189
+
190
+ Units longer than the largest bucket run alone in one of the coarse LONG_LENS buckets up to max_len, with a
191
+ blocked attention (Q_BLOCK queries x KV_BLOCK keys, online softmax), so memory grows with the length instead of
192
+ its square; a group longer than max_len is bisected, a single prompt longer than max_len is refused (the server
193
+ truncates the state first: `context`)."""
194
+
195
+ # a coarser grid than the CUDA graphs': every shape is an XLA compilation (about 2 s on a v5e) at start-up
196
+ LENS = [128, 192, 256, 320, 384, 448, 512, 640, 768, 896, 1024, 1280, 1536, 1792, 2048, 2304, 2560, 3072]
197
+ BATCHES = [1, 2, 4, 8, 16, 32]
198
+ LETTER_SLOTS = 256 # output-head rows read per position (format 2: up to 255 option codes); fixed, so new code ids
199
+ # never recompile
200
+ KIND = "tpu" # streams (a group is reported as soon as its forwards are read out), one call at a time (one device):
201
+ # engine.KIND_CAPS
202
+ LONG_LENS = [4096, 6144, 8192, 12288, 16384, 24576, 32768] # above LENS[-1]; multiples of Q_BLOCK and KV_BLOCK
203
+ Q_BLOCK = 1024 # queries per attention block for lengths above LENS[-1]
204
+ KV_BLOCK = 1024 # keys per attention block for lengths above LENS[-1]
205
+ READOUTS = 64 # positions per readout call (padded; a forward with more readouts reads them in several calls),
206
+ # so the readout has one shape per bucket whatever the questions x option orders of its rows
207
+
208
+ def __init__(self, model_dir, dtype="bfloat16", shared=True, warm=True, max_len=4096, platform="tpu",
209
+ adapter=None):
210
+ import jax
211
+ self.jax = jax
212
+ if dtype not in DTYPES:
213
+ raise ValueError(f"--mode tpu supports --dtype {' / '.join(DTYPES)}, got {dtype!r}")
214
+ why = modelopt_refused(model_dir, "tpu") # (load_params reads the weights alone, no ModelOpt scales)
215
+ if why:
216
+ raise ValueError(f"{model_dir}: {why}")
217
+ try:
218
+ self.device = jax.devices(platform)[0]
219
+ except RuntimeError as e:
220
+ raise RuntimeError(f"--mode tpu: JAX sees no {platform} device (available: {jax.devices()}); run on a TPU "
221
+ "VM with jax[tpu] installed") from e
222
+ c = model_config(model_dir)
223
+ max_len = min(max_len, c["max_pos"] or max_len) # never beyond the model's positions
224
+ self.max_len = max_len
225
+ self.context, self.context_reason = max_len, f"--max-len {max_len} of --mode tpu"
226
+ self.long_lens = [x for x in self.LONG_LENS if self.LENS[-1] < x < max_len]
227
+ if max_len > self.LENS[-1]:
228
+ step = math.lcm(self.Q_BLOCK, self.KV_BLOCK)
229
+ self.long_lens.append(-(-max_len // step) * step)
230
+ cache = os.environ.get("JAX_COMPILATION_CACHE_DIR") or str(Path.home() / ".cache" / "basal" / "jax")
231
+ jax.config.update("jax_compilation_cache_dir", cache)
232
+ self.tok = AutoTokenizer.from_pretrained(model_dir)
233
+ self.tok.pad_token = self.tok.pad_token or self.tok.eos_token
234
+ self.prefill = PREFILL
235
+ self._init_packing(None, shared) # (the host side of the packing; the forwards run in JAX on self.device)
236
+ self.cfg, self.params = load_params(model_dir, dtype, self.device, adapter)
237
+ self.adapter_modules = len(adapter.deltas) if adapter else 0
238
+ full, qb, kvb = self.LENS[-1], self.Q_BLOCK, self.KV_BLOCK
239
+ self._fwd = jax.jit(lambda p, ids, pos, end: forward(
240
+ p, ids, pos, end, c=c, **(dict(q_block=qb, kv_block=kvb) if ids.shape[1] > full else {})))
241
+ self._read = jax.jit(lambda p, h, rows, cols, li: readout(p, h, rows, cols, li, c=c))
242
+ self.slots, self._lids = {}, None
243
+ if warm:
244
+ self._warm()
245
+
246
+ def _warm(self):
247
+ """Compile every bucket shape before serving: the forward and the readout per (batch, length), so no request
248
+ waits for a compilation (the readout's shape does not depend on the number of readouts)."""
249
+ for L in self.LENS + self.long_lens:
250
+ for b in self.BATCHES:
251
+ if b * L <= self.TOKEN_BUDGET or b == 1:
252
+ self._forward_rows([([0] * L, list(range(L)), [0] * L, [L - 1], [-1])] * b, b, L)
253
+
254
+ def _bucket(self, n, xs):
255
+ for x in xs:
256
+ if n <= x:
257
+ return x
258
+ if xs is self.LENS:
259
+ for x in self.long_lens:
260
+ if n <= x:
261
+ return x
262
+ raise ValueError(f"prompt of {n} tokens is longer than --max-len {self.max_len} (--mode tpu)")
263
+
264
+ def _letter_slots(self, ids_list):
265
+ """Column of each letter id in the logits; the device array of output-head rows changes only for new ids."""
266
+ new = [i for ids in ids_list for i in ids if i not in self.slots]
267
+ if new or self._lids is None:
268
+ for i in new:
269
+ self.slots.setdefault(i, len(self.slots))
270
+ n = -(-max(len(self.slots), 1) // self.LETTER_SLOTS) * self.LETTER_SLOTS
271
+ lids = np.zeros(n, np.int32)
272
+ for i, s in self.slots.items():
273
+ lids[s] = i
274
+ self._lids = self.jax.device_put(lids, self.device)
275
+ return self.slots
276
+
277
+ def _forward_rows(self, packs, b, L):
278
+ """Packed rows (GraphBackend._pack) padded to (b, L) -> fp32 logits (readouts of all rows in order,
279
+ LETTER_SLOTS) on the host."""
280
+ if self._lids is None:
281
+ self._letter_slots([])
282
+ ids = np.full((b, L), self.tok.pad_token_id, np.int32)
283
+ pos = np.tile(np.arange(L, dtype=np.int32), (b, 1))
284
+ end = np.tile(np.arange(1, L + 1, dtype=np.int32), (b, 1)) # padding sees itself only
285
+ rows, cols = [], []
286
+ for r, (t, pp, sg, last, parent) in enumerate(packs):
287
+ ids[r, : len(t)], pos[r, : len(t)], end[r, : len(t)] = t, pp, subtree_ends(sg, parent)
288
+ rows += [r] * len(last); cols += last
289
+ n, R = len(rows), self.READOUTS
290
+ ri, ci = np.zeros(-(-n // R) * R, np.int32), np.zeros(-(-n // R) * R, np.int32)
291
+ ri[:n], ci[:n] = rows, cols
292
+ h = self._fwd(self.params, ids, pos, end)
293
+ out = [self._read(self.params, h, ri[i: i + R], ci[i: i + R], self._lids) for i in range(0, n, R)]
294
+ return np.concatenate([np.asarray(x) for x in out])[:n]
295
+
296
+ def _oversize(self, pack, n):
297
+ """A unit that must be bisected: longer than max_len. The trie mask runs any unit as one row (several roots,
298
+ any number of tokens below the root), so a request's state is computed once whenever it fits."""
299
+ return len(pack[0]) > self.max_len
300
+
301
+ def run(self, prompts, ids_list, policy=None):
302
+ return [r[0] for r in self.run_shared([([p], [x]) for p, x in zip(prompts, ids_list)])]
303
+
304
+ def run_shared(self, groups, policy=None, done=None):
305
+ """GraphBackend.run_shared's contract: the option probabilities of every prompt of every group; done(k, res)
306
+ (optional) is called for group k as soon as all its units are read out. Without `shared` every prompt is a
307
+ unit of its own (GraphBackend._units)."""
308
+ units = self._units(groups)
309
+ longest = max(len(u[0][0]) for u in units)
310
+ if longest > self.max_len: # refuse before anything is compiled or run
311
+ raise ValueError(f"prompt of {longest} tokens is longer than --max-len {self.max_len} (--mode tpu)")
312
+ slots = self._letter_slots([x for _, ids_list, *_ in groups for x in ids_list])
313
+ res = [[None] * len(g[0]) for g in groups]
314
+ left = [0] * len(groups)
315
+ for u in units:
316
+ left[u[2]] += 1
317
+ for idx in self._chunks([len(u[0][0]) for u in units]):
318
+ L = self._bucket(max(len(units[k][0][0]) for k in idx), self.LENS)
319
+ b = self._bucket(len(idx), self.BATCHES)
320
+ lg = self._forward_rows([units[k][0] for k in idx], b, L).astype(np.float64)
321
+ j = 0
322
+ for k in idx:
323
+ _, lids, g, a = units[k]
324
+ res[g][a: a + len(lids)] = [_softmax(lg[j + o, [slots[i] for i in ids]]) for o, ids in enumerate(lids)]
325
+ j += len(lids)
326
+ left[g] -= 1
327
+ if left[g] == 0 and done is not None:
328
+ done(g, res[g])
329
+ return res
330
+
331
+ def memory_gb(self):
332
+ stats = self.device.memory_stats() or {}
333
+ return stats.get("peak_bytes_in_use", float("nan")) / 2**30
334
+
335
+ def device_name(self):
336
+ return self.device.device_kind
basal/tpu_kernels.py ADDED
@@ -0,0 +1,129 @@
1
+ """Plain-JAX kernels of the TPU backend
2
+ """
3
+ import math
4
+ import jax
5
+ import jax.numpy as jnp
6
+
7
+
8
+ def dot_precision(dtype):
9
+ return jax.lax.Precision.HIGHEST if dtype == jnp.float32 else None
10
+
11
+
12
+ def rms_norm(x, w, eps=1e-6):
13
+ """x (..., H), w (H,): normalised in fp32, returned in x.dtype."""
14
+ x32 = x.astype(jnp.float32)
15
+ x32 = x32 / jnp.sqrt(jnp.mean(x32 * x32, axis=-1, keepdims=True) + eps)
16
+ return (x32 * w).astype(x.dtype)
17
+
18
+
19
+ def linear(x, w, b=None):
20
+ """x (M, K) @ w (K, N) + b (N,), fp32 accumulation."""
21
+ out = jnp.dot(x, w, preferred_element_type=jnp.float32, precision=dot_precision(x.dtype))
22
+ if b is not None:
23
+ out = out + b.astype(jnp.float32)
24
+ return out.astype(x.dtype)
25
+
26
+
27
+ def swiglu(x, wg, bg, wu, bu):
28
+ """silu(x @ wg + bg) * (x @ wu + bu); biases are added before the activation (Llama mlp_bias)."""
29
+ prec = dot_precision(x.dtype)
30
+ g = jnp.dot(x, wg, preferred_element_type=jnp.float32, precision=prec) + bg.astype(jnp.float32)
31
+ u = jnp.dot(x, wu, preferred_element_type=jnp.float32, precision=prec) + bu.astype(jnp.float32)
32
+ return (g * jax.nn.sigmoid(g) * u).astype(x.dtype)
33
+
34
+
35
+ def rope_cache(n, head_dim, theta):
36
+ """cos / sin tables (n, head_dim // 2), fp32."""
37
+ inv = jnp.exp(jnp.arange(head_dim // 2, dtype=jnp.float32) * -(math.log(theta) * 2.0 / head_dim))
38
+ ang = jnp.arange(n, dtype=jnp.float32)[:, None] * inv[None]
39
+ return jnp.cos(ang), jnp.sin(ang)
40
+
41
+
42
+ def rope(x, pos, cos, sin):
43
+ """x (b, L, heads, d), pos (b, L): HF "rotate half" RoPE at explicit positions."""
44
+ half = x.shape[-1] // 2
45
+ c, s = cos[pos][:, :, None], sin[pos][:, :, None]
46
+ x1, x2 = x[..., :half], x[..., half:]
47
+ return jnp.concatenate([x1 * c - x2 * s, x1 * s + x2 * c], -1).astype(x.dtype)
48
+
49
+
50
+ def tree_mask(end):
51
+ """end (b, L): for every token, the end (exclusive) of the subtree of its block in the depth-first packed prefix
52
+ trie (padding: its own index + 1) -> bool (b, L, L). allowed(i, j) = j <= i and i < end[j]: in depth-first order
53
+ the queries inside the subtree of key j's block are exactly those of its own block and its descendants, so every
54
+ token sees its ancestor blocks and itself only, as in a separate forward of its own prompt. Padding sits after
55
+ every real token, so causality hides it from every row that is read out."""
56
+ L = end.shape[1]
57
+ i = jnp.arange(L, dtype=end.dtype)
58
+ return (i[None, None, :] <= i[None, :, None]) & (i[None, :, None] < end[:, None, :])
59
+
60
+
61
+ def _attend(qg, k, v, mask, scale):
62
+ """qg (b, nkv, g, q, d) query heads grouped per KV head, k / v (b, nkv, L, d), mask (b, q, L) -> (b, nkv, g, q, d)."""
63
+ prec = dot_precision(qg.dtype)
64
+ s = jnp.einsum("bkgqd,bkld->bkgql", qg, k, precision=prec, preferred_element_type=jnp.float32) * scale
65
+ s = jnp.where(mask[:, None, None], s, -jnp.inf)
66
+ p = jax.nn.softmax(s, axis=-1)
67
+ return jnp.einsum("bkgql,bkld->bkgqd", p.astype(v.dtype), v, precision=prec)
68
+
69
+
70
+ def attention(q, k, v, end, scale, q_block=None, kv_block=None):
71
+ """q (b, nh, L, d), k / v (b, nkv, L, d) with GQA, end (b, L) (see tree_mask) -> (b, nh, L, d). The query heads
72
+ of one KV head are grouped instead of repeating K / V, so K / V are never copied per query head.
73
+
74
+ q_block / kv_block (long prompts; L a multiple of both): blocks of q_block queries, one after the other, each over
75
+ blocks of kv_block keys with a running max and sum (online softmax, as in flash attention). The same softmax up to
76
+ rounding, but no tensor spans L x L (16 heads x 8192^2 x 4 bytes = 4.3 GB at once) and no reduction spans all L
77
+ keys: on a v5e, XLA's full-row softmax hits a cliff at some lengths (6144 / 8192 keys: 128 / 291 ms per layer for
78
+ 1.5B shapes, against 2.1 / 3.6 ms blocked). A query block reads only the key blocks up to its last query: the
79
+ later ones are hidden from all its queries by causality (about half of the blocks of a long prompt), and skipping
80
+ them changes no bit (each added nothing: probabilities 0, rescale 1)."""
81
+ b, nh, L, d = q.shape
82
+ nkv, g = k.shape[1], nh // k.shape[1]
83
+ qg = q.reshape(b, nkv, g, L, d)
84
+ if q_block is None or L <= q_block:
85
+ o = _attend(qg, k, v, tree_mask(end), scale)
86
+ return o.reshape(b, nh, L, d).astype(q.dtype)
87
+ kv_block = kv_block or q_block
88
+ nq, nk = L // q_block, L // kv_block
89
+ assert nq * q_block == L and nk * kv_block == L, (L, q_block, kv_block)
90
+ prec = dot_precision(q.dtype)
91
+ kb = k.reshape(b, nkv, nk, kv_block, d).transpose(2, 0, 1, 3, 4)
92
+ vb = v.reshape(b, nkv, nk, kv_block, d).transpose(2, 0, 1, 3, 4)
93
+ eb = end.reshape(b, nk, kv_block).transpose(1, 0, 2)
94
+
95
+ def q_step(args):
96
+ qi, q0 = args # (b, nkv, g, q_block, d), first query index of the block
97
+ i = q0 + jnp.arange(q_block, dtype=end.dtype)
98
+
99
+ def kv_step(carry, blk):
100
+ m, l, acc = carry
101
+ kj, vj, ej, k0 = blk
102
+ j = k0 + jnp.arange(kv_block, dtype=end.dtype)
103
+ mask = (j[None, None, :] <= i[None, :, None]) & (i[None, :, None] < ej[:, None, :])
104
+ s = jnp.einsum("bkgqd,bkld->bkgql", qi, kj, precision=prec, preferred_element_type=jnp.float32) * scale
105
+ s = jnp.where(mask[:, None, None], s, -jnp.inf)
106
+ m_new = jnp.maximum(m, s.max(-1))
107
+ m_safe = jnp.where(jnp.isfinite(m_new), m_new, 0.0) # nothing visible yet: p and the rescale are 0
108
+ p = jnp.exp(s - m_safe[..., None])
109
+ a = jnp.exp(m - m_safe)
110
+ pv = jnp.einsum("bkgql,bkld->bkgqd", p.astype(vj.dtype), vj, precision=prec,
111
+ preferred_element_type=jnp.float32)
112
+ return (m_new, l * a + p.sum(-1), acc * a[..., None] + pv), None
113
+
114
+ init = (jnp.full((b, nkv, g, q_block), -jnp.inf, jnp.float32), jnp.zeros((b, nkv, g, q_block), jnp.float32),
115
+ jnp.zeros((b, nkv, g, q_block, d), jnp.float32))
116
+ # the key blocks in order up to the one holding the block's last query (the scan over every block read the
117
+ # later ones too: all masked)
118
+ seen = (q0 + q_block - 1) // kv_block + 1
119
+
120
+ def step(t, carry):
121
+ blk = [jax.lax.dynamic_index_in_dim(x, t, keepdims=False) for x in (kb, vb, eb)]
122
+ return kv_step(carry, (*blk, (t * kv_block).astype(end.dtype)))[0]
123
+
124
+ _, l, acc = jax.lax.fori_loop(0, seen, step, init)
125
+ return acc / l[..., None] # every real row sees itself, so l > 0
126
+
127
+ blocks = qg.reshape(b, nkv, g, nq, q_block, d).transpose(3, 0, 1, 2, 4, 5)
128
+ o = jax.lax.map(q_step, (blocks, jnp.arange(nq, dtype=end.dtype) * q_block)) # (nq, b, nkv, g, q_block, d)
129
+ return o.transpose(1, 2, 3, 0, 4, 5).reshape(b, nh, L, d).astype(q.dtype)
basal/trace.py ADDED
@@ -0,0 +1,125 @@
1
+ """"trace": true (3.0): why each question got its answer, in one object per question, beside the answers.
2
+
3
+ The response gains "trace": {question name: {"candidates", "probabilities", "chosen", "threshold", "action",
4
+ "reason"}}; the answers are the same bytes as without it. candidates are the options in their order and
5
+ probabilities the answer's own; chosen is the option, label set, action or tool the answer gives; threshold is the
6
+ confidence that max_error applied (the one certified for the question's type at that target; null without max_error
7
+ or without a certificate), or a multi question's label threshold; action is what basal did with the question:
8
+ answer, abstain, defer, act, select, skip (ask_if), error ("errors": "per_question"); reason says it in a sentence.
9
+ Task and rank answers, read from several decisions, have an action and a reason only."""
10
+ import json
11
+
12
+ ACTIONS = ("answer", "abstain", "defer", "act", "select", "skip", "error")
13
+
14
+
15
+ def _f(x):
16
+ return f"{x:.4f}" if isinstance(x, (int, float)) else str(x)
17
+
18
+
19
+ def _against(conf, thr, kind, target):
20
+ """The reason of a max_error decision and whether it passed."""
21
+ if thr is None:
22
+ return False, f"no threshold is certified for {kind} questions at max_error {target:g}"
23
+ if conf is not None and conf >= thr:
24
+ return True, f"confidence {_f(conf)} reaches the threshold {_f(thr)} certified for {kind} at max_error {target:g}"
25
+ return False, f"confidence {_f(conf)} is below the threshold {_f(thr)} certified for {kind} at max_error {target:g}"
26
+
27
+
28
+ def trace(questions, answers, cal, think_cal=None):
29
+ """{name: trace object} of every question of the request (questions: as the request gave them); a thought answer
30
+ (--think) is read under the second readout's calibration, as it was decided."""
31
+ from .server import certified
32
+ out = {}
33
+ for name, q in questions.items():
34
+ q = q if isinstance(q, dict) else {}
35
+ a = answers.get(name)
36
+ thought = isinstance(a, dict) and isinstance(a.get("think"), dict) and "tokens" in a["think"]
37
+ try:
38
+ out[name] = one(q, a, think_cal if thought and think_cal else cal, certified)
39
+ except (KeyError, TypeError, ValueError, AttributeError): # (an answer shape this reader does not know)
40
+ out[name] = {"candidates": None, "probabilities": None, "chosen": None, "threshold": None,
41
+ "action": "answer", "reason": "an answer of a kind the trace does not read"}
42
+ return out
43
+
44
+
45
+ def skipped(q):
46
+ """The trace of a question with the answer null (skipped by its ask_if)."""
47
+ cond = q.get("ask_if") if isinstance(q, dict) else None
48
+ return {"candidates": None, "probabilities": None, "chosen": None, "threshold": None, "action": "skip",
49
+ "reason": f"ask_if {json.dumps(cond, ensure_ascii=False)} is not met by the answers it names" if cond
50
+ else "not answered"}
51
+
52
+
53
+ def routed(a, reason, candidates=None):
54
+ """The trace of an answer basal-router made or chose (a blend, the fallback LLM's, a cascade level's that came
55
+ without one): the answer's options (else candidates) and probabilities and the option it gives; no threshold (no
56
+ calibration certifies it)."""
57
+ probs = a.get("probabilities") if isinstance(a.get("probabilities"), dict) else None
58
+ chosen = next((a[k] for k in ("choice", "tool", "action", "selected") if a.get(k) is not None), None)
59
+ if chosen is None and probs and a.get("type") in ("noul", "score"):
60
+ chosen = ("true" if probs.get("true", 0) >= probs.get("false", 0) else "false") if a["type"] == "noul" else \
61
+ max(probs, key=probs.get)
62
+ return {"candidates": list(probs) if probs else candidates, "probabilities": probs, "chosen": chosen,
63
+ "threshold": None, "action": "answer", "reason": reason}
64
+
65
+
66
+ def one(q, a, cal, certified):
67
+ t = q.get("type", "choice")
68
+ empty = {"candidates": None, "probabilities": None, "chosen": None, "threshold": None}
69
+ if a is None:
70
+ return skipped(q)
71
+ if "error" in a and "type" not in a:
72
+ return {**empty, "action": "error", "reason": a["error"]}
73
+ t = a.get("type", t)
74
+ probs = a.get("probabilities") if isinstance(a.get("probabilities"), dict) else None
75
+ base = {"candidates": list(probs) if probs else None, "probabilities": probs, "chosen": None, "threshold": None}
76
+ target = q.get("max_error")
77
+ target = float(target) if isinstance(target, (int, float)) and not isinstance(target, bool) else None
78
+ if t in ("choice", "noul", "score"):
79
+ chosen = a["choice"] if t == "choice" else (
80
+ ("true" if probs["true"] >= probs["false"] else "false") if t == "noul" else max(probs, key=probs.get))
81
+ base["chosen"], conf = chosen, a.get("confidence")
82
+ extra = (f"; coverage {a['coverage']:g}: the answer set {a['answer_set']}" if "answer_set" in a else "")
83
+ if target is None:
84
+ return {**base, "action": "answer", "reason": f"the most probable option, {chosen!r} at {_f(conf)} (no "
85
+ f"max_error){extra}"}
86
+ base["threshold"] = certified(cal, target, t)
87
+ ok, why = _against(conf, base["threshold"], t, target)
88
+ if a.get("abstain"):
89
+ return {**base, "action": "abstain", "reason": f"{why}: abstain{extra}"}
90
+ return {**base, "action": "answer", "reason": f"{why}: {chosen!r}{extra}"}
91
+ if t == "multi":
92
+ base["chosen"], base["threshold"] = a["selected"], a.get("threshold")
93
+ how = (f"the labels with P >= {a['threshold']:g}" if a.get("threshold") is not None
94
+ else f"the set of the highest expected {a.get('objective')} ({_f(a.get('expected_score'))})")
95
+ if a.get("constraints_applied"):
96
+ how += f"; constraints applied: {json.dumps(a['constraints_applied'], ensure_ascii=False)}"
97
+ return {**base, "action": "select", "reason": f"{how}: {a['selected']}"}
98
+ if t == "act":
99
+ costs = a["expected_costs"]
100
+ base.update(candidates=list(costs), chosen=a["action"])
101
+ cheapest = a.get("refused", a["action"])
102
+ why = f"the lowest expected cost is {cheapest!r} ({_f(costs[cheapest])})"
103
+ if target is not None:
104
+ kind = "noul" if probs and set(probs) == {"true", "false"} else "choice"
105
+ base["threshold"] = certified(cal, target, kind)
106
+ if "refused" in a: # (the cheapest action was automatic, and the confidence did not allow it)
107
+ _, below = _against(a.get("confidence"), base["threshold"], kind, target)
108
+ return {**base, "action": "defer", "reason": f"{why}, but {below}: deferred to {a['action']!r}"}
109
+ if a.get("deferred"): # (the defer action is the cheapest)
110
+ return {**base, "action": "defer", "reason": f"{why}: the defer action"}
111
+ return {**base, "action": "act", "reason": f"{why}: {a['action']!r}"}
112
+ if t == "tool":
113
+ if a.get("multi"):
114
+ base["chosen"] = a["tools"]
115
+ return {**base, "action": "select", "reason": f"the set of tools {a['tools']}"}
116
+ base["chosen"] = a.get("tool")
117
+ if target is not None:
118
+ base["threshold"] = certified(cal, target, "choice")
119
+ if a.get("deferred"):
120
+ _, below = _against(a.get("confidence"), base["threshold"], "choice", target)
121
+ return {**base, "action": "defer", "reason": f"{below}: deferred (the model's choice was "
122
+ f"{a.get('refused')!r})"}
123
+ call = "a tool call" if a.get("call") else "no tool call"
124
+ return {**base, "action": "answer", "reason": f"the most probable option, {a.get('tool')!r} ({call})"}
125
+ return {**empty, "action": "answer", "reason": f"a {t} answer, read from several decisions (see its fields)"}