Repository navigation
Expand file tree
/
Copy pathbindings.cpp
More file actions
3086 lines (2827 loc) · 113 KB
/
Copy pathbindings.cpp
File metadata and controls
3086 lines (2827 loc) · 113 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(
"_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(
"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(
"shexp_glu_combo_has_kernel",
&mlx_kquant::shexp_glu_combo_has_kernel,
"kquant_type"_a,
"shexp_gate_type"_a,
"shexp_up_type"_a,
"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.");
m.def(
"shexp_mix_combo_has_kernel",
&mlx_kquant::shexp_mix_combo_has_kernel,
"kquant_type"_a,
"shexp_type"_a,
"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.");
m.def(
"shexp_mix_slot_parallel",
&mlx_kquant::shexp_mix_slot_parallel,
"kquant_type"_a,
"shexp_type"_a,
"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 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(
"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.
Args:
q (array): [B, L, H, D], float16/bfloat16, D even.
k (array): same shape and dtype as q.
q_w (array): [D] q norm weight, any float dtype.
k_w (array): [D] k norm weight, any float dtype.
cos (array): [L, D / 2] per-row cosines, any float dtype, shared
by the batch.
sin (array): [L, D / 2] per-row sines.
eps (float): norm epsilon.
Returns:
tuple(array, array): q and k as row-contiguous [B, H, L, D] in
the input dtype.
)");
m.def(
"quantized_matmul_glu",
&mlx_kquant::quantized_matmul_glu,
"x"_a,
"w_gate"_a,
"w_up"_a,
"kquant_type"_a,
"activation"_a = "silu",
nb::kw_only(),
"stream"_a = nb::none(),
R"(
GLU product of two quantized matmuls that share x:
y = act(x @ Wg^T) * (x @ Wu^T).
On a NAX GPU, for q4_k, q5_k and q6_k weights and for q8_0 weights
on bfloat16, with K a multiple of the codec's K tile (64 for q8_0,
128 for the others) and at least 1024 rows, one dispatch computes
the product with y as its only buffer. It walks K for the gate
weight and stores the activation of that sum in y, then walks K for
the up weight and multiplies the stored activation into that sum at
the final store. The sums, the activation and the product run in
f32, with one rounding of the activation to the dtype of y and one
of the product. A float16 store keeps a finite value in the finite
half range, and a NaN or an infinity passes. Every other case
builds the same product from quantized_matmul and stock ops, which
round each matmul to the activation dtype first. mx.grad gives the
gradient with respect to x at every row count: the gradient of the
fused kernel runs the unfused ops. The weights are frozen, as in
quantized_matmul. mx.jvp and mx.vmap raise at every row count.
Args:
x (array): [..., K], float16/bfloat16. float32 runs in bfloat16.
w_gate (array): [N, K bytes] uint8 wire bytes, the weight under
the activation.
w_up (array): same shape and codec as w_gate. The two may be
row slices of one wider weight.
kquant_type (str): the codec of both weights.
activation (str): "silu" or "gelu_tanh".
Returns:
array: [..., N] in the dtype quantized_matmul gives for x.
)");
m.def(
"quantized_matmul_lora",
[](mx::array x,
mx::array w,
const std::string& kquant_type,
mx::array lora_a,
mx::array lora_b,
const std::optional<mx::array>& strength,
const std::optional<std::vector<std::vector<int>>>& bands,
mx::StreamOrDevice s) {
std::optional<std::vector<int>> flat;
if (bands.has_value()) {
flat.emplace();
for (const auto& row : *bands) {
if (row.size() != 4) {
throw std::invalid_argument(
"[mlx_kquant.quantized_matmul_lora] bands must hold rows "
"of (col_start, col_end, z_start, rank).");
}
flat->insert(flat->end(), row.begin(), row.end());
}
}
return mlx_kquant::quantized_matmul_lora(
std::move(x),
std::move(w),
kquant_type,
std::move(lora_a),
std::move(lora_b),
strength,
flat,
s);
},
"x"_a,
"w"_a,
"kquant_type"_a,
"lora_a"_a,
"lora_b"_a,
nb::kw_only(),
"strength"_a = nb::none(),
"bands"_a = nb::none(),
"stream"_a = nb::none(),
R"(
Quantized matmul with a low-rank term:
y = x @ W^T + (strength * (x @ A)) @ B.
On a NAX GPU, for q4_k, q5_k, q6_k and q8_0 weights on bfloat16
with K up to 4096 and N of at least K, with at least 4096 rows
and at most 128 ranks per column (from 1024 rows and at every rank
where N is at least 8192), every band starting on a multiple of 64
columns and ending on a multiple of 32 columns or at N, at most 16
bands and a rank of at most 256 per band (without bands, a rank of
at most 256), stock ops compute z = strength * (x @ A) and one
dispatch walks the rank for z and B and then K for the weight in
the same f32 sums. y is the only
output buffer and is rounded once, at the store. KQ_QMM_LORA=2
runs the kernel from 1024 rows at every K and N, and 0 turns the
kernel off. Every other case builds the same sum from
quantized_matmul and stock ops, which round the matmul to the
activation dtype before the add. mx.grad gives the gradient with
respect to x, lora_a, lora_b and strength at every row count: the
gradient of the kernel runs the unfused ops. The weight is frozen,
as in quantized_matmul. mx.jvp and mx.vmap run with respect to
lora_a, lora_b and strength at every row count. With respect to x
both raise "Not implemented for KQuantMatmul" at every row count,
since quantized_matmul has neither.
Several adapters are one call: join their A columns and their B
rows, and give one strength per column.
A function compiled with shapeless=True keeps the path of its
trace at every later shape: a trace that ran the kernel runs it
below 1024 rows too, and the result is right there. A shapeless
function cannot hold a call with bands that builds the unfused
ops: that call raises ValueError.
Args:
x (array): [..., K], float16/bfloat16. float32 runs in bfloat16.
Fewer than 2^31 rows.
w (array): [N, K bytes] uint8 wire bytes. K and N below 2^25.
kquant_type (str): the codec of w.
lora_a (array): [K, R], any float dtype. R below 2^25.
lora_b (array): [R, N], any float dtype.
strength (array, optional): the scale of each column of
x @ A, in any float dtype: a 0-D array or [1] for one
scale, or [R] for one per column. Any other shape raises
ValueError. A new value needs no new trace.
bands (sequence, optional): rows of (col_start, col_end,
z_start, rank), in column order and disjoint. The columns
[col_start, col_end) of y take the ranks [z_start, z_start
+ rank) and that block of lora_b. A column outside every
band takes no low-rank term. None (the default): every
column takes every rank. An empty sequence: no column
takes a rank, and y is quantized_matmul(x, w), bit for
bit.
Returns:
array: [..., N] in the dtype quantized_matmul gives for x.
)");
m.def(
"conv2d_3x3",
&mlx_kquant::conv2d_3x3,
"x"_a,
"w"_a,
nb::kw_only(),
"bias"_a = nb::none(),
"stream"_a = nb::none(),
R"(
3x3 convolution, stride 1, padding 1, channels last:
y = conv(x, w) + bias, as mx.conv2d(x, w, padding=1) + bias.
On a NAX GPU, for bfloat16 with C a multiple of 16, from 1024
output pixels, one dispatch computes y as an implicit GEMM: f32
sums over the 9 taps and C channels, the bias added in f32, one
rounding. KQ_CONV_NAX=2 runs the kernel at every pixel count, and
0 turns it off. Every other case builds MLX's convolution on the
flipped kernel, which takes its implicit GEMM with f32 sums and not
its Winograd transform, then a stock add of the bias. mx.grad,
mx.jvp and mx.vmap run on that composition.
Args:
x (array): [B, H, W, C], a float dtype. B H W C and B H W O
below 2^31 for the kernel.
w (array): [O, 3, 3, C] in any float dtype. It runs in the
dtype of x.
bias (array, optional): [O] in any float dtype.
Returns:
array: [B, H, W, O] in the dtype of x.
)");
m.def(
"quantized_matmul_residual",
&mlx_kquant::quantized_matmul_residual,
"x"_a,
"w"_a,
"kquant_type"_a,
"residual"_a,
nb::kw_only(),
"gate"_a = nb::none(),
"stream"_a = nb::none(),
R"(
Quantized matmul with a residual epilogue:
y = residual + gate * (x @ W^T).
The residual add of a transformer block after its output
projection, with the gate of an adaptive norm where the block has
one. On a NAX GPU, for q4_k, q5_k, q6_k and q8_0 weights on
bfloat16, from 1024 rows, one dispatch walks K into f32 sums and
stores residual + gate * sum, rounded once: the product is never
written. KQ_QMM_RESID=2 runs the kernel at every row count, and 0
turns it off. Every other case builds the same sum from
quantized_matmul and stock ops, which round the product and the
gated product to the output dtype before the add. mx.grad gives
the gradient with respect to x, residual and gate: the gradient of
the kernel runs the unfused ops. The weight is frozen, as in
quantized_matmul. mx.jvp and mx.vmap run with respect to residual
and gate. With respect to x both raise "Not implemented for
KQuantMatmul", since quantized_matmul has neither.
Args:
x (array): [..., K], float16/bfloat16. float32 runs in bfloat16.
Fewer than 2^31 rows.
w (array): [N, K bytes] uint8 wire bytes. K and N below 2^25.
kquant_type (str): the codec of w.
residual (array): the output shape, x's shape with N last, in
any float dtype. It runs in the output dtype.
gate (array, optional): [N], or x's batch dims, then 1, then N
(one row per batch), in any float dtype. It runs in the
output dtype. None (the default): y = residual + x @ W^T.
Returns:
array: [..., N] in the dtype quantized_matmul gives for 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