Repository navigation
Expand file tree
/
Copy pathbindings.cpp
More file actions
3736 lines (3427 loc) · 142 KB
/
Copy pathbindings.cpp
File metadata and controls
3736 lines (3427 loc) · 142 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/tuple.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(
"metallib_kernels",
&mlx_kquant::metallib_kernels,
"Sorted names of the kernels in the bundled metallib (empty on builds "
"without Metal). Tile overrides select from these names.");
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(
"gpu_core_count",
&mlx_kquant::gpu_core_count,
"GPU core count from IOKit (KQ_GPU_CORES overrides it); 0 when unknown.");
m.def(
"max_threadgroup_memory",
&mlx_kquant::max_threadgroup_memory,
"The GPU's threadgroup memory limit in bytes; 0 without Metal.");
m.def(
"_probe_kernels",
&mlx_kquant::probe_kernels,
"True in a build with the CMake option KQ_PROBE_KERNELS=ON, for the "
"kernel name tests.");
m.def(
"_split_kernel_names",
&mlx_kquant::split_kernel_names,
"Every kernel name the split-K dispatchers can build, for the kernel "
"name tests (empty without Metal).");
m.def(
"_nax_large_row",
&mlx_kquant::nax_large_row,
"kquant_type"_a,
"The codec's NAX qmm_t large-M row as [bm, bn, wm, wn, swizzle_log, "
"min_m, min_n, max_k, inherited], for the policy tests (empty without "
"Metal).");
m.def(
"_alu_dequantize_row",
&mlx_kquant::alu_dequantize_row,
"arch"_a,
"nax"_a,
"kquant_type"_a,
"M"_a,
"N"_a,
"K"_a,
"The row that runs a plain transposed quantized_matmul as dequantize "
"then the stock matmul by default, for an architecture string, NAX, "
"codec, rows of x, N and K, as [min_m, min_k, max_k, min_n, max_n]; "
"empty where the qmm_t kernel runs.");
m.def(
"_moe_c32_nx",
&mlx_kquant::moe_c32_nx,
"arch"_a,
"The K-lanes per output row (8 or 16) of the c32 MoE GLU gathers "
"for an architecture string, unless KQ_MOE_NX forces one.");
m.def(
"_moe_c32_on",
&mlx_kquant::moe_c32_on,
"arch"_a,
"codec"_a,
"Whether the MoE gathers of a codec take the c32 kernels at t = 1 by "
"default for an architecture string, unless KQ_MOE_C32 forces it.");
m.def(
"_qmv_c32_on",
&mlx_kquant::qmv_c32_on,
"arch"_a,
"codec"_a,
"Whether the one-row quantized_matmul of a codec takes the c32 kernel "
"by default for an architecture string, unless KQ_QMV_C32 forces it.");
m.def(
"_dequantize_route_takes",
&mlx_kquant::dequantize_route_takes,
"arch"_a,
"nax"_a,
"mode"_a,
"pinned"_a,
"kquant_type"_a,
"M"_a,
"N"_a,
"K"_a,
"Whether a plain transposed quantized_matmul on a 2-D weight on a GPU "
"stream takes the dequantize route, for an architecture string, NAX, "
"the KQ_DEQUANT_ROUTE mode, a pinned KQ_QMM_TILE, codec, rows of x, N "
"and K.");
m.def(
"qmv_fine_max_n",
&mlx_kquant::qmv_fine_max_n,
"kquant_type"_a,
"Largest N at which the single-row mat-vec takes the fine tiling for "
"this codec on this GPU; 0 means coarse.");
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(
"seg_nax_enabled",
&mlx_kquant::seg_nax_enabled,
"kquant_type"_a,
"k"_a,
"True when gather_qmm_seg runs its NAX kernel for this codec at input "
"width k: nax_gather_enabled holds, k is a multiple of 64, and "
"KQ_DISABLE_GATHER_SEG_NAX is unset (read once; any value sets it). "
"KQuantSwitchLinear's sorted arm takes its rows-per-expert rule here.");
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(
"moe_qf_kernels",
&mlx_kquant::moe_qf_kernels,
"kquant_type"_a,
"True when the fused MoE gathers on this codec run its tuned mat-vec "
"loops (the qf kernels) instead of the generic kernels. KQ_MOE_QF=0 "
"or a forced KQ_MOE_NX keeps the generic kernels; both are read live "
"once set. False on a build without Metal.");
m.def(
"shexp_glu_combo_has_kernel",
&mlx_kquant::shexp_glu_combo_has_kernel,
"kquant_type"_a,
"shexp_gate_type"_a,
"shexp_up_type"_a,
"shared_slots"_a = 1,
"True when moe_glu_gather_shexp_kq has a kernel for expert stacks in "
"kquant_type with the shared expert's gate and up tensors in these "
"two codecs, the shared expert shared_slots routed experts wide.");
m.def(
"shexp_mix_combo_has_kernel",
&mlx_kquant::shexp_mix_combo_has_kernel,
"kquant_type"_a,
"shexp_type"_a,
"shared_slots"_a = 1,
"slot_width"_a = 0,
"True when gather_qmv_mix_kq has a kernel for expert stacks in "
"kquant_type with the shared expert's down tensor in shexp_type, the "
"shared expert shared_slots routed experts wide. slot_width is the "
"routed expert width; shared_slots > 1 needs it, and each shared slot "
"must start on a whole shexp_type block.");
m.def(
"shexp_mix_slot_parallel",
&mlx_kquant::shexp_mix_slot_parallel,
"kquant_type"_a,
"shexp_type"_a,
"shared_slots"_a = 1,
"slot_width"_a = 0,
"True when gather_qmv_mix_kq runs that codec combination on its "
"slot-parallel kernel at decode and verify widths.");
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 has matmul kernels (qmv/qmm/gather). A "
"gather-only lookup-table codec (mxfp8) returns False: it has no "
"matmul on any device, and the matmul ops reject it.");
// --- 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``.
``mxfp8`` values can pass the float16 range (its e8m0 scales
reach 2^127), so decode it to ``bfloat16`` or ``float32``.
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(),
"lora_ids"_a = nb::none(),
"lora_table"_a = nb::none(),
"out_scale"_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.
lora_ids (array, optional): uint32 [rows], the adapter of each
row from a stack: ``lora_a`` [S, K, r] and ``lora_b`` [S, r,
N]. Row i adds ``(x_i @ lora_a[e]) @ lora_b[e]`` with ``e =
lora_ids[i]``. Every id must index the stack (or
``lora_table``); the kernel does not check.
lora_table (array, optional): int32 1-D remap applied to
``lora_ids``: ``e = lora_table[lora_ids[i]]``, and an entry
below 0 skips the row. Needs ``lora_ids``.
out_scale (array, optional): float32 scale of the product, shape
(1,) or (N,): the result is ``out_scale * (x @ dequant(w).T)``,
with the LoRA delta added after it. nvfp4 with
``transpose=True`` only (the per-tensor ``.scale`` of an
NVFP4 GGUF).
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(),
"lora_ids"_a = nb::none(),
"lora_table"_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.
lora_ids (array, optional): uint32 [rows], the adapter of each
row from a stack: ``lora_a`` [S, K, r] and ``lora_b`` [S, r,
N]. Row i adds ``(x_i @ lora_a[e]) @ lora_b[e]`` with ``e =
lora_ids[i]``. Every id must index the stack (or
``lora_table``); the kernel does not check.
lora_table (array, optional): int32 1-D remap applied to
``lora_ids``: ``e = lora_table[lora_ids[i]]``, and an entry
below 0 skips the row. Needs ``lora_ids``.
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), and 16
for one query of one row of unquantized KV at D=128.
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_prefill_window",
&mlx_kquant::sdpa_prefill_window,
"q"_a,
"k"_a,
"v"_a,
"scale"_a,
"window"_a,
"sinks"_a = nb::none(),
"starts"_a = nb::none(),
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Sliding-window causal prefill attention on the tensor-op units.
The queries are the last qL of the kL key positions; query row i
sees the keys at positions p with p <= i + kL - qL and
p > i + kL - qL - window. Only the key blocks inside each query
block's window are read, where a dense masked attention reads every
block up to the diagonal. Needs a NAX GPU (M5 and later).
Args:
q (array): queries [B, n_q_heads, qL, D], float16/bfloat16,
D in {64, 128, 256}. Batch, head and row strided is fine;
the head_dim must be contiguous.
k (array): keys [B, n_kv_heads, kL, D] in position order, kL
>= qL; n_kv_heads must divide n_q_heads.
v (array): values [B, n_kv_heads, kL, D].
scale (float): query scale (typically 1/sqrt(D)).
window (int): keys each query sees, itself included; >= 1.
sinks (array, optional): per-q-head attention sinks, shape
[n_q_heads]; an extra softmax logit with no value row.
starts (array, optional): int32 [B]; batch row b skips the keys
below starts[b] (a left-padded batch), clamped to [0, kL].
A query row below its start reads zeros.
Returns:
array: attention output [B, n_q_heads, qL, D].
)");
m.def(
"sdpa_qk8_inputs",
&mlx_kquant::sdpa_qk8_inputs,
"q"_a,
"k"_a,
"scale"_a,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Quantizes q and k to the int8 operands of sdpa_qk8. Each row of
q * scale becomes 128 int8 codes and a float32 scale, max |x| / 127,
with codes rounded to nearest. Each row of k minus k's mean over its
kL rows becomes codes and a scale the same way; the shift leaves the
softmax unchanged. The mean is taken in bfloat16, whose rounding
depends on k's layout, so k8 and k_scale repeat their bits only for
the same layout of k. Runs on any Metal GPU.
Args:
q (array): queries [B, n_q_heads, qL, 128], bfloat16. Batch,
head and row strided is fine.
k (array): keys [B, n_kv_heads, kL, 128], bfloat16;
n_kv_heads must divide n_q_heads.
scale (float): query scale (typically 1/sqrt(128)), finite.
Returns:
tuple(array, array, array, array): q8 int8 [B, n_q_heads, qL,
128], q_scale float32 [B, n_q_heads, qL], k8 int8 [B,
n_kv_heads, kL, 128] and k_scale float32 [B, n_kv_heads, kL].
)");
m.def(
"sdpa_qk8",
&mlx_kquant::sdpa_qk8,
"q8"_a,
"q_scale"_a,
"k8"_a,
"k_scale"_a,
"v"_a,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Attention with int8 Q K^T and bfloat16 P V on the tensor-op units,
without a mask: softmax(Q K^T) V with Q and K the dequantized
q8 and k8 (the query scale is in q8). Lossy: the error against
bfloat16 attention is that of the int8 rows. A call on a slice of
the query rows returns the bits of those rows of the whole call,
so the rows can run in chunks with K quantized once. Needs a NAX
GPU (M5 and later).
Args:
q8 (array): int8 [B, n_q_heads, qL, 128] from sdpa_qk8_inputs,
or a slice of its rows such as q8[:, :, a:b]. Batch, head
and row strided is fine; it is read in place.
q_scale (array): float32 [B, n_q_heads, qL], sliced as q8,
positive as sdpa_qk8_inputs returns it. Strided is fine;
it is copied when not row-major.
k8 (array): int8 [B, n_kv_heads, kL, 128], strided as q8.
k_scale (array): float32 [B, n_kv_heads, kL], as q_scale.
v (array): values [B, n_kv_heads, kL, 128], bfloat16. Batch,
head and row strided is fine.
Returns:
array: attention output [B, n_q_heads, qL, 128], bfloat16,
laid out as [B, qL, n_q_heads, 128].
)");
m.def(
"int8_quantize_rows",
&mlx_kquant::int8_quantize_rows,
"x"_a,
nb::kw_only(),
"group_size"_a = nb::none(),
"stream"_a = nb::none(),
R"(
Quantizes the rows of x to int8 codes and float32 scales, the
operands of int8_matmul, for activations and weights alike. Each
row splits into groups of group_size columns (the whole row when
group_size is None; the last group may be short). For each group,
m = max |x|, s = max(m / 127, FLT_MIN) (1 / 127 when m is 0), and
codes = clamp(rint(x / s), -127, 127), ties to even. A weight
[N, K] gives one scale per output channel, [N, 1]. x must be
finite: an inf or NaN codes as -127 and a NaN does not reach the
output. At most 2^27 - 8 groups a call. Runs on any Metal GPU.
Args:
x (array): bfloat16, float16 or float32 [..., K], K >= 1. A
non row-major x is copied; a strided view of more than
2^32 elements is refused at eval.
group_size (int, optional): columns per scale, a multiple of
32. None, or a value of at least K, means one scale a row.
Returns:
tuple(array, array): codes int8 of x's shape and scales
float32 [..., G], G = ceil(K / group_size), 1 without a group.
)");
m.def(
"int8_matmul",
&mlx_kquant::int8_matmul,
"x8"_a,
"x_scales"_a,
"w8"_a,
"w_scales"_a,
nb::kw_only(),
"group_size"_a = nb::none(),
"out_dtype"_a = mx::bfloat16,
"stream"_a = nb::none(),
R"(
int8 x int8 matmul on the tensor-op units: y = x8 w8^T, with the
weight laid out [N, K] as in quantized_matmul(transpose=True).
y[r, c] = sum over groups g of (sum over the group of x8[r, k]
w8[c, k]) * x_scales[r, g], times w_scales[c]: each group's sum is
exact in int32 (groups, or K without one, of at most 133120
columns) and the sum over groups is float32, in group order.
Without a group, y[r, c] = acc * x_scales[r, 0] * w_scales[c].
Lossy against the float product: the error is that of the int8
codes. A call on a slice of the rows returns the bits of those
rows of the whole call. Inference only. Needs a NAX GPU (M5 and
later).
Args:
x8 (array): int8 [..., K] from int8_quantize_rows, K a
multiple of 32, or a slice of its rows. Codes of x8 and
w8 must lie in [-127, 127], as int8_quantize_rows makes
them; a -128 can wrap the int32 sum of a long group.
x_scales (array): float32 [..., G], the scales of x8 for the
same group_size, sliced as x8.
w8 (array): int8 [N, K], one output channel a row, N at most
2^29 - 128.
w_scales (array): float32 [N].
group_size (int, optional): the group_size x8 was quantized
with, a multiple of 32; None for one scale a row.
out_dtype (Dtype): bfloat16 (default), float16 or float32.
Returns:
array: [..., N] in out_dtype, row-major.
)");
m.def(
"_vsa_fixed_shapes",
&mlx_kquant::vsa_fixed_shapes,
"x"_a,
nb::kw_only(),
"stream"_a = nb::none(),
"The identity on x, refusing any shapeless compiled replay (for "
"vsa_attention).");
m.def(
"_vsa_tile_sums",
&mlx_kquant::vsa_tile_sums,
"x"_a,
nb::kw_only(),
"stream"_a = nb::none(),
"The float32 sum of each 64-row tile of bfloat16 x, with the bits of "
"MLX's float32 sum, and on the GPU no float32 copy of x (for "
"vsa_attention).");
m.def(
"_vsa_gather_source",
&mlx_kquant::vsa_gather_source,
"x"_a,
nb::kw_only(),
"stream"_a = nb::none(),
"x, or a row-major copy of a strided x that MLX's GPU gather would read "
"with 32-bit offsets (for vsa_attention).");
m.def(
"vsa_block_sparse",
&mlx_kquant::vsa_block_sparse,
"q"_a,
"k"_a,
"v"_a,
"block_idx"_a,
"block_num"_a,
"variable_block_sizes"_a,
"num_prefix_tiles"_a,
"scale"_a,
nb::kw_only(),
"tile_size"_a = 64,
"query_rows"_a = nb::none(),
"coarse"_a = nb::none(),
"gate"_a = nb::none(),
"stream"_a = nb::none(),
R"(
Block-sparse attention of MiniMax-H3 video sparse attention (VSA)
on the tensor-op units. Each video query tile attends only the key
tiles its routing lists, and of each only the live rows, with no
gathered copy of K and V and no dense mask. The kernel is ported
from FastVideo's NAX VSA kernel and returns the bits of MLX's fused
attention over the gathered key tiles with the dead rows masked.
Needs a NAX GPU (M5 and later). A CPU stream or another GPU raises.
A function compiled with shapeless=True raises ValueError when it
is called at input shapes other than those of its trace. Compile
such a function with fixed shapes.
Args:
q (array): tiled queries [S_pad, heads, 128], bfloat16, with
S_pad = len(variable_block_sizes) * tile_size.
k (array): tiled keys, the shape and dtype of q.
v (array): tiled values, the shape and dtype of q.
block_idx (array): integer [heads, video tiles, k], the key
tile indices each video query tile reads, prefix tiles
included. An index outside [0, tiles) is skipped.
block_num (array): integer [heads, video tiles], how many
entries of each block_idx list are live (clamped to k).
variable_block_sizes (array): integer [tiles], the live rows
of each tile, at most tile_size. The pad slots after them
are never read.
num_prefix_tiles (int): the leading tiles that are the dense
prefix. Their query rows are not computed here.
scale (float): query scale (typically 1/sqrt(128)).
tile_size (int): rows per tile, 64.
query_rows (int, optional): query rows per threadgroup, 16,
32 or 64. By default 32 below 70 video tiles and 64 from
70, the faster of the two on M5 Max.
coarse (array, optional): float32 [heads, tiles, 128], the
pooled-compression output of each tile, given with gate.
gate (array, optional): the tiled gate, the shape and dtype of
q. Each live video query row adds
bf16(coarse[h, tile] * gate[row]) to its bfloat16 output:
the attention output and the product are each rounded to
bfloat16, then summed, as the unfused MLX ops round them.
Returns:
array: [S_pad, heads, 128] bfloat16. The live rows of the video
query tiles hold the attention output, plus the gate term when
gate is given. Prefix rows and pad rows are zero, and so are
the rows of a tile with no live key tile when no gate is given.
)");
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(
"qk_norm_rope",
&mlx_kquant::qk_norm_rope,
"q"_a,
"k"_a,
"q_w"_a,
"k_w"_a,
"cos"_a,
"sin"_a,
"eps"_a,
nb::kw_only(),
"stream"_a = nb::none(),
R"(
Per-head RMSNorm and RoPE of attention q and k in one dispatch:
y = rms_norm(x, w, eps) over the head dim, then each interleaved
pair (y[2i], y[2i + 1]) rotates by the angle with cosine cos[l, i]
and sine sin[l, i]. The output is written in the attention layout,
so no transpose copy follows. f32 math with one round at the write.
q and k are read through their strides, so slices of one fused qkv
output need no copy. On the GPU head dims 64, 96, 128 and 256 run
the fused kernel; other even head dims and CPU streams run the same
math as stock ops. The op is for inference. On the GPU the fused
kernel has no gradient or vmap, and mx.grad or mx.vmap through it
raises.