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/jsonl.py ADDED
@@ -0,0 +1,172 @@
1
+ """JSONL as JSON writes it: one record per "\n"-terminated line, read and written the same way by every CLI.
2
+
3
+ - records(path): each line with text as (its line number, its record); a line that is not JSON (or, with
4
+ objects=True, not a JSON object) is a JSONLError "<file>:<line>: ...", the place a person can open.
5
+ - dumps(obj): the JSON of a record, refusing NaN and infinities (allow_nan=False: they are not JSON, and other
6
+ readers refuse the tokens json.dumps would write), with the place of the first one in the message.
7
+ - write(path, records) / write_json(path, obj): the whole file or nothing: written into a temp file next to it and
8
+ renamed over it at the end, so an error or a kill midway leaves the old file (or none) and never half of one.
9
+ """
10
+ import contextlib
11
+ import json
12
+ import math
13
+ import os
14
+ import secrets
15
+ import shutil
16
+ import stat
17
+ from pathlib import Path
18
+
19
+ from .textio import open_text, read_text
20
+
21
+
22
+ class JSONLError(ValueError):
23
+ """A line that is not JSON, or a record that cannot be written as JSON; the message names the file and the line
24
+ (a ValueError, as the readers raised before)."""
25
+
26
+
27
+ def read_lines(path):
28
+ """The lines of a JSONL file, split at "\n" only (a "\r" before it is dropped; no empty last line). The file is
29
+ UTF-8 with or without a BOM, or UTF-16 with its BOM (textio.open_text).
30
+
31
+ str.splitlines also splits at U+2028, U+2029 and U+0085, which json.dumps(..., ensure_ascii=False) leaves
32
+ unescaped inside strings (text pasted from a word processor or a PDF), and so cut a valid line in two."""
33
+ out = [x[:-1] if x.endswith("\r") else x for x in read_text(path).split("\n")]
34
+ if out and not out[-1]:
35
+ out.pop()
36
+ return out
37
+
38
+
39
+ def loads(line, where, objects=False):
40
+ """The record of one line (its "\n" or "\r\n" included or not); JSONLError "<where>: not JSON (<why> at column
41
+ <n>)", and with objects=True also "<where>: a line must be a JSON object, not <type>"."""
42
+ line = line[:-1] if line.endswith("\n") else line # (else json counts the column on a second line)
43
+ line = line[:-1] if line.endswith("\r") else line
44
+ try:
45
+ rec = json.loads(line)
46
+ except json.JSONDecodeError as e: # its messages that end in "at" ("Unterminated string starting at") take the column
47
+ at = f"{e.msg} column {e.colno}" if e.msg.endswith(" at") else f"{e.msg} at column {e.colno}"
48
+ raise JSONLError(f"{where}: not JSON ({at})") from None
49
+ except RecursionError:
50
+ raise JSONLError(f"{where}: not JSON (nested too deep)") from None
51
+ if objects and not isinstance(rec, dict):
52
+ raise JSONLError(f"{where}: a line must be a JSON object, not {type(rec).__name__}")
53
+ return rec
54
+
55
+
56
+ def records(path, objects=False):
57
+ """(line number, record) of each line with text, in order, read as they go (a pipe or a FIFO too); the lines and
58
+ their numbers are those of read_lines. A line that is not JSON raises JSONLError "<path>:<line>: ..."."""
59
+ with open_text(path) as f:
60
+ for n, line in enumerate(f, 1):
61
+ if line.strip():
62
+ yield n, loads(line, f"{path}:{n}", objects)
63
+
64
+
65
+ def _nonfinite(obj, at=""):
66
+ """Where the first NaN or infinity of obj is ('["p"][1]'), None when it has none."""
67
+ if isinstance(obj, float):
68
+ return None if math.isfinite(obj) else at or "the value"
69
+ if isinstance(obj, dict):
70
+ items = obj.items()
71
+ elif isinstance(obj, (list, tuple)):
72
+ items = enumerate(obj)
73
+ else:
74
+ return None
75
+ for k, v in items:
76
+ found = _nonfinite(v, f"{at}[{json.dumps(k, ensure_ascii=False)}]")
77
+ if found:
78
+ return found
79
+ return None
80
+
81
+
82
+ def dumps(obj, **kw):
83
+ """json.dumps(obj) without NaN and infinities (ensure_ascii=False unless given): a ValueError that says where the
84
+ first one is ("a NaN or an infinity at [\"p\"][1]"); other keywords as json.dumps's."""
85
+ kw.setdefault("ensure_ascii", False)
86
+ try:
87
+ return json.dumps(obj, allow_nan=False, **kw)
88
+ except ValueError as e:
89
+ at = _nonfinite(obj)
90
+ if at is None:
91
+ raise
92
+ raise ValueError(f"a NaN or an infinity at {at}: JSON has no value for it") from e
93
+
94
+
95
+ def finite(obj):
96
+ """obj with every NaN and infinity as None (null), for records where a missing number is a NaN (a readout without
97
+ a probability) and a reader treats null as it treats the NaN."""
98
+ if isinstance(obj, float):
99
+ return obj if math.isfinite(obj) else None
100
+ if isinstance(obj, dict):
101
+ return {k: finite(v) for k, v in obj.items()}
102
+ if isinstance(obj, (list, tuple)):
103
+ return [finite(v) for v in obj]
104
+ return obj
105
+
106
+
107
+ def _new_file_mode(directory):
108
+ """The mode a new file gets in directory under this process's umask (0644 under 022), read from a file made
109
+ there and removed: os.umask would set the process-wide mask to read it, under other threads' feet."""
110
+ probe = Path(directory) / f".mode.{os.getpid()}.{secrets.token_hex(4)}.tmp"
111
+ os.close(os.open(probe, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666))
112
+ try:
113
+ return stat.S_IMODE(os.stat(probe).st_mode)
114
+ finally:
115
+ probe.unlink()
116
+
117
+
118
+ @contextlib.contextmanager
119
+ def atomic(path):
120
+ """A text file (UTF-8, "\n" line ends) that replaces `path` whole when the block ends: written into a temp file
121
+ in the same directory, flushed to disk and renamed over it; an error (or a kill) midway leaves `path` as it was.
122
+ A symbolic link is followed (its target is replaced); the mode of a file it replaces is kept. A path that is not
123
+ a regular file (a FIFO) is written directly, and so is one under /dev/ or /proc/ (/dev/stdout, /dev/fd/3): a
124
+ shell's `> file` makes /dev/stdout a regular file, but a temp file cannot go next to it (/dev/fd/ on macOS) and
125
+ renaming over its real path (Linux) would replace a file the shell may append to (`>>`). Those are opened for
126
+ appending, so they keep what the shell's redirection put there."""
127
+ path = Path(path)
128
+ device = str(path).startswith(("/dev/", "/proc/"))
129
+ if device or (path.exists() and not path.is_file()):
130
+ with open(path, "a" if device else "w", encoding="utf-8", newline="\n") as f:
131
+ yield f
132
+ return
133
+ real = Path(os.path.realpath(path))
134
+ tmp = real.with_name(f".{real.name}.{os.getpid()}.{secrets.token_hex(4)}.tmp")
135
+ try:
136
+ # the temp file holds the new contents: private (0600) and our own (O_EXCL) from its creation, whatever the
137
+ # umask; it gets its final mode only once they are written
138
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0), 0o600)
139
+ with open(fd, "w", encoding="utf-8", newline="\n", closefd=True) as f:
140
+ yield f
141
+ f.flush()
142
+ os.fsync(f.fileno())
143
+ if real.exists():
144
+ shutil.copymode(real, tmp)
145
+ else:
146
+ os.chmod(tmp, _new_file_mode(real.parent))
147
+ os.replace(tmp, real)
148
+ finally:
149
+ with contextlib.suppress(FileNotFoundError):
150
+ tmp.unlink()
151
+
152
+
153
+ def write(path, recs, **kw):
154
+ """recs (any iterable) as JSONL at path, one dumps line each, the file whole or not at all (atomic). A record with
155
+ a NaN or an infinity raises JSONLError "<path>: record <n>: ..." and leaves path as it was."""
156
+ with atomic(path) as f:
157
+ for n, rec in enumerate(recs, 1):
158
+ try:
159
+ f.write(dumps(rec, **kw) + "\n")
160
+ except ValueError as e:
161
+ raise JSONLError(f"{path}: record {n}: {e}") from None
162
+
163
+
164
+ def write_json(path, obj, **kw):
165
+ """One JSON document (dumps(obj, **kw), then "\n") at path, whole or not at all (atomic); a NaN or an infinity
166
+ raises JSONLError "<path>: ..." and leaves path as it was."""
167
+ try:
168
+ text = dumps(obj, **kw)
169
+ except ValueError as e:
170
+ raise JSONLError(f"{path}: {e}") from None
171
+ with atomic(path) as f:
172
+ f.write(text + "\n")
basal/lean.py ADDED
@@ -0,0 +1,204 @@
1
+ """A lean Llama forward for the CUDA graph engine (--lean on): the loaded model's weights run through ONE layer
2
+ function, compiled once (dynamic shapes) and called for every layer with that layer's weights as arguments, instead of
3
+ transformers' module tree compiled as a whole. The arithmetic is transformers' Llama layer (RMSNorm in fp32, rotary
4
+ embeddings from fp32 tables, SDPA attention, SiLU MLP); the residual add is fused into the next normalisation's
5
+ kernel, the projections are merged when the model was (merge_projections), and FP8 checkpoints keep FP8Linear's GEMM.
6
+
7
+ forward(ids, kv=None) plain causal rows (pass 1); kv: per-layer (K, V) buffers it fills
8
+ forward_suffix(ids, mask, pos, prefix) pass 2: rows over the root keys / values, with an additive mask, or with
9
+ a TreeMask (FlexAttention over the KV heads as they are, no dense mask)
10
+ """
11
+ from collections import namedtuple
12
+
13
+ import torch
14
+ import torch.nn.functional as F
15
+
16
+ from . import blockquant, fp8block, nvfp4
17
+ from .engine import FP8_FAST_ACCUM, FP8Linear, _ATTN
18
+
19
+ E4M3 = torch.float8_e4m3fn
20
+
21
+
22
+ # The trie mask of pass 2 for FlexAttention: pr [b] root tokens of each row; s [b, S] block of each branch token (S:
23
+ # padding); anc [b, S + 1, S + 1] anc[r, x, y] = block y is block x or one of its ancestors (row / column S: none).
24
+ TreeMask = namedtuple("TreeMask", "pr s anc")
25
+
26
+
27
+ def tree_mask_mod(t, L):
28
+ """A token of a branch sees the root tokens of its row, earlier tokens of its own block and every token of its
29
+ ancestor blocks, and itself (padding included): the additive mask of GraphBackend._mask_from_seg plus the root."""
30
+ def mod(b, h, q, kv):
31
+ j = (kv - L).clamp(min=0)
32
+ tree = (kv >= L) & ((t.anc[b, t.s[b, q], t.s[b, j]] & (j <= q)) | (j == q))
33
+ return (kv < t.pr[b]) | tree
34
+ return mod
35
+
36
+
37
+ def block_mask(t, L, S):
38
+ """A FlexAttention block mask of every (query block, key block) pair, each evaluated with tree_mask_mod: the same
39
+ blocks for any trie of this shape, so a CUDA graph keeps it and only the TreeMask tensors change."""
40
+ from torch.nn.attention.flex_attention import BlockMask
41
+ B = t.pr.shape[0]
42
+ blk = 128
43
+ nq, nk = -(-S // blk), -(-(L + S) // blk)
44
+ num = torch.full((B, 1, nq), nk, dtype=torch.int32, device=t.pr.device)
45
+ idx = torch.arange(nk, dtype=torch.int32, device=t.pr.device).expand(B, 1, nq, nk).contiguous()
46
+ return BlockMask.from_kv_blocks(num, idx, BLOCK_SIZE=blk, mask_mod=tree_mask_mod(t, L), seq_lengths=(S, L + S))
47
+
48
+
49
+ def supports(model):
50
+ """Only plain Llama decoders (every layer LlamaDecoderLayer with LlamaAttention / LlamaMLP)."""
51
+ return all(type(layer).__name__ == "LlamaDecoderLayer" and type(layer.self_attn).__name__ == "LlamaAttention"
52
+ and type(layer.mlp).__name__ == "LlamaMLP" for layer in model.model.layers) \
53
+ and getattr(model.config, "hidden_act", "silu") == "silu"
54
+
55
+
56
+ def _params(m):
57
+ """A linear module -> its weights as arguments: (weight, bias), (weight, weight_scale, input_scale, bias) of an
58
+ FP8Linear or (weight, block scales, bias) of a blockquant.BlockLinear (block-scaled FP8 or int8)."""
59
+ if isinstance(m, FP8Linear):
60
+ return (m.weight, m.weight_scale, m.input_scale, m.bias)
61
+ if isinstance(m, blockquant.BlockLinear):
62
+ return (m.weight, m.weight_scale, m.bias)
63
+ if isinstance(m, nvfp4.NVFP4Linear):
64
+ return (m.weight, m.weight_scale, m.alpha, m.inv_g, m.bias)
65
+ return (m.weight, m.bias)
66
+
67
+
68
+ def linear(x, p):
69
+ """F.linear, FP8Linear's arithmetic (static input scale, rows padded to 16, one scaled GEMM, bias fused) or the
70
+ block-scaled FP8 GEMM (fp8block.linear)."""
71
+ if len(p) == 2:
72
+ return F.linear(x, p[0], p[1])
73
+ if len(p) == 3: # block-scaled (blockquant.BlockLinear): FP8, or int8 (int8block.Int8BlockLinear)
74
+ if p[0].dtype == torch.int8:
75
+ from . import int8block
76
+ return int8block.linear(x, *p)
77
+ return fp8block.linear(x, *p)
78
+ if len(p) == 5:
79
+ return nvfp4.linear(x, *p)
80
+ w, ws, xs, b = p
81
+ shape, dt = x.shape, x.dtype
82
+ x = x.reshape(-1, shape[-1])
83
+ q = (x.float() / xs).clamp(-448.0, 448.0).to(E4M3)
84
+ if x.is_cuda:
85
+ m = q.shape[0]
86
+ if m % 16:
87
+ q = F.pad(q.view(torch.uint8), (0, 0, 0, -m % 16)).view(E4M3)
88
+ y = torch._scaled_mm(q, w.t(), scale_a=xs, scale_b=ws, bias=None if b is None else b.to(dt), out_dtype=dt,
89
+ use_fast_accum=FP8_FAST_ACCUM[0])[:m]
90
+ else:
91
+ y = (q.float() * xs) @ (w.float() * ws).t()
92
+ y = (y if b is None else y + b.float()).to(dt)
93
+ return y.reshape(*shape[:-1], w.shape[0])
94
+
95
+
96
+ class Lean:
97
+ def __init__(self, model, compile=True, deterministic=False):
98
+ mm, cfg = model.model, model.config
99
+ self.H, self.Hkv = cfg.num_attention_heads, cfg.num_key_value_heads
100
+ self.d = getattr(cfg, "head_dim", None) or cfg.hidden_size // cfg.num_attention_heads
101
+ self.eps, self.scale = cfg.rms_norm_eps, self.d ** -0.5
102
+ self.emb, self.norm = mm.embed_tokens.weight, mm.norm.weight
103
+ dt, dev = self.emb.dtype, self.emb.device
104
+ rope = mm.rotary_emb
105
+ n = getattr(cfg, "max_position_embeddings", 32768)
106
+ f = torch.outer(torch.arange(n, device=dev, dtype=torch.float32), rope.inv_freq.float().to(dev))
107
+ e = torch.cat([f, f], -1)
108
+ s = getattr(rope, "attention_scaling", 1.0)
109
+ self.cos, self.sin = (e.cos() * s).to(dt), (e.sin() * s).to(dt)
110
+ self.layers = []
111
+ for layer in mm.layers:
112
+ a, m = layer.self_attn, layer.mlp
113
+ qkv = [a.qkv_proj] if hasattr(a, "qkv_proj") else [a.q_proj, a.k_proj, a.v_proj]
114
+ gu = [m.gate_up_proj] if hasattr(m, "gate_up_proj") else [m.gate_proj, m.up_proj]
115
+ self.layers.append((layer.input_layernorm.weight, layer.post_attention_layernorm.weight,
116
+ tuple(_params(x) for x in qkv), _params(a.o_proj), tuple(_params(x) for x in gu),
117
+ _params(m.down_proj)))
118
+ from .engine import compile_llama # (pointwise kernels untimed, as every compiled Llama function)
119
+ self.layer = compile_llama(self._layer, dynamic=True, deterministic=deterministic) if compile else self._layer
120
+
121
+ def rms(self, x, w):
122
+ xf = x.float()
123
+ return w * (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)).to(x.dtype)
124
+
125
+ @staticmethod
126
+ def rot(x, cos, sin):
127
+ h = x.shape[-1] // 2
128
+ return x * cos + torch.cat((-x[..., h:], x[..., :h]), -1) * sin
129
+
130
+ def attend(self, q, k, v, mask=None):
131
+ """q [b, L, H, d], k / v [b, Hkv, Lk, d] -> [b, L, H, d]. Without a mask: causal, with the kernel of --attn;
132
+ with a FlexAttention block mask: flex_attention over the KV heads as they are; with an additive mask
133
+ [b, 1, L, Lk]: SDPA over the KV heads repeated, as transformers does."""
134
+ from torch.nn.attention.flex_attention import BlockMask, flex_attention
135
+ if isinstance(mask, BlockMask): # the prefill kernel: Inductor's decoding kernel has no dynamic-shape choice
136
+ return flex_attention(q.transpose(1, 2), k, v, block_mask=mask, scale=self.scale, enable_gqa=True,
137
+ kernel_options={"FORCE_USE_FLEX_ATTENTION": True}).transpose(1, 2)
138
+ direct = _ATTN["direct"]
139
+ if mask is None:
140
+ if direct is not None and q.dtype in (torch.bfloat16, torch.float16):
141
+ return direct(q.transpose(1, 2), k, v, self.scale)
142
+ o = F.scaled_dot_product_attention(q.transpose(1, 2), k, v, is_causal=True, scale=self.scale,
143
+ enable_gqa=True)
144
+ return o.transpose(1, 2)
145
+ r = self.H // self.Hkv
146
+ b, _, Lk, d = k.shape
147
+ # contiguous: with one key / value head the reshape is a stride-0 view, from which SDPA's memory-efficient
148
+ # kernel (the dispatcher's pick for a masked call) returns a wrong last query row on torch < 2.14.1
149
+ # (pytorch/pytorch#191937); with more heads the reshape copies anyway
150
+ k = k[:, :, None].expand(b, self.Hkv, r, Lk, d).reshape(b, self.H, Lk, d).contiguous()
151
+ v = v[:, :, None].expand(b, self.Hkv, r, Lk, d).reshape(b, self.H, Lk, d).contiguous()
152
+ return F.scaled_dot_product_attention(q.transpose(1, 2), k, v, attn_mask=mask, scale=self.scale).transpose(1, 2)
153
+
154
+ def _layer(self, h, res, P, cos, sin, kb=None, vb=None, pk=None, pv=None, mask=None):
155
+ """One decoder layer: h + res (the previous layer's MLP output) is the residual stream. kb / vb: buffers that
156
+ receive this layer's keys and values (pass 1); pk / pv: prefix keys and values the rows continue (pass 2)."""
157
+ ln1, ln2, qkv, o, gu, down = P
158
+ b, L, _ = h.shape
159
+ h = h + res
160
+ x = self.rms(h, ln1)
161
+ if len(qkv) == 1:
162
+ q, k, v = linear(x, qkv[0]).split([self.H * self.d, self.Hkv * self.d, self.Hkv * self.d], -1)
163
+ else:
164
+ q, k, v = (linear(x, p) for p in qkv)
165
+ q = self.rot(q.view(b, L, self.H, self.d), cos, sin)
166
+ k = self.rot(k.view(b, L, self.Hkv, self.d), cos, sin).transpose(1, 2)
167
+ v = v.view(b, L, self.Hkv, self.d).transpose(1, 2)
168
+ if kb is not None:
169
+ kb.copy_(k)
170
+ vb.copy_(v)
171
+ if pk is not None:
172
+ k, v = torch.cat([pk, k], 2), torch.cat([pv, v], 2)
173
+ a = self.attend(q, k, v, mask)
174
+ h = h + linear(a.reshape(b, L, self.H * self.d), o)
175
+ x = self.rms(h, ln2)
176
+ if len(gu) == 1:
177
+ g, u = linear(x, gu[0]).chunk(2, -1)
178
+ else:
179
+ g, u = linear(x, gu[0]), linear(x, gu[1])
180
+ return h, linear(F.silu(g) * u, down)
181
+
182
+ def _run(self, ids, cos, sin, kv=None, prefix=None, mask=None):
183
+ h = F.embedding(ids, self.emb)
184
+ res = torch.zeros_like(h)
185
+ for i, P in enumerate(self.layers):
186
+ kb, vb = kv[i] if kv is not None else (None, None)
187
+ pk, pv = prefix[i] if prefix is not None else (None, None)
188
+ h, res = self.layer(h, res, P, cos, sin, kb, vb, pk, pv, mask)
189
+ return self.rms(h + res, self.norm)
190
+
191
+ @torch.no_grad()
192
+ def forward(self, ids, kv=None):
193
+ """Plain causal rows [b, L] from position 0 -> normalised hidden states [b, L, D]; kv: per-layer (K, V) buffers
194
+ [b, kv heads, L, head dim] that receive the keys and values (the root pass)."""
195
+ L = ids.shape[1]
196
+ return self._run(ids, self.cos[:L, None], self.sin[:L, None], kv=kv)
197
+
198
+ @torch.no_grad()
199
+ def forward_suffix(self, ids, mask, pos, prefix):
200
+ """Pass 2: rows [b, S] at positions pos that continue per-layer prefix (K, V) [b, kv heads, P, head dim], with
201
+ an additive mask [b, 1, S, P + S] or a TreeMask -> normalised hidden states [b, S, D]."""
202
+ if isinstance(mask, TreeMask):
203
+ mask = block_mask(mask, prefix[0][0].shape[2], ids.shape[1])
204
+ return self._run(ids, self.cos[pos][:, :, None], self.sin[pos][:, :, None], prefix=prefix, mask=mask)
basal/llama_attn.py ADDED
@@ -0,0 +1,252 @@
1
+ """Self-contained pure-Triton metadata attention for Llama / Bielik 3.0 (basal/llama_graph.py).
2
+ Zero dependency on 3.1+'s attn_meta.py so 3.0.1 forward-ports cleanly across release/3.1..3.4.
3
+
4
+ Tile tuning targets:
5
+ - H100 / H200 (sm_90) and B200 / B300 (sm_100): 227 KB smem -> BM=128, BN=64 (D=128) / BN=128 (D=64), 8 warps, 3 stages
6
+ - RTX PRO 6000 / RTX 5090 / GB10 (sm_120 / sm_121): 99 KB smem -> BM=64, BN=64, 4 warps, 2 stages (zero spills)
7
+ - A100 (sm_80): 163 KB smem -> BM=64, BN=64, 4 warps, 3 stages
8
+ - Non-power-of-2 GQA (Bielik-1.5B: 12 Q / 2 KV = GQA 6): HP="group" resolves to largest pow2 divisor (`group & -group`)
9
+ so MQT = BLOCK_M // HP is exact and every head in a tile shares one KV head.
10
+ """
11
+ import torch
12
+
13
+ _KERNEL = []
14
+ _SPLITK = []
15
+
16
+ CONFIGS = {
17
+ "small": { # ~99 KB: sm_120 / sm_121 (RTX PRO 6000 Blackwell, RTX 5090, GB10)
18
+ ("rows", 64): dict(BLOCK_M=64, BLOCK_N=64, num_warps=4, num_stages=2, HP=1),
19
+ ("rows", 128): dict(BLOCK_M=64, BLOCK_N=64, num_warps=4, num_stages=2, HP=1),
20
+ ("readout", 64): dict(BLOCK_M=16, BLOCK_N=64, num_warps=4, num_stages=2, HP="group"),
21
+ ("readout", 128): dict(BLOCK_M=16, BLOCK_N=64, num_warps=4, num_stages=2, HP="group"),
22
+ },
23
+ "small8": { # ~99 KB: sm_86 / sm_89 (RTX 3090, RTX 4090, RTX 6000 Ada)
24
+ ("rows", 64): dict(BLOCK_M=64, BLOCK_N=64, num_warps=4, num_stages=2, HP=1),
25
+ ("rows", 128): dict(BLOCK_M=64, BLOCK_N=64, num_warps=4, num_stages=2, HP=1),
26
+ ("readout", 64): dict(BLOCK_M=16, BLOCK_N=64, num_warps=4, num_stages=2, HP="group"),
27
+ ("readout", 128): dict(BLOCK_M=16, BLOCK_N=64, num_warps=4, num_stages=2, HP="group"),
28
+ },
29
+ "mid": { # ~163 KB: sm_80 (A100)
30
+ ("rows", 64): dict(BLOCK_M=128, BLOCK_N=64, num_warps=4, num_stages=3, HP=1),
31
+ ("rows", 128): dict(BLOCK_M=64, BLOCK_N=64, num_warps=4, num_stages=3, HP=1),
32
+ ("readout", 64): dict(BLOCK_M=16, BLOCK_N=64, num_warps=4, num_stages=2, HP="group"),
33
+ ("readout", 128): dict(BLOCK_M=16, BLOCK_N=64, num_warps=4, num_stages=2, HP="group"),
34
+ },
35
+ "big": { # ~227 KB: sm_90 (H100 / H200) and sm_100 (B200 / B300)
36
+ ("rows", 64): dict(BLOCK_M=128, BLOCK_N=128, num_warps=8, num_stages=3, HP=1),
37
+ ("rows", 128): dict(BLOCK_M=128, BLOCK_N=64, num_warps=8, num_stages=3, HP=1),
38
+ ("readout", 64): dict(BLOCK_M=16, BLOCK_N=128, num_warps=4, num_stages=3, HP="group"),
39
+ ("readout", 128): dict(BLOCK_M=16, BLOCK_N=128, num_warps=4, num_stages=3, HP="group"),
40
+ },
41
+ "fp32": {
42
+ ("rows", 64): dict(BLOCK_M=32, BLOCK_N=32, num_warps=4, num_stages=1, HP=1),
43
+ ("rows", 128): dict(BLOCK_M=32, BLOCK_N=32, num_warps=4, num_stages=1, HP=1),
44
+ ("readout", 64): dict(BLOCK_M=16, BLOCK_N=32, num_warps=4, num_stages=1, HP="group"),
45
+ ("readout", 128): dict(BLOCK_M=16, BLOCK_N=32, num_warps=4, num_stages=1, HP="group"),
46
+ },
47
+ }
48
+
49
+
50
+ def gpu_class(smem, major=12):
51
+ if smem >= 200 * 1024:
52
+ return "big"
53
+ if smem >= 140 * 1024:
54
+ return "mid"
55
+ return "small" if major >= 12 else "small8"
56
+
57
+
58
+ def _pow2_divisor(n):
59
+ return n & -n if n > 0 else 1
60
+
61
+
62
+ def config(kind, d, group, smem, fp32=False, major=12):
63
+ d_key = 128 if d > 64 else 64
64
+ cf = dict(CONFIGS["fp32" if fp32 else gpu_class(smem, major)][(kind, d_key)])
65
+ if cf["HP"] == "group":
66
+ hp = _pow2_divisor(group)
67
+ cf["HP"] = hp
68
+ cf["BLOCK_M"] = max(cf["BLOCK_M"], hp)
69
+ return cf
70
+
71
+
72
+ def available():
73
+ if not torch.cuda.is_available():
74
+ return "needs a CUDA GPU"
75
+ if torch.cuda.get_device_capability() < (8, 0):
76
+ return "needs an Ampere or newer GPU (sm_80+)"
77
+ try:
78
+ import triton # noqa: F401
79
+ except ImportError:
80
+ return "needs Triton"
81
+ return None
82
+
83
+
84
+ def visible(B, Mq, Lk, qi=None, pr=None, start=None, sb=None, anc=None, nr=None, se=None, tw=None, device="cpu"):
85
+ """Boolean [B, Mq, Lk]: key j visible from query i of row b (exact reference for all Llama row kinds)."""
86
+ nr = Lk if nr is None else nr
87
+ i = torch.arange(Mq, device=device)[None].expand(B, Mq) if qi is None else qi
88
+ if se is not None:
89
+ j = torch.arange(Lk, device=device)
90
+ vis = (j >= start[i][..., None]) & (j <= i[..., None]) & (i[..., None] < se[j][None, None])
91
+ if tw is not None:
92
+ vis = vis | ((j >= start[i][..., None]) & (j < tw[i][..., None]))
93
+ return vis
94
+ r = torch.arange(nr, device=device)
95
+ if sb is not None: # Pass 2: every branch token comes after the root and sees all pr[b] root keys
96
+ hi = pr[:, None].expand_as(i).clamp(max=nr) if pr is not None else torch.full_like(i, nr)
97
+ else:
98
+ hi = torch.minimum(i + 1, torch.full_like(i, nr))
99
+ if tw is not None:
100
+ hi = torch.minimum(torch.maximum(i + 1, tw[:, None]), torch.full_like(i, nr))
101
+ if pr is not None:
102
+ hi = torch.minimum(hi, pr[:, None])
103
+ lo = start[i] if start is not None else torch.zeros_like(i)
104
+ root = (r[None, None] >= lo[..., None]) & (r[None, None] < hi[..., None])
105
+ if sb is None:
106
+ return root if nr == Lk else torch.cat([root, root.new_zeros(B, Mq, Lk - nr)], -1)
107
+ S = Lk - nr
108
+ j = torch.arange(S, device=device)
109
+ bq = sb.gather(1, i)
110
+ a = anc.bool()[torch.arange(B, device=device)[:, None, None], bq[..., None], sb[:, None, :]]
111
+ br = (a & (j[None, None] <= i[..., None])) | (j[None, None] == i[..., None])
112
+ return torch.cat([root, br], -1)
113
+
114
+
115
+ def reference(q, k, v, scale=1.0, **meta):
116
+ """Exact fp32/fp64 softmax attention reference on CPU/tests -> [B, Mq, H, D]."""
117
+ B, H, Mq, _ = q.shape
118
+ g, dt = H // k.shape[1], torch.promote_types(q.dtype, torch.float32)
119
+ m = visible(B, Mq, k.shape[2], device=q.device, **meta)
120
+ kk, vv = k.to(dt).repeat_interleave(g, 1), v.to(dt).repeat_interleave(g, 1)
121
+ s = (q.to(dt) @ kk.transpose(-1, -2)) * scale
122
+ s = s.masked_fill(~m[:, None], float("-inf"))
123
+ return (torch.softmax(s, -1) @ vv).to(q.dtype).transpose(1, 2)
124
+
125
+
126
+ def _build():
127
+ from .llama_attn_kernels import llama_attn_kernel
128
+ from torch.library import triton_op, wrap_triton
129
+
130
+ @triton_op("basal::llama_attn", mutates_args=())
131
+ def op(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, qi: torch.Tensor | None,
132
+ pr: torch.Tensor | None, st: torch.Tensor | None, sb: torch.Tensor | None,
133
+ anc: torch.Tensor | None, nr: int, scale: float,
134
+ block_m: int, block_n: int, warps: int, stages: int, hp: int,
135
+ se: torch.Tensor | None = None, tw: torch.Tensor | None = None) -> torch.Tensor:
136
+ B, H, Mq, D = q.shape
137
+ o = q.new_empty(B, Mq, H, D)
138
+ if Mq and B:
139
+ mqt = block_m // hp
140
+ grid = ((Mq + mqt - 1) // mqt, B * (H // hp))
141
+ wrap_triton(llama_attn_kernel)[grid](
142
+ q, k, v, o,
143
+ q if qi is None else qi, q if pr is None else pr, q if st is None else st,
144
+ q if sb is None else sb, q if anc is None else anc, q if se is None else se,
145
+ q if tw is None else tw,
146
+ q.stride(0) // 16, q.stride(1) // 16, q.stride(2) // 16,
147
+ k.stride(0) // 16, k.stride(1) // 16, k.stride(2) // 16,
148
+ v.stride(0) // 16, v.stride(1) // 16, v.stride(2) // 16,
149
+ o.stride(0) // 16, o.stride(1) // 16, o.stride(2) // 16,
150
+ 0 if qi is None else qi.stride(0), 0 if sb is None else sb.stride(0),
151
+ 0 if anc is None else anc.stride(0), 0 if anc is None else anc.stride(1),
152
+ Mq, nr,
153
+ H=H, GROUP=H // k.shape[1], HP=hp, BLOCK_M=block_m, BLOCK_N=block_n, D=D,
154
+ HAS_QI=qi is not None, HAS_PR=pr is not None, HAS_ST=st is not None,
155
+ TREE=sb is not None, FLAT=se is not None, HAS_TW=tw is not None,
156
+ IEEE=q.dtype == torch.float32, QK_SCALE=scale * 1.4426950408889634,
157
+ num_warps=warps, num_stages=stages)
158
+ return o
159
+
160
+ return op
161
+
162
+
163
+ def _build_splitk():
164
+ from .llama_attn_kernels import readout_splitk_kernel, readout_splitk_reduce
165
+ from torch.library import triton_op, wrap_triton
166
+
167
+ @triton_op("basal::llama_attn_splitk", mutates_args=())
168
+ def op(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, qi: torch.Tensor | None,
169
+ pr: torch.Tensor | None, st: torch.Tensor | None, se: torch.Tensor | None,
170
+ tw: torch.Tensor | None, nr: int, scale: float,
171
+ block_m: int, block_n: int, warps: int, stages: int, hp: int, nsplits: int) -> torch.Tensor:
172
+ B, H, Mq, D = q.shape
173
+ o = q.new_empty(B, Mq, H, D)
174
+ if Mq and B:
175
+ op_buf = torch.empty((B, Mq, H, nsplits, D), dtype=torch.float32, device=q.device)
176
+ lp_buf = torch.empty((B, Mq, H, nsplits), dtype=torch.float32, device=q.device)
177
+ mqt = block_m // hp
178
+ grid = ((Mq + mqt - 1) // mqt, B * (H // hp), nsplits)
179
+ wrap_triton(readout_splitk_kernel)[grid](
180
+ q, k, v, op_buf, lp_buf,
181
+ q if qi is None else qi, q if pr is None else pr, q if st is None else st,
182
+ q if se is None else se, q if tw is None else tw,
183
+ q.stride(0) // 16, q.stride(1) // 16, q.stride(2) // 16,
184
+ k.stride(0) // 16, k.stride(1) // 16, k.stride(2) // 16,
185
+ v.stride(0) // 16, v.stride(1) // 16, v.stride(2) // 16,
186
+ 0 if qi is None else qi.stride(0), Mq, nr,
187
+ H=H, GROUP=H // k.shape[1], HP=hp, BLOCK_M=block_m, BLOCK_N=block_n, D=D, NSPLITS=nsplits,
188
+ HAS_QI=qi is not None, HAS_PR=pr is not None, HAS_ST=st is not None,
189
+ FLAT=se is not None, HAS_TW=tw is not None, IEEE=q.dtype == torch.float32,
190
+ QK_SCALE=scale * 1.4426950408889634, num_warps=warps, num_stages=stages)
191
+ wrap_triton(readout_splitk_reduce)[(B * Mq * H,)](
192
+ op_buf, lp_buf, o, o.stride(0), o.stride(1), o.stride(2), Mq,
193
+ H=H, D=D, NSPLITS=nsplits, num_warps=4)
194
+ return o
195
+
196
+ return op
197
+
198
+
199
+ def prepare():
200
+ if not _KERNEL:
201
+ _KERNEL.append(_build())
202
+ if not _SPLITK:
203
+ _SPLITK.append(_build_splitk())
204
+
205
+
206
+ _GPU = {}
207
+
208
+
209
+ def device_properties(device):
210
+ index = device.index if device.index is not None else torch.cuda.current_device()
211
+ if index not in _GPU:
212
+ props = torch.cuda.get_device_properties(index)
213
+ _GPU[index] = (props.shared_memory_per_block_optin, props.major)
214
+ return _GPU[index]
215
+
216
+
217
+ def attention(q, k, v, scale=1.0, qi=None, pr=None, start=None, sb=None, anc=None, nr=None, se=None,
218
+ tw=None, cfg=None, splitk=False):
219
+ """q [B, H, Mq, d], k / v [B, Hkv, Lk, d] -> [B, Mq, H, d]. Zero-copy on 16-aligned NHD views."""
220
+ nr = k.shape[2] if nr is None else nr
221
+ if not q.is_cuda:
222
+ meta = dict(qi=qi, start=start, se=se, tw=tw) if se is not None else dict(
223
+ qi=qi, pr=pr, start=start, sb=sb, anc=anc, nr=nr, tw=tw)
224
+ return reference(q, k, v, scale, **meta)
225
+ prepare()
226
+ D, group = q.shape[-1], q.shape[1] // k.shape[1]
227
+ if D % 16 or D > 128:
228
+ raise ValueError(f"basal::llama_attn: head_dim {D} (expected multiple of 16, <= 128)")
229
+ if cfg is None:
230
+ smem, major = device_properties(q.device)
231
+ cfg = config("readout" if qi is not None else "rows", D, group, smem, q.dtype == torch.float32, major)
232
+ q, k, v = (x if x.stride(-1) == 1 and all(s % 16 == 0 for s in x.stride()[:-1]) else x.contiguous()
233
+ for x in (q, k, v))
234
+
235
+ def as_long(x):
236
+ return None if x is None else (x if x.dtype == torch.int64 else x.long()).contiguous()
237
+
238
+ if (splitk and qi is not None and sb is None and q.shape[2] <= 32
239
+ and not isinstance(nr, torch.SymInt) and nr >= 1024):
240
+ nsplits = 8 if nr < 4096 else 16
241
+ return torch.ops.basal.llama_attn_splitk(
242
+ q, k, v, as_long(qi), as_long(pr), as_long(start), as_long(se), as_long(tw),
243
+ int(nr), float(scale), cfg["BLOCK_M"], cfg["BLOCK_N"], cfg["num_warps"], cfg["num_stages"],
244
+ cfg["HP"], nsplits)
245
+
246
+ return torch.ops.basal.llama_attn(
247
+ q, k, v, as_long(qi), as_long(pr), as_long(start), as_long(sb),
248
+ None if anc is None else anc.to(torch.uint8) if anc.dtype == torch.bool else anc,
249
+ int(nr) if not isinstance(nr, torch.SymInt) else nr, float(scale),
250
+ cfg["BLOCK_M"], cfg["BLOCK_N"], cfg["num_warps"], cfg["num_stages"], cfg["HP"],
251
+ **({} if se is None else {"se": as_long(se)}),
252
+ **({} if tw is None else {"tw": as_long(tw)}))