-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbindings.cpp
More file actions
2447 lines (2244 loc) · 88.2 KB
/
Copy pathbindings.cpp
File metadata and controls
2447 lines (2244 loc) · 88.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <nanobind/nanobind.h>
#include <nanobind/stl/optional.h>
#include <nanobind/stl/pair.h>
#include <nanobind/stl/string.h>
#include <nanobind/stl/variant.h>
#include <nanobind/stl/vector.h>
#include "kquant.h"
#include "kquant_codec.h"
#include "kquant_cpu_neon.h"
#include "kquant_gguf.h"
namespace nb = nanobind;
using namespace nb::literals;
namespace {
// Convert a decoded GGUF metadata value to a Python object: scalars to
// int/float/bool/str, arrays to lists, monostate to None.
nb::object meta_to_py(const mlx_kquant::GgufMetaValue& v) {
return std::visit(
[](auto&& x) -> nb::object {
using T = std::decay_t<decltype(x)>;
if constexpr (std::is_same_v<T, std::monostate>) {
return nb::none();
} else {
return nb::cast(x);
}
},
v);
}
// Map a KVarN tile-orientation string to the vside flag.
bool kvarn_kind_is_v(const std::string& kind, const char* op) {
if (kind == "v") {
return true;
}
if (kind == "k") {
return false;
}
throw std::invalid_argument(
std::string("[mlx_kquant.") + op +
"] kind must be \"k\" or \"v\", got \"" + kind + "\".");
}
} // namespace
NB_MODULE(_ext, m) {
m.doc() =
"mlx-kquant: standalone GGUF K-quant ops for MLX (custom Metal kernels).";
// --- toolchain self-checks ---
m.def(
"codecs",
&mlx_kquant::codec_names,
"Return the list of supported K-quant codec names.");
m.def(
"metallib_dir",
&mlx_kquant::metallib_dir,
"Directory holding the bundled mlx_kquant.metallib.");
m.def(
"metallib_loads",
&mlx_kquant::metallib_loads,
"Load the bundled metallib via the Metal device (toolchain self-check).");
m.def(
"cpu_neon_available",
&mlx_kquant::kq_cpu_neon_available,
"True when the arm64 NEON int8 CPU GEMV kernels can run here (arm64 "
"build with the dotprod extension, not disabled via KQ_CPU_NEON=0).");
m.def(
"nax_available",
&mlx_kquant::nax_available,
"True when the GPU supports the NAX (tensor-core) matmul kernels.");
m.def(
"nax_gather_enabled",
&mlx_kquant::nax_gather_enabled,
"kquant_type"_a,
"True when gather_qmm's sorted-rhs NAX GEMM leaf can serve this codec "
"here: NAX hardware present, the codec ships NAX kernels, and "
"KQ_DISABLE_NAX is unset (read live). Sorted-prefill callers defer to "
"gather_qmm when this holds.");
m.def(
"codec_has_moe_glu",
&mlx_kquant::codec_has_moe_glu,
"kquant_type"_a,
"True when this codec has the fused MoE GLU/gather kernel family "
"(kq.moe_glu_gather_kq and friends).");
m.def(
"codec_has_matmul",
[](const std::string& kquant_type) {
const auto* codec = mlx_kquant::codec_by_name(kquant_type);
return codec != nullptr && codec->has_matmul_kernel;
},
"kquant_type"_a,
"True when this codec ships Metal matmul kernels (qmv/qmm/gather). "
"CPU-only wire codecs return False; their matmuls must stay on the "
"CPU stream.");
// --- ops ---
m.def(
"dequantize",
&mlx_kquant::dequantize,
"w"_a,
"scales"_a,
"kquant_type"_a,
"dtype"_a = nb::none(),
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Dequantize GGUF K-quant wire bytes to a float array.
Args:
w (array): uint8 wire bytes; last dim a multiple of the codec's
bytes_per_block.
scales (array): vestigial placeholder (K-quant scales live inside
``w``); ignored by the kernel.
kquant_type (str): codec name, e.g. ``"q4_k"``, ``"q8_0"``.
dtype (Dtype, optional): output float dtype. Default ``float16``.
Returns:
array: the dequantized weights.
)");
m.def(
"quantized_matmul",
&mlx_kquant::quantized_matmul,
"x"_a,
"w"_a,
"scales"_a,
"kquant_type"_a,
"transpose"_a = true,
nb::kw_only(),
"lora_a"_a = nb::none(),
"lora_b"_a = nb::none(),
"lora_rows"_a = nb::none(),
"stream"_a = nb::none(),
R"(
Quantized matmul: ``x @ dequant(w)`` for GGUF K-quant weights.
Args:
x (array): float activations.
w (array): uint8 K-quant wire bytes (laid out [N, K] when
transpose=True).
scales (array): vestigial placeholder; ignored by the kernel.
kquant_type (str): codec name, e.g. ``"q4_k"``.
transpose (bool): whether ``w`` is transposed ([N, K]). Default True.
lora_a (array, optional): LoRA A^T [K, r] in the activation
dtype. With ``lora_b``, adds ``lora_rows * (x @ lora_a) @
lora_b`` to the output inside the same op (any codec, any
shape), instead of separate matmul and add ops.
lora_b (array, optional): LoRA B^T [r, N] (fold the adapter
scale in here).
lora_rows (array, optional): float32 per-row scale [rows] over
the flattened leading dims of ``x``; 0 skips a row.
Returns:
array: the matmul result (x.dtype, float32 promoted to bfloat16).
)");
m.def(
"quantized_matmul_qmv_bias",
&mlx_kquant::quantized_matmul_qmv_bias,
"x"_a,
"w"_a,
"scales"_a,
"bias"_a,
"kquant_type"_a,
nb::kw_only(),
"lora_a"_a = nb::none(),
"lora_b"_a = nb::none(),
"lora_rows"_a = nb::none(),
"stream"_a = nb::none(),
R"(
Bias-fused quantized matmul: ``x @ dequant(w) + bias`` for GGUF
K-quant weights, fusing the add into the matmul kernel dispatch.
Decode-only: ``x`` must carry exactly one row (``x.shape[-2] == 1``
after flattening leading batch dims) -- raises otherwise. Only
``kquant_type="q8_0"`` is wired so far. ``transpose`` is always True
(the only regime this is used for). For any other shape or codec, use
``quantized_matmul`` followed by a separate ``+ bias``.
Args:
x (array): float activations, exactly one row.
w (array): uint8 K-quant wire bytes, laid out [N, K].
scales (array): vestigial placeholder; ignored by the kernel.
bias (array): 1D, length N (the output dim).
kquant_type (str): codec name; only ``"q8_0"`` is wired so far.
lora_a (array, optional): LoRA A^T [K, r] in the activation
dtype. With ``lora_b``, adds ``lora_rows * (x @ lora_a) @
lora_b`` to the output inside the same op (any codec, any
shape), instead of separate matmul and add ops.
lora_b (array, optional): LoRA B^T [r, N] (fold the adapter
scale in here).
lora_rows (array, optional): float32 per-row scale [rows] over
the flattened leading dims of ``x``; 0 skips a row.
Returns:
array: the matmul-plus-bias result (x.dtype, float32 promoted to
bfloat16).
)");
m.def(
"sdpa_vector",
&mlx_kquant::sdpa_vector,
"q"_a,
"k"_a,
"v"_a,
"scale"_a,
"causal"_a = true,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Vector scaled-dot-product attention for large head dims (256, 512) that
stock MLX's fused vector allowlist excludes.
Args:
q (array): queries [B, n_q_heads, qL, D], float16/bfloat16.
k (array): keys [B, n_kv_heads, kL, D]; head/seq strided is fine
(read in place), D dim must be contiguous.
v (array): values [B, n_kv_heads, kL, D].
scale (float): query scale (typically 1/sqrt(D)).
causal (bool): apply an offset causal mask. Default True.
Returns:
array: attention output [B, n_q_heads, qL, D].
)");
m.def(
"sdpa_decode_gqa",
[](mx::array q,
mx::array k,
mx::array v,
float scale,
const std::optional<mx::array>& sinks,
int splits,
int tile_c,
const std::optional<mx::array>& starts,
const std::optional<mx::array>& k_scales,
const std::optional<mx::array>& k_biases,
const std::optional<mx::array>& v_scales,
const std::optional<mx::array>& v_biases,
const std::optional<mx::array>& ends,
bool return_lse,
mx::StreamOrDevice s) -> nb::object {
if (return_lse) {
auto outs = mlx_kquant::sdpa_decode_gqa_lse(
std::move(q),
std::move(k),
std::move(v),
scale,
sinks,
splits,
tile_c,
starts,
k_scales,
k_biases,
v_scales,
v_biases,
ends,
s);
return nb::make_tuple(outs[0], outs[1]);
}
return nb::cast(mlx_kquant::sdpa_decode_gqa(
std::move(q),
std::move(k),
std::move(v),
scale,
sinks,
splits,
tile_c,
starts,
k_scales,
k_biases,
v_scales,
v_biases,
ends,
s));
},
"q"_a,
"k"_a,
"v"_a,
"scale"_a,
"sinks"_a = nb::none(),
"splits"_a = 0,
"tile_c"_a = 0,
"starts"_a = nb::none(),
"k_scales"_a = nb::none(),
"k_biases"_a = nb::none(),
"v_scales"_a = nb::none(),
"v_biases"_a = nb::none(),
nb::kw_only(),
"ends"_a = nb::none(),
"return_lse"_a = false,
"stream"_a = nb::none(),
R"(
Decode/verify GQA attention tuned for long KV caches: the key axis
is split into a fixed number of coarse contiguous chunks and each
chunk is streamed through threadgroup-staged K/V tiles shared by the
whole GQA group, so device memory reads the KV once per kv-head. At
qL 2..4 (speculative-verify width) every query also shares the staged
tiles, causally clamped to its own trailing position. With `starts`,
batch row b attends keys [starts[b], kL) -- a left-padded batched KV
cache -- and fully padded-out key chunks are skipped, not staged.
With k_scales/k_biases/v_scales/v_biases (all four), k and v are
mlx affine-quantized wire (uint32, bits 8, group 64) and dequant is
fused into the tile stage.
Args:
q (array): queries [B, n_q_heads, qL, D], float16/bfloat16;
qL in 1..4, D in {64, 128, 256, 512}.
k (array): keys [B, n_kv_heads, kL, D]; head/seq strided is fine
(read in place), the head_dim must be contiguous.
v (array): values [B, n_kv_heads, kL, D].
scale (float): query scale (typically 1/sqrt(D)).
sinks (array, optional): per-q-head attention sinks, shape
[n_q_heads] -- an extra softmax logit with no value row.
splits (int): key-axis split count; 0 picks the default.
tile_c (int): staged tile height, 8/16/32; 0 (default) picks by
head_dim (32 up to D=128, 16 at D=256, 8 at D=512).
starts (array, optional): per-batch-row key start offsets,
int32 [B], each in [0, kL - qL]; row b attends [starts[b],
kL). Out-of-range values read as an empty row (zero output).
ends (array, optional): per-batch-row key ends, int32 [B]; row b
attends [starts[b], ends[b]) with its causal block ending at
ends[b], and kL is then only the capacity every row fits in,
so batched rows may differ in length without
right-justification. Values are clamped to [0, kL]; a row
needs at least qL keys above its start, and a row with none
reads as empty (zero output).
Returns:
array: attention output [B, n_q_heads, qL, D]. With
``return_lse=True``, a tuple ``(out, lse)`` where lse
[B, n_q_heads, qL] float32 is the natural-log softmax
normalizer per query row (the merge weight for combining
attention over disjoint key regions).
)");
m.def(
"sdpa_prefill_block_sparse",
&mlx_kquant::sdpa_prefill_block_sparse,
"q"_a,
"k"_a,
"v"_a,
"scale"_a,
"pages"_a,
"pmask"_a,
"counts"_a,
"offset"_a,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Block-sparse FA prefill over QSA-selected 4-row key pages. Queries
fold into windows of 4 (with the GQA group); window w walks ONLY
pages[w, :counts[w]] through a simdgroup-matrix FA tile. A key
counts for a query when its page's pmask bit for that query is set
(the builder sets bits only for blocks complete at the query), or
when it lies in the query's own incomplete tail block (causal).
The page list must include each window's tail-span blocks.
Args:
q (array): queries [1, n_q_heads, L, D]; n_q_heads must be
12 * n_kv_heads, D must be 256, L a multiple of 4.
k (array): keys [1, n_kv_heads, S, D] (full cache view).
v (array): values [1, n_kv_heads, S, D].
scale (float): query scale (typically 1/sqrt(D)).
pages (array): int32 [L / 4, max_pages] page indices per
window, padded with -1 past counts[w].
pmask (array): uint16 [L / 4, max_pages] membership bits
(bit i = query i of the window selected the page).
counts (array): int32 [L / 4] live page count per window.
offset (int): global position of query row 0 (S - L for a
standard prefill chunk).
Returns:
array: attention output [1, n_q_heads, L, D].
)");
m.def(
"sdpa_fa_verify",
[](mx::array q,
mx::array k,
mx::array v,
float scale,
int q_len,
int splits,
bool return_lse,
mx::StreamOrDevice s) -> nb::object {
if (return_lse) {
auto outs = mlx_kquant::sdpa_fa_verify_lse(
std::move(q),
std::move(k),
std::move(v),
scale,
q_len,
splits,
s);
return nb::make_tuple(outs[0], outs[1]);
}
return nb::cast(mlx_kquant::sdpa_fa_verify(
std::move(q), std::move(k), std::move(v), scale, q_len, splits, s));
},
"q"_a,
"k"_a,
"v"_a,
"scale"_a,
"q_len"_a,
"splits"_a = 0,
nb::kw_only(),
"return_lse"_a = false,
"stream"_a = nb::none(),
R"(
Speculative-verify attention on the GPU matrix units for a GQA-folded
query tile. Fold the GQA group into the query rows first --
q [1, Hq, q_len, D] reshaped to [1, Hkv, G*q_len, D] with kv-major
heads -- and pass the original q_len: folded row r is causally
clamped to key <= kL - q_len + (r % q_len). The query tile (32 rows,
or 64 for oversized folds such as gqa16 x q_len 4) streams each
contiguous KV split once, computing S = Q @ K^T and O += P @ V on
simdgroup_matrix with float32 accumulators and a per-row online
softmax; per-split partials are merged by the same reduction pass as
``sdpa_decode_gqa``.
Args:
q (array): folded queries [1, n_kv_heads, G*q_len, D],
float16/bfloat16; D = 64, 128, 256 or 512; G*q_len <= 64
except <= 32 at D=512.
k (array): keys [1, n_kv_heads, kL, D]; head/seq strided is fine
(read in place), the head_dim must be contiguous.
v (array): values [1, n_kv_heads, kL, D].
scale (float): query scale (typically 1/sqrt(D)).
q_len (int): pre-fold query length (1..8); sets each folded
row's causal clamp. q_len 1 is plain GQA decode on the
matrix units (every folded row attends the full KV).
splits (int): key-axis split count; 0 picks the default.
Returns:
array: attention output [1, n_kv_heads, G*q_len, D]. With
``return_lse=True``, a tuple ``(out, lse)`` where lse
[1, n_kv_heads, G*q_len] float32 is the natural-log softmax
normalizer per folded row (cascade merge weight).
)");
m.def(
"sdpa_fa_indexed",
&mlx_kquant::sdpa_fa_indexed,
"q"_a,
"kv"_a,
"idx"_a,
"scale"_a,
"splits"_a = 0,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Index-gathered attention over a shared K/V latent, for an absorbed
MLA decode step with a sparse key selection. Query j of q
[1, Hq, Q, 512] attends the rows of kv [1, 1, N, 512] listed in
idx[j, :] (int32 [Q, M]; a negative or out-of-range entry is a
padded slot). K and V are the one latent array. Each 32-head strip
of a query reads every listed row once straight from the latent, so
the gather into a contiguous copy and the materialized softmax both
disappear. Tensor-op GPUs run a NAX tile kernel; other GPUs run the
head_dim-512 simdgroup tile of sdpa_fa_verify, whose result matches
sdpa_fa_verify over the gathered rows bit for bit when the list has
no padded slots (KQ_SDPA_IDX_NAX=0 forces that kernel anywhere).
Returns [1, Hq, Q, 512] in the query dtype. `splits` 0 picks the
default. Metal-only.
)");
m.def(
"gather_mix",
&mlx_kquant::gather_mix,
"y"_a,
"inv_order"_a,
"scores"_a,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Fused unsort and score mix for sorted-prefill MoE:
out[t] = sum_s scores[t, s] * y[inv_order[t * k + s]] in one
dispatch, replacing the gather back to token order, the score
multiply and the sum over slots. f32 accumulation, one round at
the write, on every GPU and the CPU.
Args:
y (array): [rows, N] expert outputs in routing-sorted row
order (rows = T * k), float16/bfloat16, N a multiple of 4.
inv_order (array): [T * k] sorted row of each (token, slot)
pair, uint32 or int32 (the argsort of the sort order).
scores (array): [T, k] routing weights; cast to fp32.
Returns:
array: [T, N] in the y dtype.
)");
m.def(
"rmsnorm_gate",
&mlx_kquant::rmsnorm_gate,
"x"_a,
"w"_a,
"gate"_a,
"eps"_a = 1e-6f,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Fused output gate of gated-delta layers: rms_norm(x, w, eps) *
sigmoid(gate) over the last axis in one dispatch, f32 math with one
round at the write, on every GPU and the CPU.
Args:
x (array): [..., D], float16/bfloat16, D 64, 128 or 256.
w (array): [D] norm weight; cast to the x dtype.
gate (array): same shape as x; cast to the x dtype.
eps (float): norm epsilon.
Returns:
array: same shape and dtype as x.
)");
m.def(
"kda_conv",
&mlx_kquant::kda_conv,
"x"_a,
"state"_a,
"w"_a,
"head_dim"_a,
"scale"_a = 0.0f,
"eps"_a = 1e-6f,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Fused causal short convolution for gated-delta prefill (KDA, GDN):
y[t] = silu(sum_j w[:, j] * in[t - K + 1 + j]) with in = [state; x],
then with scale != 0 an l2 norm over each head_dim-channel head
with the scale folded in (scale * rms_norm(y, eps)). One dispatch
replaces the concat, conv1d, silu, rms_norm and multiply, with all
math in f32 and one round at the write, on every GPU and the CPU.
Args:
x (array): [B, T, C], float16/bfloat16.
state (array): [B, K - 1, C] carried rows (zeros for a fresh
sequence); cast to the x dtype.
w (array): [C, K] or [C, K, 1] depthwise taps (the nn.Conv1d
weight layout), K from 2 to 8; cast to the x dtype.
head_dim (int): norm group width, 64, 128 or 256; C must be a
multiple of it.
scale (float): folded norm scale; 0 skips the norm.
eps (float): norm epsilon.
Returns:
tuple: (y [B, T, C], state_out [B, K - 1, C]), the last K - 1
rows of [state; x] for the next call.
)");
m.def(
"kda_chunk_gated",
&mlx_kquant::kda_chunk_gated,
"q"_a,
"k"_a,
"v"_a,
"a"_a,
"a_scale"_a,
"dt_bias"_a,
"beta"_a,
"state"_a,
"lb"_a,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
kda_chunk with the decay formed inside the kernel:
log_g = lb * sigmoid(a_scale[h] * (a + dt_bias[h, d])) per token and
key channel (the KDA gate of Kimi Linear and GLM-5.3-Flash), so the
fp32 gate tensor is never written.
Args:
q, k, v (array): [B, T, H, 128], one float dtype.
a (array): [B, T, H, 128] gate pre-activation in the q dtype.
a_scale (array): [H] per-head factor, exp(A_log); used in fp32.
dt_bias (array): H * 128 values ([H, 128] or flat); fp32.
beta (array): [B, T, H] write gate.
state (array): [B, H, 128, 128] incoming state, fp32.
lb (float): gate lower bound (log g in (lb, 0)).
Returns:
tuple: (o [B, T, H, 128] in the q dtype, state_out fp32), as
kda_chunk on that log gate.
)");
m.def(
"kda_chunk",
&mlx_kquant::kda_chunk,
"q"_a,
"k"_a,
"v"_a,
"log_g"_a,
"beta"_a,
"state"_a,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Chunked KDA prefill: the per-key-channel gated delta rule
S_t = S_{t-1} diag(g_t) + beta_t (v_t - S_{t-1} diag(g_t) k_t) k_t^T,
o_t = S_t q_t, over a whole sequence. q, k, v are [B, T, H, 128]
(float16, bfloat16 or float32, one dtype), log_g [B, T, H, 128] the
per-channel log decay (log g_t, at most 0), beta [B, T, H] and
state [B, H, 128, 128] fp32 the incoming recurrent state. Returns
(o [B, T, H, 128] in the q dtype, state_out [B, H, 128, 128] fp32).
Tensor-op GPUs run the sequence in 32-token chunks with the state
resident on the matrix units, one threadgroup per (batch, head);
the products take bf16 operands with fp32 accumulation, so o and
state_out sit within about 4e-3 relative of the token-by-token
recurrence and the error does not grow with T. log_g must stay
above about -5.5 per token (16 tokens of decay within fp32 range).
The CPU path is the sequential recurrence in fp32; other GPUs raise,
so gate the call on nax_available(). T need not be a multiple of
32.
)");
m.def(
"sdpa_decode_gqa_paged",
&mlx_kquant::sdpa_decode_gqa_paged,
"q"_a,
"k"_a,
"v"_a,
"scale"_a,
"pages"_a,
"splits"_a = 0,
"tile_c"_a = 0,
"starts"_a = nb::none(),
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Sparse page-gather decode attention: attend ONLY the key/value
pages listed per (batch, kv-head), walking the selected pages
through the decode kernel instead of the full cache. The page
unit is the head dim's staged tile height: 32 rows at head_dim
64/128, 16 at 256, 8 at 512; tile_c=4 selects a 4-row page at
head_dim 256 (block-sparse attention with a 4-token selection
unit). Optional starts (int32 [B])
restricts row b to keys [starts[b], N) for left-padded batches.
Args:
q (array): queries [B, n_q_heads, 1, D], float16/bfloat16.
k (array): keys [B, n_kv_heads, S, D] (full cache view).
v (array): values [B, n_kv_heads, S, D].
scale (float): query scale (typically 1/sqrt(D)).
pages (array): int32 [B, n_kv_heads, n_pages] page indices in
[0, ceil(S / page_size)); no duplicates. The final partial
page is tail-clamped to S automatically.
splits (int): key-axis split count; 0 buckets by the SELECTED
key count.
tile_c (int): page size in rows; 0 picks the head dim's
default. 4 is instantiated at head_dim 256 only.
Returns:
array: attention output [B, n_q_heads, 1, D].
)");
m.def(
"sdpa_decode_gqa_cascade",
[](mx::array q,
mx::array k_shared,
mx::array v_shared,
mx::array k_priv,
mx::array v_priv,
float scale,
const std::optional<mx::array>& starts,
int splits_shared,
int splits_priv,
int tile_c,
bool return_lse,
const std::optional<mx::array>& k_shared_scales,
const std::optional<mx::array>& k_shared_biases,
const std::optional<mx::array>& v_shared_scales,
const std::optional<mx::array>& v_shared_biases,
const std::optional<mx::array>& k_priv_scales,
const std::optional<mx::array>& k_priv_biases,
const std::optional<mx::array>& v_priv_scales,
const std::optional<mx::array>& v_priv_biases,
mx::StreamOrDevice s) -> nb::object {
auto outs = mlx_kquant::sdpa_decode_gqa_cascade(
std::move(q),
std::move(k_shared),
std::move(v_shared),
std::move(k_priv),
std::move(v_priv),
scale,
starts,
splits_shared,
splits_priv,
tile_c,
return_lse,
k_shared_scales,
k_shared_biases,
v_shared_scales,
v_shared_biases,
k_priv_scales,
k_priv_biases,
v_priv_scales,
v_priv_biases,
s);
if (return_lse) {
return nb::make_tuple(outs[0], outs[1]);
}
return nb::cast(outs[0]);
},
"q"_a,
"k_shared"_a,
"v_shared"_a,
"k_priv"_a,
"v_priv"_a,
"scale"_a,
"starts"_a = nb::none(),
"splits_shared"_a = 0,
"splits_priv"_a = 0,
"tile_c"_a = 0,
nb::kw_only(),
"return_lse"_a = false,
"k_shared_scales"_a = nb::none(),
"k_shared_biases"_a = nb::none(),
"v_shared_scales"_a = nb::none(),
"v_shared_biases"_a = nb::none(),
"k_priv_scales"_a = nb::none(),
"k_priv_biases"_a = nb::none(),
"v_priv_scales"_a = nb::none(),
"v_priv_biases"_a = nb::none(),
"stream"_a = nb::none(),
R"(
Fused shared-prefix (cascade) decode attention: every batch row
attends one COMMON prefix, stored once, plus its own private
suffix. The shared region is walked ONCE for all B*gqa query rows
on the matrix-unit row tile; the private region runs per row (with
optional left-pad ``starts``); both partial sets fold through a
single merge pass. Equivalent to ``sdpa_decode_gqa`` over the
concatenated KV, reading the prefix once instead of B times.
Args:
q (array): queries [B, n_q_heads, qL, D], float16/bfloat16;
qL in [1, 8] (verify width: end-aligned causal on the
private suffix, full shared visibility); D in
{64, 128, 256, 512}; gqa <= 16; B*gqa*qL <= 64 (<= 32 at
D=512); gqa*ceil(qL/2) <= 32 at qL > 1.
k_shared (array): shared prefix keys [1, n_kv_heads, P, D].
v_shared (array): shared prefix values [1, n_kv_heads, P, D].
k_priv (array): private suffix keys [B, n_kv_heads, Sp, D],
Sp >= 1.
v_priv (array): private suffix values [B, n_kv_heads, Sp, D].
scale (float): query scale (typically 1/sqrt(D)).
starts (array, optional): int32 [B] per-row private-region key
start offsets (left-padded private suffixes).
splits_shared (int): shared-region split count; 0 = default.
splits_priv (int): private-region split count; 0 = default.
tile_c (int): private-pass staged tile height; 0 picks by
head_dim.
k_shared_scales ... v_priv_biases (array, optional): quantized
KV (mlx affine wire, bits 8 / group 64). Pass all eight and
both k/v slabs bind as packed uint32 words ([.., S, D/4])
with scales/biases [.., S, D/64] in q's dtype; dequant
happens at tile stage. Not supported at D=512.
Returns:
array: attention output [B, n_q_heads, 1, D]. With
``return_lse=True``, a tuple ``(out, lse)``.
)");
m.def(
"moe_glu_gather",
&mlx_kquant::moe_glu_gather,
"x"_a,
"gate_w"_a,
"gate_scales"_a,
"gate_bias"_a,
"up_w"_a,
"up_scales"_a,
"up_bias"_a,
"indices"_a,
"alpha"_a = 1.702f,
"limit"_a = 7.0f,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Fused MoE GLU gather on the MLX packed mxfp4 layout: gate and up
expert matvecs (sharing each activation load), expert biases, and the
clamped-SwiGLU epilogue
``(min(g, limit) * sigmoid(alpha * g)) * (clip(u, -limit, limit) + 1)``
in one dispatch. Decode-shaped: one activation row per token, shared
across that token's expert slots.
Args:
x (array): activations [T, K], float16/bfloat16.
gate_w (array): packed gate weights uint32 [E, N, K/8].
gate_scales (array): E8M0 group scales uint8 [E, N, K/32].
gate_bias (array): gate biases [E, N].
up_w / up_scales / up_bias: same layout for the up projection.
indices (array): expert indices [T, R].
alpha (float): sigmoid slope. Default 1.702.
limit (float): activation clamp. Default 7.0.
Returns:
array: activated hidden states [T, R, N] in x.dtype.
)");
m.def(
"gather_qmv_bias",
&mlx_kquant::gather_qmv_bias,
"x"_a,
"w"_a,
"scales"_a,
"bias"_a,
"indices"_a,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Gathered matvec with the expert bias fused, on the MLX packed mxfp4
layout (see moe_glu_gather). One activation row per expert slot.
Args:
x (array): activations [T, R, K], float16/bfloat16.
w (array): packed weights uint32 [E, N, K/8].
scales (array): E8M0 group scales uint8 [E, N, K/32].
bias (array): biases [E, N].
indices (array): expert indices [T, R].
Returns:
array: output [T, R, N] in x.dtype.
)");
m.def(
"gather_qmv_mix_bias",
&mlx_kquant::gather_qmv_mix_bias,
"x"_a,
"w"_a,
"scales"_a,
"bias"_a,
"indices"_a,
"scores"_a,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
gather_qmv_bias with the routing mix folded in: each routed slot's
matvec + expert bias is accumulated in f32 weighted by its score,
replacing gather_qmv_bias + (y * scores).sum(-2).
Args:
x (array): activations [T, S, K], float16/bfloat16.
w (array): packed weights uint32 [E, N, K/8].
scales (array): E8M0 group scales uint8 [E, N, K/32].
bias (array): biases [E, N].
indices (array): expert indices [T, S].
scores (array): mix weights [T, S]; cast to float32.
Returns:
array: mixed output [T, N] in x.dtype.
)");
m.def(
"dsa_sparse_attention",
&mlx_kquant::dsa_sparse_attention,
"q"_a,
"local_kv"_a,
"pooled"_a,
"topk_indices"_a,
"sinks"_a,
"scale"_a,
"q_offset"_a,
"compress_ratio"_a,
"local_window"_a,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
DeepSeek-V4-Flash sparse attention: sliding local window + gathered
indexer-selected pooled rows + per-head attention sinks in one
dispatch (flash online softmax, f32 accumulation). Ported from omlx
glm_moe_dsa; qL >= 1, so decode, MTP verify (qL = 2) and prefill all
run this kernel.
Args:
q (array): queries [B, 64, qL, 512], float16/bfloat16.
local_kv (array): sliding-window KV [B, 1, localL, 512]
(K == V shared latent), temporal order, localL >= qL.
pooled (array): compressed pooled rows [B, P, 512].
topk_indices (array): uint32 [B, 1, qL, N] pooled-row indices;
slots >= the causal horizon (q_offset + pos + 1) /
compress_ratio are masked out kernel-side.
sinks (array): per-head sink logits [64].
scale (float): attention scale (1/sqrt(512)).
q_offset (int): absolute position of the chunk start.
compress_ratio (int): pooled compression ratio.
local_window (int): sliding-window size (128).
Returns:
array: attention output [B, 64, qL, 512] in the input dtype.
)");
m.def(
"dsa_indexer_scores",
&mlx_kquant::dsa_indexer_scores,
"queries"_a,
"keys"_a,
"weights"_a,
"causal"_a = true,
"unused_causal_prefix_topk"_a = 0,
"skip_causal_future_store"_a = false,
"causal_q_offset"_a = -1,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
DeepSeek-V4-Flash lightning-indexer relevance scores (steel GEMM):
out[b, 0, m, n] = sum_h relu(q[b, h, m] . k[b, 0, n]) * w[h, m].
Ported from omlx glm_moe_dsa. Feed the result to dsa_topk_indices to
pick the pooled rows dsa_sparse_attention gathers.
Args:
queries (array): [B, H, M, 128], H 32 or 64, M % 64 == 0,
float16/bfloat16. Decode pads the single query row to 64
and keeps output row 0.
keys (array): pooled indexer keys [B, 1, N, 128], N % 64 == 0.
weights (array): per-head query weights, [B, M, H] (lh layout)
or [B, H, M, 1].
causal (bool): mask n > causal_q_offset + m with -inf.
unused_causal_prefix_topk (int): skip writing tiles whose rows
all fall inside a causal prefix of this many keys (they are
identity-selected by a causal_valid_prefix top-k).
skip_causal_future_store (bool): leave fully-masked future tiles
unwritten instead of storing -inf (pair with a
causal_valid_prefix top-k that never reads them).
causal_q_offset (int): absolute position of query row 0; -1
means N - M.
Returns:
array: scores [B, 1, M, N] in the input dtype.
)");
m.def(
"dsa_topk_indices",
&mlx_kquant::dsa_topk_indices,
"scores"_a,
"topk"_a,
"bucketed"_a = false,
"causal_valid_prefix"_a = false,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Per-row top-k arg-select over 16-bit float scores (2-pass radix
select, one threadgroup per row). Ported from omlx glm_moe_dsa.
The selected index set matches a full sort; the order within a row
does not (ties at the threshold are admitted in scan order) --
dsa_sparse_attention is order-insensitive.
Args:
scores (array): [B, 1, L, K], float16/bfloat16, K >= topk.
topk (int): 512 or 2048.
bucketed (bool): deterministic bucketed emission (>threshold
entries before ==threshold entries).
causal_valid_prefix (bool): clamp each row's scan to its causal
prefix K - L + (row % L) + 1 and emit the identity prefix
when it fits inside topk.
Returns:
array: uint32 indices [B, 1, L, topk].
)");
m.def(
"dsa_indexer_score_decode",
&mlx_kquant::dsa_indexer_score_decode,
"queries"_a,
"keys"_a,
"weights"_a,
"q_offset"_a,
"ratio"_a,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Decode-width lightning-indexer scores, fused:
out[b, 0, j, p] = sum_h relu(q[b, h, j] . k[b, p]) * w[b, j, h]
for qL <= 4 query rows without materializing the [H, P] per-head
scores. Selection-equivalent to the inline path when any positive
global scale is folded out. Pooled visibility follows
PoolingCache.make_mask(qL, q_offset): row p is visible to query j
iff p < (q_offset + j + 1) // ratio, and every row is visible when
qL == 1; invisible rows score the dtype's finite min.
Args:
queries (array): [B, H, qL, 128], H in {4, 32, 64}, qL in
[1, 4], float16/bfloat16.
keys (array): the pooled indexer key cache [B, P, 128].
weights (array): per-head query weights [B, qL, H]. float32
weights are read as-is (sign-free head gates stay exact);
other dtypes follow the q/k dtype.
q_offset (int): absolute position of query row 0's step
(make_mask's ``offset``).
ratio (int): pooled compression ratio.