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/gemma4_graph.py ADDED
@@ -0,0 +1,931 @@
1
+ """The Gemma 4 (basal-omni) forward of the CUDA graph engine (GraphBackend: --mode fast, fast-nocompile; basal 2.3).
2
+ GraphBackend keeps its machinery (static shapes and one CUDA graph per shape, the prefix trie of a request in one
3
+ packed row, pass 1 over the root into key / value buffers, pass 2 over every branch with the trie mask, the state
4
+ cache); for a Gemma 4 model (Gemma4 / Gemma4Unified, text: E2B, E4B, 12B, 31B) it replays this forward instead of the
5
+ Llama one:
6
+
7
+ forward(ids, kv=None, ro=None) plain causal rows from position 0 (single prompts, pass-1 roots)
8
+ forward_suffix(ids, mask, pos, prefix, ro=None) pass 2: rows over root keys / values with the trie mask
9
+
10
+ What differs from Llama, layer by layer as transformers' Gemma4TextDecoderLayer (the same modules are called):
11
+
12
+ - **Layer types.** Sliding-window layers (window W: E2B / E4B 512, 12B / 31B 1024; head size 256) between global layers
13
+ (head size 512, partial rotary embeddings, on 12B / 31B one projection for keys and values: attention_k_eq_v, the
14
+ values normalised but not rotated). A token of a packed row sees its ancestors in the trie at the positions they have
15
+ in its own prompt, so in sliding layers the window is a condition on positions added to the trie mask: a branch
16
+ token sees a root key at position j only when its own position is < j + W, exactly as in its prompt alone.
17
+ - **Readout rows.** From the last layer with its own keys and values on, a layer's output matters only where it is
18
+ read: E2B / E4B reuse the keys and values of earlier layers in their last layers (E4B: the last 18 of 42), and the
19
+ attention and MLP of the last own-key layer only feed those (on 12B / 31B the last layer is that layer). With `ro`
20
+ (the readout positions of every row) these layers run at the readout rows only, their queries over the keys and
21
+ values of every token; same maths, ~40% less compute on E4B.
22
+ - **Per-layer inputs** (E2B / E4B), the embedding scale, q / k / v norms, the four norms around attention and MLP, the
23
+ layer scalar: transformers' own modules and methods.
24
+ - **Attention kernels** per layer type (`kernels`, {"sliding_attention": k, "full_attention": k}): "math" = torch
25
+ SDPA's math kernel with a boolean mask, the kernel EagerBackend runs for Gemma 4 (the reference; queries in parts,
26
+ so that the scores of a long row fit); "flex" = FlexAttention with block masks of the same conditions; "fa3" =
27
+ FlashAttention 3 (sliding layers' plain rows; flex where a mask is needed). flex and fa3 run in compiled forwards
28
+ only (uncompiled, flex_attention is a slow reference); uncompiled forwards run math.
29
+ - The output head reads the code rows in fp32 with the final logit softcap (GraphBackend.softcap).
30
+
31
+ Attention is causal for text; the bidirectional attention of image tokens (use_bidirectional_attention "vision") is
32
+ not used here, since this path takes text only (media run in the eager backend).
33
+ """
34
+ from collections import namedtuple
35
+ from functools import lru_cache
36
+
37
+ import torch
38
+ import torch.nn.functional as F
39
+
40
+ from . import attn512
41
+
42
+
43
+ def text_model(model):
44
+ """The decoder of a Gemma 4 model: Gemma4(Unified)ForConditionalGeneration -> model.language_model,
45
+ Gemma4ForCausalLM -> model. (The same helper as basal/gemma4.py of the eager backend.)"""
46
+ return getattr(model.model, "language_model", model.model)
47
+
48
+
49
+ @torch.no_grad()
50
+ def move_except(model, dev, skip):
51
+ """Moves the parameters and buffers of model's modules to dev in place, except those of the modules under `skip`
52
+ (a module whose submodules stay where they are). Parameters keep their identity (.data is replaced), so tied ones
53
+ stay tied."""
54
+ out = {id(m) for m in skip.modules()}
55
+ for m in model.modules():
56
+ if id(m) in out:
57
+ continue
58
+ for p in m._parameters.values():
59
+ if p is not None:
60
+ p.data = p.data.to(dev)
61
+ for k, b in m._buffers.items():
62
+ if b is not None:
63
+ m._buffers[k] = b.to(dev)
64
+
65
+
66
+ def is_gemma4(model):
67
+ return str(getattr(model.config, "model_type", "")).startswith("gemma4")
68
+
69
+
70
+ def is_gemma4_dir(model_dir, strict=False):
71
+ """A model directory with a Gemma 4 config.json (before loading it). strict: a config.json that cannot be read
72
+ (permissions, a full disk) or parsed raises instead of answering False (a missing one still answers False)."""
73
+ import json
74
+ from pathlib import Path
75
+ p = Path(model_dir) / "config.json"
76
+ try:
77
+ return str(json.loads(p.read_text(encoding="utf-8")).get("model_type", "")).startswith("gemma4")
78
+ except (OSError, ValueError) as e:
79
+ if strict and not isinstance(e, FileNotFoundError):
80
+ raise
81
+ return False
82
+
83
+
84
+
85
+
86
+ @lru_cache(maxsize=None)
87
+ def _smem(index):
88
+ return torch.cuda.get_device_properties(index).shared_memory_per_block_optin
89
+
90
+
91
+ def supports(model):
92
+ """None if this forward runs the model, else why not (the MoE layers of 26B-A4B are not ported)."""
93
+ if not is_gemma4(model):
94
+ return "not a Gemma 4 model"
95
+ if getattr(text_model(model).config, "enable_moe_block", False):
96
+ return "Gemma 4 MoE layers (26B-A4B) are not in the CUDA graph engine; use --mode eager or vllm"
97
+ cfg = text_model(model).config
98
+ if getattr(cfg, "hidden_activation", "gelu_pytorch_tanh") != "gelu_pytorch_tanh":
99
+ return "the Gemma graph requires the gelu_pytorch_tanh activation; use --mode eager"
100
+ if getattr(cfg, "attention_bias", False):
101
+ return "the Gemma graph requires bias-free attention projections; use --mode eager"
102
+ if set(cfg.layer_types) - {"full_attention", "sliding_attention"}:
103
+ return "unrecognized Gemma attention layer type; use --mode eager"
104
+ return None
105
+
106
+
107
+ KERNELS = ("math", "flex", "fa3")
108
+ _FLEX = []
109
+
110
+
111
+ def _compile(fn):
112
+ """torch.compile in Inductor's deterministic mode (TORCHINDUCTOR_DETERMINISTIC=0: without it). Otherwise Inductor
113
+ times some reduction kernels at their first launch and keeps the faster config: the RMSNorm kernels ran with a
114
+ reduction block of 4,096 or 2,048 (Inductor adds the halved block when a kernel needs many registers), whichever
115
+ was faster by timings within 1% of each other, and the block sets the order of the sum. The choice is not always
116
+ cached, so another process can time it again: basal-omni-1.0-mini on an H100, 2.3.3, two runs on fresh compile
117
+ caches differed in 485 of 840 identity readouts (top answer in 7), a cold and a warm cache in 400 (top answer in
118
+ 4; 22 Oct). In this mode every such kernel has one config, chosen without timing. Set per compile: Dynamo resets the
119
+ global switch after every frame it traces (it restores torch.use_deterministic_algorithms, which sets it).
120
+ Pointwise kernels too (engine.compile_untimed): deterministic mode left them timed, and two cold starts of a dual
121
+ model picked other block shapes for 17 of 36 of them and answered its long rank requests differently."""
122
+ from .engine import compile_untimed
123
+ return compile_untimed(fn)
124
+
125
+
126
+ def _flex_attention():
127
+ """flex_attention as it is inside the compiled forward (Inductor generates its kernel there); from uncompiled code
128
+ (fast-nocompile, shapes without a graph, the long lane) one compiled instance (automatic dynamic shapes), since
129
+ uncompiled flex_attention is a slow reference implementation."""
130
+ from torch.nn.attention.flex_attention import flex_attention
131
+ if torch.compiler.is_compiling():
132
+ return flex_attention
133
+ if not _FLEX:
134
+ _FLEX.append(_compile(flex_attention))
135
+ return _FLEX[0]
136
+
137
+
138
+ LayerC = namedtuple("LayerC", "heads kv_heads d eps sizes") # constants of a layer (sizes: of a merged q / k / v)
139
+
140
+
141
+ def load_nvfp4_amax(amax):
142
+ """--nvfp4-amax as the NVFP4 path reads it: {"<layer>.<projection>": largest |input|} from a dict or a JSON file,
143
+ either that mapping or {"amax": mapping} (the shipped NVFP4_AMAX.json)."""
144
+ if not isinstance(amax, dict):
145
+ import json
146
+ with open(amax, encoding="utf-8") as f:
147
+ amax = json.load(f)
148
+ return amax.get("amax", amax) if isinstance(amax.get("amax"), dict) else amax
149
+
150
+
151
+ def _rms(x, w, eps):
152
+ """Gemma4RMSNorm: in fp32, x * (mean(x^2) + eps)^-0.5, times the weight (None: the values' norm), back to x's
153
+ dtype."""
154
+ xf = x.float()
155
+ y = xf * torch.pow(xf.pow(2).mean(-1, keepdim=True) + eps, -0.5)
156
+ return (y * w.float() if w is not None else y).type_as(x)
157
+
158
+
159
+ def _rot(x, cos, sin):
160
+ """apply_rotary_pos_emb of Gemma 4 on [b, L, heads, d] with cos / sin [b, L, d]."""
161
+ cos, sin = cos[:, :, None], sin[:, :, None]
162
+ h = x.shape[-1] // 2
163
+ return x * cos + torch.cat((-x[..., h:], x[..., :h]), -1) * sin
164
+
165
+
166
+ def _pack(sel):
167
+ """Block lists of a FlexAttention block mask from a [query blocks, key blocks] selection: the count per query
168
+ block and the selected key blocks first, ascending ([1, 1, ...] for every row and head)."""
169
+ n = sel.shape[1]
170
+ cols = torch.arange(n, device=sel.device)[None]
171
+ idx = torch.where(sel, cols, n).sort(1).values.clamp(max=n - 1)
172
+ return sel.sum(1).to(torch.int32)[None, None], idx.to(torch.int32)[None, None]
173
+
174
+
175
+ def _pack_rows(sel):
176
+ """_pack per row: a [rows, query blocks, key blocks] selection -> the counts [rows, 1, n] and the key blocks
177
+ [rows, 1, n, n], selected first, ascending."""
178
+ n = sel.shape[-1]
179
+ cols = torch.arange(n, device=sel.device)
180
+ idx = torch.where(sel, cols, n).sort(-1).values.clamp(max=n - 1)
181
+ return sel.sum(-1).to(torch.int32)[:, None], idx.to(torch.int32)[:, None]
182
+
183
+
184
+ def _pre(h, P, C, cos, sin, kb=None, vb=None, pk=None, pv=None):
185
+ """A decoder layer up to attention: the input norm and the projections -> (q [b, L, heads x d] as projected,
186
+ k, v [b, kv heads, P + L, d]: normed, keys rotated, written to kb / vb and after the prefix pk / pv; None for a
187
+ KV-shared layer). transformers' Gemma4TextAttention, with attention_k_eq_v (values = the key projection)."""
188
+ from .lean import linear
189
+ x = _rms(h, P["ln_in"], C.eps)
190
+ if C.sizes is not None:
191
+ q, k, *v = linear(x, P["qkv"]).split(C.sizes, -1)
192
+ v = v[0] if v else k
193
+ else:
194
+ q = linear(x, P["q"])
195
+ if not C.kv_heads:
196
+ return q, None, None
197
+ k = linear(x, P["k"])
198
+ v = linear(x, P["v"]) if "v" in P else k
199
+ b, L = x.shape[:2]
200
+ k = _rot(_rms(k.view(b, L, C.kv_heads, C.d), P["k_norm"], C.eps), cos, sin).transpose(1, 2)
201
+ v = _rms(v.view(b, L, C.kv_heads, C.d), None, C.eps).transpose(1, 2)
202
+ if kb is not None:
203
+ kb.copy_(k)
204
+ vb.copy_(v)
205
+ if pk is not None:
206
+ k, v = torch.cat([pk, k], 2), torch.cat([pv, v], 2)
207
+ return q, k, v
208
+
209
+
210
+ def _post(h, q, k, v, P, C, cos, sin, mask, pli):
211
+ """The rest of a decoder layer (transformers' Gemma4TextDecoderLayer): queries normed and rotated, attention
212
+ with the kernel of the mask, o_proj, the four norms around attention and MLP, the per-layer input, the layer
213
+ scalar."""
214
+ from .lean import linear
215
+ b, L = h.shape[:2]
216
+ q = _rot(_rms(q.view(b, L, C.heads, C.d), P["q_norm"], C.eps), cos, sin).transpose(1, 2)
217
+ h = h + _rms(linear(Gemma4Graph._attend(q, k, v, mask), P["o"]), P["ln_attn"], C.eps)
218
+ x = _rms(h, P["ln_pre"], C.eps)
219
+ if "gu" in P:
220
+ g, u = linear(x, P["gu"]).chunk(2, -1)
221
+ else:
222
+ g, u = linear(x, P["gate"]), linear(x, P["up"])
223
+ h = h + _rms(linear(F.gelu(g, approximate="tanh") * u, P["down"]), P["ln_ff"], C.eps)
224
+ if pli is not None:
225
+ g = F.gelu(linear(h, P["ple_gate"]), approximate="tanh") * pli
226
+ h = h + _rms(linear(g, P["ple_proj"]), P["ln_ple"], C.eps)
227
+ return (h * P["scalar"]).to(h.dtype) # in place in transformers (h *= scalar): the same rounding
228
+
229
+
230
+ class Gemma4Graph:
231
+ # "math": queries per SDPA call, so that the scores (rows x heads x queries x keys, fp32) stay within SCORES
232
+ # elements: in CUDA graphs every captured shape keeps its own peak in the graph pool (1.1-max with 2,048-query
233
+ # parts: 33 GB in the pool, out of memory before warm-up ended, 2026-10-20)
234
+ SCORES = 2 ** 26
235
+ BLOCK = 128 # "flex": block size of the block masks
236
+
237
+ global_attn = "flex" # the kernel of the global layers' plain rows (--global-attn)
238
+
239
+ def __init__(self, model, kernels="math", compile=False, merge=False, fp8=None, fp8_bf16_layers=0, nvfp4_amax=None,
240
+ nvfp4_scope="all", stream=None, global_attn="flex"):
241
+ lm = self.lm = text_model(model)
242
+ cfg = self.cfg = lm.config
243
+ n = cfg.num_hidden_layers
244
+ self.layers = list(lm.layers[:n])
245
+ self.types = list(cfg.layer_types[:n])
246
+ self.window = cfg.sliding_window
247
+ self.softcap = getattr(cfg, "final_logit_softcapping", None)
248
+ dev = lm.embed_tokens.weight.device
249
+ if dev.type == "cuda":
250
+ _smem(dev.index if dev.index is not None else torch.cuda.current_device())
251
+ self.own = [not layer.self_attn.is_kv_shared_layer for layer in self.layers]
252
+ assert all(self.own[: sum(self.own)]), "layers with their own keys and values come first"
253
+ self.n_kv = sum(self.own)
254
+ # the last layer with its own keys and values; a shared layer reads the last such layer of its type (the
255
+ # layer transformers marks store_full_length_kv)
256
+ self.last_kv = self.n_kv - 1
257
+ self.src = {i: max(j for j in range(self.n_kv) if self.types[j] == t)
258
+ for i, t in enumerate(self.types) if not self.own[i]}
259
+ self.store = set(self.src.values())
260
+ # per own layer: (key / value heads, head size), the shape of its key / value buffers
261
+ self.kv_shapes = [(a.k_proj.out_features // a.head_dim, a.head_dim)
262
+ for a in (layer.self_attn for layer in self.layers[: self.n_kv])]
263
+ self.ple = bool(getattr(cfg, "hidden_size_per_layer_input", 0))
264
+ if kernels in ("fa3", "fa3+math"): # FlashAttention 3 in the sliding-window layers; flex or math in the
265
+ kernels = {"sliding_attention": "fa3", "full_attention": "flex" if kernels == "fa3" else "math"} # global
266
+ if isinstance(kernels, str):
267
+ kernels = {t: kernels for t in set(self.types)}
268
+ for k in kernels.values():
269
+ if k not in KERNELS:
270
+ raise ValueError(f"unknown Gemma 4 attention kernel {k!r} (one of {', '.join(KERNELS)})")
271
+ self.kernels = kernels
272
+ if kernels.get("full_attention") == "fa3":
273
+ raise ValueError("fa3 runs the sliding-window layers only (FlashAttention 3 takes heads up to 256 wide)")
274
+ self.flex = any(k != "math" for k in kernels.values()) # fa3 is flex where a mask is needed
275
+ # --global-attn triton: the global layers' plain rows (single prompts, the roots of pass 1) through
276
+ # basal/attn512.py instead of flex; pass 2, compact rows and the readout rows keep flex
277
+ if global_attn not in ("flex", "triton"):
278
+ raise ValueError(f"unknown --global-attn {global_attn!r} (flex or triton)")
279
+ if global_attn == "triton":
280
+ dims = {layer.self_attn.head_dim for t, layer in zip(self.types, self.layers) if t == "full_attention"}
281
+ why = attn512.available()
282
+ if not why and dims != {512}:
283
+ why = f"the global layers' heads are {sorted(dims)} wide, not 512"
284
+ if not why and kernels.get("full_attention") != "flex":
285
+ why = "the global layers run the math kernel here (--gemma-attn math / fa3+math, eager, two-way rows)"
286
+ if why:
287
+ raise ValueError(f"--global-attn triton: {why}")
288
+ attn512.prepare()
289
+ self.global_attn = global_attn
290
+ self.qkv, self.gu = {}, {} # merged projections per layer: (linear, output sizes)
291
+ if stream is None:
292
+ self.merged = self._merge() if merge else 0
293
+ # after merging: a merged weight's parts are its blocks
294
+ self.fp8 = self._fp8_block(fp8_bf16_layers) if fp8 == "block" else 0
295
+ if fp8 == "int8":
296
+ self.fp8 = self._fp8_block(fp8_bf16_layers, int8=True)
297
+ if fp8 == "nvfp4":
298
+ self.fp8 = self._nvfp4(nvfp4_amax, fp8_bf16_layers, nvfp4_scope)
299
+ else: # the decoder layers come from host memory (--quant-load cpu): each one to `stream` (the GPU), merged and
300
+ # quantised there before the next, the same operations on the same weights as above
301
+ self.merged = self.fp8 = 0
302
+ if fp8 == "nvfp4":
303
+ nvfp4_amax = load_nvfp4_amax(nvfp4_amax)
304
+ for i, layer in enumerate(self.layers):
305
+ layer.to(stream)
306
+ self.merged += self._merge([i]) if merge else 0
307
+ if fp8 in ("block", "int8"):
308
+ self.fp8 += self._fp8_block(fp8_bf16_layers, [i], int8=fp8 == "int8")
309
+ elif fp8 == "nvfp4":
310
+ self.fp8 += self._nvfp4(nvfp4_amax, fp8_bf16_layers, nvfp4_scope, [i])
311
+ if compile or self.flex: # flex: uncompiled code calls one compiled flex_attention (_flex_attention), an
312
+ # entry per mask kind, head size and rows-only pass: 13 for mini's long states, past the default 8, after
313
+ # which flex_attention runs its unfused reference (fast-nocompile, 2026-10-20)
314
+ from .engine import compile_set
315
+ compile_set("dynamo", cache_size_limit=64)
316
+ self.args = self._layer_args()
317
+ # one compiled function per layer part, with automatic dynamic shapes (a static compile, then the dimensions
318
+ # that change: rows and tokens). The whole forward compiled as one graph took 15+ minutes of start-up on mini
319
+ # (each recompile of 42 layers; and with dynamic=True every dimension went symbolic and tracing did not end)
320
+ self.compiled = compile
321
+ if compile:
322
+ self.pre, self.post, self.embed = _compile(_pre), _compile(_post), _compile(self._embed)
323
+
324
+ @staticmethod
325
+ def _fuse(mods):
326
+ """One linear for several that read the same input (blockquant.fuse: the modules' own weights become views of
327
+ its weight) -> (linear, output sizes)."""
328
+ from .blockquant import fuse
329
+ w, sizes = fuse(mods)
330
+ lin = torch.nn.Linear(w.shape[1], w.shape[0], bias=False, device="meta", dtype=w.dtype)
331
+ lin.weight = torch.nn.Parameter(w, requires_grad=False)
332
+ return lin, sizes
333
+
334
+ @torch.no_grad()
335
+ def _merge(self, layers=None):
336
+ """One q / k / v GEMM per layer with its own keys and values (q / k with attention_k_eq_v) and one gate / up
337
+ GEMM per layer, for plain bf16 / fp32 linears without bias (FP8 and torchao linears keep theirs); layers: their
338
+ indices (default every layer). -> the number of layers merged."""
339
+ def plain(mods):
340
+ return all(type(x) is torch.nn.Linear and x.bias is None for x in mods) \
341
+ and len({x.weight.dtype for x in mods}) == 1
342
+ n = 0
343
+ for i in range(len(self.layers)) if layers is None else layers:
344
+ layer = self.layers[i]
345
+ a, m = layer.self_attn, layer.mlp
346
+ if self.own[i]:
347
+ qkv = [a.q_proj, a.k_proj] + ([a.v_proj] if a.v_proj is not None else [])
348
+ if plain(qkv):
349
+ self.qkv[i] = self._fuse(qkv)
350
+ if plain([m.gate_proj, m.up_proj]):
351
+ self.gu[i] = self._fuse([m.gate_proj, m.up_proj])
352
+ n += i in self.qkv or i in self.gu
353
+ if torch.cuda.is_available():
354
+ torch.cuda.empty_cache()
355
+ return n
356
+
357
+ @torch.no_grad()
358
+ def _fp8_block(self, keep=0, layers=None, int8=False):
359
+ """Block-scaled FP8 weights (basal/fp8block.py: 128 x 128 blocks, activations in 1 x 128 tiles) for the
360
+ projections the layers run: q / k / v / o and gate / up / down, merged or not (every size is a multiple of 128,
361
+ so a merged weight's blocks are its parts' blocks; the parts become views of it and transformers' forward of
362
+ the model still runs). The per-layer input projections (E2B / E4B), the embeddings and the head stay as loaded.
363
+ Layer by layer, so the bf16 weights are freed as it goes (31B: 59 GB -> 31 GB). The first `keep` and the last
364
+ `keep` layers stay bf16 (--fp8-bf16-layers). layers: their indices (default every layer). int8: block-scaled
365
+ int8 instead (basal/int8block.py, --mode int8; the same blocks). -> the number of GEMMs."""
366
+ from .fp8block import BLOCK, BlockFP8Linear, fits, sm90
367
+ if int8:
368
+ from .int8block import Int8BlockLinear as BlockFP8Linear, build
369
+ build() # the Triton kernel, before any layer is compiled
370
+ else:
371
+ sm90() # which GEMM the layers run, decided before they are compiled
372
+ n = 0
373
+
374
+ def ok(merged):
375
+ return merged is not None and fits(merged[0]) and all(k % BLOCK == 0 for k in merged[1])
376
+
377
+ def merged(lin, sizes, mod, names):
378
+ f, o = BlockFP8Linear.of(lin), 0
379
+ for name, k in zip(names, sizes):
380
+ setattr(mod, name, f.part(o, k))
381
+ o += k
382
+ return f
383
+
384
+ for i in range(len(self.layers)) if layers is None else layers:
385
+ if i < keep or i >= len(self.layers) - keep:
386
+ continue
387
+ layer = self.layers[i]
388
+ a, m = layer.self_attn, layer.mlp
389
+ names = ["q_proj"] + (["k_proj"] + (["v_proj"] if a.v_proj is not None else []) if self.own[i] else [])
390
+ if ok(self.qkv.get(i)):
391
+ self.qkv[i] = (merged(self.qkv[i][0], self.qkv[i][1], a, names), self.qkv[i][1])
392
+ n += 1
393
+ elif i not in self.qkv: # (a merged weight that does not fit stays bf16, as one GEMM)
394
+ for name in names:
395
+ if fits(getattr(a, name)):
396
+ setattr(a, name, BlockFP8Linear.of(getattr(a, name)))
397
+ n += 1
398
+ if ok(self.gu.get(i)):
399
+ self.gu[i] = (merged(self.gu[i][0], self.gu[i][1], m, ["gate_proj", "up_proj"]), self.gu[i][1])
400
+ n += 1
401
+ elif i not in self.gu:
402
+ for name in ("gate_proj", "up_proj"):
403
+ if fits(getattr(m, name)):
404
+ setattr(m, name, BlockFP8Linear.of(getattr(m, name)))
405
+ n += 1
406
+ for mod, name in ((a, "o_proj"), (m, "down_proj")):
407
+ if fits(getattr(mod, name)):
408
+ setattr(mod, name, BlockFP8Linear.of(getattr(mod, name)))
409
+ n += 1
410
+ if torch.cuda.is_available():
411
+ torch.cuda.empty_cache()
412
+ return n
413
+
414
+ @torch.no_grad()
415
+ def _nvfp4(self, amax, keep=0, scope="all", layers=None):
416
+ """NVFP4 weights (basal/nvfp4.py) for q / k / v / o and gate / up / down (scope "all") or gate / up / down only
417
+ ("mlp": attention stays bf16), merged or not, with the input global scales of `amax` (a JSON file or dict
418
+ {"<layer>.<projection>": the calibrated largest |input|}). The first and the last `keep` layers stay bf16, as
419
+ do the embeddings and the head. Layer by layer, the bf16 weights freed as it goes; layers: their indices
420
+ (default every layer). -> the number of GEMMs."""
421
+ from .nvfp4 import NVFP4Linear, build, fits
422
+ if scope not in ("all", "mlp"):
423
+ raise ValueError(f"--nvfp4-scope {scope!r}: all or mlp")
424
+ amax = load_nvfp4_amax(amax)
425
+ build()
426
+ n = 0
427
+
428
+ def one(i, mod, name):
429
+ lin = getattr(mod, name)
430
+ if fits(lin):
431
+ setattr(mod, name, NVFP4Linear.of(lin, amax[f"{i}.{name}"]))
432
+ return 1
433
+ return 0
434
+
435
+ def merged(i, pair, mod, names):
436
+ lin, sizes = pair
437
+ if not (fits(lin) and all(k % 128 == 0 for k in sizes)):
438
+ return pair, 0
439
+ f, o = NVFP4Linear.of(lin, max(amax[f"{i}.{x}"] for x in names)), 0
440
+ for name, k in zip(names, sizes):
441
+ setattr(mod, name, f.part(o, k))
442
+ o += k
443
+ return (f, sizes), 1
444
+
445
+ for i in range(len(self.layers)) if layers is None else layers:
446
+ if i < keep or i >= len(self.layers) - keep:
447
+ continue
448
+ layer = self.layers[i]
449
+ a, m = layer.self_attn, layer.mlp
450
+ if scope == "all":
451
+ names = ["q_proj"] + (["k_proj"] + (["v_proj"] if a.v_proj is not None else []) if self.own[i] else [])
452
+ if i in self.qkv:
453
+ self.qkv[i], k = merged(i, self.qkv[i], a, names)
454
+ n += k
455
+ else:
456
+ n += sum(one(i, a, x) for x in names)
457
+ n += one(i, a, "o_proj")
458
+ if i in self.gu:
459
+ self.gu[i], k = merged(i, self.gu[i], m, ["gate_proj", "up_proj"])
460
+ n += k
461
+ else:
462
+ n += one(i, m, "gate_proj") + one(i, m, "up_proj")
463
+ n += one(i, m, "down_proj")
464
+ if torch.cuda.is_available():
465
+ torch.cuda.empty_cache()
466
+ return n
467
+
468
+ # -- the layer --------------------------------------------------------------------------------------------------
469
+ def _rope(self, pos, t, dtype):
470
+ """cos / sin [b, L, head size] of layer type t at positions pos [b, L], as Gemma4TextRotaryEmbedding (fp32,
471
+ then the model's dtype)."""
472
+ r = self.lm.rotary_emb
473
+ inv = getattr(r, f"{t}_inv_freq")
474
+ f = pos[..., None].float() * inv.float()
475
+ e = torch.cat([f, f], -1)
476
+ s = getattr(r, f"{t}_attention_scaling")
477
+ return (e.cos() * s).to(dtype), (e.sin() * s).to(dtype)
478
+
479
+ def _layer_args(self):
480
+ """Per layer: its weights as tensors (lean.py's linear parameters: bf16, torchao or FP8Linear) and its
481
+ constants. The layer functions take them as arguments, so one compiled function serves every layer of a kind
482
+ (a module argument would be guarded by identity: a compile per layer)."""
483
+ from .lean import _params
484
+ eps = self.cfg.rms_norm_eps
485
+ out = []
486
+ for i, layer in enumerate(self.layers):
487
+ a, m = layer.self_attn, layer.mlp
488
+ P = dict(ln_in=layer.input_layernorm.weight, q_norm=a.q_norm.weight, o=_params(a.o_proj),
489
+ ln_attn=layer.post_attention_layernorm.weight, ln_pre=layer.pre_feedforward_layernorm.weight,
490
+ ln_ff=layer.post_feedforward_layernorm.weight, down=_params(m.down_proj),
491
+ scalar=layer.layer_scalar)
492
+ sizes = None
493
+ if i in self.qkv:
494
+ P["qkv"], sizes = _params(self.qkv[i][0]), tuple(self.qkv[i][1])
495
+ else:
496
+ P["q"] = _params(a.q_proj)
497
+ if self.own[i]:
498
+ P["k"] = _params(a.k_proj)
499
+ if a.v_proj is not None:
500
+ P["v"] = _params(a.v_proj)
501
+ if self.own[i]:
502
+ P["k_norm"] = a.k_norm.weight
503
+ if i in self.gu:
504
+ P["gu"] = _params(self.gu[i][0])
505
+ else:
506
+ P["gate"], P["up"] = _params(m.gate_proj), _params(m.up_proj)
507
+ if self.ple:
508
+ P.update(ple_gate=_params(layer.per_layer_input_gate), ple_proj=_params(layer.per_layer_projection),
509
+ ln_ple=layer.post_per_layer_input_norm.weight)
510
+ heads = a.q_proj.out_features // a.head_dim
511
+ kv_heads = self.kv_shapes[i][0] if self.own[i] else 0
512
+ out.append((P, LayerC(heads, kv_heads, a.head_dim, eps, sizes)))
513
+ return out
514
+
515
+ def _embed(self, ids):
516
+ """Token embeddings (scaled) and, on E2B / E4B, the per-layer inputs [b, L, layers, 256]."""
517
+ h = self.lm.embed_tokens(ids)
518
+ return h, self.lm.project_per_layer_inputs(h, self.lm.get_per_layer_inputs(ids, None)) if self.ple else None
519
+
520
+ # -- attention ----------------------------------------------------------------------------------------------------
521
+ @staticmethod
522
+ @torch.compiler.disable
523
+ def _math(q, k, v, m):
524
+ """SDPA's math kernel: q [b, H, Lq, d], k / v [b, Hkv, Lk, d], m bool [b, 1, Lq, Lk] (True = attend) ->
525
+ [b, Lq, H * d]. Long rows in parts of queries (SCORES). Outside the compiled graph (the reference kernel)."""
526
+ from torch.nn.attention import SDPBackend, sdpa_kernel
527
+ b, H, Lq, _ = q.shape
528
+ n = max(16, Gemma4Graph.SCORES // (b * H * k.shape[2]))
529
+ outs = []
530
+ with sdpa_kernel([SDPBackend.MATH]):
531
+ for s in range(0, Lq, n):
532
+ outs.append(F.scaled_dot_product_attention(q[:, :, s: s + n], k, v, attn_mask=m[:, :, s: s + n],
533
+ scale=1.0, enable_gqa=True))
534
+ o = outs[0] if len(outs) == 1 else torch.cat(outs, 2)
535
+ return o.transpose(1, 2).reshape(q.shape[0], q.shape[2], -1)
536
+
537
+ @staticmethod
538
+ def _flex(q, k, v, bm):
539
+ """FlexAttention with a block mask. The 512-wide global heads take 32 x 32 tiles: Inductor's default tiles
540
+ need more shared memory than an H100 has (Triton "out of resource", 2026-10-20); in fp32 one stage as well.
541
+ With 99 KB per block (RTX PRO 6000 Blackwell; H100: 227 KB) one stage in bf16 too, and 16 x 16 tiles in fp32
542
+ in both layer types (sm_120 probe, 2026-10-20: d512 bf16 32 x 32 x 1 stage 0.44 ms against math's 3.13;
543
+ fp32 32 x 32 x 1 stage needed 131 KB)."""
544
+ opts = {"FORCE_USE_FLEX_ATTENTION": True}
545
+ small = q.device.type == "cuda" and _smem(q.device.index) < 160 * 1024
546
+ fp32 = q.dtype == torch.float32
547
+ if fp32 and small:
548
+ opts.update(BLOCK_M=16, BLOCK_N=16, num_stages=1)
549
+ elif q.shape[-1] > 256:
550
+ opts.update(BLOCK_M=32, BLOCK_N=32, **({"num_stages": 1} if fp32 or small else {}))
551
+ o = _flex_attention()(q, k, v, block_mask=bm, scale=1.0, enable_gqa=True, kernel_options=opts)
552
+ return o.transpose(1, 2).reshape(q.shape[0], q.shape[2], -1)
553
+
554
+ @staticmethod
555
+ def _fa3(q, k, v, W):
556
+ """FlashAttention 3, causal with a window of W tokens (None: none), plain rows from position 0: q [b, H, L, d],
557
+ k / v [b, Hkv, L, d] -> [b, L, H * d]."""
558
+ import flash_attn_interface as fa3
559
+ o = fa3.flash_attn_func(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), softmax_scale=1.0,
560
+ causal=True, window_size=(W - 1 if W else -1, 0))
561
+ o = o[0] if isinstance(o, (tuple, list)) else o
562
+ return o.reshape(q.shape[0], q.shape[2], -1)
563
+
564
+ @staticmethod
565
+ def _fa3_varlen(q, k, v, W, cu):
566
+ """FlashAttention 3's varlen kernel over compact rows (prompts back to back in one row [1, T], cu: cumulative
567
+ token counts, int32), causal with a window of W tokens within each prompt -> [1, T, H * d]."""
568
+ import flash_attn_interface as fa3
569
+ T = q.shape[2]
570
+ o = fa3.flash_attn_varlen_func(q[0].transpose(0, 1), k[0].transpose(0, 1), v[0].transpose(0, 1), cu, cu, T, T,
571
+ softmax_scale=1.0, causal=True, window_size=(W - 1 if W else -1, 0))
572
+ o = o[0] if isinstance(o, (tuple, list)) else o
573
+ return o.reshape(1, T, -1)
574
+
575
+ @staticmethod
576
+ def _attend(q, k, v, m):
577
+ """Attention with the kernel the mask is for: a boolean mask (math), a block mask (flex), ("fa3", window),
578
+ ("fa3v", window, cu) (compact rows) or ("t512",) (plain causal rows of 512-wide heads, basal/attn512.py)."""
579
+ if isinstance(m, tuple):
580
+ if m[0] == "t512":
581
+ return attn512.attention(q, k, v, 1.0).transpose(1, 2).reshape(q.shape[0], q.shape[2], -1)
582
+ if m[0] == "fa3v":
583
+ return Gemma4Graph._fa3_varlen(q, k, v, m[1], m[2])
584
+ return Gemma4Graph._fa3(q, k, v, m[1])
585
+ if isinstance(m, torch.Tensor):
586
+ return Gemma4Graph._math(q, k, v, m)
587
+ return Gemma4Graph._flex(q, k, v, m)
588
+
589
+ # -- masks --------------------------------------------------------------------------------------------------------
590
+ def _window(self, t):
591
+ return self.window if t == "sliding_attention" else None
592
+
593
+ MARGIN = 256 # sliding layers of a long state keep window + MARGIN tokens: a state that continues it a few tokens
594
+ # before its end (a tokenizer merge where new text joins the old) still has a window of keys (incremental states)
595
+
596
+ def kv_lens(self, L):
597
+ """Root tokens per own layer that pass 2 (or a continuation of the state) can read, for a root of L tokens: a
598
+ sliding layer's last window + MARGIN only, as later rows see window - 1 tokens back at most."""
599
+ return [min(L, self.window + self.MARGIN) if t == "sliding_attention" else L for t in self.types[: self.n_kv]]
600
+
601
+ def _plain_masks(self, L, qpos, dev, twl=None):
602
+ """Boolean masks [b, 1, Lq, L] per layer type of plain causal rows (keys at positions 0..L-1) for queries at
603
+ qpos [b, Lq] (all positions, or the readout rows). twl [b]: two-way rows (a model trained with two-way
604
+ reading): in the global layers every query of row b also sees the keys up to twl[b], its last real token
605
+ (-1: a row read one way); the sliding-window layers stay causal."""
606
+ k = torch.arange(L, device=dev)[None, None, :]
607
+ causal = k <= qpos[:, :, None]
608
+ out = {}
609
+ for t in set(self.types):
610
+ W = self._window(t)
611
+ if W:
612
+ out[t] = (causal & (k > qpos[:, :, None] - W))[:, None]
613
+ else:
614
+ out[t] = (causal if twl is None else causal | (k <= twl[:, None, None]))[:, None]
615
+ return out
616
+
617
+ def _suffix_masks(self, mask, pos, lens):
618
+ """Pass 2: the trie mask (additive, 0 = visible) [b, 1, S, P + S] -> boolean masks per layer type over its
619
+ keys: the root's last lens[t] (all P, or a sliding layer's window of a long root: kv_lens) and the branches;
620
+ sliding layers also need the key within the window of the query's position (root keys at P - lens[t]..P - 1,
621
+ branch keys at pos)."""
622
+ P = mask.shape[-1] - pos.shape[1]
623
+ out = {}
624
+ for t in set(self.types):
625
+ o, W = P - lens[t], self._window(t)
626
+ allow = mask[..., o:] >= 0
627
+ if W:
628
+ kpos = torch.cat([torch.arange(o, P, device=pos.device)[None].expand(pos.shape[0], P - o), pos], 1)
629
+ allow = allow & (kpos[:, None, :] > pos[:, :, None] - W)[:, None]
630
+ out[t] = allow
631
+ return out
632
+
633
+ def _plain_block(self, L, t, dev):
634
+ """FlexAttention block mask of a plain causal row of length L for layer type t (no batch dimension: the same
635
+ for every row), built from block arithmetic (create_block_mask evaluates all L x L pairs: 2.5 GB at 50k
636
+ tokens): key block j is visible from query block i when 0 <= i - j <= dmax (the window), and full (no mask
637
+ evaluated) when 1 <= i - j <= fmax. Built inside the forward, so a compiled forward reads L as a symbolic
638
+ size (a cached mask made outside fixed L in its guards: a recompile for every graph length)."""
639
+ from torch.nn.attention.flex_attention import BlockMask
640
+ W, Bk = self._window(t), self.BLOCK
641
+ n = -(-L // Bk)
642
+ cols = torch.arange(n, device=dev)[None]
643
+ d = torch.arange(n, device=dev)[:, None] - cols # [n, n]: query block - key block
644
+ vis = (d >= 0) & (d <= (W + Bk - 2) // Bk) if W else d >= 0
645
+ full = (d >= 1) & (d <= (W - Bk) // Bk) if W else d >= 1
646
+ part = vis & ~full
647
+
648
+ def mod(b, h, q, kv):
649
+ return (q >= kv) & (q - kv < W) if W else q >= kv
650
+ return BlockMask.from_kv_blocks(*_pack(part), *_pack(full), BLOCK_SIZE=Bk, mask_mod=mod, seq_lengths=(L, L))
651
+
652
+ def _compact_window_block(self, T, cu, W, mod):
653
+ """FlexAttention block mask of compact rows when every layer runs flex (Blackwell workstation GPUs: no varlen
654
+ FlashAttention): query block i visits only the key blocks from its first query's prompt start (and window, W
655
+ not None) on, up to i; a key block is full (no mask evaluated) when it and the query block lie in one prompt
656
+ and every pair is within the window. mod: the mask inside the partial blocks."""
657
+ from torch.nn.attention.flex_attention import BlockMask
658
+ Bk, dev = self.BLOCK, cu.device
659
+ n = -(-T // Bk)
660
+ first = torch.arange(n, device=dev) * Bk # each block's first token
661
+ doc = torch.bucketize(torch.stack([first, first + Bk - 1]).clamp(max=T - 1), cu[1:], right=True) # [2, n]:
662
+ # the prompt of a block's first / last token (no host tensor: this runs inside graph captures)
663
+ lo = cu[doc[0]] // Bk # first key block a query block needs
664
+ if W:
665
+ lo = torch.maximum(lo, (first - W + 1).clamp(min=0) // Bk)
666
+ cols = torch.arange(n, device=dev)[None]
667
+ d = torch.arange(n, device=dev)[:, None] - cols # [n, n]: query block - key block
668
+ vis = (cols >= lo[:, None]) & (d >= 0)
669
+ full = (d >= 1) & (doc[0][None] == doc[1][:, None])
670
+ if W:
671
+ full = full & (d <= (W - Bk) // Bk)
672
+ return BlockMask.from_kv_blocks(*_pack(vis & ~full), *_pack(full), BLOCK_SIZE=Bk, mask_mod=mod,
673
+ seq_lengths=(T, T))
674
+
675
+ def _dense_block(self, B, Lq, Lk, mod, dev):
676
+ """A block mask that visits every (query block, key block) pair, each evaluated with mod: its block lists do
677
+ not depend on the values the mask reads, so a CUDA graph keeps it and only those tensors change."""
678
+ from torch.nn.attention.flex_attention import BlockMask
679
+ nq, nk = -(-Lq // self.BLOCK), -(-Lk // self.BLOCK)
680
+ num = torch.full((B, 1, nq), nk, dtype=torch.int32, device=dev)
681
+ idx = torch.arange(nk, dtype=torch.int32, device=dev).expand(B, 1, nq, nk).contiguous()
682
+ return BlockMask.from_kv_blocks(num, idx, BLOCK_SIZE=self.BLOCK, mask_mod=mod, seq_lengths=(Lq, Lk))
683
+
684
+ def _pads(self, pos, mask, ro):
685
+ """The index tensors the flex masks read, each padded by a block: flex evaluates a mask on whole blocks, so
686
+ query (and branch key) indices run up to a block past the rows; padded copies keep every read in bounds. Made
687
+ outside the compiled forward and passed in (a clamp of the index in the mask broke Inductor's flex template,
688
+ "XBLOCK is not defined", and tensors made inside it cannot be read by a mask: "'function' object has no
689
+ attribute 'graph'", 2026-10-20)."""
690
+ from .lean import TreeMask
691
+ if not self.flex:
692
+ return {}
693
+ Bk, out = self.BLOCK, {}
694
+ if ro is not None:
695
+ out["ro"] = F.pad(ro, (0, Bk))
696
+ if isinstance(mask, TreeMask): # padding tokens are block S, which sees nothing but itself
697
+ out["s"] = F.pad(mask.s, (0, Bk), value=pos.shape[1])
698
+ out["pos"] = F.pad(pos, (0, Bk))
699
+ return out
700
+
701
+ def _twoway_block(self, L, twl):
702
+ """FlexAttention block mask of plain rows of length L in a global layer where every query of row b also sees
703
+ the keys up to twl[b] (a two-way row: its last real token; a prefix-bidirectional model's row: the last token
704
+ of its state prefix; -1: causal): key block j is visible from query block i when j <= i or it starts at or
705
+ before twl[b], and full (no mask evaluated) when j < i or it ends at or before twl[b]. Built from twl inside
706
+ the forward, so a captured graph computes the lists of each replay's rows."""
707
+ from torch.nn.attention.flex_attention import BlockMask
708
+ Bk = self.BLOCK
709
+ n = -(-L // Bk)
710
+ blk = torch.arange(n, device=twl.device)
711
+ d = blk[:, None] - blk[None] # [n, n]: query block - key block
712
+ tw = twl[:, None, None]
713
+ vis = (d >= 0)[None] | (blk * Bk <= tw) # [rows, n, n]
714
+ full = (d >= 1)[None] | ((blk + 1) * Bk - 1 <= tw)
715
+
716
+ def mod(b, h, q, kv):
717
+ return (q >= kv) | (kv <= twl[b])
718
+ return BlockMask.from_kv_blocks(*_pack_rows(vis & ~full), *_pack_rows(full), BLOCK_SIZE=Bk, mask_mod=mod,
719
+ seq_lengths=(L, L))
720
+
721
+ def _rows_block(self, rop, R, L, t, twl=None):
722
+ """Block mask of the readout rows (rop: their positions, padded) of plain causal rows of length L; twl: the
723
+ two-way part of each row in a global layer (_twoway_block)."""
724
+ W = self._window(t)
725
+
726
+ def mod(b, h, q, kv):
727
+ p = rop[b, q]
728
+ return (p >= kv) & (p - kv < W) if W else p >= kv
729
+
730
+ def mod_tw(b, h, q, kv):
731
+ return (rop[b, q] >= kv) | (kv <= twl[b])
732
+ return self._dense_block(rop.shape[0], R, L, mod if twl is None or W else mod_tw, rop.device)
733
+
734
+ def _tree_block(self, tm, pads, S, P, t, R=None, off=0):
735
+ """Block mask of pass 2 (the TreeMask of basal/lean.py: root tokens per row, block of every branch token,
736
+ ancestors per block; lean.tree_mask_mod's mask) with the window on positions in sliding layers; P keys before
737
+ the rows, the root's from position off on (a sliding layer's window of a long root: kv_lens); R: the readout
738
+ rows only (pads["ro"])."""
739
+ W = self._window(t)
740
+ sp, posp, rop = pads["s"], pads["pos"], pads.get("ro") if R is not None else None
741
+
742
+ def mod(b, h, q, kv):
743
+ qq = rop[b, q] if rop is not None else q
744
+ j = kv - P # the branch token a key is (negative: a root key)
745
+ jj = j * (j >= 0)
746
+ tree = (j >= 0) & ((tm.anc[b, sp[b, qq], sp[b, jj]] & (jj <= qq)) | (jj == qq))
747
+ rk = kv + off if off else kv # a root key's position
748
+ ok = (rk < tm.pr[b]) | tree
749
+ if W:
750
+ ok = ok & (posp[b, qq] - torch.where(j >= 0, posp[b, jj], rk) < W)
751
+ return ok
752
+ return self._dense_block(sp.shape[0], S if R is None else R, P + S, mod, sp.device)
753
+
754
+ # -- the forward --------------------------------------------------------------------------------------------------
755
+ def _compact_masks(self, kernels, T, cu, ro, pads):
756
+ """Masks of compact rows: each prompt attends to itself only. With the fa3 kernels: FlashAttention 3's varlen
757
+ kernel with the window in the sliding layers and in the global layers a flex block mask that visits, for each
758
+ query block, the key blocks from the start of its first query's prompt on (the prompts are contiguous); with
759
+ flex in every layer, _compact_window_block. The readout rows: a dense block mask over the row (one query per
760
+ prompt)."""
761
+ from torch.nn.attention.flex_attention import BlockMask
762
+ Bk, dev = self.BLOCK, cu.device
763
+ tok = torch.arange(T, device=dev)
764
+ doc = torch.bucketize(tok, cu[1:], right=True) # the prompt of every token
765
+ start = cu[doc] # its prompt's first token
766
+ n = -(-T // Bk)
767
+ qb = torch.arange(n, device=dev)
768
+ lo = start[qb * Bk] // Bk # first key block of each query block
769
+ idx = torch.minimum(lo[:, None] + qb[None], qb[:, None]).to(torch.int32)
770
+ num = (qb - lo + 1).to(torch.int32)
771
+ docp, rop = pads["doc"], pads["ro"]
772
+
773
+ m_all, m_ro = {}, {}
774
+ for t in set(self.types):
775
+ W = self._window(t)
776
+
777
+ def same(b, h, q, kv, W=W): # the same prompt, causal (and the window: positions advance with indices)
778
+ ok = (docp[q] == docp[kv]) & (q >= kv)
779
+ return ok & (q - kv < W) if W else ok
780
+ if kernels[t] == "fa3":
781
+ m_all[t] = ("fa3v", W, cu)
782
+ elif "fa3" not in kernels.values(): # (fa3: the global layers' mask below, as gated on Hopper)
783
+ m_all[t] = self._compact_window_block(T, cu, W, same)
784
+ else:
785
+ m_all[t] = BlockMask.from_kv_blocks(num[None, None], idx[None, None].contiguous(), BLOCK_SIZE=Bk,
786
+ mask_mod=same, seq_lengths=(T, T))
787
+
788
+ def rows(b, h, q, kv, W=W):
789
+ p = rop[0, q]
790
+ ok = (docp[p] == docp[kv]) & (p >= kv)
791
+ return ok & (p - kv < W) if W else ok
792
+ m_ro[t] = self._dense_block(1, ro.shape[1], T, rows, dev)
793
+ return m_all, m_ro
794
+
795
+ def _masks(self, kernels, L, pos, prefix, mask, ro, pads, twl=None):
796
+ """The attention masks of one forward per layer type, for every query and for the readout rows ro: boolean
797
+ masks for "math", block masks for "flex" (reading pads), ("fa3", window) for FlashAttention 3 over plain
798
+ rows. twl: the two-way part of plain rows (_plain_masks; in global layers with the flex kernel _twoway_block)."""
799
+ from .lean import TreeMask
800
+ dev, types = pos.device, set(self.types)
801
+ math = [t for t in types if kernels[t] == "math"]
802
+ flex = [t for t in types if kernels[t] != "math"] # fa3: FlashAttention 3 for every query of plain rows
803
+ m_all, m_ro = {}, {}
804
+ if prefix is None:
805
+ if twl is not None and any(kernels[t] == "fa3" or self.global_attn == "triton"
806
+ for t in types if self._window(t) is None):
807
+ raise ValueError("two-way rows need the math or flex kernel in the global layers")
808
+ if math:
809
+ m_all = self._plain_masks(L, pos, dev, twl)
810
+ m_ro = self._plain_masks(L, ro, dev, twl) if ro is not None else {}
811
+ for t in flex:
812
+ tw = twl if self._window(t) is None else None # the sliding-window layers stay causal
813
+ if kernels[t] == "fa3":
814
+ m_all[t] = ("fa3", self._window(t))
815
+ elif self.global_attn == "triton" and self._window(t) is None:
816
+ m_all[t] = ("t512",)
817
+ elif tw is not None:
818
+ m_all[t] = self._twoway_block(L, tw)
819
+ else:
820
+ m_all[t] = self._plain_block(L, t, dev)
821
+ if ro is not None:
822
+ m_ro[t] = self._rows_block(pads["ro"], ro.shape[1], L, t, tw)
823
+ return m_all, m_ro
824
+ lens = {self.types[i]: prefix[i][0].shape[2] for i in range(self.n_kv)} # root keys per layer type
825
+ P = max(lens.values()) # the root (its global layers keep every key)
826
+ if isinstance(mask, TreeMask):
827
+ if math:
828
+ raise ValueError("the trie as a TreeMask needs the flex kernel in every layer type")
829
+ elif math:
830
+ m_all = self._suffix_masks(mask, pos, lens)
831
+ if ro is not None:
832
+ b, R = ro.shape
833
+ m_ro = {t: m.gather(2, ro[:, None, :, None].expand(b, 1, R, m.shape[-1])) for t, m in m_all.items()}
834
+ if flex and not isinstance(mask, TreeMask):
835
+ raise ValueError("the flex kernel takes the trie of pass 2 as a TreeMask")
836
+ for t in flex:
837
+ m_all[t] = self._tree_block(mask, pads, L, lens[t], t, off=P - lens[t])
838
+ if ro is not None:
839
+ m_ro[t] = self._tree_block(mask, pads, L, lens[t], t, ro.shape[1], P - lens[t])
840
+ return m_all, m_ro
841
+
842
+ def _run(self, kernels, ids, pos, kv=None, prefix=None, mask=None, ro=None, between=None, pads=None,
843
+ compiled=False, cu=None, twl=None):
844
+ """kernels: per layer type; ids / pos [b, L]; kv: per own layer (K, V) buffers [b, kv heads, L, d] that receive
845
+ this pass's keys and values (pass 1; a shorter buffer receives the last ones: kv_lens); prefix: per own layer
846
+ (K, V) [b, kv heads, P, d] (sliding layers: the last kv_lens of the root may be all there is) the rows continue
847
+ (pass 2) with mask (the trie: additive, or a TreeMask for flex); ro [b, R]: readout positions -> final hidden states
848
+ [b, R, D] (None: every position, [b, L, D]); between(i) is called before layer i (the long lane); pads: the
849
+ padded index tensors of the flex masks (_pads); compiled: the compiled layer functions; twl: two-way rows (_plain_masks). The masks of every
850
+ query and of the readout rows are built here (_masks; the kernel follows the mask). A layer is two functions
851
+ (_pre, _post), so the rows-only layers can split after the keys and values; a shared layer's keys and values
852
+ are those its source layer kept."""
853
+ if cu is not None: # compact rows (forward_compact)
854
+ m_all, m_ro = self._compact_masks(kernels, ids.shape[1], cu, ro, pads)
855
+ else:
856
+ m_all, m_ro = self._masks(kernels, ids.shape[1], pos, prefix, mask, ro, pads or {}, twl)
857
+ pre, post, embed = (self.pre, self.post, self.embed) if compiled else (_pre, _post, self._embed)
858
+ h, pli = embed(ids)
859
+ types = set(self.types)
860
+ cs = {t: self._rope(pos, t, h.dtype) for t in types}
861
+ masks, kept = m_all, {}
862
+ for i, (P, C) in enumerate(self.args):
863
+ if between is not None:
864
+ between(i)
865
+ t = self.types[i]
866
+ buf = kv[i] if kv is not None and self.own[i] else (None, None)
867
+ tail = buf[0] is not None and buf[0].shape[2] < ids.shape[1] # a sliding layer's window (kv_lens)
868
+ pre_kv = prefix[i] if prefix is not None and self.own[i] else (None, None)
869
+ q, k, v = pre(h, P, C, *cs[t], *((None, None) if tail else buf), *pre_kv)
870
+ if tail:
871
+ n = buf[0].shape[2]
872
+ buf[0].copy_(k[:, :, -n:])
873
+ buf[1].copy_(v[:, :, -n:])
874
+ if self.own[i]:
875
+ if i in self.store:
876
+ kept[t] = (k, v)
877
+ else:
878
+ k, v = kept[t]
879
+ if ro is not None and i == self.last_kv: # from here on, the readout rows only
880
+ g = ro[:, :, None]
881
+ h, q = h.gather(1, g.expand(-1, -1, h.shape[-1])), q.gather(1, g.expand(-1, -1, q.shape[-1]))
882
+ if pli is not None:
883
+ pli = pli.gather(1, ro[:, :, None, None].expand(-1, -1, *pli.shape[2:]))
884
+ cs = {u: tuple(c.gather(1, g.expand(-1, -1, c.shape[-1])) for c in cs[u]) for u in types}
885
+ masks = m_ro
886
+ h = post(h, q, k, v, P, C, *cs[t], masks[t], pli[:, :, i] if pli is not None else None)
887
+ return _rms(h, self.lm.norm.weight, self.cfg.rms_norm_eps)
888
+
889
+ def _kernels(self, dense=False):
890
+ """The kernels of a call: the configured ones, or the math kernel for pass 2 with a dense mask (flex takes the
891
+ trie as a TreeMask)."""
892
+ if not (dense and self.flex):
893
+ return self.kernels
894
+ return {t: "math" for t in self.kernels}
895
+
896
+ @torch.no_grad()
897
+ def forward(self, ids, kv=None, ro=None, between=None, compiled=True, twl=None):
898
+ """Plain causal rows [b, L] from position 0 (right padding cannot reach a real token); kv: per own layer
899
+ (K, V) buffers [b, kv heads, L, d] that receive the keys and values (pass 1); ro [b, R]: readout positions ->
900
+ [b, R, D] (None: [b, L, D]); between(i) before layer i (the long lane: uncompiled, one layer at a time).
901
+ compiled: through the compiled forward (when the engine compiles; shapes without a graph run uncompiled).
902
+ twl [b]: per row the last token its global layers read both ways (a two-way row: its last real token; a
903
+ prefix-bidirectional model: the last token of the state prefix), else -1; the global layers' kernel is then
904
+ math or flex (_twoway_block)."""
905
+ L = ids.shape[1]
906
+ pos = torch.arange(L, device=ids.device)[None].expand(ids.shape[0], L)
907
+ compiled = compiled and between is None
908
+ return self._run(self.kernels, ids, pos, kv=kv, ro=ro, between=between, pads=self._pads(pos, None, ro),
909
+ compiled=compiled and self.compiled, twl=twl)
910
+
911
+ @torch.no_grad()
912
+ def forward_compact(self, ids, pos, cu, ro, compiled=True):
913
+ """Compact rows (--batches compact, with the fa3 or flex kernels): single prompts packed back to back in one row
914
+ [1, T] (positions from 0 per prompt, cu: cumulative token counts [prompts + 2], int32; the padding after the
915
+ last prompt is one more prompt nobody reads) -> final hidden states at ro [R] (one readout per prompt): [R, D].
916
+ No padding of rows to graph lengths or of row counts."""
917
+ T = ids.shape[1]
918
+ doc = torch.bucketize(torch.arange(T, device=ids.device), cu[1:], right=True)
919
+ pads = dict(ro=F.pad(ro[None], (0, self.BLOCK)), doc=F.pad(doc, (0, self.BLOCK), value=-1))
920
+ out = self._run(self.kernels, ids, pos, ro=ro[None], pads=pads, compiled=compiled and self.compiled, cu=cu)
921
+ return out[0]
922
+
923
+ @torch.no_grad()
924
+ def forward_suffix(self, ids, mask, pos, prefix, ro=None, compiled=True, kv=None):
925
+ """Pass 2: rows [b, S] at positions pos over per own layer prefix (K, V) [b, kv heads, P, d] (or a sliding
926
+ layer's last kv_lens(P) of them), with the trie mask (additive [b, 1, S, P + S], 0 = visible; a TreeMask for
927
+ flex) -> [b, R, D] at ro [b, R] (None: all)."""
928
+ from .lean import TreeMask
929
+ kernels = self._kernels(dense=not isinstance(mask, TreeMask))
930
+ return self._run(kernels, ids, pos, kv=kv, prefix=prefix, mask=mask, ro=ro, pads=self._pads(pos, mask, ro),
931
+ compiled=compiled and self.compiled)