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
@@ -0,0 +1,1057 @@
1
+ """Custom pure-Metal FlashAttention & Split-KV Readout kernels for Apple Silicon MLX (basal 3.0.1).
2
+
3
+ Designed for native NHD layout `[T, H, D]` (zero `[B, H, L, D]` transposes) and Single-Pass Flat SOAM
4
+ (zero `[T, T]` dense boolean masks):
5
+ - `flat_soam_attn(q, k, v, grp, seg, blk_bounds, scale, two_way=False)`:
6
+ Tiled `simdgroup_matrix` FlashAttention-2 (`BQ=32, BK=32, D=64/128`, 4 simdgroups = 128 threads)
7
+ with O(1) block-sparse skipping of non-matching groups / sibling suffix branches and an unmasked
8
+ fast-path for all-visible prefix/causal tiles. Supports causal, flat SOAM prefix-tree, and
9
+ `two_way` / `prefix_bidir` attention.
10
+ - `readout_attn(q, k, v, ro_idx, grp, seg, scale, two_way=False)`:
11
+ Two-stage Split-KV FP32-accumulated readout attention for layer `N-1` (`R` readout queries over
12
+ `T` keys). Saturates all Apple Silicon GPU cores even for `R=1..12` and eliminates MLX's GQA-6/8
13
+ BF16 small-Q vector-SDPA precision loss.
14
+ """
15
+ from functools import lru_cache
16
+
17
+ import mlx.core as mx
18
+
19
+ _METAL_HEADER = """#include <metal_simdgroup_matrix>
20
+ using namespace metal;
21
+ """
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Probe whether this Apple GPU supports `simdgroup_matrix<bfloat, 8, 8>` (M3/M4/M5)
25
+ # vs needing float32 tiles fallback (M1/M2).
26
+ # ---------------------------------------------------------------------------
27
+
28
+
29
+ @lru_cache(maxsize=1)
30
+ def _supports_sg_bfloat() -> bool:
31
+ src = """
32
+ simdgroup_matrix<bfloat, 8, 8> A;
33
+ simdgroup_matrix<bfloat, 8, 8> B;
34
+ simdgroup_matrix<float, 8, 8> C = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
35
+ simdgroup_load(A, a, 8);
36
+ simdgroup_load(B, b, 8);
37
+ simdgroup_multiply_accumulate(C, A, B, C);
38
+ simdgroup_store(C, out, 8);
39
+ """
40
+ try:
41
+ k = mx.fast.metal_kernel(
42
+ name="basal_probe_sg_bf16",
43
+ input_names=["a", "b"],
44
+ output_names=["out"],
45
+ source=src,
46
+ header=_METAL_HEADER,
47
+ )
48
+ a = mx.ones((8, 8), dtype=mx.bfloat16)
49
+ b = mx.ones((8, 8), dtype=mx.bfloat16)
50
+ (o,) = k(inputs=[a, b], grid=(32, 1, 1), threadgroup=(32, 1, 1),
51
+ output_shapes=[(8, 8)], output_dtypes=[mx.float32])
52
+ mx.eval(o)
53
+ return abs(float(o[0, 0].item()) - 8.0) < 1e-2
54
+ except Exception:
55
+ return False
56
+
57
+
58
+ def _mat_dtype(dt):
59
+ if dt == mx.bfloat16:
60
+ return mx.bfloat16 if _supports_sg_bfloat() else mx.float32
61
+ if dt == mx.float16:
62
+ return mx.float16
63
+ return mx.float32
64
+
65
+
66
+ @lru_cache(maxsize=16)
67
+ def _scale_scalar(scale: float):
68
+ return mx.array([scale], dtype=mx.float32)
69
+
70
+
71
+ # ---------------------------------------------------------------------------
72
+ # 1. Tiled simdgroup_matrix Flat SOAM FlashAttention (`BQ=32, BK=32`)
73
+ # ---------------------------------------------------------------------------
74
+
75
+ _FLAT_SOAM_ATTN_SRC = r"""
76
+ constexpr uint BQ = 32;
77
+ constexpr uint BK = 32;
78
+ constexpr uint D_TILES = D / 8;
79
+
80
+ uint qb = threadgroup_position_in_grid.x;
81
+ uint hq = threadgroup_position_in_grid.y;
82
+ uint tid = thread_position_in_threadgroup.x;
83
+ uint sg = simdgroup_index_in_threadgroup; // 0..3 (4 simdgroups)
84
+ uint lane = thread_index_in_simdgroup; // 0..31
85
+
86
+ uint T_len = uint(q_shape[0]);
87
+ uint q_base = qb * BQ;
88
+ if (q_base >= T_len) return;
89
+
90
+ uint hkv = hq / (H / HKV);
91
+ float scale = scale_arr[0];
92
+
93
+ // Shared memory: KV_smem [32, D] in MAT_T (reused for Q load, K, V, and O output staging),
94
+ // S_smem [32, 32] float32, P_smem [32, 32] MAT_T, plus tiny metadata arrays.
95
+ threadgroup MAT_T KV_smem[BQ * D];
96
+ threadgroup float S_smem[BQ * BK];
97
+ threadgroup MAT_T P_smem[BQ * BK];
98
+ threadgroup float Diag_smem[4 * 64]; // 8x8 diagonal tile per simdgroup (1 KB total)
99
+ threadgroup int tg_gq[BQ];
100
+ threadgroup int tg_sq[BQ];
101
+ threadgroup int tg_gk[BK];
102
+ threadgroup int tg_sk[BK];
103
+
104
+ // 1. Load Q metadata and Q tile [BQ, D] cooperatively.
105
+ if (tid < BQ) {
106
+ uint qi = q_base + tid;
107
+ tg_gq[tid] = (qi < T_len) ? grp[qi] : -1;
108
+ tg_sq[tid] = (qi < T_len) ? seg[qi] : -1;
109
+ }
110
+ for (uint idx = tid; idx < BQ * D; idx += 128) {
111
+ uint r = idx / D;
112
+ uint d = idx - r * D;
113
+ uint qi = q_base + r;
114
+ KV_smem[idx] = (qi < T_len) ? MAT_T(q[(qi * H + hq) * D + d]) : MAT_T(0.0f);
115
+ }
116
+ threadgroup_barrier(mem_flags::mem_threadgroup);
117
+
118
+ // Load each simdgroup's 8xD slice of Q into registers and zero O accumulators.
119
+ simdgroup_matrix<MAT_T, 8, 8> Q_reg[D_TILES];
120
+ simdgroup_matrix<float, 8, 8> O_reg[D_TILES];
121
+ for (uint dt = 0; dt < D_TILES; ++dt) {
122
+ simdgroup_load(Q_reg[dt], KV_smem + (sg * 8) * D + dt * 8, D);
123
+ O_reg[dt] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
124
+ }
125
+ threadgroup_barrier(mem_flags::mem_threadgroup);
126
+
127
+ // Per-row softmax state: within each simdgroup (32 lanes, 8 rows), 4 lanes own 1 row (8 cols each).
128
+ uint r_in_sg = lane >> 2; // 0..7
129
+ uint col_grp = lane & 3; // 0..3 -> handles keys col_grp*8 .. col_grp*8 + 7
130
+ uint r_in_blk = sg * 8 + r_in_sg;
131
+ uint qi_mine = q_base + r_in_blk;
132
+ int gq_mine = tg_gq[r_in_blk];
133
+ int sq_mine = tg_sq[r_in_blk];
134
+
135
+ float m_i = -INFINITY;
136
+ float l_i = 0.0f;
137
+
138
+ // Quick summary of Q block for O(1) K-block skip & all-visible checks.
139
+ int q_grp0 = tg_gq[0];
140
+ int q_seg0 = tg_sq[0];
141
+ bool q_uniform_grp = (q_grp0 >= 0);
142
+ bool q_uniform_seg = true;
143
+ for (uint r = 1; r < BQ; ++r) {
144
+ if (q_base + r < T_len) {
145
+ if (tg_gq[r] != q_grp0) q_uniform_grp = false;
146
+ if (tg_sq[r] != q_seg0) q_uniform_seg = false;
147
+ }
148
+ }
149
+
150
+ uint kb_start = uint(blk_bounds[qb * 2 + 0]);
151
+ uint kb_end = uint(blk_bounds[qb * 2 + 1]);
152
+
153
+ for (uint kb = kb_start; kb < kb_end; ++kb) {
154
+ uint k_base = kb * BK;
155
+
156
+ // Load K metadata first to test block-level sparsity before touching K/V DRAM.
157
+ if (tid < BK) {
158
+ uint kj = k_base + tid;
159
+ tg_gk[tid] = (kj < T_len) ? grp[kj] : -1;
160
+ tg_sk[tid] = (kj < T_len) ? seg[kj] : -1;
161
+ }
162
+ threadgroup_barrier(mem_flags::mem_threadgroup);
163
+
164
+ // Block-level sparsity classification.
165
+ int k_grp0 = tg_gk[0];
166
+ int k_seg0 = tg_sk[0];
167
+ bool k_uniform_grp = (k_grp0 >= 0);
168
+ bool k_uniform_seg = true;
169
+ bool k_full = (k_base + BK <= T_len);
170
+ for (uint c = 1; c < BK; ++c) {
171
+ if (k_base + c < T_len) {
172
+ if (tg_gk[c] != k_grp0) k_uniform_grp = false;
173
+ if (tg_sk[c] != k_seg0) k_uniform_seg = false;
174
+ }
175
+ }
176
+
177
+ // Fast skip: uniform Q & K groups that don't match, OR sibling suffix branches.
178
+ if (q_uniform_grp && k_uniform_grp) {
179
+ if (q_grp0 != k_grp0) continue;
180
+ if (q_uniform_seg && k_uniform_seg && k_seg0 > 0 && q_seg0 != k_seg0) {
181
+ // Q is prefix (0) or another suffix branch (!= k_seg0); cannot see suffix k_seg0.
182
+ continue;
183
+ }
184
+ }
185
+ // Causal skip when !HAS_TW and k_base > q_base + BQ - 1.
186
+ if (!HAS_TW && k_base >= q_base + BQ) break;
187
+
188
+ bool all_visible = false;
189
+ if (k_full && (q_base + BQ <= T_len) && q_uniform_grp && k_uniform_grp && (q_grp0 == k_grp0)
190
+ && k_uniform_seg && (k_seg0 == 0)) {
191
+ if (k_base + BK <= q_base) {
192
+ all_visible = true; // Strictly past shared prefix tokens.
193
+ } else if (HAS_TW && q_uniform_seg && (q_seg0 == 0)) {
194
+ all_visible = true; // Bidirectional prefix-to-prefix tile.
195
+ }
196
+ }
197
+
198
+ // 2. Load K tile [BK, D] into KV_smem.
199
+ for (uint idx = tid; idx < BK * D; idx += 128) {
200
+ uint r = idx / D;
201
+ uint d = idx - r * D;
202
+ uint kj = k_base + r;
203
+ KV_smem[idx] = (kj < T_len) ? MAT_T(k[(kj * HKV + hkv) * D + d]) : MAT_T(0.0f);
204
+ }
205
+ threadgroup_barrier(mem_flags::mem_threadgroup);
206
+
207
+ // 3. Compute S[8, 32] = Q[8, D] @ K[32, D]^T per simdgroup via 4 tiles of 8x8.
208
+ for (uint kt = 0; kt < 4; ++kt) {
209
+ simdgroup_matrix<float, 8, 8> S_acc = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
210
+ for (uint dt = 0; dt < D_TILES; ++dt) {
211
+ simdgroup_matrix<MAT_T, 8, 8> K_reg;
212
+ // Load K[kt*8..+7, dt*8..+7] transposed -> 8(d) x 8(k).
213
+ simdgroup_load(K_reg, KV_smem + (kt * 8) * D + dt * 8, D, ulong2(0, 0), true);
214
+ simdgroup_multiply_accumulate(S_acc, Q_reg[dt], K_reg, S_acc);
215
+ }
216
+ simdgroup_store(S_acc, S_smem + (sg * 8) * BK + kt * 8, BK);
217
+ }
218
+ // Simdgroup-local visibility guaranteed because S_smem[sg*8..] is private to simdgroup sg,
219
+ // wait: synchronize lanes within the simdgroup before reading S_smem!
220
+ simdgroup_barrier(mem_flags::mem_threadgroup);
221
+
222
+ // 4. Online softmax over S_smem[r_in_blk, 0..31] (4 lanes per row, 8 keys per lane).
223
+ float s_vals[8];
224
+ float row_max = -INFINITY;
225
+ uint s_row_base = r_in_blk * BK + col_grp * 8;
226
+ if (all_visible) {
227
+ for (uint j = 0; j < 8; ++j) {
228
+ float v = S_smem[s_row_base + j] * scale;
229
+ s_vals[j] = v;
230
+ row_max = metal::max(row_max, v);
231
+ }
232
+ } else {
233
+ for (uint j = 0; j < 8; ++j) {
234
+ uint kj = k_base + col_grp * 8 + j;
235
+ int gk = tg_gk[col_grp * 8 + j];
236
+ int sk = tg_sk[col_grp * 8 + j];
237
+ bool vis = (qi_mine < T_len) && (kj < T_len) && (gq_mine >= 0) && (gk == gq_mine);
238
+ if (vis) {
239
+ if (HAS_TW && sq_mine == 0 && sk == 0) {
240
+ vis = true;
241
+ } else {
242
+ vis = (kj <= qi_mine) && (sk == 0 || sk == sq_mine);
243
+ }
244
+ }
245
+ float v = vis ? (S_smem[s_row_base + j] * scale) : -INFINITY;
246
+ s_vals[j] = v;
247
+ row_max = metal::max(row_max, v);
248
+ }
249
+ }
250
+ // Reduce row_max across the 4 lanes owning this row.
251
+ row_max = metal::max(row_max, simd_shuffle_xor(row_max, 1));
252
+ row_max = metal::max(row_max, simd_shuffle_xor(row_max, 2));
253
+
254
+ float m_new = metal::max(m_i, row_max);
255
+ float alpha = (m_new > -INFINITY && m_i > -INFINITY) ? metal::exp(m_i - m_new) : 0.0f;
256
+ // If this block had zero visible keys for this row (row_max == -inf), keep alpha = 1.0!
257
+ if (row_max == -INFINITY) {
258
+ alpha = 1.0f;
259
+ m_new = m_i;
260
+ }
261
+
262
+ float row_sum = 0.0f;
263
+ for (uint j = 0; j < 8; ++j) {
264
+ float p = (s_vals[j] > -INFINITY) ? metal::exp(s_vals[j] - m_new) : 0.0f;
265
+ P_smem[s_row_base + j] = MAT_T(p);
266
+ row_sum += p;
267
+ }
268
+ row_sum += simd_shuffle_xor(row_sum, 1);
269
+ row_sum += simd_shuffle_xor(row_sum, 2);
270
+
271
+ // Check if any of the 8 rows in this simdgroup needs O rescaling (alpha != 1.0f).
272
+ bool need_scale = simd_any(alpha != 1.0f);
273
+ if (need_scale) {
274
+ // Write 8x8 diagonal matrix for this simdgroup into Diag_smem[sg*64 .. +63].
275
+ uint d_base = sg * 64;
276
+ // Clear 64 floats with 32 lanes (2 per lane), then write 8 diagonal entries.
277
+ Diag_smem[d_base + lane] = 0.0f;
278
+ Diag_smem[d_base + lane + 32] = 0.0f;
279
+ simdgroup_barrier(mem_flags::mem_threadgroup);
280
+ if (col_grp == 0) {
281
+ Diag_smem[d_base + r_in_sg * 8 + r_in_sg] = alpha;
282
+ }
283
+ simdgroup_barrier(mem_flags::mem_threadgroup);
284
+ simdgroup_matrix<float, 8, 8> Alpha_mat;
285
+ simdgroup_load(Alpha_mat, Diag_smem + d_base, 8);
286
+ for (uint dt = 0; dt < D_TILES; ++dt) {
287
+ simdgroup_multiply(O_reg[dt], Alpha_mat, O_reg[dt]);
288
+ }
289
+ }
290
+ l_i = l_i * alpha + row_sum;
291
+ m_i = m_new;
292
+
293
+ // 5. Load V tile [BK, D] into KV_smem (barrier ensures all simdgroups finished reading K).
294
+ threadgroup_barrier(mem_flags::mem_threadgroup);
295
+ for (uint idx = tid; idx < BK * D; idx += 128) {
296
+ uint r = idx / D;
297
+ uint d = idx - r * D;
298
+ uint kj = k_base + r;
299
+ KV_smem[idx] = (kj < T_len) ? MAT_T(v[(kj * HKV + hkv) * D + d]) : MAT_T(0.0f);
300
+ }
301
+ threadgroup_barrier(mem_flags::mem_threadgroup);
302
+
303
+ // 6. Accumulate O[8, D] += P[8, 32] @ V[32, D].
304
+ for (uint kt = 0; kt < 4; ++kt) {
305
+ simdgroup_matrix<MAT_T, 8, 8> P_reg;
306
+ simdgroup_load(P_reg, P_smem + (sg * 8) * BK + kt * 8, BK);
307
+ for (uint dt = 0; dt < D_TILES; ++dt) {
308
+ simdgroup_matrix<MAT_T, 8, 8> V_reg;
309
+ simdgroup_load(V_reg, KV_smem + (kt * 8) * D + dt * 8, D);
310
+ simdgroup_multiply_accumulate(O_reg[dt], P_reg, V_reg, O_reg[dt]);
311
+ }
312
+ }
313
+ threadgroup_barrier(mem_flags::mem_threadgroup);
314
+ }
315
+
316
+ // 7. Normalize O by 1/l_i via 8x8 diagonal multiply and store to global memory via S_smem staging.
317
+ {
318
+ uint d_base = sg * 64;
319
+ Diag_smem[d_base + lane] = 0.0f;
320
+ Diag_smem[d_base + lane + 32] = 0.0f;
321
+ simdgroup_barrier(mem_flags::mem_threadgroup);
322
+ if (col_grp == 0) {
323
+ Diag_smem[d_base + r_in_sg * 8 + r_in_sg] = (l_i > 0.0f) ? (1.0f / l_i) : 0.0f;
324
+ }
325
+ simdgroup_barrier(mem_flags::mem_threadgroup);
326
+ simdgroup_matrix<float, 8, 8> InvL;
327
+ simdgroup_load(InvL, Diag_smem + d_base, 8);
328
+ for (uint dt = 0; dt < D_TILES; ++dt) {
329
+ simdgroup_multiply(O_reg[dt], InvL, O_reg[dt]);
330
+ }
331
+ }
332
+
333
+ // Stage O_reg [32, D] into S_smem in chunks of 32 columns (4 tiles of 8x8 = 32 cols -> 32x32 floats = S_smem!).
334
+ for (uint d_chunk = 0; d_chunk < D; d_chunk += 32) {
335
+ uint dt0 = d_chunk / 8;
336
+ for (uint t4 = 0; t4 < 4; ++t4) {
337
+ simdgroup_store(O_reg[dt0 + t4], S_smem + (sg * 8) * 32 + t4 * 8, 32);
338
+ }
339
+ threadgroup_barrier(mem_flags::mem_threadgroup);
340
+ for (uint idx = tid; idx < BQ * 32; idx += 128) {
341
+ uint r = idx / 32;
342
+ uint c = idx - r * 32;
343
+ uint qi = q_base + r;
344
+ if (qi < T_len) {
345
+ out[(qi * H + hq) * D + d_chunk + c] = T(S_smem[idx]);
346
+ }
347
+ }
348
+ threadgroup_barrier(mem_flags::mem_threadgroup);
349
+ }
350
+ """
351
+
352
+
353
+ @lru_cache(maxsize=4)
354
+ def _flat_soam_kernel():
355
+ return mx.fast.metal_kernel(
356
+ name="basal_flat_soam_attn",
357
+ input_names=["q", "k", "v", "grp", "seg", "blk_bounds", "scale_arr"],
358
+ output_names=["out"],
359
+ source=_FLAT_SOAM_ATTN_SRC,
360
+ header=_METAL_HEADER,
361
+ ensure_row_contiguous=True,
362
+ compile_options={"math_mode": "safe"},
363
+ )
364
+
365
+
366
+ def compute_block_bounds(grp_list: list[int], seg_list: list[int], two_way: bool = False) -> mx.array:
367
+ """Precompute `[n_qblk, 2]` int32 K-block `[kb_start, kb_end)` bounds for each 32-token Q-block."""
368
+ T = len(grp_list)
369
+ n_blk = (T + 31) // 32
370
+ # Group spans in token indices.
371
+ g_min, g_max = {}, {}
372
+ for i, g in enumerate(grp_list):
373
+ if g < 0:
374
+ continue
375
+ if g not in g_min:
376
+ g_min[g] = i
377
+ g_max[g] = i
378
+ bounds = []
379
+ for qb in range(n_blk):
380
+ q0 = qb * 32
381
+ q1 = min(T, q0 + 32)
382
+ gs = [grp_list[i] for i in range(q0, q1) if grp_list[i] >= 0]
383
+ if not gs:
384
+ bounds.append([0, 0])
385
+ continue
386
+ k0 = min(g_min[g] for g in gs)
387
+ if two_way and any(seg_list[i] == 0 for i in range(q0, q1) if grp_list[i] >= 0):
388
+ k1 = max(g_max[g] for g in gs) + 1
389
+ else:
390
+ k1 = q1
391
+ bounds.append([k0 // 32, (k1 + 31) // 32])
392
+ return mx.array(bounds, dtype=mx.int32)
393
+
394
+
395
+ def flat_soam_attn(
396
+ q: mx.array,
397
+ k: mx.array,
398
+ v: mx.array,
399
+ grp: mx.array,
400
+ seg: mx.array,
401
+ blk_bounds: mx.array,
402
+ scale: float,
403
+ two_way: bool = False,
404
+ ) -> mx.array:
405
+ """Tiled `simdgroup_matrix` Flat SOAM FlashAttention in native NHD layout `[T, H, D]`."""
406
+ T, H, D = q.shape
407
+ Hkv = k.shape[1]
408
+ n_qblk = (T + 31) // 32
409
+ mat_t = _mat_dtype(q.dtype)
410
+ (out,) = _flat_soam_kernel()(
411
+ inputs=[q, k, v, grp.astype(mx.int32), seg.astype(mx.int32), blk_bounds.astype(mx.int32), _scale_scalar(scale)],
412
+ template=[("T", q.dtype), ("MAT_T", mat_t), ("H", H), ("HKV", Hkv), ("D", D), ("HAS_TW", int(two_way))],
413
+ grid=(128 * n_qblk, H, 1),
414
+ threadgroup=(128, 1, 1),
415
+ output_shapes=[(T, H, D)],
416
+ output_dtypes=[q.dtype],
417
+ )
418
+ return out
419
+
420
+
421
+ # ---------------------------------------------------------------------------
422
+ # 2. Split-KV FP32-Accumulated Readout Attention for Layer N-1 (`R` queries over `T` keys)
423
+ # ---------------------------------------------------------------------------
424
+
425
+ _READOUT_SPLITK_SRC = r"""
426
+ constexpr uint ELEMS = D / 32; // 4 for D=128, 2 for D=64
427
+ uint split_id = threadgroup_position_in_grid.x;
428
+ uint r = threadgroup_position_in_grid.y;
429
+ uint hq = threadgroup_position_in_grid.z;
430
+ uint sg = simdgroup_index_in_threadgroup; // 0..3
431
+ uint lane = thread_index_in_simdgroup; // 0..31
432
+
433
+ uint T_len = uint(k_shape[0]);
434
+ uint n_splits = uint(o_part_shape_in[0]);
435
+ uint hkv = hq / (H / HKV);
436
+ float scale = scale_arr[0];
437
+
438
+ uint qi = uint(ro_idx[r]);
439
+ int gq = grp[qi];
440
+ int sq = seg[qi];
441
+
442
+ // Key span assigned to this split.
443
+ uint chunk = (T_len + n_splits - 1) / n_splits;
444
+ uint k_start = split_id * chunk;
445
+ uint k_end = metal::min(T_len, k_start + chunk);
446
+ if (!HAS_TW || sq != 0) {
447
+ k_end = metal::min(k_end, qi + 1);
448
+ }
449
+
450
+ // Load Q[r, hq, d] into registers (ELEMS floats per lane).
451
+ float q_reg[ELEMS];
452
+ uint q_base = (r * H + hq) * D;
453
+ for (uint e = 0; e < ELEMS; ++e) {
454
+ q_reg[e] = float(q[q_base + lane * ELEMS + e]);
455
+ }
456
+
457
+ float m_s = -INFINITY;
458
+ float l_s = 0.0f;
459
+ float o_s[ELEMS];
460
+ for (uint e = 0; e < ELEMS; ++e) o_s[e] = 0.0f;
461
+
462
+ // Each of the 4 simdgroups strides keys by 4.
463
+ for (uint kj = k_start + sg; kj < k_end; kj += 4) {
464
+ int gk = grp[kj];
465
+ if (gq < 0 || gk != gq) continue;
466
+ int sk = seg[kj];
467
+ if (!(HAS_TW && sq == 0 && sk == 0)) {
468
+ if (kj > qi || (sk != 0 && sk != sq)) continue;
469
+ }
470
+ uint kv_base = (kj * HKV + hkv) * D + lane * ELEMS;
471
+ float dot = 0.0f;
472
+ for (uint e = 0; e < ELEMS; ++e) {
473
+ dot += q_reg[e] * float(k[kv_base + e]);
474
+ }
475
+ dot = simd_sum(dot) * scale;
476
+
477
+ float m_new = metal::max(m_s, dot);
478
+ float alpha = (m_s > -INFINITY) ? metal::exp(m_s - m_new) : 0.0f;
479
+ float p = metal::exp(dot - m_new);
480
+ for (uint e = 0; e < ELEMS; ++e) {
481
+ o_s[e] = o_s[e] * alpha + p * float(v[kv_base + e]);
482
+ }
483
+ l_s = l_s * alpha + p;
484
+ m_s = m_new;
485
+ }
486
+
487
+ // Merge the 4 simdgroups in threadgroup memory.
488
+ threadgroup float tg_m[4];
489
+ threadgroup float tg_l[4];
490
+ threadgroup float tg_o[4 * D];
491
+ if (lane == 0) {
492
+ tg_m[sg] = m_s;
493
+ tg_l[sg] = l_s;
494
+ }
495
+ for (uint e = 0; e < ELEMS; ++e) {
496
+ tg_o[sg * D + lane * ELEMS + e] = o_s[e];
497
+ }
498
+ threadgroup_barrier(mem_flags::mem_threadgroup);
499
+
500
+ if (sg == 0) {
501
+ float m_all = metal::max(metal::max(tg_m[0], tg_m[1]), metal::max(tg_m[2], tg_m[3]));
502
+ float l_all = 0.0f;
503
+ float acc[ELEMS];
504
+ for (uint e = 0; e < ELEMS; ++e) acc[e] = 0.0f;
505
+ if (m_all > -INFINITY) {
506
+ for (uint s = 0; s < 4; ++s) {
507
+ if (tg_m[s] > -INFINITY) {
508
+ float w = metal::exp(tg_m[s] - m_all);
509
+ l_all += tg_l[s] * w;
510
+ for (uint e = 0; e < ELEMS; ++e) {
511
+ acc[e] += tg_o[s * D + lane * ELEMS + e] * w;
512
+ }
513
+ }
514
+ }
515
+ }
516
+ uint out_idx = (r * H + hq) * n_splits + split_id;
517
+ if (lane == 0) {
518
+ lse_part[out_idx] = (l_all > 0.0f) ? (m_all + metal::log(l_all)) : -INFINITY;
519
+ }
520
+ float inv_l = (l_all > 0.0f) ? (1.0f / l_all) : 0.0f;
521
+ for (uint e = 0; e < ELEMS; ++e) {
522
+ o_part[out_idx * D + lane * ELEMS + e] = acc[e] * inv_l;
523
+ }
524
+ }
525
+ """
526
+
527
+ _READOUT_REDUCE_SRC = r"""
528
+ uint d = thread_position_in_grid.x;
529
+ uint r = thread_position_in_grid.y;
530
+ uint hq = thread_position_in_grid.z;
531
+ if (d >= D) return;
532
+
533
+ uint n_splits = uint(lse_part_shape[2]);
534
+ uint base = (r * H + hq) * n_splits;
535
+ float m_all = -INFINITY;
536
+ for (uint s = 0; s < n_splits; ++s) {
537
+ m_all = metal::max(m_all, lse_part[base + s]);
538
+ }
539
+ float denom = 0.0f;
540
+ float acc = 0.0f;
541
+ if (m_all > -INFINITY) {
542
+ for (uint s = 0; s < n_splits; ++s) {
543
+ float ls = lse_part[base + s];
544
+ if (ls > -INFINITY) {
545
+ float w = metal::exp(ls - m_all);
546
+ denom += w;
547
+ acc += w * o_part[(base + s) * D + d];
548
+ }
549
+ }
550
+ }
551
+ out[(r * H + hq) * D + d] = T((denom > 0.0f) ? (acc / denom) : 0.0f);
552
+ """
553
+
554
+
555
+ @lru_cache(maxsize=4)
556
+ def _readout_splitk_kernel():
557
+ return mx.fast.metal_kernel(
558
+ name="basal_readout_splitk",
559
+ input_names=["q", "k", "v", "ro_idx", "grp", "seg", "o_part_shape_in", "scale_arr"],
560
+ output_names=["o_part", "lse_part"],
561
+ source=_READOUT_SPLITK_SRC,
562
+ ensure_row_contiguous=True,
563
+ compile_options={"math_mode": "safe"},
564
+ )
565
+
566
+
567
+ @lru_cache(maxsize=4)
568
+ def _readout_reduce_kernel():
569
+ return mx.fast.metal_kernel(
570
+ name="basal_readout_reduce",
571
+ input_names=["o_part", "lse_part"],
572
+ output_names=["out"],
573
+ source=_READOUT_REDUCE_SRC,
574
+ ensure_row_contiguous=True,
575
+ compile_options={"math_mode": "safe"},
576
+ )
577
+
578
+
579
+ @lru_cache(maxsize=16)
580
+ def _int_scalar(n: int):
581
+ return mx.array([n], dtype=mx.int32)
582
+
583
+
584
+ def readout_attn(
585
+ q: mx.array,
586
+ k: mx.array,
587
+ v: mx.array,
588
+ ro_idx: mx.array,
589
+ grp: mx.array,
590
+ seg: mx.array,
591
+ scale: float,
592
+ two_way: bool = False,
593
+ ) -> mx.array:
594
+ """Split-KV FP32-accumulated readout attention: `q[R, H, D]` over `k,v[T, Hkv, D]` -> `[R, H, D]`."""
595
+ R, H, D = q.shape
596
+ T, Hkv, _ = k.shape
597
+ # Choose splits so total threadgroups saturate Apple GPU cores without wasting reduction work.
598
+ if T >= 1024:
599
+ n_splits = 16
600
+ elif T >= 256:
601
+ n_splits = 8
602
+ elif T >= 64:
603
+ n_splits = 4
604
+ else:
605
+ n_splits = 1
606
+
607
+ o_part, lse_part = _readout_splitk_kernel()(
608
+ inputs=[q, k, v, ro_idx.astype(mx.int32), grp.astype(mx.int32), seg.astype(mx.int32),
609
+ _int_scalar(n_splits), _scale_scalar(scale)],
610
+ template=[("H", H), ("HKV", Hkv), ("D", D), ("HAS_TW", int(two_way))],
611
+ grid=(128 * n_splits, R, H),
612
+ threadgroup=(128, 1, 1),
613
+ output_shapes=[(R, H, n_splits, D), (R, H, n_splits)],
614
+ output_dtypes=[mx.float32, mx.float32],
615
+ )
616
+ if n_splits == 1:
617
+ return o_part[:, :, 0, :].astype(q.dtype)
618
+
619
+ tg_x = min(D, 128)
620
+ (out,) = _readout_reduce_kernel()(
621
+ inputs=[o_part, lse_part],
622
+ template=[("T", q.dtype), ("H", H), ("D", D)],
623
+ grid=(D, R, H),
624
+ threadgroup=(tg_x, 1, 1),
625
+ output_shapes=[(R, H, D)],
626
+ output_dtypes=[q.dtype],
627
+ )
628
+ return out
629
+
630
+
631
+ # ---------------------------------------------------------------------------
632
+ # 3. Ultra-fast Single-Group Suffix-Tree Attention (`suffix_soam_attn`)
633
+ # Pairs with Apple Steel FlashAttention on prefix [0..P) for hybrid Single-Pass Flat SOAM:
634
+ # 8 simdgroups (256 threads) = 8 suffix queries sharing K/V loads in threadgroup memory
635
+ # over the unmasked prefix [0..P), then each simdgroup attends directly to its own short
636
+ # suffix branch [b_start..qi] with ZERO sibling-branch work and ZERO dense [T, T] mask!
637
+ # ---------------------------------------------------------------------------
638
+
639
+ _SUFFIX_SOAM_SRC = r"""
640
+ constexpr uint NSG = 8; // 8 simdgroups = 256 threads -> 8 suffix queries share K/V
641
+ constexpr uint BK = 16; // 16 keys per shared tile (BK * D * 2 * 2 = 8 KB for D=128)
642
+ constexpr uint ELEMS = D / 32; // 4 for D=128, 2 for D=64
643
+
644
+ uint qb = threadgroup_position_in_grid.x;
645
+ uint hq = threadgroup_position_in_grid.y;
646
+ uint tid = thread_position_in_threadgroup.x;
647
+ uint sg = simdgroup_index_in_threadgroup; // 0..7
648
+ uint lane = thread_index_in_simdgroup; // 0..31
649
+
650
+ uint S_len = uint(q_sfx_shape[0]);
651
+ uint P_len = uint(p_len_arr[0]);
652
+ uint hkv = hq / (H / HKV);
653
+ float scale = scale_arr[0];
654
+
655
+ uint s_idx = qb * NSG + sg;
656
+ bool valid_q = (s_idx < S_len);
657
+
658
+ // Load Q[s_idx, hq, d] into registers (only ELEMS floats per lane!).
659
+ float q_reg[ELEMS];
660
+ if (valid_q) {
661
+ uint q_base = (s_idx * H + hq) * D + lane * ELEMS;
662
+ for (uint e = 0; e < ELEMS; ++e) {
663
+ q_reg[e] = float(q_sfx[q_base + e]);
664
+ }
665
+ } else {
666
+ for (uint e = 0; e < ELEMS; ++e) q_reg[e] = 0.0f;
667
+ }
668
+
669
+ float m_i = -INFINITY;
670
+ float l_i = 0.0f;
671
+ float o_reg[ELEMS];
672
+ for (uint e = 0; e < ELEMS; ++e) o_reg[e] = 0.0f;
673
+
674
+ threadgroup T K_smem[BK * D];
675
+ threadgroup T V_smem[BK * D];
676
+
677
+ // Phase 1: Attend to ALL shared prefix tokens [0 .. P_len) — 100% unmasked, 8x K/V reuse!
678
+ for (uint k_base = 0; k_base < P_len; k_base += BK) {
679
+ uint k_lim = metal::min(BK, P_len - k_base);
680
+ for (uint idx = tid; idx < BK * D; idx += 256) {
681
+ uint r = idx / D;
682
+ uint d = idx - r * D;
683
+ if (r < k_lim) {
684
+ uint kv_off = ((k_base + r) * HKV + hkv) * D + d;
685
+ K_smem[idx] = k_all[kv_off];
686
+ V_smem[idx] = v_all[kv_off];
687
+ }
688
+ }
689
+ threadgroup_barrier(mem_flags::mem_threadgroup);
690
+
691
+ if (valid_q) {
692
+ for (uint j = 0; j < k_lim; ++j) {
693
+ uint sm_off = j * D + lane * ELEMS;
694
+ float dot = 0.0f;
695
+ for (uint e = 0; e < ELEMS; ++e) {
696
+ dot += q_reg[e] * float(K_smem[sm_off + e]);
697
+ }
698
+ dot = simd_sum(dot) * scale;
699
+ float m_new = metal::max(m_i, dot);
700
+ float alpha = (m_i > -INFINITY) ? metal::exp(m_i - m_new) : 0.0f;
701
+ float p = metal::exp(dot - m_new);
702
+ for (uint e = 0; e < ELEMS; ++e) {
703
+ o_reg[e] = o_reg[e] * alpha + p * float(V_smem[sm_off + e]);
704
+ }
705
+ l_i = l_i * alpha + p;
706
+ m_i = m_new;
707
+ }
708
+ }
709
+ threadgroup_barrier(mem_flags::mem_threadgroup);
710
+ }
711
+
712
+ // Phase 2: Attend to OWN suffix branch tokens [b_start .. P_len + s_idx] — zero barriers, zero sibling reads!
713
+ if (valid_q) {
714
+ uint qi = P_len + s_idx;
715
+ uint b_start = uint(sfx_bstart[s_idx]);
716
+ for (uint kj = b_start; kj <= qi; ++kj) {
717
+ uint kv_off = (kj * HKV + hkv) * D + lane * ELEMS;
718
+ float dot = 0.0f;
719
+ for (uint e = 0; e < ELEMS; ++e) {
720
+ dot += q_reg[e] * float(k_all[kv_off + e]);
721
+ }
722
+ dot = simd_sum(dot) * scale;
723
+ float m_new = metal::max(m_i, dot);
724
+ float alpha = (m_i > -INFINITY) ? metal::exp(m_i - m_new) : 0.0f;
725
+ float p = metal::exp(dot - m_new);
726
+ for (uint e = 0; e < ELEMS; ++e) {
727
+ o_reg[e] = o_reg[e] * alpha + p * float(v_all[kv_off + e]);
728
+ }
729
+ l_i = l_i * alpha + p;
730
+ m_i = m_new;
731
+ }
732
+ float inv_l = (l_i > 0.0f) ? (1.0f / l_i) : 0.0f;
733
+ uint out_base = (s_idx * H + hq) * D + lane * ELEMS;
734
+ for (uint e = 0; e < ELEMS; ++e) {
735
+ out[out_base + e] = T(o_reg[e] * inv_l);
736
+ }
737
+ }
738
+ """
739
+
740
+
741
+ @lru_cache(maxsize=4)
742
+ def _suffix_soam_kernel():
743
+ return mx.fast.metal_kernel(
744
+ name="basal_suffix_soam_attn",
745
+ input_names=["q_sfx", "k_all", "v_all", "sfx_bstart", "p_len_arr", "scale_arr"],
746
+ output_names=["out"],
747
+ source=_SUFFIX_SOAM_SRC,
748
+ ensure_row_contiguous=True,
749
+ compile_options={"math_mode": "safe"},
750
+ )
751
+
752
+
753
+ def suffix_soam_attn(
754
+ q_sfx: mx.array,
755
+ k_all: mx.array,
756
+ v_all: mx.array,
757
+ sfx_bstart: mx.array,
758
+ p_len: int,
759
+ scale: float,
760
+ ) -> mx.array:
761
+ """Single-group suffix attention over unmasked prefix `[0..p_len)` + own branch `[bstart..qi]` in NHD."""
762
+ S, H, D = q_sfx.shape
763
+ Hkv = k_all.shape[1]
764
+ n_qblk = (S + 7) // 8
765
+ (out,) = _suffix_soam_kernel()(
766
+ inputs=[q_sfx, k_all, v_all, sfx_bstart.astype(mx.int32), _int_scalar(int(p_len)), _scale_scalar(scale)],
767
+ template=[("T", q_sfx.dtype), ("H", H), ("HKV", Hkv), ("D", D)],
768
+ grid=(256 * n_qblk, H, 1),
769
+ threadgroup=(256, 1, 1),
770
+ output_shapes=[(S, H, D)],
771
+ output_dtypes=[q_sfx.dtype],
772
+ )
773
+ return out
774
+
775
+
776
+ # ---------------------------------------------------------------------------
777
+ # 4. Zero-Copy Shared-Prefix Past-KV Attention (`past_kv_attn` & `past_kv_readout_attn`)
778
+ # Reads shared `past_k, past_v` [1, Hkv, P, D] directly across ALL B suffix rows and GQA heads
779
+ # with ZERO `mx.repeat` and ZERO `mx.concatenate`, plus causal local `cur_k, cur_v` [B, S, Hkv, D]!
780
+ # Also runs in exact FP32 accumulation (eliminating MLX's GQA-6/8 BF16 vector-SDPA precision bug).
781
+ # ---------------------------------------------------------------------------
782
+
783
+ _PAST_KV_ATTN_SRC = r"""
784
+ // Flatten all (b, s) queries across B suffix rows: Q_total = B * S_len.
785
+ // 8 simdgroups (256 threads) = 8 queries sharing the exact same past_k/past_v[hkv] tiles in threadgroup mem!
786
+ constexpr uint NSG = 8;
787
+ constexpr uint BK = 16;
788
+ constexpr uint ELEMS = D / 32;
789
+
790
+ uint qb = threadgroup_position_in_grid.x;
791
+ uint hq = threadgroup_position_in_grid.y;
792
+ uint tid = thread_position_in_threadgroup.x;
793
+ uint sg = simdgroup_index_in_threadgroup;
794
+ uint lane = thread_index_in_simdgroup;
795
+
796
+ uint B_sz = uint(q_cur_shape[0]);
797
+ uint S_len = uint(q_cur_shape[1]);
798
+ uint P_len = uint(past_k_shape[2]); // past_k is BHD [1, Hkv, P, D]
799
+ uint hkv = hq / (H / HKV);
800
+ float scale = scale_arr[0];
801
+
802
+ uint flat_q = qb * NSG + sg;
803
+ bool valid_q = (flat_q < B_sz * S_len);
804
+ uint b_idx = valid_q ? (flat_q / S_len) : 0;
805
+ uint s_idx = valid_q ? (flat_q - b_idx * S_len) : 0;
806
+
807
+ float q_reg[ELEMS];
808
+ if (valid_q) {
809
+ uint q_base = ((b_idx * S_len + s_idx) * H + hq) * D + lane * ELEMS;
810
+ for (uint e = 0; e < ELEMS; ++e) q_reg[e] = float(q_cur[q_base + e]);
811
+ } else {
812
+ for (uint e = 0; e < ELEMS; ++e) q_reg[e] = 0.0f;
813
+ }
814
+
815
+ float m_i = -INFINITY;
816
+ float l_i = 0.0f;
817
+ float o_reg[ELEMS];
818
+ for (uint e = 0; e < ELEMS; ++e) o_reg[e] = 0.0f;
819
+
820
+ threadgroup T K_smem[BK * D];
821
+ threadgroup T V_smem[BK * D];
822
+
823
+ uint pk_head_base = hkv * P_len * D;
824
+ // Phase 1: Shared past_k / past_v [0 .. P_len) — ZERO copy across B rows!
825
+ for (uint k_base = 0; k_base < P_len; k_base += BK) {
826
+ uint k_lim = metal::min(BK, P_len - k_base);
827
+ for (uint idx = tid; idx < BK * D; idx += 256) {
828
+ uint r = idx / D;
829
+ uint d = idx - r * D;
830
+ if (r < k_lim) {
831
+ uint off = pk_head_base + (k_base + r) * D + d;
832
+ K_smem[idx] = past_k[off];
833
+ V_smem[idx] = past_v[off];
834
+ }
835
+ }
836
+ threadgroup_barrier(mem_flags::mem_threadgroup);
837
+
838
+ if (valid_q) {
839
+ for (uint j = 0; j < k_lim; ++j) {
840
+ uint sm_off = j * D + lane * ELEMS;
841
+ float dot = 0.0f;
842
+ for (uint e = 0; e < ELEMS; ++e) dot += q_reg[e] * float(K_smem[sm_off + e]);
843
+ dot = simd_sum(dot) * scale;
844
+ float m_new = metal::max(m_i, dot);
845
+ float alpha = (m_i > -INFINITY) ? metal::exp(m_i - m_new) : 0.0f;
846
+ float p = metal::exp(dot - m_new);
847
+ for (uint e = 0; e < ELEMS; ++e) o_reg[e] = o_reg[e] * alpha + p * float(V_smem[sm_off + e]);
848
+ l_i = l_i * alpha + p;
849
+ m_i = m_new;
850
+ }
851
+ }
852
+ threadgroup_barrier(mem_flags::mem_threadgroup);
853
+ }
854
+
855
+ // Phase 2: Causal local cur_k / cur_v [b_idx, 0 .. s_idx] in NHD [B, S, Hkv, D].
856
+ if (valid_q) {
857
+ for (uint kj = 0; kj <= s_idx; ++kj) {
858
+ uint kv_off = ((b_idx * S_len + kj) * HKV + hkv) * D + lane * ELEMS;
859
+ float dot = 0.0f;
860
+ for (uint e = 0; e < ELEMS; ++e) dot += q_reg[e] * float(k_cur[kv_off + e]);
861
+ dot = simd_sum(dot) * scale;
862
+ float m_new = metal::max(m_i, dot);
863
+ float alpha = (m_i > -INFINITY) ? metal::exp(m_i - m_new) : 0.0f;
864
+ float p = metal::exp(dot - m_new);
865
+ for (uint e = 0; e < ELEMS; ++e) o_reg[e] = o_reg[e] * alpha + p * float(v_cur[kv_off + e]);
866
+ l_i = l_i * alpha + p;
867
+ m_i = m_new;
868
+ }
869
+ float inv_l = (l_i > 0.0f) ? (1.0f / l_i) : 0.0f;
870
+ uint out_base = ((b_idx * S_len + s_idx) * H + hq) * D + lane * ELEMS;
871
+ for (uint e = 0; e < ELEMS; ++e) out[out_base + e] = T(o_reg[e] * inv_l);
872
+ }
873
+ """
874
+
875
+ _PAST_KV_READOUT_SPLITK_SRC = r"""
876
+ // Split-KV FP32 readout attention over shared past_k/v [1, Hkv, P, D] + local cur_k/v [B, S, Hkv, D]
877
+ // for R=B readout queries q_ro [B, H, D] at row positions ro_pos [B] (0 <= ro_pos[b] < S).
878
+ constexpr uint ELEMS = D / 32;
879
+ uint split_id = threadgroup_position_in_grid.x;
880
+ uint b = threadgroup_position_in_grid.y;
881
+ uint hq = threadgroup_position_in_grid.z;
882
+ uint sg = simdgroup_index_in_threadgroup; // 0..3
883
+ uint lane = thread_index_in_simdgroup; // 0..31
884
+
885
+ uint P_len = uint(past_k_shape[2]);
886
+ uint S_len = uint(k_cur_shape[1]);
887
+ uint n_splits = uint(n_splits_arr[0]);
888
+ uint hkv = hq / (H / HKV);
889
+ float scale = scale_arr[0];
890
+
891
+ uint ro_s = uint(ro_pos[b]);
892
+ uint total_k = P_len + ro_s + 1;
893
+
894
+ uint chunk = (total_k + n_splits - 1) / n_splits;
895
+ uint k_start = split_id * chunk;
896
+ uint k_end = metal::min(total_k, k_start + chunk);
897
+
898
+ float q_reg[ELEMS];
899
+ uint q_base = (b * H + hq) * D + lane * ELEMS;
900
+ for (uint e = 0; e < ELEMS; ++e) q_reg[e] = float(q_ro[q_base + e]);
901
+
902
+ float m_s = -INFINITY;
903
+ float l_s = 0.0f;
904
+ float o_s[ELEMS];
905
+ for (uint e = 0; e < ELEMS; ++e) o_s[e] = 0.0f;
906
+
907
+ uint pk_head_base = hkv * P_len * D + lane * ELEMS;
908
+ for (uint kj = k_start + sg; kj < k_end; kj += 4) {
909
+ float dot = 0.0f;
910
+ if (kj < P_len) {
911
+ uint off = pk_head_base + kj * D;
912
+ for (uint e = 0; e < ELEMS; ++e) dot += q_reg[e] * float(past_k[off + e]);
913
+ dot = simd_sum(dot) * scale;
914
+ float m_new = metal::max(m_s, dot);
915
+ float alpha = (m_s > -INFINITY) ? metal::exp(m_s - m_new) : 0.0f;
916
+ float p = metal::exp(dot - m_new);
917
+ for (uint e = 0; e < ELEMS; ++e) o_s[e] = o_s[e] * alpha + p * float(past_v[off + e]);
918
+ l_s = l_s * alpha + p;
919
+ m_s = m_new;
920
+ } else {
921
+ uint sj = kj - P_len;
922
+ uint off = ((b * S_len + sj) * HKV + hkv) * D + lane * ELEMS;
923
+ for (uint e = 0; e < ELEMS; ++e) dot += q_reg[e] * float(k_cur[off + e]);
924
+ dot = simd_sum(dot) * scale;
925
+ float m_new = metal::max(m_s, dot);
926
+ float alpha = (m_s > -INFINITY) ? metal::exp(m_s - m_new) : 0.0f;
927
+ float p = metal::exp(dot - m_new);
928
+ for (uint e = 0; e < ELEMS; ++e) o_s[e] = o_s[e] * alpha + p * float(v_cur[off + e]);
929
+ l_s = l_s * alpha + p;
930
+ m_s = m_new;
931
+ }
932
+ }
933
+
934
+ threadgroup float tg_m[4];
935
+ threadgroup float tg_l[4];
936
+ threadgroup float tg_o[4 * D];
937
+ if (lane == 0) {
938
+ tg_m[sg] = m_s;
939
+ tg_l[sg] = l_s;
940
+ }
941
+ for (uint e = 0; e < ELEMS; ++e) tg_o[sg * D + lane * ELEMS + e] = o_s[e];
942
+ threadgroup_barrier(mem_flags::mem_threadgroup);
943
+
944
+ if (sg == 0) {
945
+ float m_all = metal::max(metal::max(tg_m[0], tg_m[1]), metal::max(tg_m[2], tg_m[3]));
946
+ float l_all = 0.0f;
947
+ float acc[ELEMS];
948
+ for (uint e = 0; e < ELEMS; ++e) acc[e] = 0.0f;
949
+ if (m_all > -INFINITY) {
950
+ for (uint s = 0; s < 4; ++s) {
951
+ if (tg_m[s] > -INFINITY) {
952
+ float w = metal::exp(tg_m[s] - m_all);
953
+ l_all += tg_l[s] * w;
954
+ for (uint e = 0; e < ELEMS; ++e) acc[e] += tg_o[s * D + lane * ELEMS + e] * w;
955
+ }
956
+ }
957
+ }
958
+ uint out_idx = (b * H + hq) * n_splits + split_id;
959
+ if (lane == 0) lse_part[out_idx] = (l_all > 0.0f) ? (m_all + metal::log(l_all)) : -INFINITY;
960
+ float inv_l = (l_all > 0.0f) ? (1.0f / l_all) : 0.0f;
961
+ for (uint e = 0; e < ELEMS; ++e) o_part[out_idx * D + lane * ELEMS + e] = acc[e] * inv_l;
962
+ }
963
+ """
964
+
965
+
966
+ @lru_cache(maxsize=4)
967
+ def _past_kv_attn_kernel():
968
+ return mx.fast.metal_kernel(
969
+ name="basal_past_kv_attn",
970
+ input_names=["q_cur", "k_cur", "v_cur", "past_k", "past_v", "scale_arr"],
971
+ output_names=["out"],
972
+ source=_PAST_KV_ATTN_SRC,
973
+ ensure_row_contiguous=True,
974
+ compile_options={"math_mode": "safe"},
975
+ )
976
+
977
+
978
+ @lru_cache(maxsize=4)
979
+ def _past_kv_readout_splitk_kernel():
980
+ return mx.fast.metal_kernel(
981
+ name="basal_past_kv_readout_splitk",
982
+ input_names=["q_ro", "k_cur", "v_cur", "past_k", "past_v", "ro_pos", "n_splits_arr", "scale_arr"],
983
+ output_names=["o_part", "lse_part"],
984
+ source=_PAST_KV_READOUT_SPLITK_SRC,
985
+ ensure_row_contiguous=True,
986
+ compile_options={"math_mode": "safe"},
987
+ )
988
+
989
+
990
+ def past_kv_attn(
991
+ q_cur: mx.array,
992
+ k_cur: mx.array,
993
+ v_cur: mx.array,
994
+ past_k: mx.array,
995
+ past_v: mx.array,
996
+ scale: float,
997
+ ) -> mx.array:
998
+ """Zero-copy shared-prefix attention: `q_cur[B,S,H,D]`, `k/v_cur[B,S,Hkv,D]`, `past_k/v[1,Hkv,P,D]` -> `[B,S,H,D]`."""
999
+ B, S, H, D = q_cur.shape
1000
+ Hkv = k_cur.shape[2]
1001
+ n_qblk = (B * S + 7) // 8
1002
+ (out,) = _past_kv_attn_kernel()(
1003
+ inputs=[q_cur, k_cur, v_cur, past_k, past_v, _scale_scalar(scale)],
1004
+ template=[("T", q_cur.dtype), ("H", H), ("HKV", Hkv), ("D", D)],
1005
+ grid=(256 * n_qblk, H, 1),
1006
+ threadgroup=(256, 1, 1),
1007
+ output_shapes=[(B, S, H, D)],
1008
+ output_dtypes=[q_cur.dtype],
1009
+ )
1010
+ return out
1011
+
1012
+
1013
+ def past_kv_readout_attn(
1014
+ q_ro: mx.array,
1015
+ k_cur: mx.array,
1016
+ v_cur: mx.array,
1017
+ past_k: mx.array,
1018
+ past_v: mx.array,
1019
+ ro_pos: mx.array,
1020
+ scale: float,
1021
+ ) -> mx.array:
1022
+ """Zero-copy Split-KV FP32 readout attention: `q_ro[B,H,D]` over `past_k/v[1,Hkv,P,D]` + `k/v_cur[B,S,Hkv,D]`."""
1023
+ B, H, D = q_ro.shape
1024
+ Hkv = k_cur.shape[2]
1025
+ P = past_k.shape[2]
1026
+ total_k = P + k_cur.shape[1]
1027
+ if total_k >= 1024:
1028
+ n_splits = 16
1029
+ elif total_k >= 256:
1030
+ n_splits = 8
1031
+ elif total_k >= 64:
1032
+ n_splits = 4
1033
+ else:
1034
+ n_splits = 1
1035
+
1036
+ o_part, lse_part = _past_kv_readout_splitk_kernel()(
1037
+ inputs=[q_ro, k_cur, v_cur, past_k, past_v, ro_pos.astype(mx.int32),
1038
+ _int_scalar(n_splits), _scale_scalar(scale)],
1039
+ template=[("H", H), ("HKV", Hkv), ("D", D)],
1040
+ grid=(128 * n_splits, B, H),
1041
+ threadgroup=(128, 1, 1),
1042
+ output_shapes=[(B, H, n_splits, D), (B, H, n_splits)],
1043
+ output_dtypes=[mx.float32, mx.float32],
1044
+ )
1045
+ if n_splits == 1:
1046
+ return o_part[:, :, 0, :].astype(q_ro.dtype)
1047
+ tg_x = min(D, 128)
1048
+ (out,) = _readout_reduce_kernel()(
1049
+ inputs=[o_part, lse_part],
1050
+ template=[("T", q_ro.dtype), ("H", H), ("D", D)],
1051
+ grid=(D, B, H),
1052
+ threadgroup=(tg_x, 1, 1),
1053
+ output_shapes=[(B, H, D)],
1054
+ output_dtypes=[q_ro.dtype],
1055
+ )
1056
+ return out
1057
+