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/gdn_graph.py ADDED
@@ -0,0 +1,1792 @@
1
+ """Qwen3.5 (Gated DeltaNet) models in the CUDA graph engine (GraphBackend: --mode fast, fast-nocompile; basal 2.4).
2
+
3
+ A Qwen3.5 decoder (basal-omni-pico: Qwen3.5-0.8B, 18 Gated DeltaNet layers and 6 gated full-attention layers) carries a
4
+ state from token to token in its linear-attention layers: a matrix per head (16 x 128 x 128 in fp32, 1 MB per layer and
5
+ sequence) and the last three inputs of a short causal convolution. GraphBackend shares a request's state (the root of
6
+ its prefix trie) as attention keys and values only, so 2.3.2 refused these models there: 2.3.1 restarted the recurrent
7
+ layers from zero state in pass 2 and answered wrongly. GDNGraphBackend keeps GraphBackend's units, batching, graphs and
8
+ readout, and changes three things:
9
+
10
+ - **Pass 1** (plain rows from position 0: single prompts, and the roots of branched units) also writes each row's
11
+ recurrent state and convolution tail at its last real token. Rows are padded on the right, and the padding tokens get
12
+ beta = 0 and g = 0 (no update, no decay), so the state at the end of the padded row is the state of the real tokens.
13
+ - **Pass 2** runs one row per leaf of the trie below the root (a question, or one option order of it): the path of
14
+ blocks from the root to that leaf, from the root's recurrent state and convolution tail (fla's chunk_gated_delta_rule
15
+ with initial_state) and over the root's keys and values (the attention layers). A block shared by several leaves (a
16
+ question's text under its two option orders) runs once per leaf: one packed row with a trie mask cannot continue one
17
+ recurrent state into two branches.
18
+ - **Graphs.** Plain graphs (rows, length) as before; pass-2 graphs (leaf rows, leaf length, root bucket). Pass 1 writes
19
+ the roots' keys and values in the layout of the root bucket (ROOT_LENS), and each pass-2 row gathers its root's keys,
20
+ values and recurrent state inside the graph, so the pass-2 graphs do not depend on the exact root length.
21
+
22
+ The layers are transformers' own modules (projections, norms, MLP, rotary embedding); the Gated DeltaNet kernel is fla's
23
+ (flash-linear-attention), as in the eager reference. Not here (refused before loading, with what to use instead):
24
+ nvfp4, int8.
25
+ - **FP8** (--mode fp8, 3.0): the projections of the layers quantised at load time, row-scaled (--fp8-scaling row, the
26
+ default: one scale per weight row and per token, cuBLAS's FP8 GEMM) or in basal-omni's block FP8 (--fp8-scaling
27
+ block; basal/fp8block.py), as in Qwen's own FP8 checkpoints (in_proj's b and a stay bf16; Qwen35Graph._fp8); the
28
+ first and the last --fp8-bf16-layers layers, the embeddings, the norms, the convolution, the recurrent state and the
29
+ readout as loaded. Served at the shapes of GDN_FP8_SHAPES (its accuracy gate), other shapes only with
30
+ --fp8-experimental on (their measured trade-off reported at start-up), with the model's own CALIBRATION.fp8.json.
31
+ - **State cache** (--state-cache-gb, 2.5): a request cut at its state boundary keeps its root as a full-state checkpoint:
32
+ the attention layers' keys and values of the state and, per Gated DeltaNet layer, the recurrent state and convolution
33
+ tail after its last token. A later request with the same state copies them where pass 1 would have written them and
34
+ runs pass 2 only. A state that begins with a whole cached one (a growing agent trace) continues it
35
+ (forward_continue) and replaces it; one that differs inside the cached tokens runs again (a recurrent state cannot
36
+ be cut there).
37
+ """
38
+ import copy
39
+ import functools
40
+ import inspect
41
+ import json
42
+ import os
43
+ import re
44
+ import sys
45
+ from pathlib import Path
46
+
47
+ import numpy as np
48
+ import torch
49
+ import torch.nn.functional as F
50
+ from transformers import AutoModelForCausalLM, AutoTokenizer
51
+
52
+ from . import adapter as adapter_module
53
+ from . import fp8block
54
+ from .blockquant import fuse
55
+ from .fp8block import E4M3, FP8_MAX
56
+ from .engine import (FP8_FAST_ACCUM, GraphBackend, MPSBackend, PREFILL, StateCache, _copy_same, _varlen_attention,
57
+ compact_refused, compile_set, compile_untimed, compiled_calls_beside_compiles, fp8_refused,
58
+ graph_memory_bytes, modelopt_refused, persist_compile_cache, set_attention,
59
+ torch_varlen_available)
60
+
61
+ # the decoders this forward implements: Qwen3.5 text models (dense MLP) of these layer kinds
62
+ GDN_MODEL_TYPES = ("qwen3_5_text", "qwen3_5")
63
+ GDN_LAYERS = {"linear_attention", "full_attention"}
64
+ # the CUDA capabilities on which a Qwen3.5 model without --mode gets fast (with fla): where its gate passed
65
+ ACCELERATED_ARCHITECTURES = {(9, 0), (12, 0)}
66
+
67
+
68
+ def _decoder_config(model_dir, strict=False):
69
+ """config.json of a model directory, the decoder part (text_config of a multimodal wrapper); None if unreadable
70
+ (strict: one that exists but cannot be read or parsed raises instead)."""
71
+ try:
72
+ cfg = json.loads((Path(model_dir) / "config.json").read_text(encoding="utf-8"))
73
+ except (OSError, ValueError, TypeError) as e:
74
+ if strict and not isinstance(e, FileNotFoundError):
75
+ raise
76
+ return None
77
+ return cfg.get("text_config") or cfg
78
+
79
+
80
+ def is_gdn(model_dir, strict=False):
81
+ """A Qwen3.5 decoder of Gated DeltaNet and full-attention layers (what GDNGraphBackend serves), from config.json.
82
+ Other recurrent models (Qwen3-Next, Mamba and hybrids) stay refused by the graph engine."""
83
+ c = _decoder_config(model_dir, strict)
84
+ if not c or c.get("model_type") not in GDN_MODEL_TYPES:
85
+ return False
86
+ kinds = set(c.get("layer_types") or ())
87
+ return "linear_attention" in kinds and kinds <= GDN_LAYERS
88
+
89
+
90
+ def fla_rule():
91
+ """fla's chunk_gated_delta_rule (flash-linear-attention), None when it is not installed."""
92
+ try:
93
+ from fla.ops.gated_delta_rule import chunk_gated_delta_rule
94
+ except Exception:
95
+ return None
96
+ return chunk_gated_delta_rule
97
+
98
+
99
+ # the functions transformers' Gated DeltaNet layers (Qwen3.5, also Qwen3.5-MoE and Qwen3-Next) call by their
100
+ # module-level names. Importing the model's module binds each to the kernel of flash-linear-attention (the rules) or
101
+ # causal-conv1d (the convolution) when that package imports, else to transformers' torch version, whatever device the
102
+ # tensors are on later
103
+ TORCH_KERNEL_NAMES = ("torch_chunk_gated_delta_rule", "torch_recurrent_gated_delta_rule", "causal_conv1d_fn",
104
+ "causal_conv1d_update")
105
+
106
+
107
+ def torch_kernels_off_cuda(model):
108
+ """The transformers forward of `model` off CUDA (--mode eager on the CPU or Apple Silicon): its Gated DeltaNet
109
+ functions (TORCH_KERNEL_NAMES) run transformers' torch versions on tensors that are not on CUDA, whatever is
110
+ installed. Bound to fla's Triton kernels where fla is installed, they were called with CPU tensors too, and on a
111
+ host without a GPU Triton found no driver: every request failed. Each such function of the model's modules becomes
112
+ one that calls what transformers bound for CUDA tensors, and for any other the torch version with the arguments
113
+ transformers passes it when the package is missing: the answers off CUDA are those of a host without fla, to the
114
+ bit, and CUDA runs as before. -> the number of functions replaced (0: none in the model, or replaced already)."""
115
+ n = 0
116
+ for mod in {sys.modules.get(type(m).__module__) for m in model.modules()}:
117
+ for name in TORCH_KERNEL_NAMES:
118
+ f = getattr(mod, name, None)
119
+ plain = inspect.unwrap(f) if callable(f) else None
120
+ # transformers' wrapper of its own torch version (defined in that module), not yet replaced
121
+ if plain is None or plain is f or plain.__module__ != mod.__name__ or getattr(f, "basal_off_cuda", False):
122
+ continue
123
+ setattr(mod, name, _off_cuda(f, plain))
124
+ n += 1
125
+ return n
126
+
127
+
128
+ def _off_cuda(bound, plain):
129
+ """bound (a function of TORCH_KERNEL_NAMES as transformers bound it) for CUDA tensors, plain (its torch version)
130
+ for any other, given the keyword arguments it takes (as transformers' wrapper passes them)."""
131
+ params = set(inspect.signature(plain).parameters)
132
+
133
+ @functools.wraps(bound)
134
+ def run(*args, **kw):
135
+ x = args[0] if args else next(iter(kw.values()))
136
+ if x.is_cuda:
137
+ return bound(*args, **kw)
138
+ return plain(*args, **{k: v for k, v in kw.items() if k in params})
139
+ run.basal_off_cuda = True
140
+ return run
141
+
142
+
143
+ def refused(quant=None, state_cache_gb=0, prefix=False, batches="default", lean=False, tree="dense",
144
+ readout_layer="off", template="off", device=True, fp8_scaling="auto"):
145
+ """Why GDNGraphBackend cannot serve a Qwen3.5 model with these settings (None: it can), before anything is loaded.
146
+ Of the quantisations only FP8 (--mode fp8, block or row scaling) runs, at the shapes of GDN_FP8_SHAPES
147
+ (fp8_shape_refused, which reads the model); the state cache, the prefix cache, compact rows, template prefixes and
148
+ the long lane run since 2.5 (their arguments stay for the callers). device: also check for a CUDA GPU and fla (the
149
+ server checks the settings before the download, the engine both).
150
+ --lean / --tree flex change nothing here, as for basal-omni's Gemma 4 forward: Qwen35Graph is lean already (one
151
+ compiled function per layer kind, called with each layer's weights), and its pass 2 has no trie mask (one row per
152
+ leaf)."""
153
+ if quant and quant != "fp8":
154
+ return (f"--mode {quant} is not available for Qwen3.5 (Gated DeltaNet) models: the CUDA graph engine serves "
155
+ "them in bf16 (--mode fast) or FP8 (--mode fp8); --mode vllm runs their FP8 checkpoints")
156
+ if quant == "fp8" and fp8_scaling not in ("auto", "block", "row"):
157
+ return f"--fp8-scaling {fp8_scaling}: auto, block or row"
158
+ if device and not torch.cuda.is_available():
159
+ return "the CUDA graph engine needs a CUDA GPU; serve Qwen3.5 models with --mode eager here"
160
+ if device and fla_rule() is None:
161
+ return ("the CUDA graph engine runs Qwen3.5's Gated DeltaNet layers with flash-linear-attention: pip install "
162
+ "flash-linear-attention (or serve with --mode eager)")
163
+ return None
164
+
165
+
166
+ # the Qwen3.5 shapes (hidden size, decoder layers) whose FP8 at load time (--mode fp8) kept the paired accuracy rule
167
+ # against bf16, each with its own calibration (docs/QUANTIZATION.md), per scaling ("block" / "row"): none yet. Another
168
+ # shape serves only with --fp8-experimental on, which reports its measured trade-off (GDN_FP8_MEASURED) at start-up
169
+ GDN_FP8_SHAPES = {"block": {}, "row": {}}
170
+ GDN_FP8_DEFAULT = "row" # --fp8-scaling auto for a Qwen3.5 model: as fast as bf16 or faster; block ran at 0.22-0.24x
171
+ # the trade-off against bf16 measured at a shape that has not passed (docs/QUANTIZATION.md), which --fp8-experimental
172
+ # on reports at start-up: (scaling, hidden size, layers, --fp8-bf16-layers) -> (the model measured; its speed against
173
+ # bf16 on an H100 at 1-8 clients; the change of the answers accepted at the 1 % and 5 % targets, all types, in points;
174
+ # the lowest and the highest change of a dev slice's accuracy, in points; the question type that changed most at a
175
+ # target: (type, target in %, change in points)), None where it was not measured
176
+ GDN_FP8_MEASURED = {
177
+ ("row", 2560, 32, 2): ("Qwen3.5-4B", "1.02-1.07x", (-1.33, -0.14), (-0.27, 0.25), ("yes / no", 1, -2.21)),
178
+ ("row", 2560, 32, 0): ("Qwen3.5-4B", "1.00-1.08x", (-0.41, -0.18), (-0.75, 0.18), ("yes / no", 1, -1.47)),
179
+ ("block", 2560, 32, 2): ("Qwen3.5-4B", "0.22-0.24x", (-0.14, -1.01), (-0.53, 0.10), ("yes / no", 5, -2.65)),
180
+ ("block", 2560, 32, 0): ("Qwen3.5-4B", None, (-0.37, -0.41), (-0.47, 0.12), ("yes / no", 5, -1.76)),
181
+ ("row", 4096, 32, 2): ("Qwen3.5-9B", "1.12-1.16x", None, None, None),
182
+ }
183
+
184
+
185
+ def fp8_scaling_of_gdn(scaling):
186
+ """--fp8-scaling for a Qwen3.5 model: auto -> GDN_FP8_DEFAULT; block / row as given."""
187
+ return GDN_FP8_DEFAULT if scaling in (None, "auto") else scaling
188
+
189
+
190
+ def _gdn_shape(model_dir):
191
+ c = _decoder_config(model_dir) or {}
192
+ return c.get("hidden_size"), c.get("num_hidden_layers")
193
+
194
+
195
+ def fp8_shape_passed(model_dir, scaling="auto"):
196
+ """Whether the Qwen3.5 model's shape passed the FP8 gate in this scaling (GDN_FP8_SHAPES), from config.json."""
197
+ return _gdn_shape(model_dir) in (GDN_FP8_SHAPES.get(fp8_scaling_of_gdn(scaling)) or {})
198
+
199
+
200
+ def fp8_shape_refused(model_dir, scaling="auto", experimental=False):
201
+ """None when the Qwen3.5 model at model_dir may serve in FP8 (--mode fp8) with this scaling: its shape passed the
202
+ gate in it (GDN_FP8_SHAPES), --fp8-experimental on (experimental: served with its trade-off reported,
203
+ fp8_experimental_warning), or BASAL_EXPERIMENTAL_GDN_FP8=1 (development: the gate's own runs); else why not, read
204
+ from config.json before any weight is loaded."""
205
+ if experimental or os.environ.get("BASAL_EXPERIMENTAL_GDN_FP8") == "1" or fp8_shape_passed(model_dir, scaling):
206
+ return None
207
+ scaling = fp8_scaling_of_gdn(scaling)
208
+ shape = _gdn_shape(model_dir)
209
+ passed = ", ".join((GDN_FP8_SHAPES.get(scaling) or {}).values()) or "no Qwen3.5 model yet"
210
+ return (f"--mode fp8 on Qwen3.5 ({scaling} FP8 at load time) passed its accuracy gate on {passed}; this model "
211
+ f"(hidden size {shape[0]}, {shape[1]} layers) is refused. Serve it with --mode fast (bf16), or its FP8 "
212
+ "checkpoint with --mode vllm; --fp8-experimental on serves it anyway, with its measured trade-off "
213
+ "(docs/QUANTIZATION.md)")
214
+
215
+
216
+ def fp8_experimental_warning(model_dir, scaling="auto", fp8_bf16_layers=2):
217
+ """The start-up warning of --fp8-experimental on for a Qwen3.5 model in FP8 whose shape has not passed the gate:
218
+ the trade-off measured at its shape (GDN_FP8_MEASURED) or that none was, and where to read about it; None when the
219
+ shape passed (plain --mode fp8)."""
220
+ if fp8_shape_passed(model_dir, scaling):
221
+ return None
222
+ scaling = fp8_scaling_of_gdn(scaling)
223
+ hidden, layers = _gdn_shape(model_dir)
224
+ keep = 2 if fp8_bf16_layers is None else fp8_bf16_layers
225
+ head = (f"--fp8-experimental on: Qwen3.5 in {scaling} FP8 at load time has not passed its accuracy gate at this "
226
+ f"shape (hidden size {hidden}, {layers} layers, --fp8-bf16-layers {keep}); ")
227
+ m = GDN_FP8_MEASURED.get((scaling, hidden, layers, keep))
228
+ if m is None:
229
+ return head + "its trade-off against bf16 was not measured. See docs/QUANTIZATION.md (Qwen3.5 in FP8)"
230
+ model, speed, share, slices, weakest = m
231
+ parts = [f"speed {speed} bf16's (H100, 1-8 clients)" if speed else "speed not measured"]
232
+ parts.append(f"answers accepted at the 1 % / 5 % targets {share[0]:+.2f} / {share[1]:+.2f} points" if share else
233
+ "accuracy not gated")
234
+ if weakest:
235
+ parts[-1] += f" ({weakest[0]} questions at {weakest[1]} %: {weakest[2]:+.2f})"
236
+ if slices:
237
+ parts.append(f"dev-slice accuracy {slices[0]:+.2f} to {slices[1]:+.2f} points")
238
+ return (head + f"measured on {model} against bf16: {'; '.join(parts)}. Its answers carry this trade-off: see "
239
+ "docs/QUANTIZATION.md (Qwen3.5 in FP8)")
240
+
241
+
242
+ def options_refused(state_cache_bits=16, global_attn="flex", state_cache_dir=None):
243
+ """Why GDNGraphBackend refuses these state-cache and attention options for a Qwen3.5 model, or None; basal-serve
244
+ asks before the model is downloaded, the engine again before it is loaded."""
245
+ if state_cache_bits != 16:
246
+ return "--state-cache-bits 8 is for attention keys and values; recurrent states are cached as computed"
247
+ if global_attn != "flex":
248
+ return f"--global-attn {global_attn}: basal-omni (Gemma 4) only"
249
+ if state_cache_dir:
250
+ return "--state-cache-dir: not for Qwen3.5 models yet (their states carry the recurrent state)"
251
+ return None
252
+
253
+
254
+ def default_fast():
255
+ """Whether a Qwen3.5 model gets --mode fast without --mode: on a capability of ACCELERATED_ARCHITECTURES with fla
256
+ importable. Checked on H100 (sm90) and RTX 5060 Ti (sm120); other capabilities (sm121, GB10, among them) get
257
+ eager."""
258
+ return (torch.cuda.is_available() and torch.cuda.get_device_capability() in ACCELERATED_ARCHITECTURES
259
+ and fla_rule() is not None)
260
+
261
+
262
+ def _rms(x, w, eps):
263
+ """Qwen3_5RMSNorm: in fp32, weight stored as 1 + w."""
264
+ h = x.float()
265
+ h = h * torch.rsqrt(h.pow(2).mean(-1, keepdim=True) + eps)
266
+ return (h * (1.0 + w.float())).type_as(x)
267
+
268
+
269
+ def _mlp(h, nw, gu, down, eps):
270
+ """h + Qwen3_5MLP(post_attention_layernorm(h)), gate and up in one GEMM."""
271
+ g, u = F.linear(_rms(h, nw, eps), gu).chunk(2, -1)
272
+ return h + F.linear(F.silu(g) * u, down)
273
+
274
+
275
+ def _gdn_in(h, nw, w_in, A_log, dt_bias, mask, eps, sizes):
276
+ """input_layernorm, the four input projections of Qwen3_5GatedDeltaNet in one GEMM, beta and g (padding: beta 0,
277
+ g 0) -> (convolution input, z, beta, g)."""
278
+ qkv, z, b, a = F.linear(_rms(h, nw, eps), w_in).split(sizes, -1)
279
+ beta = b.sigmoid()
280
+ g = -A_log.float().exp() * F.softplus(a.float() + dt_bias)
281
+ if mask is not None: # padding: no update (beta 0), no decay (g 0)
282
+ beta = beta * mask[..., None]
283
+ g = g * mask[..., None]
284
+ return qkv, z, beta, g
285
+
286
+
287
+ def _conv(qkv, w, c0, sizes):
288
+ """The causal depthwise convolution and SiLU of Qwen3_5GatedDeltaNet (causal_conv1d_fn) -> q, k, v (views); c0
289
+ [b, kernel - 1, channels]: the inputs before the rows (pass 2: the root's last ones)."""
290
+ T = qkv.shape[1]
291
+ if c0 is None:
292
+ y = F.conv1d(qkv.transpose(1, 2).to(w.dtype), w, padding=w.shape[-1] - 1, groups=w.shape[0])[..., :T]
293
+ else:
294
+ y = F.conv1d(torch.cat([c0, qkv], 1).transpose(1, 2).to(w.dtype), w, groups=w.shape[0])
295
+ return F.silu(y).to(qkv.dtype).transpose(1, 2).split(sizes, -1)
296
+
297
+
298
+ def _conv_fla(qkv, w, c0, sizes, conv):
299
+ """_conv with fla's causal_conv1d kernel (token-major tiles, SiLU applied in fp32 before the rounding): one call
300
+ per q / k / v over its channels, each output contiguous for fla's Gated DeltaNet kernel. cuDNN's generic depthwise
301
+ kernel and the transposes of q / k / v into fla's layout took about a third of a forward's GPU time on an H100
302
+ (kernel profile, 1.5k-token state, 22 Oct). c0 goes in as fla's initial state [b, channels, kernel] (the newest
303
+ input last; the first slot is not read by a kernel of that size)."""
304
+ init = None
305
+ if c0 is not None:
306
+ init = F.pad(c0.transpose(1, 2), (1, 0))
307
+ out, a = [], 0
308
+ for m in sizes:
309
+ y, _ = conv(qkv[..., a: a + m], w[a: a + m, 0], initial_state=None if init is None else
310
+ init[:, a: a + m].contiguous(), activation="silu")
311
+ out.append(y)
312
+ a += m
313
+ return out
314
+
315
+
316
+ def fla_conv1d():
317
+ """fla's causal_conv1d, None when it is not there."""
318
+ try:
319
+ from fla.modules.conv.causal_conv1d import causal_conv1d
320
+ except Exception:
321
+ return None
322
+ return causal_conv1d
323
+
324
+
325
+ def conv_kernel(cuda):
326
+ """The Gated DeltaNet convolution's kernel -> (fla's causal_conv1d or None, its name): on CUDA fla's where this fla
327
+ has it, else torch's conv1d (_conv; cuDNN on CUDA). torch's rounds differently (SiLU on the bf16 output, not in fp32
328
+ before the rounding) from fla's, the one --mode fast was checked with: on CUDA that fallback is said on stderr."""
329
+ conv = fla_conv1d() if cuda else None
330
+ if cuda and conv is None:
331
+ print("basal: warning: this flash-linear-attention has no causal_conv1d (fla.modules.conv.causal_conv1d): the "
332
+ "Gated DeltaNet convolution runs on torch's conv1d (cuDNN), which rounds differently from fla's kernel "
333
+ "--mode fast was checked with (flash-linear-attention 0.5.2)", file=sys.stderr, flush=True)
334
+ return conv, "fla causal_conv1d" if conv is not None else "torch conv1d"
335
+
336
+
337
+ def fla_varlen():
338
+ """fla's pieces for compact rows (prompts packed back to back in one row): the forward of its Gated DeltaNet rule
339
+ and its l2 norm, which take the chunk indices of the packed prompts as an argument; None when this fla has no such
340
+ entry points (compact rows are refused then)."""
341
+ try:
342
+ from fla.modules.l2norm import l2norm_fwd
343
+ from fla.ops.gated_delta_rule.chunk import chunk_gated_delta_rule_fwd
344
+ except Exception:
345
+ return None
346
+ if "chunk_indices" not in inspect.signature(chunk_gated_delta_rule_fwd).parameters:
347
+ return None
348
+ return chunk_gated_delta_rule_fwd, l2norm_fwd
349
+
350
+
351
+ def _rule_varlen(q, k, v, g, beta, s0, cu, ci, fns):
352
+ """fla's chunk_gated_delta_rule (l2-normalised q / k, as use_qk_l2norm_in_kernel) over compact rows [1, T, heads,
353
+ d]: cu [prompts + 1] int32 cumulative token counts, every prompt's start a multiple of 64, ci [T / 64, 2] int32 the
354
+ (prompt, chunk) of every 64-token chunk, s0 [prompts, heads, dk, dv] fp32 the states the prompts continue (None:
355
+ zero). The forward of fla's autograd function with the chunk indices given: fla would compute them from cu with a
356
+ host sync (no CUDA graph), and keep them per tensor identity (a graph's static cu would get stale ones)."""
357
+ fwd, l2norm = fns
358
+ q, _ = l2norm(q.contiguous())
359
+ k, _ = l2norm(k.contiguous())
360
+ o = fwd(q, k, v.contiguous(), g.contiguous(), beta.contiguous(), k.shape[-1] ** -0.5, s0, False, cu_seqlens=cu,
361
+ chunk_indices=ci)[1]
362
+ return o.to(q.dtype)
363
+
364
+
365
+ def _conv_varlen(qkv, w, c0, sizes, conv, cu, ci):
366
+ """_conv_fla over compact rows (cu, ci as in _rule_varlen); c0 [prompts, kernel - 1, channels]: each prompt's
367
+ convolution tail (None: zeros)."""
368
+ init = None if c0 is None else F.pad(c0.transpose(1, 2), (1, 0))
369
+ out, a = [], 0
370
+ for m in sizes:
371
+ y, _ = conv(qkv[..., a: a + m], w[a: a + m, 0], initial_state=None if init is None else
372
+ init[:, a: a + m].contiguous(), activation="silu", cu_seqlens=cu, chunk_indices=ci)
373
+ out.append(y)
374
+ a += m
375
+ return out
376
+
377
+
378
+ def _spans(cu):
379
+ """Compact rows' cumulative counts -> (prompt, start, end) of every non-empty prompt."""
380
+ c = [int(x) for x in cu]
381
+ return [(s, a, b) for s, (a, b) in enumerate(zip(c, c[1:])) if b > a]
382
+
383
+
384
+ def _varlen_sdpa(q, k, v, cu, scale, layer=0, impl=None):
385
+ """engine._varlen_attention with one SDPA call per packed prompt (its queries attend causally to its keys,
386
+ bottom-right: a template prefix's keys first, as gathered): fp32 compact rows (the FlashAttention kernels take
387
+ bf16 / fp16) and the CPU (tests). Reads cu on the host, so no CUDA graph."""
388
+ T, G = q.shape[2], q.shape[1] // k.shape[1]
389
+ k, v = k[0].transpose(0, 1), v[0].transpose(0, 1)
390
+ if isinstance(cu, tuple):
391
+ cu, cu_k, gather, prefix = cu
392
+ pk, pv = prefix[layer]
393
+ k, v = torch.cat([pk, k]).index_select(0, gather), torch.cat([pv, v]).index_select(0, gather)
394
+ else:
395
+ cu_k = cu
396
+ out = torch.zeros((T, q.shape[1], q.shape[3]), dtype=q.dtype, device=q.device)
397
+ for s, a, b in _spans(cu):
398
+ ka, kb = int(cu_k[s]), int(cu_k[s + 1])
399
+ n, m = b - a, kb - ka
400
+ kk, vv = (t[ka:kb].transpose(0, 1).repeat_interleave(G, 0) for t in (k, v))
401
+ allow = torch.arange(m, device=q.device)[None] <= (m - n + torch.arange(n, device=q.device))[:, None]
402
+ out[a:b] = F.scaled_dot_product_attention(q[0, :, a:b], kk, vv, attn_mask=allow, scale=scale).transpose(0, 1)
403
+ return out[None]
404
+
405
+
406
+ # fla's Triton kernels pick their launch config by timing the candidates at the first launch of every shape key
407
+ # (triton.autotune), so two starts of the server could pick different configs, round differently and give different
408
+ # probabilities (and a new shape stalled a request while it was timed). FLA_CONFIGS holds, per GPU, the configs that GPU
409
+ # picked for the keys basal's pass shapes use (fla_record; the H100 80 GB and the RTX PRO 6000 Blackwell): with its
410
+ # GPU's table every recorded fla kernel takes the recorded config of its key, and its most common one for any other
411
+ # key, without timing (a kernel not in the table autotunes as before). Only on the GPU and fla version a table was
412
+ # recorded with; on any other GPU the first start times them and keeps its picks for the next starts (fla_pin).
413
+ # (On the RTX PRO 6000 Blackwell the three configs of chunk_fwd_kernel_o timed within 0.4% of each other, and its BK
414
+ # 64 and 128 give other probabilities: before its table, pico's cold starts there landed in one of three answer sets.)
415
+ FLA_CONFIGS = Path(__file__).parent / "fla_configs.json"
416
+ FLA_PINNED = None # what fla_pin did in this process: "pinned" (a recorded table), "kept" (an earlier start's), "timed"
417
+
418
+
419
+ def _fla_autotuners():
420
+ """fla's Triton autotuners: {"module.kernel": Autotuner}, after importing the modules basal's passes use (the
421
+ convolution's are imported only at its first call)."""
422
+ import gc
423
+ import importlib
424
+ from triton.runtime.autotuner import Autotuner
425
+ for name in ("fla.ops.gated_delta_rule", "fla.modules.conv.triton", "fla.modules.l2norm"):
426
+ try:
427
+ importlib.import_module(name)
428
+ except Exception:
429
+ pass
430
+ out = {}
431
+ for o in gc.get_objects():
432
+ try:
433
+ if isinstance(o, Autotuner) and str(getattr(o.base_fn, "__module__", "")).startswith("fla."):
434
+ out[f"{o.base_fn.__module__}.{o.base_fn.__qualname__}"] = o
435
+ except ReferenceError: # a weakref.proxy whose object is gone: isinstance() reads its __class__
436
+ continue
437
+ return out
438
+
439
+
440
+ def _config_dict(c):
441
+ return dict(kwargs=c.kwargs, num_warps=c.num_warps, num_stages=c.num_stages, num_ctas=c.num_ctas,
442
+ maxnreg=c.maxnreg)
443
+
444
+
445
+ def _table(tuners):
446
+ """The configs these autotuners picked so far, as one table of this GPU (the format fla_record writes)."""
447
+ import fla
448
+ from collections import Counter
449
+ kernels = {}
450
+ for name, t in sorted(tuners.items()):
451
+ # (a key value JSON cannot hold is written as its str: that key then gets the kernel's default when pinned)
452
+ entries = [json.loads(json.dumps([list(k), _config_dict(c)], default=str)) for k, c in t.cache.items()]
453
+ if entries:
454
+ common = Counter(json.dumps(c, sort_keys=True) for _, c in entries).most_common(1)[0][0]
455
+ kernels[name] = dict(default=json.loads(common), keys=entries)
456
+ return dict(gpu=torch.cuda.get_device_name(), fla=fla.__version__, kernels=kernels)
457
+
458
+
459
+ def fla_record(path):
460
+ """Write the configs fla's autotuners picked so far (after a warm-up of every pass shape) as one table of this GPU
461
+ (FLA_CONFIGS lists one per GPU; a prepared directory holds one)."""
462
+ table = _table(_fla_autotuners())
463
+ Path(path).write_text(json.dumps(table, indent=1, sort_keys=True), encoding="utf-8")
464
+ return len(table["kernels"])
465
+
466
+
467
+ class _PinnedCache(dict):
468
+ """An autotuner's cache that has every key: the recorded config, else the kernel's default (nothing is timed)."""
469
+
470
+ def __init__(self, entries, default):
471
+ super().__init__(entries)
472
+ self.default = default
473
+
474
+ def __contains__(self, key):
475
+ return True
476
+
477
+ def __missing__(self, key):
478
+ return self.default
479
+
480
+
481
+ def fla_tables(path):
482
+ """The tables of an fla configs file: one table (fla_record's; a prepared directory's) or a list of them, one per
483
+ GPU (the shipped FLA_CONFIGS)."""
484
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
485
+ return data if isinstance(data, list) else [data]
486
+
487
+
488
+ def kept_fla_configs():
489
+ """Where a GPU without a recorded table keeps its first start's fla picks: ~/.cache/basal/fla/<GPU>-<fla>.json
490
+ (None without a home directory)."""
491
+ import fla
492
+ try:
493
+ home = Path.home()
494
+ except (RuntimeError, KeyError): # no home directory (RuntimeError), no account (KeyError)
495
+ return None
496
+ gpu = re.sub(r"[^0-9A-Za-z]+", "_", torch.cuda.get_device_name()).strip("_")
497
+ return home / ".cache" / "basal" / "fla" / f"{gpu}-{fla.__version__}.json"
498
+
499
+
500
+ def _keep(tuner, tuners, path):
501
+ """After tuner times a new key, write every autotuner's picks to path (a temporary file renamed over it: never a
502
+ half-written table), so the next start takes them (fla_pin). A failed write leaves the start as it is."""
503
+ run = tuner.run
504
+
505
+ def kept(*args, **kwargs):
506
+ n = len(tuner.cache)
507
+ out = run(*args, **kwargs)
508
+ if len(tuner.cache) != n:
509
+ try:
510
+ path.parent.mkdir(parents=True, exist_ok=True)
511
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
512
+ tmp.write_text(json.dumps(_table(tuners), indent=1, sort_keys=True), encoding="utf-8")
513
+ os.replace(tmp, path)
514
+ except OSError:
515
+ pass
516
+ return out
517
+ tuner.run = kept
518
+
519
+
520
+ def _this_gpu(tables):
521
+ """The table of this GPU and fla version among tables, None if there is none."""
522
+ import fla
523
+ gpu = torch.cuda.get_device_name()
524
+ return next((t for t in tables if t.get("gpu") == gpu and t.get("fla") == fla.__version__), None)
525
+
526
+
527
+ def fla_pin(path=None):
528
+ """Give fla's autotuners the recorded configs of this GPU (see FLA_CONFIGS; a prepared start-up's own table replaces
529
+ it, prepared.load) -> the number of kernels pinned (FLA_PINNED says from where). Only the kernels in the table are
530
+ pinned: a kernel the recording never launched has no measured config (its first candidate may not even fit the
531
+ GPU), so it autotunes as without a table. A GPU without a recorded table takes the picks an earlier start on this
532
+ machine kept (kept_fla_configs); the kernels still timed keep theirs there for the next start, so a restart answers
533
+ as the first start did (they were timed anew at every start: another restart could round differently). Triton's
534
+ own autotune cache could not do this: its directory followed TRITON_CACHE_DIR, which Inductor set only in a start
535
+ that compiles (engine.pin_triton_cache now sets it before anything compiles), so the first restart looked
536
+ elsewhere and timed again. BASAL_FLA_PIN=0 turns it all off."""
537
+ global FLA_PINNED
538
+ path = path or FLA_CONFIGS
539
+ if os.environ.get("BASAL_FLA_PIN", "1") != "1" or not torch.cuda.is_available():
540
+ return 0
541
+ from triton.runtime.autotuner import Config
542
+ table = _this_gpu(fla_tables(path)) if Path(path).exists() else None
543
+ keep = None
544
+ if table is None:
545
+ keep = kept_fla_configs()
546
+ if keep is not None and keep.exists():
547
+ try:
548
+ table = _this_gpu(fla_tables(keep))
549
+ except (OSError, ValueError): # a broken file: timed again, and written anew
550
+ table = None
551
+ n = 0
552
+ def cfg(d):
553
+ return Config(d["kwargs"], num_warps=d["num_warps"], num_stages=d["num_stages"], num_ctas=d["num_ctas"],
554
+ maxnreg=d["maxnreg"])
555
+ tuners = _fla_autotuners()
556
+ for name, t in tuners.items():
557
+ e = (table or {}).get("kernels", {}).get(name)
558
+ if e is not None:
559
+ t.cache = _PinnedCache({tuple(k): cfg(c) for k, c in e["keys"]}, cfg(e["default"]))
560
+ n += 1
561
+ elif keep is not None:
562
+ _keep(t, tuners, keep)
563
+ FLA_PINNED = "timed" if not n else "kept" if keep is not None else "pinned"
564
+ return n
565
+
566
+
567
+ def eager_fla_configs(model_dir):
568
+ """--mode eager on CUDA: transformers runs a Qwen3.5 model's Gated DeltaNet layers on fla's kernels when fla is
569
+ installed, timed at their first launch as in the graph engine, so they get the same pinning (fla_pin) -> what it
570
+ did (FLA_PINNED: the start-up line), None for any other model or without fla."""
571
+ if not is_gdn(model_dir) or fla_rule() is None:
572
+ return None
573
+ fla_pin()
574
+ return FLA_PINNED
575
+
576
+
577
+ def _gdn_out(h, o, z, gw, out_w, eps):
578
+ """h + out_proj(Qwen3_5RMSNormGated(o, z)) over the value heads."""
579
+ dt, shape = o.dtype, o.shape
580
+ x = o.reshape(-1, shape[-1]).float()
581
+ x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
582
+ x = gw * x.to(dt)
583
+ x = (x * F.silu(z.reshape(-1, shape[-1]).float())).to(dt)
584
+ return h + F.linear(x.reshape(*shape[:2], -1), out_w)
585
+
586
+
587
+ def _rotary(x, cos, sin, r):
588
+ """apply_rotary_pos_emb of Qwen3.5 on one of q / k [b, heads, T, d]: the first r dims rotated (half split)."""
589
+ c, s = cos[:, None], sin[:, None]
590
+ xr = x[..., :r]
591
+ rot = torch.cat([-xr[..., r // 2:], xr[..., : r // 2]], -1)
592
+ return torch.cat([xr * c + rot * s, x[..., r:]], -1)
593
+
594
+
595
+ def _att_in(h, nw, w_qkv, qn, kn, cos, sin, eps, sizes, d, r):
596
+ """input_layernorm, q (with its output gate) / k / v in one GEMM, q / k norms, rotary embedding of the first r dims
597
+ -> q, k, v [b, heads, T, d], gate [b, T, heads * d]. (Head counts from sizes, not -1: Inductor failed on the
598
+ inferred dimension with dynamic shapes.)"""
599
+ b, T, _ = h.shape
600
+ H, Hkv = sizes[0] // (2 * d), sizes[1] // d
601
+ qg, k, v = F.linear(_rms(h, nw, eps), w_qkv).split(sizes, -1)
602
+ q, gate = torch.chunk(qg.view(b, T, H, d * 2), 2, dim=-1)
603
+ q = _rotary(_rms(q, qn, eps).transpose(1, 2), cos, sin, r)
604
+ k = _rotary(_rms(k.view(b, T, Hkv, d), kn, eps).transpose(1, 2), cos, sin, r)
605
+ return q, k, v.view(b, T, Hkv, d).transpose(1, 2), gate.reshape(b, T, H * d)
606
+
607
+
608
+ def _att_out(h, o, gate, o_w):
609
+ """h + o_proj(attention * sigmoid(gate))."""
610
+ b, T = gate.shape[:2]
611
+ return h + F.linear(o.transpose(1, 2).reshape(b, T, -1) * torch.sigmoid(gate), o_w)
612
+
613
+
614
+ # --- block FP8 (--mode fp8): the functions above with their projections through block-scaled FP8 weights. A separate
615
+ # set, so that the bf16 forward (the functions above, and the graphs built from them) stays as it is.
616
+
617
+ def _lin8(x, w):
618
+ """x [..., K] through a block-scaled FP8 weight w = (e4m3 values [N, K], fp32 scales [N / 128, K / 128])
619
+ (fp8block.linear: flashinfer's SM90 kernel on Hopper where it is installed, else the Triton block GEMM; on the CPU
620
+ the same maths dequantised)."""
621
+ return fp8block.linear(x, *w)
622
+
623
+
624
+ def row_quantize(w):
625
+ """[N, K] -> (e4m3 values [N, K], fp32 scales [1, N]): each output row divided by its amax / 448 (row-scaled FP8,
626
+ --fp8-scaling row; rows of a merged weight keep their own scales)."""
627
+ s = w.float().abs().amax(1, keepdim=True).clamp(min=1e-12) / FP8_MAX
628
+ return (w.float() / s).clamp(-FP8_MAX, FP8_MAX).to(E4M3), s.t().contiguous()
629
+
630
+
631
+ def _linr(x, w):
632
+ """x [..., K] through a row-scaled FP8 weight w = (e4m3 values [N, K], fp32 scales [1, N]): each token's
633
+ activations by their own scale (amax / 448; inside a compiled layer Inductor fuses this with what precedes it), one
634
+ cuBLAS FP8 GEMM with row-wise scales (torch._scaled_mm, rows padded to a multiple of 16; fast accumulation unless
635
+ --deterministic / --fp8-accum full, as the FP8 checkpoints), bf16 out. On the CPU the same maths in fp32."""
636
+ q, sw = w
637
+ shape, dt = x.shape, x.dtype
638
+ x2 = x.reshape(-1, shape[-1])
639
+ sx = x2.float().abs().amax(-1, keepdim=True).clamp(min=1e-12) / FP8_MAX
640
+ xq = (x2.float() / sx).clamp(-FP8_MAX, FP8_MAX).to(E4M3)
641
+ if x.is_cuda:
642
+ m = xq.shape[0]
643
+ if m % 16:
644
+ xq = F.pad(xq.view(torch.uint8), (0, 0, 0, -m % 16)).view(E4M3)
645
+ sx = F.pad(sx, (0, 0, 0, -m % 16), value=1.0)
646
+ y = torch._scaled_mm(xq, q.t(), scale_a=sx, scale_b=sw, out_dtype=dt, use_fast_accum=FP8_FAST_ACCUM[0])[:m]
647
+ else:
648
+ y = ((xq.float() * sx) @ (q.float() * sw.t()).t()).to(dt)
649
+ return y.reshape(*shape[:-1], q.shape[0])
650
+
651
+
652
+ class RowFP8Linear(torch.nn.Module):
653
+ """A linear layer of a row-scaled FP8 weight (row_quantize; _linr): the parts of a merged weight stay modules of
654
+ their own (transformers' forward of the model still runs)."""
655
+
656
+ def __init__(self, weight, scale):
657
+ super().__init__()
658
+ self.weight = torch.nn.Parameter(weight, requires_grad=False)
659
+ self.weight_scale = torch.nn.Parameter(scale, requires_grad=False)
660
+ self.out_features, self.in_features = weight.shape
661
+
662
+ def forward(self, x):
663
+ return _linr(x, (self.weight, self.weight_scale.contiguous()))
664
+
665
+
666
+ def _mlp8(h, nw, gu, down, eps, lin=_lin8):
667
+ """_mlp with FP8 gate / up (one GEMM) and down (lin: _lin8, block scales, or _linr, row scales)."""
668
+ g, u = lin(_rms(h, nw, eps), gu).chunk(2, -1)
669
+ return h + lin(F.silu(g) * u, down)
670
+
671
+
672
+ def _gdn_in8(h, nw, w_in, A_log, dt_bias, mask, eps, sizes, lin=_lin8):
673
+ """_gdn_in with qkv and z in one FP8 GEMM and b and a (one row per value head) in one bf16 GEMM, as Qwen's own FP8
674
+ checkpoints keep in_proj_b / in_proj_a: w_in = (FP8 values of qkv + z, their scales, the bf16 weight of b + a)."""
675
+ x = _rms(h, nw, eps)
676
+ qkv, z = lin(x, w_in[:2]).split(sizes[:2], -1)
677
+ b, a = F.linear(x, w_in[2]).split(sizes[2:], -1)
678
+ beta = b.sigmoid()
679
+ g = -A_log.float().exp() * F.softplus(a.float() + dt_bias)
680
+ if mask is not None: # padding: no update (beta 0), no decay (g 0)
681
+ beta = beta * mask[..., None]
682
+ g = g * mask[..., None]
683
+ return qkv, z, beta, g
684
+
685
+
686
+ def _gdn_out8(h, o, z, gw, out_w, eps, lin=_lin8):
687
+ """_gdn_out with an FP8 out_proj."""
688
+ dt, shape = o.dtype, o.shape
689
+ x = o.reshape(-1, shape[-1]).float()
690
+ x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
691
+ x = gw * x.to(dt)
692
+ x = (x * F.silu(z.reshape(-1, shape[-1]).float())).to(dt)
693
+ return h + lin(x.reshape(*shape[:2], -1), out_w)
694
+
695
+
696
+ def _att_in8(h, nw, w_qkv, qn, kn, cos, sin, eps, sizes, d, r, lin=_lin8):
697
+ """_att_in with q (and its gate) / k / v in one FP8 GEMM."""
698
+ b, T, _ = h.shape
699
+ H, Hkv = sizes[0] // (2 * d), sizes[1] // d
700
+ qg, k, v = lin(_rms(h, nw, eps), w_qkv).split(sizes, -1)
701
+ q, gate = torch.chunk(qg.view(b, T, H, d * 2), 2, dim=-1)
702
+ q = _rotary(_rms(q, qn, eps).transpose(1, 2), cos, sin, r)
703
+ k = _rotary(_rms(k.view(b, T, Hkv, d), kn, eps).transpose(1, 2), cos, sin, r)
704
+ return q, k, v.view(b, T, Hkv, d).transpose(1, 2), gate.reshape(b, T, H * d)
705
+
706
+
707
+ def _att_out8(h, o, gate, o_w, lin=_lin8):
708
+ """_att_out with an FP8 o_proj."""
709
+ b, T = gate.shape[:2]
710
+ return h + lin(o.transpose(1, 2).reshape(b, T, -1) * torch.sigmoid(gate), o_w)
711
+
712
+
713
+ class Qwen35Graph:
714
+ """The forward of a Qwen3.5 decoder for GDNGraphBackend, layer by layer as transformers' Qwen3_5DecoderLayer (its
715
+ modules' weights and maths; the projections that read one input are one GEMM):
716
+
717
+ forward(ids, lens, kv, st) plain rows from position 0; kv / st: buffers that receive each
718
+ row's keys / values and recurrent state (pass 1)
719
+ forward_suffix(ids, pos, unit, plen, kv, st) pass 2: rows that continue root `unit` (plen tokens) from its
720
+ keys / values and recurrent state
721
+
722
+ compile (--mode fast): the parts between the Gated DeltaNet kernels and the attention (norms, projections, gates,
723
+ rotary embedding, MLP) as torch.compile functions of dynamic shapes, one per kind for every layer. On CUDA the
724
+ convolution is fla's kernel in both modes.
725
+
726
+ fp8 (--mode fp8): FP8 weights at load time (_fp8) for the projections of every layer but the first and the last
727
+ `keep` (--fp8-bf16-layers), run by a second set of functions (f8: the same maths, the projections through _lin8 for
728
+ scaling "block", 128 x 128 weight blocks and 1 x 128 activation tiles, or _linr for "row", one scale per weight row
729
+ and per token); the bf16 layers and every other weight (embeddings, norms, convolution, the readout) are as
730
+ loaded, and the bf16 set of functions is the same with or without fp8.
731
+ """
732
+
733
+ def __init__(self, model, compile=False, fp8=False, keep=2, scaling="block"):
734
+ from transformers.models.qwen3_5 import modeling_qwen3_5 as q35
735
+ self.m = model.model
736
+ cfg = self.m.config
737
+ self.layers = list(self.m.layers[: cfg.num_hidden_layers])
738
+ self.kinds = [cfg.layer_types[i] for i in range(len(self.layers))]
739
+ self.eps = cfg.rms_norm_eps
740
+ # fla's kernel on CUDA; transformers' torch version on the CPU (the tests: the same arguments; unwrapped, as
741
+ # transformers routes that name to fla whenever fla is installed)
742
+ cuda = next(model.parameters()).device.type == "cuda"
743
+ self.rule = (fla_rule() if cuda else None) or inspect.unwrap(q35.torch_chunk_gated_delta_rule)
744
+ self.args = [] # per layer: its weights and sizes for the functions above
745
+ for lay, kind in zip(self.layers, self.kinds):
746
+ mlp = (lay.post_attention_layernorm.weight, fuse([lay.mlp.gate_proj, lay.mlp.up_proj])[0],
747
+ lay.mlp.down_proj.weight)
748
+ if kind == "linear_attention":
749
+ a = lay.linear_attn
750
+ if a.conv1d.bias is not None:
751
+ raise ValueError("a Gated DeltaNet convolution with a bias (not in Qwen3.5)")
752
+ w_in, sizes = fuse([a.in_proj_qkv, a.in_proj_z, a.in_proj_b, a.in_proj_a])
753
+ self.args.append(dict(a=a, nw=lay.input_layernorm.weight, w_in=w_in, sizes=sizes, mlp=mlp))
754
+ else:
755
+ a = lay.self_attn
756
+ w_qkv, sizes = fuse([a.q_proj, a.k_proj, a.v_proj])
757
+ self.args.append(dict(a=a, nw=lay.input_layernorm.weight, w_qkv=w_qkv, sizes=sizes, mlp=mlp))
758
+ att = [x["a"] for x, k in zip(self.args, self.kinds) if k == "full_attention"]
759
+ gdn = [x["a"] for x, k in zip(self.args, self.kinds) if k == "linear_attention"]
760
+ self.kv_shapes = [(cfg.num_key_value_heads, a.head_dim) for a in att]
761
+ self.heads = cfg.num_attention_heads
762
+ g = gdn[0]
763
+ # per Gated DeltaNet layer: the recurrent state [value heads, key dim, value dim] (fp32, as fla returns it) and
764
+ # the convolution tail [kernel - 1, conv channels]: the inputs of the convolution at the last tokens
765
+ self.state_shape = (g.num_v_heads, g.head_k_dim, g.head_v_dim)
766
+ self.tail_shape = (g.conv_kernel_size - 1, g.conv_dim)
767
+ self.n_gdn = len(gdn)
768
+ # the model's constants bound here, so that a compiled function sees them as constants (dynamic=True traces
769
+ # its float and int arguments as symbols; Inductor then failed on the norms' eps)
770
+ eps, geps, d = self.eps, g.norm.variance_epsilon, att[0].head_dim
771
+ gs = self.args[self.kinds.index("linear_attention")]["sizes"]
772
+ qs = self.args[self.kinds.index("full_attention")]["sizes"]
773
+ rd = self.m.rotary_emb.inv_freq.shape[0] * 2 # rotated dims of a head (partial_rotary_factor)
774
+ cs = [g.key_dim, g.key_dim, g.value_dim]
775
+ fns = dict(mlp=lambda h, nw, gu, down: _mlp(h, nw, gu, down, eps),
776
+ gdn_in=lambda h, nw, w, A_log, dt_bias, mask: _gdn_in(h, nw, w, A_log, dt_bias, mask, eps, gs),
777
+ conv=lambda qkv, w, c0: _conv(qkv, w, c0, cs),
778
+ gdn_out=lambda h, o, z, gw, out_w: _gdn_out(h, o, z, gw, out_w, geps),
779
+ att_in=lambda h, nw, w, qn, kn, cos, sin: _att_in(h, nw, w, qn, kn, cos, sin, eps, qs, d, rd),
780
+ att_out=_att_out, rms=lambda h, w: _rms(h, w, eps))
781
+ conv, self.conv_kernel = conv_kernel(cuda) # on CUDA fla's kernel, uncompiled (Triton), in both modes
782
+ self.conv, self.conv_sizes, self.cuda = conv, cs, cuda
783
+ # compact rows (GDNGraphBackend sets them): the attention kernel, fla's varlen pieces, the template prefixes
784
+ self.varlen = self.fla_v = self.template_kv = self.template_st = None
785
+ self.f_eager = dict(fns) # uncompiled (the long lane: run beside the graphs, from another thread)
786
+ if compile:
787
+ import torch._dynamo as dynamo
788
+ compile_set("dynamo", cache_size_limit=max(dynamo.config.cache_size_limit, 64)) # (as the Llama forward)
789
+ # the fused kernels round to bf16 where the uncompiled maths does (norms, gates, SwiGLU), so the compiled
790
+ # forward gives the uncompiled one's numbers (tiny model, bf16, CPU: bit-identical; max diff 0.023
791
+ # without). Without it the pico's top answers moved away from eager's (300 five-question x two-order
792
+ # requests on an H100: 99.3% against 99.6% for fast-nocompile)
793
+ compile_set("inductor", emulate_precision_casts=True)
794
+ # Inductor's deterministic mode (TORCHINDUCTOR_DETERMINISTIC=0: without it), as basal-omni's forward since
795
+ # 2.3.4: otherwise Inductor times some reduction kernels at their first launch and keeps the faster config,
796
+ # and what its cache holds then depends on its history, so two starts could round differently; and pointwise
797
+ # autotuning off (engine.compile_untimed), which deterministic mode left on: each start timed the pointwise
798
+ # kernels' block shapes and kept its own (basal-omni)
799
+ fns = {k: compile_untimed(f, dynamic=True) for k, f in fns.items()}
800
+ if conv is not None:
801
+ fns["conv"] = self.f_eager["conv"] = lambda qkv, w, c0: _conv_fla(qkv, w, c0, cs, conv)
802
+ self.f = fns
803
+ # --mode fp8: the FP8 layers' functions (f8; f8_eager for the long lane), the convolution and the final norm
804
+ # shared with f; None without fp8 (every layer runs f)
805
+ self.f8 = self.f8_eager = None
806
+ self.scaling = scaling if fp8 else None
807
+ self.fp8 = self._fp8(keep, scaling) if fp8 else 0
808
+ if fp8:
809
+ lin = _linr if scaling == "row" else _lin8
810
+ f8 = dict(mlp=lambda h, nw, gu, down: _mlp8(h, nw, gu, down, eps, lin),
811
+ gdn_in=lambda h, nw, w, A_log, dt_bias, mask: _gdn_in8(h, nw, w, A_log, dt_bias, mask, eps, gs,
812
+ lin),
813
+ gdn_out=lambda h, o, z, gw, out_w: _gdn_out8(h, o, z, gw, out_w, geps, lin),
814
+ att_in=lambda h, nw, w, qn, kn, cos, sin: _att_in8(h, nw, w, qn, kn, cos, sin, eps, qs, d, rd,
815
+ lin),
816
+ att_out=lambda h, o, gate, o_w: _att_out8(h, o, gate, o_w, lin))
817
+ self.f8_eager = dict(self.f_eager, **f8)
818
+ if compile: # (untimed, as f: identical answers at every start)
819
+ f8 = {k: compile_untimed(f, dynamic=True) for k, f in f8.items()}
820
+ self.f8 = dict(self.f, **f8)
821
+
822
+ def _fns(self, x):
823
+ """The functions of a layer's args x: f8 for a layer with FP8 weights, else f."""
824
+ return self.f8 if x.get("fp8") else self.f
825
+
826
+ @torch.no_grad()
827
+ def _fp8(self, keep, scaling="block"):
828
+ """FP8 weights for the projections of every layer but the first and the last `keep`: q (with its gate) / k / v
829
+ and o_proj of the attention layers, in_proj's qkv and z (merged) and out_proj of the Gated DeltaNet layers, the
830
+ merged gate / up and down of every MLP. scaling "block": basal/fp8block.py's 128 x 128 blocks (activations in
831
+ 1 x 128 tiles); "row": one scale per output row (row_quantize; activations one scale per token), which keeps
832
+ each part of a merged weight exact. in_proj's b and a (one row per value head) stay bf16, one GEMM of their own,
833
+ as in Qwen's FP8 checkpoints (modules_to_not_convert: in_proj_a, in_proj_b, conv1d). The modules' bf16 weights
834
+ are dropped as it goes (their parts become FP8 modules, views of the merged FP8 weight; a part that does not fill
835
+ whole blocks keeps a bf16 copy for transformers' forward), so the bf16 copy is freed layer by layer. -> the
836
+ number of FP8 GEMMs."""
837
+ BLOCK, BlockFP8Linear = fp8block.BLOCK, fp8block.BlockFP8Linear
838
+ row = scaling == "row"
839
+ cuda = next(self.m.parameters()).device.type == "cuda"
840
+ if cuda and not row:
841
+ fp8block.sm90() # which GEMM the layers run, decided before they are compiled
842
+ n, L = 0, len(self.layers)
843
+
844
+ def quant(w, mod=None, names=(), sizes=()):
845
+ """(FP8 values, scales) of a weight (block: of whole 128 x 128 blocks); the modules of its parts become
846
+ views of it (BlockFP8Linear / RowFP8Linear), or bf16 copies where a part does not fill whole blocks."""
847
+ if row:
848
+ if w.shape[0] % 16 or w.shape[1] % 16: # (the FP8 GEMM's operands: dimensions of 16)
849
+ raise ValueError(f"row FP8: a {tuple(w.shape)} projection is not a multiple of 16 each way")
850
+ q, s = row_quantize(w)
851
+ o = 0
852
+ for name, k in zip(names, sizes):
853
+ setattr(mod, name, RowFP8Linear(q[o: o + k], s[:, o: o + k]))
854
+ o += k
855
+ return q, s
856
+ if w.shape[0] % BLOCK or w.shape[1] % BLOCK:
857
+ raise ValueError(f"block FP8: a {tuple(w.shape)} projection is not in whole 128 x 128 blocks")
858
+ q, s = BlockFP8Linear.FORMAT.quantize(w)
859
+ o = 0
860
+ for name, k in zip(names, sizes):
861
+ if o % BLOCK == 0 and k % BLOCK == 0:
862
+ setattr(mod, name, BlockFP8Linear(q[o: o + k], s[o // BLOCK: (o + k) // BLOCK]))
863
+ else:
864
+ lin = getattr(mod, name)
865
+ lin.weight = torch.nn.Parameter(lin.weight.detach().clone(), requires_grad=False)
866
+ o += k
867
+ return q, s
868
+
869
+ for i, (x, kind, lay) in enumerate(zip(self.args, self.kinds, self.layers)):
870
+ if i < keep or i >= L - keep:
871
+ continue
872
+ m, a = lay.mlp, x["a"]
873
+ nw, gu, down = x["mlp"]
874
+ x["mlp"] = (nw, quant(gu, m, ("gate_proj", "up_proj"), (m.gate_proj.out_features, m.up_proj.out_features)),
875
+ quant(down, m, ("down_proj",), (down.shape[0],)))
876
+ if kind == "linear_attention": # qkv and z FP8; b and a a bf16 weight of their own (views: the modules')
877
+ sizes, w = x["sizes"], x["w_in"]
878
+ n8 = sizes[0] + sizes[1]
879
+ ba = w[n8:].clone()
880
+ a.in_proj_b.weight = torch.nn.Parameter(ba[: sizes[2]], requires_grad=False)
881
+ a.in_proj_a.weight = torch.nn.Parameter(ba[sizes[2]:], requires_grad=False)
882
+ x["w_in"] = (*quant(w[:n8], a, ("in_proj_qkv", "in_proj_z"), sizes[:2]), ba)
883
+ x["out"] = quant(a.out_proj.weight, a, ("out_proj",), (a.out_proj.out_features,))
884
+ else:
885
+ x["w_qkv"] = quant(x["w_qkv"], a, ("q_proj", "k_proj", "v_proj"), x["sizes"])
886
+ x["o"] = quant(a.o_proj.weight, a, ("o_proj",), (a.o_proj.out_features,))
887
+ x["fp8"] = True
888
+ n += 4
889
+ if cuda:
890
+ torch.cuda.empty_cache()
891
+ return n
892
+
893
+ def _rope(self, h, pos):
894
+ return self.m.rotary_emb(h, pos[None].expand(3, *pos.shape)) # text: the same position in all three sections
895
+
896
+ def _gdn(self, x, h, mask=None, lens=None, out=None, s0=None, c0=None):
897
+ """h + Qwen3_5GatedDeltaNet(input_layernorm(h)) without a cache: mask [b, T] zeroes beta and g of padding
898
+ (pass 1), out = (state [b, ...], tail [b, ...]) receives the state and convolution tail at token lens - 1; s0 /
899
+ c0: the state and tail the rows continue (pass 2)."""
900
+ a, f = x["a"], self._fns(x)
901
+ b, T, _ = h.shape
902
+ qkv, z, beta, g = f["gdn_in"](h, x["nw"], x["w_in"], a.A_log, a.dt_bias, mask)
903
+ w = a.conv1d.weight # [channels, 1, kernel]
904
+ q, k, v = f["conv"](qkv, w, c0)
905
+ q = q.reshape(b, T, -1, a.head_k_dim)
906
+ k = k.reshape(b, T, -1, a.head_k_dim)
907
+ v = v.reshape(b, T, -1, a.head_v_dim)
908
+ r = a.num_v_heads // a.num_k_heads
909
+ if r > 1:
910
+ q, k = q.repeat_interleave(r, dim=2), k.repeat_interleave(r, dim=2)
911
+ o, fs = self.rule(q, k, v, g=g, beta=beta, initial_state=s0, output_final_state=out is not None,
912
+ use_qk_l2norm_in_kernel=True)
913
+ if out is not None:
914
+ out[0].copy_(fs)
915
+ n = w.shape[-1] - 1
916
+ # tokens lens - n .. lens - 1; a row that continues a tail (c0) reads its first ones there
917
+ src = qkv if c0 is None else torch.cat([c0.to(qkv.dtype), qkv], 1)
918
+ ix = lens[:, None] - n + torch.arange(n, device=h.device)[None] + (0 if c0 is None else n)
919
+ t = src.gather(1, ix.clamp_min(0)[..., None].expand(-1, -1, src.shape[-1]))
920
+ out[1].copy_(t * (ix >= 0)[..., None]) # before position 0: zeros (a root shorter than the tail)
921
+ return f["gdn_out"](h, o, z.reshape(b, T, -1, a.head_v_dim), a.norm.weight, x.get("out", a.out_proj.weight))
922
+
923
+ def _attention(self, x, h, cos, sin, out=None, prefix=None):
924
+ """h + Qwen3_5Attention(input_layernorm(h)) (queries with an output gate, q / k norms, partial rotary
925
+ embedding). out = (K, V) buffers [b, kv heads, T, d] it fills (pass 1); prefix = (root K, root V [b, kv heads,
926
+ Lk, d], allow [b, 1, groups * T, Lk + T]): the rows attend to their root and causally to themselves (pass 2)."""
927
+ a, f = x["a"], self._fns(x)
928
+ b, T, _ = h.shape
929
+ d = a.head_dim
930
+ q, k, v, gate = f["att_in"](h, x["nw"], x["w_qkv"], a.q_norm.weight, a.k_norm.weight, cos, sin)
931
+ if out is not None:
932
+ out[0].copy_(k)
933
+ out[1].copy_(v)
934
+ G = a.num_key_value_groups
935
+ if prefix is None: # causal, no mask: SDPA's flash kernel (FlashAttention 3 where --attn chose it)
936
+ kk, vv = (t[:, :, None].expand(-1, -1, G, -1, -1).reshape(b, -1, T, d) for t in (k, v))
937
+ o = F.scaled_dot_product_attention(q, kk, vv, is_causal=True, scale=a.scaling)
938
+ else: # the G query heads of a key / value head folded into the query length: no repeated keys
939
+ pk, pv, allow = prefix
940
+ kk, vv = torch.cat([pk, k], 2), torch.cat([pv, v], 2)
941
+ o = F.scaled_dot_product_attention(q.reshape(b, kk.shape[1], G * T, d), kk, vv, attn_mask=allow,
942
+ scale=a.scaling).reshape(b, -1, T, d)
943
+ return f["att_out"](h, o, gate, x.get("o", a.o_proj.weight))
944
+
945
+ between = None # the long lane's copy (GDNGraphBackend._long_net): called with i before layer i
946
+
947
+ def _layers(self, h, gdn, att):
948
+ ia = ig = 0
949
+ for j, (x, kind) in enumerate(zip(self.args, self.kinds)):
950
+ if self.between is not None:
951
+ self.between(j)
952
+ if kind == "linear_attention":
953
+ h = gdn(x, h, ig)
954
+ ig += 1
955
+ else:
956
+ h = att(x, h, ia)
957
+ ia += 1
958
+ h = self._fns(x)["mlp"](h, *x["mlp"])
959
+ return self.f["rms"](h, self.m.norm.weight)
960
+
961
+ @torch.no_grad()
962
+ def forward(self, ids, lens=None, kv=None, st=None):
963
+ """Plain rows [b, T] from position 0 -> normalised hidden states [b, T, D]. lens [b]: real tokens per row (the
964
+ rest is padding; needed with st); kv: per attention layer (K, V) [b, kv heads, T, d] to fill; st: per Gated
965
+ DeltaNet layer (state [b, ...] fp32, tail [b, kernel - 1, channels]) to fill at token lens - 1."""
966
+ b, T = ids.shape
967
+ h = self.m.embed_tokens(ids)
968
+ cos, sin = self._rope(h, torch.arange(T, device=ids.device)[None].expand(b, T))
969
+ mask = None if lens is None else torch.arange(T, device=ids.device)[None] < lens[:, None]
970
+ return self._layers(
971
+ h,
972
+ lambda x, h, i: self._gdn(x, h, mask, lens, None if st is None else st[i]),
973
+ lambda x, h, i: self._attention(x, h, cos, sin, None if kv is None else kv[i]))
974
+
975
+ @torch.no_grad()
976
+ def forward_suffix(self, ids, pos, unit, plen, kv, st):
977
+ """Pass 2: rows [b, S] (positions pos) that continue the roots unit [b] (rows of the pass-1 buffers kv / st,
978
+ per attention layer (K, V) [roots, kv heads, Lk, d], per Gated DeltaNet layer (state, tail)), whose first
979
+ plen [b] tokens are real -> normalised hidden states [b, S, D]."""
980
+ b, S = ids.shape
981
+ dev = ids.device
982
+ h = self.m.embed_tokens(ids)
983
+ cos, sin = self._rope(h, pos)
984
+ Lk = kv[0][0].shape[2] if kv else 0
985
+ G = self.heads // self.kv_shapes[0][0] if kv else 1
986
+ root = (torch.arange(Lk, device=dev)[None] < plen[:, None])[:, None].expand(b, S, Lk)
987
+ own = torch.ones(S, S, dtype=torch.bool, device=dev).tril()[None].expand(b, S, S)
988
+ allow = torch.cat([root, own], -1)[:, None, None].expand(b, 1, G, S, Lk + S).reshape(b, 1, G * S, Lk + S)
989
+ # each layer gathers its own roots' keys and values (attention) or state and tail (Gated DeltaNet) for the rows
990
+ # when it runs, not every layer's before layer 0: the same gathers, but only one layer's are alive at a time,
991
+ # in a captured graph's pool too
992
+ return self._layers(
993
+ h,
994
+ lambda x, h, i: self._gdn(x, h, s0=st[i][0].index_select(0, unit), c0=st[i][1].index_select(0, unit)),
995
+ lambda x, h, i: self._attention(x, h, cos, sin, prefix=(kv[i][0].index_select(0, unit),
996
+ kv[i][1].index_select(0, unit), allow)))
997
+
998
+
999
+ @torch.no_grad()
1000
+ def forward_continue(self, ids, n, kv0, st0, kv, st):
1001
+ """Rows [b, T] that continue a cached state of n tokens (positions n ..): kv0 per attention layer (K, V)
1002
+ [b, kv heads, n, d], st0 per Gated DeltaNet layer (state, tail); fills kv (K, V) [b, kv heads, T, d] with the
1003
+ rows' own keys and values and st (state, tail) after their last token -> normalised hidden states [b, T, D]."""
1004
+ b, T = ids.shape
1005
+ dev = ids.device
1006
+ h = self.m.embed_tokens(ids)
1007
+ cos, sin = self._rope(h, torch.arange(n, n + T, device=dev)[None].expand(b, T))
1008
+ G = self.heads // self.kv_shapes[0][0] if kv else 1
1009
+ own = torch.ones(T, T, dtype=torch.bool, device=dev).tril()
1010
+ allow = torch.cat([torch.ones(T, n, dtype=torch.bool, device=dev), own], -1)
1011
+ allow = allow[None, None, None].expand(b, 1, G, T, n + T).reshape(b, 1, G * T, n + T)
1012
+ lens = torch.full((b,), T, dtype=torch.long, device=dev)
1013
+ return self._layers(
1014
+ h,
1015
+ lambda x, h, i: self._gdn(x, h, None, lens, st[i], s0=st0[i][0], c0=st0[i][1]),
1016
+ lambda x, h, i: self._attention(x, h, cos, sin, kv[i], prefix=(*kv0[i], allow)))
1017
+
1018
+
1019
+ def _gdn_varlen(self, x, h, cu, ci, st):
1020
+ """_gdn over compact rows [1, T] (cu, ci: _rule_varlen's; ci None: no CUDA, each prompt on its own with
1021
+ transformers' kernel, as _gdn): every prompt from its own recurrent state and convolution tail, st = (s0
1022
+ [prompts, ...], c0 [prompts, ...]), or from zero (st None)."""
1023
+ a, f = x["a"], self._fns(x)
1024
+ T = h.shape[1]
1025
+ qkv, z, beta, g = f["gdn_in"](h, x["nw"], x["w_in"], a.A_log, a.dt_bias, None)
1026
+ w = a.conv1d.weight
1027
+ s0, c0 = st if st is not None else (None, None)
1028
+ r = a.num_v_heads // a.num_k_heads
1029
+
1030
+ def heads(q, k, v, n):
1031
+ q, k, v = (t.reshape(1, n, -1, d) for t, d in ((q, a.head_k_dim), (k, a.head_k_dim), (v, a.head_v_dim)))
1032
+ return (q.repeat_interleave(r, dim=2), k.repeat_interleave(r, dim=2), v) if r > 1 else (q, k, v)
1033
+ if ci is not None:
1034
+ q, k, v = heads(*_conv_varlen(qkv, w, c0, self.conv_sizes, self.conv, cu, ci), T)
1035
+ o = _rule_varlen(q, k, v, g, beta, s0, cu, ci, self.fla_v)
1036
+ else:
1037
+ parts = []
1038
+ for i, lo, hi in _spans(cu):
1039
+ q, k, v = heads(*f["conv"](qkv[:, lo:hi], w, None if c0 is None else c0[i: i + 1]), hi - lo)
1040
+ parts.append(self.rule(q, k, v, g=g[:, lo:hi], beta=beta[:, lo:hi], output_final_state=False,
1041
+ initial_state=None if s0 is None else s0[i: i + 1],
1042
+ use_qk_l2norm_in_kernel=True)[0])
1043
+ o = torch.cat(parts, 1)
1044
+ return f["gdn_out"](h, o, z.reshape(1, T, -1, a.head_v_dim), a.norm.weight, x.get("out", a.out_proj.weight))
1045
+
1046
+ def _attention_varlen(self, x, h, cos, sin, cu, i, ro=None):
1047
+ """_attention over compact rows: each prompt attends causally to itself (and to its template prefix's keys and
1048
+ values, cu = (cu, cu_k, gather, template keys / values) as for engine._varlen_attention); ro: the readout
1049
+ positions, where alone the output gate, o_proj and the rest of the layer run (--readout-layer on)."""
1050
+ a, f = x["a"], self._fns(x)
1051
+ q, k, v, gate = f["att_in"](h, x["nw"], x["w_qkv"], a.q_norm.weight, a.k_norm.weight, cos, sin)
1052
+ o = self.varlen(q, k, v, cu, a.scaling, i) # [1, T, heads, d]
1053
+ if ro is not None:
1054
+ h, o, gate = h[:, ro], o[:, ro], gate[:, ro]
1055
+ return f["att_out"](h, o.transpose(1, 2), gate, x.get("o", a.o_proj.weight))
1056
+
1057
+ @torch.no_grad()
1058
+ def forward_compact(self, ids, pos, cu, ci=None, tix=None, cu_k=None, gather=None, ro=None):
1059
+ """Compact rows (--batches compact): prompts packed back to back in one row [1, T] (positions from 0, or from
1060
+ the end of their template prefix; cu: cumulative token counts, int32; on CUDA every prompt starts on a
1061
+ 64-token chunk and ci [T / 64, 2] gives fla the chunk indices). Each prompt attends to itself only and its Gated
1062
+ DeltaNet layers start from zero, or with tix [prompts] (--template-prefix on) from template tix's checkpoint:
1063
+ its keys / values (template_kv, gathered by cu_k / gather) and states / tails (template_st; the last row is
1064
+ zeros). ro (--readout-layer on, a model whose last layer is attention): the readout positions [R], where alone
1065
+ the last layer runs after its attention -> [1, R, D]; else the normalised hidden states [1, T, D]."""
1066
+ h = self.m.embed_tokens(ids)
1067
+ cos, sin = self._rope(h, pos)
1068
+ st, cu_a = [None] * self.n_gdn, cu
1069
+ if tix is not None:
1070
+ st = [(s.index_select(0, tix), c.index_select(0, tix)) for s, c in self.template_st]
1071
+ cu_a = (cu, cu_k, gather, self.template_kv)
1072
+ n_att = len(self.kv_shapes)
1073
+ return self._layers(
1074
+ h,
1075
+ lambda x, h, i: self._gdn_varlen(x, h, cu, ci, st[i]),
1076
+ lambda x, h, i: self._attention_varlen(x, h, cos, sin, cu_a, i, ro if i == n_att - 1 else None))
1077
+
1078
+
1079
+ class GDNGraphBackend(GraphBackend):
1080
+ """GraphBackend for Qwen3.5 (Gated DeltaNet) models: GraphBackend(model_dir, ...) of such a model builds this one
1081
+ (GraphBackend.__new__). Single prompts run in the plain graphs as before; a branched unit runs its root in a plain
1082
+ graph that also keeps each row's recurrent state, then one row per leaf of its trie (see the module docstring)."""
1083
+
1084
+ SHARE_SPLIT_ROOTS = False # its pass 1 also carries each row's recurrent state: every part computes its root
1085
+ COLD_CAPTURE = False # fla's kernels pick their launch configs per shape at the first launch: every shape warms up
1086
+ TREE_ROWS = [1, 2, 4, 8] # roots per pass-1 forward (rows of the state buffers)
1087
+ ROOT_LENS = [512, 1024, 2048, 4096, 8192] # pass-2 root buckets: the layout pass 1 writes the roots' keys in
1088
+ LEAF_ROWS = [1, 2, 4, 5, 8, 10, 16, 20, 32, 40, 64] # pass-2 graph rows (leaves: questions x option orders)
1089
+ LEAF_LENS = [32, 64, 128, 256, 512, 1024] # pass-2 graph row lengths (a leaf's path below the root)
1090
+ SUFFIX_EAGER = 128 # longer leaf rows (no graph) are padded to a multiple of this
1091
+ PASS2_KEYS = 65536 # pass-2 rows x root bucket per forward: the root keys / values each row gathers
1092
+ ONE_FORWARD = 1 << 30 # a prompt beyond the largest graph runs as one uncaptured forward
1093
+ row_per_leaf = True # pass 2 runs one row per leaf (basal-serve cuts only single prompts at a template prefix)
1094
+ _warmed = False # warm() ran: the pass-2 graphs it did not capture (GPU memory) stay uncaptured
1095
+
1096
+ def __init__(self, model_dir, dtype="bfloat16", quant=None, compile=False, shared=True, warm=True, attn="auto",
1097
+ merge="auto", lean=False, tree="dense", state_cache_gb=0, prefix=False, batches="default",
1098
+ readout_layer="off", template="off", gemma_attn="auto", fp8_scaling="auto", fp8_bf16_layers=2,
1099
+ nvfp4_amax=None, nvfp4_scope="all", quant_load="gpu", state_cache_bits=16, graph_memory_gb=None,
1100
+ device=None, global_attn="flex", adapter=None, state_cache_dir=None, state_cache_disk_gb=20.0,
1101
+ fp8_experimental=False,
1102
+ state_cache_match="prefix", llama_graph="off", varloop_passes=None, varloop_exit_tau=None):
1103
+ if state_cache_match != "prefix":
1104
+ raise ValueError("--state-cache-match whole requires the attention graph backend")
1105
+ # (fp8_scaling .. quant_load: GraphBackend's quantisation options, which basal-serve passes to every graph
1106
+ # engine; of them FP8 (--mode fp8) runs here, with fp8_bf16_layers, the others are refused. fp8_experimental:
1107
+ # --fp8-experimental on, FP8 at a shape that has not passed its gate.
1108
+ # graph_memory_gb: the pass-2 graphs captured, _pin_memory). device: "mps" / "cpu" (GDNMPSBackend: no CUDA
1109
+ # graphs, uncompiled)
1110
+ if compile == "layer":
1111
+ raise ValueError(f"{model_dir}: --compile-scope layer: the bf16 Llama forward only (Qwen3.5's compiled "
1112
+ "code is per layer kind already)")
1113
+ why = modelopt_refused(model_dir, "graph", gdn=True) # (it loads with transformers, never load_modelopt_fp8)
1114
+ if why:
1115
+ raise ValueError(f"{model_dir}: {why}")
1116
+ if compile:
1117
+ persist_compile_cache() # before anything compiles (GraphBackend.__init__)
1118
+ compiled_calls_beside_compiles() # (GraphBackend.__init__)
1119
+ why = fp8_shape_refused(model_dir, fp8_scaling, fp8_experimental) if quant == "fp8" else None # (the gated
1120
+ # shapes, first)
1121
+ why = why or refused(quant, state_cache_gb, prefix, batches, lean, tree, readout_layer, template,
1122
+ device is None, fp8_scaling) # before loading
1123
+ why = why or options_refused(state_cache_bits, global_attn, state_cache_dir) # (state_cache_disk_gb: unused)
1124
+ if not why and quant == "fp8": # block FP8: a GPU with FP8 tensor cores, edge layers >= 0, loaded on the GPU
1125
+ why = fp8_refused() if device is None else None
1126
+ if not why and fp8_bf16_layers is not None and fp8_bf16_layers < 0:
1127
+ why = f"--fp8-bf16-layers {fp8_bf16_layers}: give 0 or more layers"
1128
+ if not why and quant_load != "gpu":
1129
+ why = "--quant-load cpu: basal-omni (Gemma 4) only; a Qwen3.5 model is quantised on the GPU"
1130
+ if why:
1131
+ raise ValueError(f"{model_dir}: {why}")
1132
+ cuda = torch.cuda.is_available() if device is None else device == "cuda"
1133
+ if cuda:
1134
+ torch.backends.cuda.enable_cudnn_sdp(False) # before capture: a captured graph keeps its attention kernel
1135
+ os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:2") # (GraphBackend.__init__)
1136
+ self.fp8_checkpoint = False
1137
+ # --mode fp8: FP8 weights at load time (Qwen35Graph._fp8), the first and the last fp8_bf16_layers bf16
1138
+ self.fp8_scaling = fp8_scaling_of_gdn(fp8_scaling) if quant == "fp8" else "row"
1139
+ self.fp8_bf16_layers = (2 if fp8_bf16_layers is None else fp8_bf16_layers) if quant == "fp8" else None
1140
+ self.graph_memory = graph_memory_bytes(graph_memory_gb)
1141
+ self.attn = set_attention(attn) # the causal plain rows; pass 2 runs SDPA with its mask
1142
+ # --batches compact (opt-in; auto keeps padded rows here): single prompts packed into one row, each starting on
1143
+ # a 64-token chunk (fla's), with FlashAttention 3's varlen kernel or torch's; without CUDA (tests) per prompt
1144
+ self.compact = batches == "compact"
1145
+ if self.compact and cuda:
1146
+ why = None if self.attn == "fa3" else torch_varlen_available(getattr(torch, dtype))
1147
+ if why and dtype != "float32":
1148
+ raise ValueError(f"{model_dir}: {compact_refused(why)}")
1149
+ if fla_varlen() is None:
1150
+ raise ValueError(f"{model_dir}: --batches compact needs flash-linear-attention's "
1151
+ "chunk_gated_delta_rule forward with chunk indices (flash-linear-attention 0.5)")
1152
+ if fla_conv1d() is None: # (compact rows call it with the chunk indices; there is no torch fallback)
1153
+ raise ValueError(f"{model_dir}: --batches compact needs flash-linear-attention's causal_conv1d "
1154
+ "(fla.modules.conv.causal_conv1d, flash-linear-attention 0.5.2)")
1155
+ # (fp32, which the FlashAttention kernels do not take: one SDPA call per prompt, no graph; the gates' fp32
1156
+ # rows)
1157
+ self.compact_kernel = ("sdpa per prompt" if dtype == "float32" else "fa3" if self.attn == "fa3"
1158
+ else "torch varlen")
1159
+ self.tok = AutoTokenizer.from_pretrained(model_dir)
1160
+ self.tok.pad_token = self.tok.pad_token or self.tok.eos_token
1161
+ self.model = AutoModelForCausalLM.from_pretrained(model_dir, dtype=getattr(torch, dtype))
1162
+ self.adapter_modules = adapter_module.merge_torch(self.model, adapter) if adapter else 0 # --adapter
1163
+ self.model = self.model.to("cuda" if cuda else device or "cpu").eval()
1164
+ self.dev = next(self.model.parameters()).device
1165
+ self.prefill = PREFILL
1166
+ self.net = Qwen35Graph(self.model, compile=compile and cuda, fp8=quant == "fp8",
1167
+ keep=self.fp8_bf16_layers or 0, scaling=self.fp8_scaling)
1168
+ self.conv_kernel = self.net.conv_kernel # (reported at start-up)
1169
+ self.fla_pinned = fla_pin() if cuda else 0 # (after Qwen35Graph imported fla's kernels)
1170
+ # (reported at start-up: pinned = this GPU's recorded configs, kept = an earlier start's, nothing timed either
1171
+ # way; timed = at their first launch, and kept for the next start)
1172
+ self.fla_configs = FLA_PINNED if cuda else None
1173
+ self.fwd, self.fwd_sfx = self.net.forward, self.net.forward_suffix
1174
+ if self.compact:
1175
+ if cuda:
1176
+ import fla.utils # fla keeps index tensors per argument identity: a graph's static cu would get stale
1177
+ fla.utils.FLA_DISABLE_TENSOR_CACHE = True # ones (only compact rows pass cu_seqlens to fla)
1178
+ self.net.fla_v = fla_varlen()
1179
+ self.net.varlen = (_varlen_sdpa if self.compact_kernel == "sdpa per prompt" else
1180
+ functools.partial(_varlen_attention, impl=self.compact_kernel))
1181
+ else:
1182
+ self.compact_kernel, self.net.varlen = "sdpa per prompt", _varlen_sdpa
1183
+ # --readout-layer on: the last layer after its attention at the readout positions only (an attention
1184
+ # layer: Qwen3.5's last is)
1185
+ self.readout_layer = readout_layer in ("on", "auto") and self.net.kinds[-1] == "full_attention"
1186
+ self.fwd_c = self.net.forward_compact
1187
+ self.merged, self.lean, self.flex = len(self.net.args), None, False
1188
+ self.shared = shared
1189
+ import threading
1190
+ self._launch = threading.Lock()
1191
+ self._wrows = {}
1192
+ if batches == "fine":
1193
+ self.BATCHES = self.FINE_BATCHES
1194
+ self._alloc_kv()
1195
+ # --state-cache-gb: roots cut at the state boundary, kept as full-state checkpoints (keys / values + states);
1196
+ # --prefix-cache: also the template prefixes of short single-prompt requests (GraphBackend's budget)
1197
+ self.prefix = bool(prefix) and shared
1198
+ gb = max(state_cache_gb, self.PREFIX_GB if self.prefix else 0)
1199
+ self.state_cache = StateCache(gb * 2 ** 30) if gb and shared else None
1200
+ self.template = [] # --template-prefix (with compact rows): [(start in template_kv, prefix ids, its row)]
1201
+ if self.compact and template in ("on", "auto"):
1202
+ self._template_prefixes(model_dir)
1203
+ self.counts = {} # forwards per kind: "plain" / "pass1" / "pass2", each "graph" or "eager" (gate scripts)
1204
+ self.pool = torch.cuda.graph_pool_handle() if cuda else None
1205
+ self.graphs = {}
1206
+ if warm and cuda:
1207
+ self.warm()
1208
+ self.one_forward = self.ONE_FORWARD
1209
+ self._shape_line()
1210
+
1211
+ # -- buffers -------------------------------------------------------------------------------------------------
1212
+ def _root_len(self, L):
1213
+ """The pass-2 root bucket of a pass-1 length."""
1214
+ return self._bucket(L, self.ROOT_LENS)
1215
+
1216
+ def _alloc_kv(self):
1217
+ """Pass-1 outputs of the plain graphs of at most TREE_ROWS[-1] rows (the others write nothing): per attention
1218
+ layer one flat buffer for keys and one for values, viewed per root bucket L2 as [rows, kv heads, L2, d] (a
1219
+ graph of length L <= L2 writes [:b, :, :L]); per Gated DeltaNet layer the recurrent states [rows, heads, dk,
1220
+ dv] (fp32) and convolution tails [rows, kernel - 1, channels]. Zeros, not empty: pass 2 reads the masked tail
1221
+ of a root's bucket too, and a masked NaN still poisons a readout (0 x NaN). With --graph-memory-gb the pass-2
1222
+ graphs captured follow it (_pin_memory)."""
1223
+ self._pin_memory()
1224
+ self.kv_shapes = self.net.kv_shapes
1225
+ self.kv_shape = self.kv_shapes[0]
1226
+ R = self.TREE_ROWS[-1]
1227
+ self._kv_n = max(b * self._root_len(L) for b, L in self.grid(self.PLAIN_LENS) if b <= R)
1228
+ dt, dev = self._dtype, self.dev
1229
+ if not self.shared:
1230
+ self._kv = self._st = None
1231
+ return
1232
+ self._kv = [tuple(torch.zeros(self._kv_n * H * D, dtype=dt, device=dev) for _ in "kv")
1233
+ for H, D in self.kv_shapes]
1234
+ self._st = [(torch.zeros((R, *self.net.state_shape), dtype=torch.float32, device=dev),
1235
+ torch.zeros((R, *self.net.tail_shape), dtype=dt, device=dev)) for _ in range(self.net.n_gdn)]
1236
+
1237
+ def _root_views(self, L2):
1238
+ """Per attention layer (K, V) [rows, kv heads, L2, d] over the flat buffers."""
1239
+ n = self._kv_n // L2
1240
+ return [(k[: n * H * L2 * D].view(n, H, L2, D), v[: n * H * L2 * D].view(n, H, L2, D))
1241
+ for (k, v), (H, D) in zip(self._kv, self.kv_shapes)]
1242
+
1243
+ def _outs(self, b, L):
1244
+ """The pass-1 outputs of b rows of length L (None, None for more than TREE_ROWS[-1] rows)."""
1245
+ if self._kv is None or b > self.TREE_ROWS[-1]:
1246
+ return None, None
1247
+ kv = [(k[:b, :, :L], v[:b, :, :L]) for k, v in self._root_views(self._root_len(L))]
1248
+ return kv, [(s[:b], c[:b]) for s, c in self._st]
1249
+
1250
+ def _fresh(self, b, L):
1251
+ """Pass-1 outputs for b roots of L tokens beyond the graphs (one uncaptured forward)."""
1252
+ dt, dev = self._dtype, self.dev
1253
+ kv = [tuple(torch.zeros((b, H, L, D), dtype=dt, device=dev) for _ in "kv") for H, D in self.kv_shapes]
1254
+ st = [(torch.zeros((b, *self.net.state_shape), dtype=torch.float32, device=dev),
1255
+ torch.zeros((b, *self.net.tail_shape), dtype=dt, device=dev)) for _ in range(self.net.n_gdn)]
1256
+ return kv, st
1257
+
1258
+ # -- graphs --------------------------------------------------------------------------------------------------
1259
+ def _graph(self, b, L):
1260
+ """Plain graph (b rows, length L): (graph, ids, real tokens per row, hidden states [b, L, D]); with at most
1261
+ TREE_ROWS[-1] rows it also writes the roots' keys, values and recurrent states (pass 1)."""
1262
+ key = ("p", b, L)
1263
+ if key in self.graphs:
1264
+ return self.graphs[key]
1265
+ ids = torch.full((b, L), self.tok.pad_token_id, dtype=torch.long, device=self.dev)
1266
+ lens = torch.full((b,), L, dtype=torch.long, device=self.dev)
1267
+ out = self._shared_out("plain", max(x * y for x, y in self.grid(self.PLAIN_LENS)) * self._hidden_size,
1268
+ self._dtype)[: b * L * self._hidden_size].view(b, L, -1)
1269
+ kv, st = self._outs(b, L)
1270
+ fwd = self.fwd
1271
+
1272
+ def plain(i, n):
1273
+ return _copy_same(out, fwd(i, n, kv, st))
1274
+ return self._capture(key, plain, ids, lens)
1275
+
1276
+ def _sfx_ok(self, b, S, L2):
1277
+ return b * S <= self.TOKEN_BUDGET and b * L2 <= self.PASS2_KEYS and self._kv_n // L2 >= 1
1278
+
1279
+ def _graph_sfx(self, b, S, L2):
1280
+ """Pass-2 graph (b leaf rows of S tokens over roots of bucket L2): (graph, ids, positions, root row of each
1281
+ row, root length of each row, hidden states [b, S, D])."""
1282
+ key = ("x", b, S, L2)
1283
+ if key in self.graphs:
1284
+ return self.graphs[key]
1285
+ dev = self.dev
1286
+ ids = torch.full((b, S), self.tok.pad_token_id, dtype=torch.long, device=dev)
1287
+ pos = torch.arange(L2, L2 + S, device=dev)[None].expand(b, S).contiguous()
1288
+ unit = torch.zeros(b, dtype=torch.long, device=dev)
1289
+ plen = torch.ones(b, dtype=torch.long, device=dev)
1290
+ top = max(x * y for x in self.LEAF_ROWS for y in self.LEAF_LENS for z in self.ROOT_LENS
1291
+ if self._sfx_ok(x, y, z))
1292
+ D = self._hidden_size
1293
+ out = self._shared_out("pass2", top * D, self._dtype)[: b * S * D].view(b, S, D)
1294
+ kv, st = self._root_views(L2), self._st
1295
+ sfx = self.fwd_sfx
1296
+
1297
+ def suffix(i, p, u, n):
1298
+ return _copy_same(out, sfx(i, p, u, n, kv, st))
1299
+ return self._capture(key, suffix, ids, pos, unit, plen)
1300
+
1301
+ # -- compact rows (--batches compact) ------------------------------------------------------------------------
1302
+ CHUNK = 64 # fla's chunk: every prompt of a compact row starts on a multiple of it, so a row of T tokens has T / 64
1303
+ # chunks whatever its prompts' lengths (fixed shapes for the graphs); GraphBackend's steps, in multiples of 64
1304
+ COMPACT_LENS = (list(range(64, 2048, 64)) + list(range(2048, 4096, 128)) + list(range(4096, 8192, 256))
1305
+ + list(range(8192, 12289, 512)))
1306
+ n_templates = 0
1307
+
1308
+ def _compact_graphs(self):
1309
+ """Whether compact rows run in CUDA graphs (a FlashAttention varlen kernel, which reads cu on the GPU)."""
1310
+ return self.pool is not None and self.compact_kernel in ("fa3", "torch varlen")
1311
+
1312
+ def _template_prefixes(self, model_dir):
1313
+ """--template-prefix: the tokens every prompt of a language starts with (GraphBackend._template_prefixes: chat
1314
+ template, system prompt and the user header up to the state, one token less) as full-state checkpoints,
1315
+ computed once: their keys / values in every attention layer (net.template_kv[layer] = (K, V) [prefix tokens
1316
+ of all languages, kv heads, d]) and their recurrent states and convolution tails (net.template_st[layer] =
1317
+ (states, tails) [languages + 1, ...], the last row zeros: a prompt without a template prefix). A compact
1318
+ prompt that starts with one runs only its own tokens from that checkpoint."""
1319
+ from .prompt import FORMATS, model_format, render
1320
+ fmt = model_format(model_dir)
1321
+ prefixes = []
1322
+ for lang, t in FORMATS[fmt]["templates"].items():
1323
+ head = t["user"].split("{state}")[0]
1324
+ state = "Stan klienta: zgłoszenie" if lang == "pl" else "Customer state: a request"
1325
+ text = render(self.tok, state, "Q?", ["a", "b"], lang, fmt)
1326
+ i = text.find(head + state)
1327
+ if i < 0:
1328
+ continue
1329
+ ids = self.tok(text[: i + len(head)], add_special_tokens=False).input_ids
1330
+ full = self.tok(text, add_special_tokens=False).input_ids
1331
+ n = len(ids) - 1
1332
+ while n and full[:n] != ids[:n]:
1333
+ n -= 1
1334
+ if n >= 2:
1335
+ prefixes.append(full[:n])
1336
+ self._set_templates(prefixes)
1337
+
1338
+ def _set_templates(self, prefixes):
1339
+ """The checkpoints of these template prefixes (token id lists), as _template_prefixes describes."""
1340
+ kvs, sts, a = [], [], 0
1341
+ for p in prefixes:
1342
+ kv, st = self._fresh(1, len(p))
1343
+ self.net.forward(self._to_dev(torch.tensor([list(p)])), self._to_dev(torch.tensor([len(p)])), kv, st)
1344
+ self.template.append((a, tuple(p), len(sts)))
1345
+ kvs.append(kv)
1346
+ sts.append(st)
1347
+ a += len(p)
1348
+ if not self.template:
1349
+ return
1350
+ self.template.sort(key=lambda x: -len(x[1])) # the longest match first
1351
+ self.template_tokens, self.template_max, self.n_templates = a, max(len(x[1]) for x in self.template), len(sts)
1352
+ self.net.template_kv = [tuple(torch.cat([kv[i][j][0].transpose(0, 1) for kv in kvs]).contiguous()
1353
+ for j in (0, 1)) for i in range(len(self.kv_shapes))]
1354
+ self.net.template_st = [tuple(torch.cat([st[i][j] for st in sts] + [torch.zeros_like(sts[0][i][j])])
1355
+ for j in (0, 1)) for i in range(self.net.n_gdn)]
1356
+
1357
+ def _graph_c(self, T):
1358
+ """Compact graph of T tokens (a multiple of CHUNK): (graph, ids, positions, cumulative counts, chunk indices,
1359
+ [template rows, key counts, key gather,] [readout positions,] hidden states)."""
1360
+ key = ("c", T)
1361
+ if key in self.graphs:
1362
+ return self.graphs[key]
1363
+ dev, NS = self.dev, self.COMPACT_SEQS + 1 # (the padding after the last prompt is one more prompt)
1364
+ ids = torch.full((1, T), self.tok.pad_token_id, dtype=torch.long, device=dev)
1365
+ pos = torch.arange(T, device=dev)[None].contiguous()
1366
+ cu = torch.full((NS + 1,), T, dtype=torch.int32, device=dev)
1367
+ cu[0] = 0
1368
+ ci = torch.stack([torch.zeros(T // self.CHUNK, dtype=torch.int32, device=dev),
1369
+ torch.arange(T // self.CHUNK, dtype=torch.int32, device=dev)], 1).contiguous()
1370
+ static = [ids, pos, cu, ci]
1371
+ if self.template:
1372
+ gather = torch.zeros(T + self.COMPACT_SEQS * self.template_max, dtype=torch.long, device=dev)
1373
+ gather[:T] = self.template_tokens + torch.arange(T, device=dev)
1374
+ static += [torch.full((NS,), self.n_templates, dtype=torch.long, device=dev), cu.clone(), gather]
1375
+ ro = None
1376
+ if self.readout_layer:
1377
+ ro = torch.zeros(self.COMPACT_SEQS, dtype=torch.long, device=dev)
1378
+ static.append(ro)
1379
+ D = self._hidden_size
1380
+ R = self.COMPACT_SEQS if ro is not None else T
1381
+ out = self._shared_out("compact", max(self.COMPACT_LENS) * D, self._dtype)[: R * D].view(1, R, D)
1382
+ fwd, tmpl = self.fwd_c, bool(self.template)
1383
+
1384
+ def compact(*a):
1385
+ tm = a[4:7] if tmpl else (None,) * 3
1386
+ return _copy_same(out, fwd(*a[:4], *tm, ro=a[-1] if ro is not None else None))
1387
+ return self._capture(key, compact, *static)
1388
+
1389
+ def warm(self):
1390
+ """Capture every plain graph of the grid and, with `shared`, the pass-2 graphs; warmed up in grid order and
1391
+ captured the largest first (_capture_deferred). Then the uncaptured shapes beyond the largest graph run once
1392
+ (their kernels compile at first use)."""
1393
+ self._deferred = {}
1394
+ if self.compact and self._compact_graphs(): # plain graphs then only for pass 1 of branched units
1395
+ for T in self.COMPACT_LENS:
1396
+ self._graph_c(T)
1397
+ for b, L in self.grid(self.PLAIN_LENS):
1398
+ if not self.compact or not self._compact_graphs() or self.shared and b <= self.TREE_ROWS[-1]:
1399
+ self._graph(b, L)
1400
+ if self.shared:
1401
+ for L2 in self.ROOT_LENS:
1402
+ for S in self.LEAF_LENS:
1403
+ for b in self.LEAF_ROWS:
1404
+ if self._sfx_ok(b, S, L2):
1405
+ self._graph_sfx(b, S, L2)
1406
+ self._capture_deferred()
1407
+ self._warmed = True
1408
+ pad = self.tok.pad_token_id
1409
+ for n in (self.PLAIN_LENS[-1] + 64, self.PLAIN_LENS[-1] + 65): # Triton specialises lengths divisible by 16
1410
+ if self.model.config.max_position_embeddings < n + 8:
1411
+ break
1412
+ root = [pad] * n
1413
+ self.run_shared([([root + [5]], [[10, 11]])] + ([([root + [5, 6], root + [6, 5]], [[10, 11], [10, 11]])]
1414
+ if self.shared else []))
1415
+ torch.cuda.empty_cache()
1416
+
1417
+ # -- forwards ------------------------------------------------------------------------------------------------
1418
+ def _count(self, kind, graph, shape=None):
1419
+ k = f"{kind} {'graph' if graph else 'eager'}"
1420
+ self.counts[k] = self.counts.get(k, 0) + 1
1421
+ if shape is not None and not graph:
1422
+ self.counts.setdefault(f"{kind} eager shapes", set()).add(shape)
1423
+
1424
+ def _rows_in(self, rows, L, b=None):
1425
+ """Token lists -> ids [b, L] padded on the right, real tokens per row [b] (padding rows: 0)."""
1426
+ b = b or len(rows)
1427
+ ids = np.full((b, L), self.tok.pad_token_id, dtype=np.int64)
1428
+ lens = np.zeros(b, dtype=np.int64)
1429
+ for r, t in enumerate(rows):
1430
+ ids[r, : len(t)] = t
1431
+ lens[r] = len(t)
1432
+ return torch.from_numpy(ids), torch.from_numpy(lens)
1433
+
1434
+ def _plain_hidden(self, packs, idx):
1435
+ """Single-prompt units -> hidden states at their readout positions: a plain graph, or one uncaptured forward
1436
+ beyond the largest graph (or without CUDA graphs)."""
1437
+ n = max(len(packs[k][0]) for k in idx)
1438
+ rows = [packs[k][0] for k in idx]
1439
+ self._count("plain", n <= self.PLAIN_LENS[-1] and self.pool is not None)
1440
+ if n > self.PLAIN_LENS[-1] or self.pool is None:
1441
+ ids, lens = self._rows_in(rows, n)
1442
+ h = self.fwd(self._to_dev(ids), self._to_dev(lens))
1443
+ else:
1444
+ L, b = self._bucket(n, self.PLAIN_LENS), self._bucket(len(idx), self.BATCHES)
1445
+ g, s_ids, s_lens, h = self._graph(b, L)
1446
+ ids, lens = self._rows_in(rows, L, b)
1447
+ s_ids.copy_(self._to_dev(ids), non_blocking=True)
1448
+ s_lens.copy_(self._to_dev(lens), non_blocking=True)
1449
+ g.replay()
1450
+ r = [j for j, k in enumerate(idx) for _ in packs[k][3]]
1451
+ c = [i for k in idx for i in packs[k][3]]
1452
+ return h[self._to_dev(torch.tensor(r)), self._to_dev(torch.tensor(c))]
1453
+
1454
+ def _forwards(self, units, cached=()):
1455
+ """GraphBackend._forwards; with compact rows the single prompts go into compact rows (shortest first, up to
1456
+ COMPACT_SEQS prompts and COMPACT_LENS[-1] tokens, each prompt counted to its next CHUNK), and only a prompt
1457
+ beyond the largest compact graph runs alone."""
1458
+ if not self.compact:
1459
+ return GraphBackend._forwards(self, units, cached)
1460
+ packs = [u[0] for u in units]
1461
+ out, cur, tot = [], [], 0
1462
+ for k in sorted((k for k, pk in enumerate(packs) if len(pk[4]) == 1), key=lambda k: len(packs[k][0])):
1463
+ n = -(-len(packs[k][0]) // self.CHUNK) * self.CHUNK
1464
+ if n > self.COMPACT_LENS[-1]:
1465
+ out.append(([k], "plain"))
1466
+ continue
1467
+ if cur and (len(cur) == self.COMPACT_SEQS or tot + n > self.COMPACT_LENS[-1]):
1468
+ out.append((cur, "compact"))
1469
+ cur, tot = [], 0
1470
+ cur.append(k)
1471
+ tot += n
1472
+ out += [(cur, "compact")] if cur else []
1473
+ for kind in ("tree", "cached"): # (GraphBackend._forwards)
1474
+ tree = [k for k, pk in enumerate(packs) if len(pk[4]) > 1 and (k in cached) == (kind == "cached")]
1475
+ roots = [packs[k][2].index(1) for k in tree]
1476
+ rest = [len(packs[k][0]) - r for k, r in zip(tree, roots)]
1477
+ out += [([tree[j] for j in idx], kind) for idx in self._chunks(roots, self.PLAIN_LENS, rest,
1478
+ self.TREE_ROWS[-1])]
1479
+ return out
1480
+
1481
+ def _compact_hidden(self, packs, idx):
1482
+ """Single-prompt units packed into one compact row, each from a multiple of CHUNK (the rest of its chunk and the
1483
+ tail of the row: padding after its tokens, read by nobody), and from its template prefix's checkpoint when it
1484
+ starts with one (only its own tokens run) -> hidden states at their readout positions."""
1485
+ C, NS, pad = self.CHUNK, self.COMPACT_SEQS + 1, self.tok.pad_token_id
1486
+ rows = [] # per prompt: own tokens, positions, readout columns, template row (n_templates: none), prefix start
1487
+ for k in idx:
1488
+ t, pp, _, last, _ = packs[k]
1489
+ hit = next(((a, len(p), r) for a, p, r in self.template if len(t) > len(p) and tuple(t[: len(p)]) == p),
1490
+ (0, 0, self.n_templates))
1491
+ P = hit[1]
1492
+ rows.append((t[P:], pp[P:], [i - P for i in last], hit))
1493
+ n = [-(-len(r[0]) // C) * C for r in rows]
1494
+ T = self._bucket(sum(n), self.COMPACT_LENS)
1495
+ h_ids = np.full(T, pad, dtype=np.int64)
1496
+ h_pos = np.zeros(T, dtype=np.int64)
1497
+ h_cu = np.full(NS + 1, T, dtype=np.int32)
1498
+ h_tix = np.full(NS, self.n_templates, dtype=np.int64)
1499
+ h_ro = np.zeros(self.COMPACT_SEQS, dtype=np.int64)
1500
+ h_cuk = np.zeros(NS + 1, dtype=np.int32)
1501
+ h_g = np.zeros(T + self.COMPACT_SEQS * max(1, getattr(self, "template_max", 0)), dtype=np.int64)
1502
+ cols, sel, o, ok = [], [], 0, 0 # (ok: keys so far, with template prefixes)
1503
+ for j, ((t, pp, last, (a, P, r)), m) in enumerate(zip(rows, n)):
1504
+ h_ids[o: o + len(t)] = t
1505
+ h_pos[o: o + len(t)] = pp
1506
+ h_pos[o + len(t): o + m] = pp[-1] + 1 + np.arange(m - len(t))
1507
+ h_cu[j], h_tix[j], h_ro[j] = o, r, o + len(t) - 1
1508
+ cols += [o + i for i in last]
1509
+ sel += [j] * len(last)
1510
+ h_cuk[j] = ok
1511
+ h_g[ok: ok + P] = np.arange(a, a + P)
1512
+ h_g[ok + P: ok + P + m] = getattr(self, "template_tokens", 0) + np.arange(o, o + m)
1513
+ ok += P + m
1514
+ o += m
1515
+ h_cu[len(idx)], h_cuk[len(idx)] = o, ok # the padding: one more prompt from position 0, without a template
1516
+ h_pos[o:] = np.arange(T - o)
1517
+ h_g[ok: ok + T - o] = getattr(self, "template_tokens", 0) + np.arange(o, T)
1518
+ h_cuk[len(idx) + 1:] = ok + T - o
1519
+ spans = np.diff(h_cu) // C
1520
+ h_ci = np.stack([np.repeat(np.arange(NS, dtype=np.int32), spans),
1521
+ np.concatenate([np.arange(x, dtype=np.int32) for x in spans])], 1)
1522
+ host = [h_ids[None], h_pos[None], h_cu, h_ci] + ([h_tix, h_cuk, h_g] if self.template else [])
1523
+ host += [h_ro] if self.readout_layer else []
1524
+ graph = self._compact_graphs()
1525
+ self._count("compact", graph)
1526
+ if graph:
1527
+ g, *static, out = self._graph_c(T)
1528
+ for dst, src in zip(static, host):
1529
+ dst.copy_(self._to_dev(src), non_blocking=True)
1530
+ g.replay()
1531
+ else: # no graph (fp32, the tests): the forward itself; without CUDA no chunk indices (one prompt at a time)
1532
+ dev = [self._to_dev(torch.from_numpy(np.ascontiguousarray(x))) for x in host]
1533
+ tm = dev[4:7] if self.template else [None] * 3
1534
+ out = self.fwd_c(*dev[:3], dev[3] if self.dev.type == "cuda" else None, *tm,
1535
+ ro=dev[-1] if self.readout_layer else None)
1536
+ if self.readout_layer:
1537
+ return out[0, self._to_dev(torch.tensor(sel))]
1538
+ return out[0, self._to_dev(torch.tensor(cols))]
1539
+
1540
+ @staticmethod
1541
+ def _leaves(pack, P):
1542
+ """The trie of a packed unit below its root (P tokens) as one row per leaf block: the token indices of the
1543
+ blocks on the path from the root to the leaf -> (rows, readouts: per prompt (row, column), row None for a
1544
+ readout inside the root, column then its index)."""
1545
+ t, pp, sg, last, par = pack
1546
+ start, end = {}, {}
1547
+ for i, s in enumerate(sg):
1548
+ start.setdefault(s, i)
1549
+ end[s] = i + 1
1550
+ kids = [[] for _ in par]
1551
+ for blk, p in enumerate(par):
1552
+ if p >= 0:
1553
+ kids[p].append(blk)
1554
+ rows, first = [], {} # first: block -> (the first row through it, its offset there)
1555
+ for leaf in (x for x in range(1, len(par)) if not kids[x]): # depth-first order: parents before children
1556
+ path, p = [], leaf
1557
+ while p > 0:
1558
+ path.append(p)
1559
+ p = par[p]
1560
+ ix = []
1561
+ for blk in reversed(path):
1562
+ first.setdefault(blk, (len(rows), len(ix)))
1563
+ ix += range(start[blk], end[blk])
1564
+ rows.append(ix)
1565
+ reads = [(None, i) if i < P else (first[sg[i]][0], first[sg[i]][1] + i - start[sg[i]]) for i in last]
1566
+ return rows, reads
1567
+
1568
+ CONTINUE_MAX = 8192 # most new tokens a cached state is continued by (beyond: the whole state runs again)
1569
+
1570
+ def _extend_states(self, units, keys, hits):
1571
+ """A request state that begins with a whole cached one (a growing agent trace or chat history): its new tokens
1572
+ continue the cached checkpoint (Qwen35Graph.forward_continue: the attention layers over the cached keys and
1573
+ values, the Gated DeltaNet layers from the cached states and tails), and the extended checkpoint replaces the
1574
+ old entry and serves as a hit. A state that differs inside the cached tokens runs again: a recurrent state
1575
+ cannot be cut there."""
1576
+ if not keys or self.state_cache is None:
1577
+ return
1578
+ na = len(self.kv_shapes)
1579
+ for k, key in enumerate(keys):
1580
+ if key is None or k in hits:
1581
+ continue
1582
+ pk = units[k][0]
1583
+ root = list(pk[0][: pk[2].index(1)])
1584
+ found = self.state_cache.longest(root)
1585
+ if found is None:
1586
+ continue
1587
+ old, e, m, n = found
1588
+ if old == key: # cached by an earlier unit of this call
1589
+ hits[k] = e
1590
+ continue
1591
+ if m != n or n >= len(root) or len(root) - n > self.CONTINUE_MAX:
1592
+ continue
1593
+ T, dt, dev = len(root) - n, self._dtype, self.dev
1594
+ kv = [tuple(torch.empty((1, H, T, D), dtype=dt, device=dev) for _ in "kv") for H, D in self.kv_shapes]
1595
+ st = [(torch.empty((1, *self.net.state_shape), dtype=torch.float32, device=dev),
1596
+ torch.empty((1, *self.net.tail_shape), dtype=dt, device=dev)) for _ in range(self.net.n_gdn)]
1597
+ with self._launch:
1598
+ self.net.forward_continue(self._to_dev(torch.tensor([root[n:]])), n,
1599
+ [(ke[None], ve[None]) for ke, ve in e[:na]],
1600
+ [(se[None], ce[None]) for se, ce in e[na:]], kv, st)
1601
+ new = ([(torch.cat([ke, kn[0]], 1), torch.cat([ve, vn[0]], 1)) for (ke, ve), (kn, vn) in zip(e[:na], kv)]
1602
+ + [(s[0], c[0]) for s, c in st])
1603
+ self.state_cache.put(key, new, tokens=root, replaces=old)
1604
+ hits[k] = new
1605
+
1606
+ @staticmethod
1607
+ def _entry(kv, st, r, p):
1608
+ """The state-cache entry of root row r (p tokens): per attention layer (K, V) [kv heads, p, d], then per Gated
1609
+ DeltaNet layer (recurrent state, convolution tail) after its last token."""
1610
+ return ([(k[r, :, :p].clone(), v[r, :, :p].clone()) for k, v in kv]
1611
+ + [(s[r].clone(), c[r].clone()) for s, c in st])
1612
+
1613
+ @staticmethod
1614
+ def _load(kv, st, hits, P):
1615
+ """Cached entries into root rows 0.. of the pass-1 outputs, where pass 1 would have written them."""
1616
+ n = len(kv)
1617
+ for r, (e, p) in enumerate(zip(hits, P)):
1618
+ for (kb, vb), (ke, ve) in zip(kv, e[:n]):
1619
+ kb[r, :, :p].copy_(ke, non_blocking=True)
1620
+ vb[r, :, :p].copy_(ve, non_blocking=True)
1621
+ for (sb, cb), (se, ce) in zip(st, e[n:]):
1622
+ sb[r].copy_(se, non_blocking=True)
1623
+ cb[r].copy_(ce, non_blocking=True)
1624
+
1625
+ @torch.no_grad()
1626
+ def _tree_hidden(self, packs, idx, keys=None, hits=None):
1627
+ """Branched units -> hidden states at their readout positions. Pass 1: the roots in a plain graph that also
1628
+ writes their keys, values and recurrent states (beyond the largest graph: one uncaptured forward into fresh
1629
+ buffers). Pass 2: one row per leaf of each unit's trie, over its root, in pass-2 graphs of up to LEAF_ROWS[-1]
1630
+ rows (uncaptured beyond them). keys / hits (--state-cache-gb): per unit, the state-cache key of its root and its
1631
+ cached entry; when every root is cached and no prompt ends inside one, pass 1 is skipped (_load); roots computed
1632
+ here are stored (_entry)."""
1633
+ P = [packs[k][2].index(1) for k in idx] # block 0 (the root) comes first and is contiguous
1634
+ b = len(idx)
1635
+ roots = [packs[k][0][:p] for k, p in zip(idx, P)]
1636
+ keys, hits = keys or [None] * b, hits or [None] * b
1637
+ leaves = [self._leaves(packs[k], p) for k, p in zip(idx, P)]
1638
+ # a prompt that is a root itself is read out in pass 1, so its unit needs pass 1
1639
+ cached = all(e is not None for e in hits) and all(q is not None for _, reads in leaves for q, _ in reads)
1640
+ row = list(range(b)) # each unit's root row; cached: units over the same root (a template prefix) share one
1641
+ if cached:
1642
+ first = {}
1643
+ row = [first.setdefault(key, len(first)) for key in keys]
1644
+ captured = self.pool is not None and max(P) <= self.PLAIN_LENS[-1] and max(row) < self.TREE_ROWS[-1]
1645
+ h1 = None
1646
+ if cached:
1647
+ self._count("pass1 cached", captured)
1648
+ if captured:
1649
+ L2 = self._root_len(self._bucket(max(P), self.PLAIN_LENS))
1650
+ kv, st = self._root_views(L2), self._st
1651
+ else:
1652
+ L2 = max(P)
1653
+ kv, st = self._fresh(max(row) + 1, L2)
1654
+ one = [row.index(r) for r in range(max(row) + 1)] # a unit of each root row
1655
+ self._load(kv, st, [hits[u] for u in one], [P[u] for u in one])
1656
+ elif captured:
1657
+ self._count("pass1", captured)
1658
+ L, B = self._bucket(max(P), self.PLAIN_LENS), self._bucket(b, self.BATCHES)
1659
+ L2 = self._root_len(L)
1660
+ g, s_ids, s_lens, h1 = self._graph(B, L)
1661
+ ids, lens = self._rows_in(roots, L, B)
1662
+ s_ids.copy_(self._to_dev(ids), non_blocking=True)
1663
+ s_lens.copy_(self._to_dev(lens), non_blocking=True)
1664
+ g.replay()
1665
+ kv, st = self._root_views(L2), self._st
1666
+ else:
1667
+ self._count("pass1", captured)
1668
+ L2 = max(P)
1669
+ kv, st = self._fresh(b, L2)
1670
+ ids, lens = self._rows_in(roots, L2)
1671
+ h1 = self.fwd(self._to_dev(ids), self._to_dev(lens), kv, st)
1672
+ if self.state_cache is not None and not cached: # the roots computed here, as full-state checkpoints
1673
+ for r, key in enumerate(keys):
1674
+ if key is not None and hits[r] is None:
1675
+ self.state_cache.put(key, self._entry(kv, st, r, P[r]), tokens=roots[r])
1676
+ rows, sel = [], [] # rows: (unit, token indices); sel: per readout (pass, row, column), in unit order
1677
+ for r, (leaf, reads) in enumerate(leaves):
1678
+ sel += [(1, r, c) if q is None else (2, len(rows) + q, c) for q, c in reads]
1679
+ rows += [(r, ix) for ix in leaf]
1680
+ width = h1.shape[-1] if h1 is not None else self._hidden_size
1681
+ out = torch.empty((len(sel), width), dtype=self._dtype if h1 is None else h1.dtype, device=self.dev)
1682
+ j1 = [n for n, x in enumerate(sel) if x[0] == 1]
1683
+ if j1:
1684
+ out[self._to_dev(torch.tensor(j1))] = h1[self._to_dev(torch.tensor([sel[n][1] for n in j1])),
1685
+ self._to_dev(torch.tensor([sel[n][2] for n in j1]))]
1686
+ for part in self._parts([len(ix) for _, ix in rows], L2): # leaf rows by length, within the budgets
1687
+ n = len(rows[part[-1]][1])
1688
+ S = next((x for x in self.LEAF_LENS if n <= x), None)
1689
+ Bp = self._bucket(len(part), self.LEAF_ROWS)
1690
+ graph = None # captured at start-up while memory allowed (_capture_deferred); without warm(), as first used
1691
+ if captured and S is not None and self._sfx_ok(Bp, S, L2):
1692
+ graph = self.graphs.get(("x", Bp, S, L2)) if self._warmed else self._graph_sfx(Bp, S, L2)
1693
+ self._count("pass2", graph is not None, (len(part), n, L2))
1694
+ if graph is None: # bucketed rows and lengths: the shapes fla's kernels were tuned and compiled for
1695
+ S = -(-n // self.SUFFIX_EAGER) * self.SUFFIX_EAGER
1696
+ ids2 = np.full((Bp, S), self.tok.pad_token_id, dtype=np.int64)
1697
+ pos2 = np.tile(np.arange(L2, L2 + S, dtype=np.int64), (Bp, 1))
1698
+ unit2 = np.zeros(Bp, dtype=np.int64)
1699
+ plen2 = np.ones(Bp, dtype=np.int64)
1700
+ for j, q in enumerate(part):
1701
+ r, ix = rows[q]
1702
+ t, pp = packs[idx[r]][0], packs[idx[r]][1]
1703
+ m = len(ix)
1704
+ ids2[j, :m] = [t[i] for i in ix]
1705
+ pos2[j, :m] = [pp[i] for i in ix]
1706
+ pos2[j, m:] = pp[ix[-1]] + 1 + np.arange(S - m)
1707
+ unit2[j], plen2[j] = row[r], P[r]
1708
+ if graph is not None:
1709
+ g2, s_ids, s_pos, s_unit, s_plen, h2 = graph
1710
+ for dst, src in ((s_ids, ids2), (s_pos, pos2), (s_unit, unit2), (s_plen, plen2)):
1711
+ dst.copy_(self._to_dev(src), non_blocking=True)
1712
+ g2.replay()
1713
+ else:
1714
+ h2 = self.fwd_sfx(self._to_dev(ids2), self._to_dev(pos2), self._to_dev(unit2), self._to_dev(plen2),
1715
+ kv, st)
1716
+ at = {q: j for j, q in enumerate(part)}
1717
+ j2 = [n for n, x in enumerate(sel) if x[0] == 2 and x[1] in at]
1718
+ if j2: # read out before the next replay overwrites the shared output
1719
+ out[self._to_dev(torch.tensor(j2))] = h2[self._to_dev(torch.tensor([at[sel[n][1]] for n in j2])),
1720
+ self._to_dev(torch.tensor([sel[n][2] for n in j2]))]
1721
+ return out
1722
+
1723
+ def _parts(self, lens, L2):
1724
+ """Leaf rows (their lengths) -> pass-2 forwards: sorted by length, each part at most LEAF_ROWS[-1] rows, rows x
1725
+ root bucket within PASS2_KEYS, and (bucketed) rows x length within TOKEN_BUDGET unless a row is alone."""
1726
+ per = min(self.LEAF_ROWS[-1], max(1, self.PASS2_KEYS // L2))
1727
+ out, cur = [], []
1728
+ for q in sorted(range(len(lens)), key=lens.__getitem__):
1729
+ S = next((x for x in self.LEAF_LENS if lens[q] <= x), -(-lens[q] // self.SUFFIX_EAGER) * self.SUFFIX_EAGER)
1730
+ if cur and (len(cur) == per or self._bucket(len(cur) + 1, self.LEAF_ROWS) * S > self.TOKEN_BUDGET):
1731
+ out.append(cur)
1732
+ cur = []
1733
+ cur.append(q)
1734
+ return out + ([cur] if cur else [])
1735
+
1736
+ def _long_net(self, between):
1737
+ """The forward of the long lane: the same layers and weights, uncompiled (the long lane's thread runs it while
1738
+ the main lane's graphs replay), between(i) called before layer i."""
1739
+ net = copy.copy(self.net)
1740
+ net.f, net.f8, net.between = self.net.f_eager, self.net.f8_eager, between
1741
+ return net
1742
+
1743
+ @torch.no_grad()
1744
+ def _long_hidden(self, pack, key=None, hit=None, between=None):
1745
+ """One unit of the long lane (GraphBackend.run_long) -> hidden states at its readout positions, uncompiled and
1746
+ one layer at a time over fresh buffers: a single prompt as one row; a branched unit's root as one row that
1747
+ writes its keys, values and recurrent states (or its state-cache checkpoint), stored when keyed, then one row
1748
+ per leaf from them. The main lane's static buffers and graphs are never touched."""
1749
+ net, dev = self._long_net(between), self._to_dev
1750
+ t, pp, sg, last, par = pack
1751
+ if len(par) == 1:
1752
+ return net.forward(dev(torch.tensor([t])))[0, last]
1753
+ P = sg.index(1) # block 0 (the root) comes first and is contiguous
1754
+ rows, reads = self._leaves(pack, P)
1755
+ h1, na = None, len(self.kv_shapes)
1756
+ if hit is not None and all(q is not None for q, _ in reads): # (a prompt that is the root needs pass 1)
1757
+ kv = [(k[None], v[None]) for k, v in hit[:na]]
1758
+ st = [(s[None], c[None]) for s, c in hit[na:]]
1759
+ else:
1760
+ kv, st = self._fresh(1, P)
1761
+ h1 = net.forward(dev(torch.tensor([t[:P]])), dev(torch.tensor([P])), kv, st)[0]
1762
+ if key is not None and self.state_cache is not None:
1763
+ self.state_cache.put(key, self._entry(kv, st, 0, P), tokens=t[:P])
1764
+ S = max(map(len, rows))
1765
+ ids = np.full((len(rows), S), self.tok.pad_token_id, dtype=np.int64)
1766
+ pos = np.zeros((len(rows), S), dtype=np.int64)
1767
+ for j, ix in enumerate(rows):
1768
+ ids[j, : len(ix)] = [t[i] for i in ix]
1769
+ pos[j, : len(ix)] = [pp[i] for i in ix]
1770
+ pos[j, len(ix):] = pp[ix[-1]] + 1 + np.arange(S - len(ix))
1771
+ unit, plen = torch.zeros(len(rows), dtype=torch.long), torch.full((len(rows),), P, dtype=torch.long)
1772
+ h2 = net.forward_suffix(dev(torch.from_numpy(ids)), dev(torch.from_numpy(pos)), dev(unit), dev(plen), kv, st)
1773
+ return torch.stack([h1[c] if q is None else h2[q, c] for q, c in reads])
1774
+
1775
+
1776
+ class GDNMPSBackend(GDNGraphBackend, MPSBackend):
1777
+ """--mode mps for Qwen3.5 models, refused in 2.5 (engine.gdn_mps_refused: too slow without a Metal kernel);
1778
+ with BASAL_EXPERIMENTAL_GDN_MPS=1, MPSBackend(model_dir) of such a model builds this one: GDNGraphBackend's two
1779
+ passes (the recurrent state carried from each root into one row per leaf) on the Apple GPU through PyTorch MPS, or
1780
+ on the CPU, without CUDA graphs or compilation; the Gated DeltaNet layers run transformers' torch kernels, as
1781
+ --mode eager does there."""
1782
+
1783
+ KIND = "mps" # one call at a time, no early readouts (engine.KIND_CAPS)
1784
+
1785
+ def __init__(self, model_dir, dtype="bfloat16", shared=True, device=None, adapter=None):
1786
+ mps = getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available()
1787
+ GDNGraphBackend.__init__(self, model_dir, dtype, shared=shared, warm=False, device=device or (
1788
+ "mps" if mps else "cpu"), adapter=adapter)
1789
+
1790
+ run = GraphBackend.run
1791
+ run_shared = GraphBackend.run_shared
1792
+ _oversize = GraphBackend._oversize