forked from modular/modular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernels.py
More file actions
2362 lines (2048 loc) · 77.5 KB
/
kernels.py
File metadata and controls
2362 lines (2048 loc) · 77.5 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
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2025, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
"""Helper functions for wrapping custom kv cache/attention related ops."""
from __future__ import annotations
from collections.abc import MutableSequence
from typing import Optional
import numpy as np
from max.dtype import DType
from max.graph import (
BufferValue,
DeviceRef,
Dim,
TensorType,
TensorValue,
TensorValueLike,
Value,
ops,
)
from max.graph.ops.quantized import repack_gguf_quantized_weights
from max.graph.quantization import QuantizationConfig, QuantizationEncoding
from .attention.mask_config import (
AttentionMaskVariant,
MHAMaskConfig,
MHAMaskVariant,
PositionalEncodingVariant,
)
from .kv_cache import (
ContinuousBatchingKVCacheCollection,
KVCacheParams,
KVCacheStrategy,
PagedKVCacheCollection,
)
_MHA_MASK_CONFIG_DICT = {
MHAMaskVariant.CAUSAL_MASK: MHAMaskConfig(
attention_mask_variant=AttentionMaskVariant.CAUSAL_MASK,
positional_encoding_variant=PositionalEncodingVariant.NO_POS,
),
MHAMaskVariant.CAUSAL_ALIBI_MASK: MHAMaskConfig(
attention_mask_variant=AttentionMaskVariant.CAUSAL_MASK,
positional_encoding_variant=PositionalEncodingVariant.ALIBI_POS,
),
MHAMaskVariant.NULL_MASK: MHAMaskConfig(
attention_mask_variant=AttentionMaskVariant.NULL_MASK,
positional_encoding_variant=PositionalEncodingVariant.NO_POS,
),
MHAMaskVariant.CHUNKED_CAUSAL_MASK: MHAMaskConfig(
attention_mask_variant=AttentionMaskVariant.CHUNKED_CAUSAL_MASK,
positional_encoding_variant=PositionalEncodingVariant.NO_POS,
),
MHAMaskVariant.SLIDING_WINDOW_CAUSAL_MASK: MHAMaskConfig(
attention_mask_variant=AttentionMaskVariant.SLIDING_WINDOW_CAUSAL_MASK,
positional_encoding_variant=PositionalEncodingVariant.NO_POS,
),
}
def fused_qkv_ragged_matmul(
kv_params: KVCacheParams,
input: TensorValue,
input_row_offsets: TensorValue,
wqkv: TensorValue,
kv_collection: ContinuousBatchingKVCacheCollection | PagedKVCacheCollection,
layer_idx: TensorValue,
n_heads: int,
bias: TensorValue | None = None,
) -> TensorValue:
"""Computes fused query, key, and value projections with ragged input.
`input` and `input_row_offsets` are used together to implement the ragged
tensor.
`input_row_offsets` indicates where each batch starts and ends in `input`
Raises:
ValueError: on input shapes/dtypes that are invalid for the kernel.
"""
if input.dtype != wqkv.dtype:
msg = (
"expected input and wqkv to have the same dtype, but got"
f" {input.dtype} and {wqkv.dtype}, respectively."
)
raise ValueError(msg)
input_rank_expected = 2
if input.rank != input_rank_expected:
msg = f"expected input to have rank {input_rank_expected}, was {input.rank}"
raise ValueError(msg)
if input_row_offsets.dtype != DType.uint32:
msg = (
"expected input_row_offsets to have dtype uint32, was"
f" {input_row_offsets.dtype}"
)
raise ValueError(msg)
if layer_idx.dtype != DType.uint32:
msg = f"expected layer_idx to have dtype uint32, was {layer_idx.dtype}"
raise ValueError(msg)
if kv_params.cache_strategy not in {
KVCacheStrategy.CONTINUOUS,
KVCacheStrategy.PAGED,
}:
msg = f"unsupported cache strategy for fused_qkv_ragged_matmul: {kv_params.cache_strategy}"
raise ValueError(msg)
parameters: dict[str, int | str | DType] = {
"num_heads": kv_params.n_kv_heads_per_device,
"head_dim": kv_params.head_dim,
}
if kv_params.cache_strategy == KVCacheStrategy.PAGED:
assert kv_params.page_size is not None
parameters["page_size"] = int(kv_params.page_size)
cache_strategy_str = kv_params.cache_strategy.kernel_substring()
op_name = f"mo.fused_qkv_matmul.ragged.{cache_strategy_str}"
values = [input, input_row_offsets, wqkv, kv_collection, layer_idx]
if bias:
op_name += ".bias"
values.append(bias)
return ops.inplace_custom(
op_name,
device=input.device,
values=values,
out_types=[
TensorType(
dtype=input.dtype,
shape=input.shape[:-1] + [n_heads * kv_params.head_dim],
device=input.device,
)
],
parameters=parameters,
)[0].tensor
def fused_qkv_ragged_matmul_scaled_float8(
kv_params: KVCacheParams,
input: TensorValue,
input_row_offsets: TensorValue,
wqkv: TensorValue,
kv_collection: PagedKVCacheCollection,
layer_idx: TensorValue,
n_heads: int,
input_scale: TensorValue,
weight_scale: TensorValue,
bias: TensorValue | None = None,
) -> TensorValue:
"""Computes fused query, key, and value projections with ragged input.
`input` and `input_row_offsets` are used together to implement the ragged
tensor.
`input_row_offsets` indicates where each batch starts and ends in `input`
Raises:
ValueError: on input shapes/dtypes that are invalid for the kernel.
"""
if input.dtype != wqkv.dtype:
raise ValueError(
"expected input and wqkv to have the same dtype, but got"
f" {input.dtype} and {wqkv.dtype}, respectively."
)
input_rank_expected = 2
if input.rank != input_rank_expected:
raise ValueError(
f"expected input to have rank {input_rank_expected}, was {input.rank}"
)
if input_row_offsets.dtype != DType.uint32:
raise ValueError(
"expected input_row_offsets to have dtype uint32, was"
f" {input_row_offsets.dtype}"
)
if layer_idx.dtype != DType.uint32:
raise ValueError(
f"expected layer_idx to have dtype uint32, was {layer_idx.dtype}"
)
# Device check - all tensors must be on the same device
if not all(
t.device == input.device
for t in [wqkv, input_row_offsets, input_scale, weight_scale]
):
raise ValueError(
f"expected all tensors to be on the same device as input ({input.device}), "
f"but got:\n"
f" wqkv={wqkv.device}\n"
f" input_row_offsets={input_row_offsets.device}\n"
f" input_scale={input_scale.device}\n"
f" weight_scale={weight_scale.device}"
)
# layer_idx must be a scalar on CPU as it's used for indexing
if layer_idx.device != DeviceRef.CPU():
raise ValueError(
f"expected layer_idx to be on CPU device, but got {layer_idx.device}"
)
# for per-tensor quantization, the scale is a scalar. We view it as a 1x1
# rank-2 tensor so that we can use the same kernel for per-tensor and
# per-channel quantization.
if input_scale.shape in [[], [1]]:
input_scale = input_scale.reshape([1, 1])
if weight_scale.shape in [[], [1]]:
weight_scale = weight_scale.reshape([1, 1])
assert kv_params.page_size is not None
parameters: dict[str, int | str | DType] = {
"kv_type": kv_params.dtype,
"num_heads": kv_params.n_kv_heads_per_device,
"head_dim": kv_params.head_dim,
"page_size": int(kv_params.page_size),
}
op_name = "mo.fused_qkv_matmul.ragged.paged.scale"
return ops.inplace_custom(
op_name,
device=input.device,
values=[
input,
input_row_offsets,
wqkv,
input_scale,
weight_scale,
kv_collection,
layer_idx,
],
out_types=[
TensorType(
dtype=DType.bfloat16,
shape=input.shape[:-1] + [n_heads * kv_params.head_dim],
device=input.device,
)
],
parameters=parameters,
)[0].tensor
def unfused_qkv_ragged_matmul_gguf_quantized(
kv_params: KVCacheParams,
input: TensorValue,
input_row_offsets: TensorValue,
n_heads: int,
q_weight: TensorValue,
k_weight: TensorValue,
v_weight: TensorValue,
quantization_encoding_q: QuantizationEncoding,
quantization_encoding_k: QuantizationEncoding,
quantization_encoding_v: QuantizationEncoding,
kv_collection: ContinuousBatchingKVCacheCollection | PagedKVCacheCollection,
layer_idx: TensorValue,
) -> TensorValue:
"""Computes fused query, key, and value projections with ragged input and
quantized weight matrices. A `quantization_config` must be provided.
`input` and `input_row_offsets` are used together to implement the ragged
tensor.
`input_row_offsets` indicates where each batch starts and ends in `input`
Raises:
ValueError: on input shapes/dtypes that are invalid for the kernel.
"""
input_rank_expected = 2
if input.rank != input_rank_expected:
msg = f"expected input to have rank {input_rank_expected}, was {input.rank}"
raise ValueError(msg)
if input.dtype != DType.float32:
msg = f"expected input to have dtype float32, was {input.dtype}"
raise ValueError(msg)
if input_row_offsets.dtype != DType.uint32:
msg = (
"expected input_row_offsets to have dtype uint32, was"
f" {input_row_offsets.dtype}"
)
raise ValueError(msg)
if layer_idx.dtype != DType.uint32:
msg = f"expected layer_idx to have dtype uint32, was {layer_idx.dtype}"
raise ValueError(msg)
if kv_params.cache_strategy not in {KVCacheStrategy.PAGED}:
msg = f"unsupported cache strategy for fused_qkv_ragged_matmul: {kv_params.cache_strategy}"
raise ValueError(msg)
if (
not quantization_encoding_q.is_gguf
or not quantization_encoding_k.is_gguf
or not quantization_encoding_v.is_gguf
):
raise ValueError(
f"expected quantization_encoding_q, quantization_encoding_k, and quantization_encoding_v to be gguf, was {quantization_encoding_q}, {quantization_encoding_k}, and {quantization_encoding_v}"
)
assert kv_params.page_size is not None
parameters: dict[str, int | str | DType] = {
"num_heads": kv_params.n_kv_heads_per_device,
"head_dim": kv_params.head_dim,
"quantization_encoding_q": quantization_encoding_q.name,
"quantization_encoding_k": quantization_encoding_k.name,
"quantization_encoding_v": quantization_encoding_v.name,
"page_size": kv_params.page_size,
}
cache_strategy_str = kv_params.cache_strategy.kernel_substring()
return ops.inplace_custom(
name=f"mo.unfused_qkv_matmul.ragged.{cache_strategy_str}.gguf_quantized",
device=input.device,
values=[
input,
input_row_offsets,
repack_gguf_quantized_weights(q_weight, quantization_encoding_q),
repack_gguf_quantized_weights(k_weight, quantization_encoding_k),
repack_gguf_quantized_weights(v_weight, quantization_encoding_v),
kv_collection,
layer_idx,
],
out_types=[
TensorType(
dtype=input.dtype,
shape=input.shape[:-1] + [n_heads * kv_params.head_dim],
device=input.device,
)
],
parameters=parameters,
)[0].tensor
def fused_qkv_ragged_matmul_quantized(
kv_params: KVCacheParams,
input: TensorValue,
input_row_offsets: TensorValue,
wqkv: TensorValue,
kv_collection: ContinuousBatchingKVCacheCollection | PagedKVCacheCollection,
layer_idx: TensorValue,
n_heads: int,
quantization_config: QuantizationConfig,
perm_idx: TensorValue | None = None,
bias: TensorValue | None = None,
) -> TensorValue:
"""Computes fused query, key, and value projections with ragged input and
quantized weight matrices. A `quantization_config` must be provided.
`input` and `input_row_offsets` are used together to implement the ragged
tensor.
`input_row_offsets` indicates where each batch starts and ends in `input`
Raises:
ValueError: on input shapes/dtypes that are invalid for the kernel.
"""
input_rank_expected = 2
if input.rank != input_rank_expected:
msg = f"expected input to have rank {input_rank_expected}, was {input.rank}"
raise ValueError(msg)
if input_row_offsets.dtype != DType.uint32:
msg = (
"expected input_row_offsets to have dtype uint32, was"
f" {input_row_offsets.dtype}"
)
raise ValueError(msg)
if layer_idx.dtype != DType.uint32:
msg = f"expected layer_idx to have dtype uint32, was {layer_idx.dtype}"
raise ValueError(msg)
if kv_params.cache_strategy not in {
KVCacheStrategy.CONTINUOUS,
KVCacheStrategy.PAGED,
}:
msg = f"unsupported cache strategy for fused_qkv_ragged_matmul: {kv_params.cache_strategy}"
raise ValueError(msg)
# In the group-wise quantization scheme, every `group_size` quantized weights
# share the same scale. If `has_zp` is `True`, there is also a group-wise zero
# point that need to be subtracted from the quantized weights.
# Since the new extensibility API doesn't currently support `bool` type parameters,
# we pass `has_zp` as an integer (`has_zp_int`).
# For GPTQ, `has_zp_int` will always be 0.
parameters: dict[str, int | str | DType] = {
"num_heads": kv_params.n_kv_heads_per_device,
"head_dim": kv_params.head_dim,
"group_size": quantization_config.group_size,
"has_zp_int": 0,
}
if perm_idx:
input = ops.gather(input, TensorValue(perm_idx), axis=1)
perm_idx = perm_idx.to(input.type.device or DeviceRef.CPU())
wqkv = ops.custom(
"GPTQ_gpu_repack_b4_g128_desc_act",
wqkv.device,
list((wqkv, perm_idx)),
out_types=[
TensorType(
DType.uint8,
((wqkv.shape[1], wqkv.shape[0])),
device=input.type.device or DeviceRef.CPU(),
)
],
)[0].tensor
else:
wqkv = ops.custom(
"GPTQ_gpu_repack_b4_g128",
wqkv.device,
list((wqkv,)),
out_types=[
TensorType(
DType.uint8,
((wqkv.shape[1], wqkv.shape[0])),
device=input.type.device or DeviceRef.CPU(),
)
],
)[0].tensor
if kv_params.cache_strategy == KVCacheStrategy.PAGED:
assert kv_params.page_size is not None
parameters["page_size"] = int(kv_params.page_size)
cache_strategy_str = kv_params.cache_strategy.kernel_substring()
args = [input, input_row_offsets, wqkv, kv_collection, layer_idx]
if bias:
args.append(bias)
bias_name_str = "bias."
else:
bias_name_str = ""
op_name = f"mo.fused_qkv_matmul.ragged.{cache_strategy_str}.{bias_name_str}quantized"
return ops.inplace_custom(
op_name,
device=input.device,
values=args,
out_types=[
TensorType(
dtype=input.dtype,
shape=input.shape[:-1] + [n_heads * kv_params.head_dim],
device=input.device,
)
],
parameters=parameters,
)[0].tensor
def fused_qkv_matmul(
kv_params: KVCacheParams,
input: TensorValue,
wqkv: TensorValue,
kv_collection: ContinuousBatchingKVCacheCollection,
layer_idx: TensorValue,
n_heads: int,
) -> TensorValue:
"""Computes fused query, key and value projections."""
if input.dtype != wqkv.dtype:
msg = (
"expected input and wqkv to have the same dtype, but got"
f" {input.dtype} and {wqkv.dtype}, respectively."
)
raise ValueError(msg)
input_rank_expected = 3
if input.rank != input_rank_expected:
msg = f"expected input to have rank {input_rank_expected}, was {input.rank}"
raise ValueError(msg)
wqkv_rank_expected = 2
if wqkv.rank != wqkv_rank_expected:
msg = (
f"expected wqkv to have rank {wqkv_rank_expected}, was {wqkv.rank}"
)
raise ValueError(msg)
if layer_idx.dtype != DType.uint32:
msg = f"expected layer_idx to have dtype uint32, was {layer_idx.dtype}"
raise ValueError(msg)
if kv_params.cache_strategy != KVCacheStrategy.CONTINUOUS:
msg = f"unsupported cache strategy for fused_qkv_matmul: {kv_params.cache_strategy}"
raise ValueError(msg)
cache_strategy_str = kv_params.cache_strategy.kernel_substring()
op_name = f"mo.fused_qkv_matmul.padded.{cache_strategy_str}"
return ops.inplace_custom(
op_name,
device=input.device,
values=[input, wqkv, kv_collection, layer_idx],
out_types=[
TensorType(
dtype=input.dtype,
shape=input.shape[:-1] + [n_heads * kv_params.head_dim],
device=input.device,
)
],
parameters={
"num_heads": kv_params.n_kv_heads_per_device,
"head_dim": kv_params.head_dim,
},
)[0].tensor
def matmul_kv_cache_ragged(
kv_params: KVCacheParams,
hidden_states: TensorValue,
input_row_offsets: TensorValue,
weight: TensorValue,
kv_collection: PagedKVCacheCollection,
layer_idx: TensorValue,
) -> None:
"""Computes key and value projections with ragged input.
`hidden_states` and `input_row_offsets` are used together to
implement the ragged tensor.
`input_row_offsets` indicates where each batch starts and ends in `input`
"""
if hidden_states.dtype != weight.dtype:
msg = (
"expected hidden_states and weight to have the same dtype, but got"
f" {hidden_states.dtype} and {weight.dtype}, respectively."
)
raise ValueError(msg)
hidden_states_rank_expected = 2
if hidden_states.rank != hidden_states_rank_expected:
msg = (
"expected hidden_states to have rank "
f"{hidden_states_rank_expected}, was {hidden_states.rank}"
)
raise ValueError(msg)
if input_row_offsets.dtype != DType.uint32:
msg = (
"expected input_row_offsets to have dtype uint32, was"
f" {input_row_offsets.dtype}"
)
raise ValueError(msg)
if kv_params.cache_strategy != KVCacheStrategy.PAGED:
msg = f"unsupported cache strategy for matmul_kv_cache_ragged: {kv_params.cache_strategy}"
raise ValueError(msg)
parameters: dict[str, int | str | DType] = {
"num_heads": kv_params.n_kv_heads_per_device,
"head_dim": kv_params.head_dim,
}
if kv_params.cache_strategy == KVCacheStrategy.PAGED:
assert kv_params.page_size is not None
parameters["page_size"] = kv_params.page_size
cache_strategy_str = kv_params.cache_strategy.kernel_substring()
op_name = f"mo.kv_matmul.ragged.{cache_strategy_str}"
ops.inplace_custom(
name=op_name,
device=hidden_states.device,
values=[
hidden_states,
input_row_offsets,
weight,
kv_collection,
layer_idx,
],
parameters=parameters,
)
def matmul_k_cache_ragged(
kv_params: KVCacheParams,
hidden_states: TensorValue,
input_row_offsets: TensorValue,
weight: TensorValue,
kv_collection: PagedKVCacheCollection,
layer_idx: TensorValue,
) -> None:
"""Computes key projections with ragged input.
`hidden_states` and `input_row_offsets` are used together to
implement the ragged tensor.
`input_row_offsets` indicates where each batch starts and ends in `input`
"""
if hidden_states.dtype != weight.dtype:
msg = (
"expected hidden_states and weight to have the same dtype, but got"
f" {hidden_states.dtype} and {weight.dtype}, respectively."
)
raise ValueError(msg)
hidden_states_rank_expected = 2
if hidden_states.rank != hidden_states_rank_expected:
msg = (
"expected hidden_states to have rank "
f"{hidden_states_rank_expected}, was {hidden_states.rank}"
)
raise ValueError(msg)
if input_row_offsets.dtype != DType.uint32:
msg = (
"expected input_row_offsets to have dtype uint32, was"
f" {input_row_offsets.dtype}"
)
raise ValueError(msg)
if kv_params.cache_strategy != KVCacheStrategy.PAGED:
msg = f"unsupported cache strategy for matmul_kv_cache_ragged: {kv_params.cache_strategy}"
raise ValueError(msg)
parameters: dict[str, int | str | DType] = {
"num_heads": kv_params.n_kv_heads_per_device,
"head_dim": kv_params.head_dim,
}
if kv_params.cache_strategy == KVCacheStrategy.PAGED:
assert kv_params.page_size is not None
parameters["page_size"] = kv_params.page_size
cache_strategy_str = kv_params.cache_strategy.kernel_substring()
op_name = f"mo.k_matmul.ragged.{cache_strategy_str}"
ops.inplace_custom(
name=op_name,
device=hidden_states.device,
values=[
hidden_states,
input_row_offsets,
weight,
kv_collection,
layer_idx,
],
parameters=parameters,
)
def fused_qk_ragged_rope(
kv_params: KVCacheParams,
input: TensorValue,
input_row_offsets: TensorValue,
kv_collection: ContinuousBatchingKVCacheCollection | PagedKVCacheCollection,
freqs_cis: TensorValue,
layer_idx: TensorValue,
interleaved: bool = True,
) -> TensorValue:
"""Computes fused query-key attention with rotary positional encodings and ragged inputs.
Args:
input: [batch_size * seq_len, n_heads, head_dim]
input_row_offsets:
freqs_cis: tensor of shape (max_seq_len * 2, head_dim)
layer_idx:
interleaved:
`input` and `input_row_offsets` are used together to implement the ragged tensor.
`input_row_offsets` indicates where each batch starts and ends in `input`
"""
if input.dtype != freqs_cis.dtype:
msg = (
"expected input and freqs_cis to share a dtype, but got"
f" {input.dtype} and {freqs_cis.dtype} respectively"
)
raise ValueError(msg)
if input_row_offsets.dtype != DType.uint32:
msg = (
"expected input_row_offsets to have dtype uint32, was"
f" {input_row_offsets.dtype}"
)
if layer_idx.dtype != DType.uint32:
msg = f"expected layer_idx to have dtype uint32, was {layer_idx.dtype}"
raise ValueError(msg)
if kv_params.cache_strategy not in {
KVCacheStrategy.CONTINUOUS,
KVCacheStrategy.PAGED,
}:
msg = f"unsupported cache strategy for fused_qk_ragged_rope: {kv_params.cache_strategy}"
raise ValueError(msg)
parameters: dict[str, bool | int | str | DType] = {
"num_heads": kv_params.n_kv_heads_per_device,
"head_dim": kv_params.head_dim,
"interleaved": interleaved,
}
if kv_params.cache_strategy == KVCacheStrategy.PAGED:
assert kv_params.page_size is not None
parameters["page_size"] = kv_params.page_size
cache_strategy_str = kv_params.cache_strategy.kernel_substring()
op_name = f"mo.fused_qk_rope.ragged.{cache_strategy_str}"
return ops.inplace_custom(
op_name,
device=input.device,
values=[input, input_row_offsets, kv_collection, freqs_cis, layer_idx],
out_types=[
TensorType(
dtype=input.dtype, shape=input.shape, device=input.device
)
],
parameters=parameters,
)[0].tensor
def fused_qk_rope(
kv_params: KVCacheParams,
input: TensorValue,
kv_collection: ContinuousBatchingKVCacheCollection,
freqs_cis_2d: TensorValue,
layer_idx: TensorValue,
interleaved: bool = True,
) -> TensorValue:
"""Computes fused query-key attention with rotary positional encodings."""
input_rank_expected = 4
if input.rank != input_rank_expected:
msg = (
f"expected input of rank {input_rank_expected} but got {input.rank}"
)
raise ValueError(msg)
freqs_cis_rank_expected = 2
if freqs_cis_2d.rank != freqs_cis_rank_expected:
msg = (
f"expected freqs_cis_2d of rank {freqs_cis_rank_expected} but got "
f"{freqs_cis_2d.rank}"
)
raise ValueError(msg)
if layer_idx.dtype != DType.uint32:
msg = f"expected uint32 layer_idx but got {layer_idx.dtype}"
raise ValueError(msg)
if kv_params.cache_strategy != KVCacheStrategy.CONTINUOUS:
msg = f"unsupported cache strategy for fused_qk_rope: {kv_params.cache_strategy}"
raise ValueError(msg)
parameters: dict[str, bool | int | str | DType] = {
"num_heads": kv_params.n_kv_heads_per_device,
"head_dim": kv_params.head_dim,
"interleaved": interleaved,
}
if kv_params.cache_strategy == KVCacheStrategy.PAGED:
assert kv_params.page_size is not None
parameters["page_size"] = kv_params.page_size
cache_strategy_str = kv_params.cache_strategy.kernel_substring()
op_name = f"mo.fused_qk_rope.padded.{cache_strategy_str}"
return ops.inplace_custom(
op_name,
device=input.device,
values=[input, kv_collection, freqs_cis_2d, layer_idx],
out_types=[
TensorType(
dtype=input.dtype, shape=input.shape, device=input.device
)
],
parameters=parameters,
)[0].tensor
def flash_attention(
kv_params: KVCacheParams,
input: TensorValue,
kv_collection: ContinuousBatchingKVCacheCollection,
layer_idx: TensorValue,
attention_mask: TensorValue,
valid_lengths: TensorValue,
scale: float,
) -> TensorValue:
"""Computes flash attention provided the mo.opaque KV Cache."""
input_rank_expected = 4
if input.rank != input_rank_expected:
msg = (
f"expected input of rank {input_rank_expected} but got {input.rank}"
)
raise ValueError(msg)
if layer_idx.dtype != DType.uint32:
msg = f"expected uint32 layer_idx but got {layer_idx.dtype}"
raise ValueError(msg)
if attention_mask.dtype != input.dtype:
msg = (
f"expected attention mask dtype {attention_mask.dtype} to match "
f"the input's dtype {input.dtype}"
)
raise ValueError(msg)
if valid_lengths.dtype != DType.uint32:
msg = f"expected uint32 valid_lengths but got {valid_lengths.dtype}"
raise ValueError(msg)
if kv_params.cache_strategy != KVCacheStrategy.CONTINUOUS:
msg = f"unsupported cache strategy for flash_attention: {kv_params.cache_strategy}"
raise ValueError(msg)
cache_strategy_str = kv_params.cache_strategy.kernel_substring()
op_name = f"mo.mha.padded.{cache_strategy_str}.tensor_mask"
parameters: dict[str, bool | int | str | DType] = {
"num_heads": kv_params.n_kv_heads_per_device,
"head_dim": kv_params.head_dim,
"score_mod_str": PositionalEncodingVariant.NO_POS.value,
}
return ops.inplace_custom(
op_name,
device=input.device,
values=[
input,
kv_collection,
layer_idx,
attention_mask,
valid_lengths,
# NOTE: The scale argument to the flash attention kernel is
# constrained to float32.
ops.constant(scale, dtype=DType.float32, device=DeviceRef.CPU()),
],
out_types=[
TensorType(
dtype=input.dtype, shape=input.shape, device=input.device
)
],
parameters=parameters,
)[0].tensor
def flash_attention_with_causal_mask(
kv_params: KVCacheParams,
input: TensorValue,
kv_collection: ContinuousBatchingKVCacheCollection,
layer_idx: TensorValue,
valid_lengths: TensorValue,
scale: float,
) -> TensorValue:
"""Computes flash attention provided the mo.opaque KV Cache.
Notably, materializes the causal mask within the kernel."""
if input.shape[0] != valid_lengths.shape[0]:
msg = (
"expected batch size of input, to equal length of valid_lengths"
f" got batch size of input ({input.shape[0]}), length of"
f" valid_lengths ({valid_lengths.shape[0]})"
)
raise ValueError(msg)
if input.dtype != kv_params.dtype:
msg = (
f"expected input to be dtype: {kv_params.dtype}, got {input.dtype}"
)
raise ValueError(msg)
if layer_idx.dtype != DType.uint32:
msg = f"expected uint32 layer_idx but got {layer_idx.dtype}"
raise ValueError(msg)
if valid_lengths.dtype != DType.uint32:
msg = f"expected uint32 valid_lengths but got {valid_lengths.dtype}"
raise ValueError(msg)
if kv_params.cache_strategy != KVCacheStrategy.CONTINUOUS:
msg = f"unsupported cache strategy for flash_attention_with_causal_mask: {kv_params.cache_strategy}"
raise ValueError(msg)
cache_strategy_str = kv_params.cache_strategy.kernel_substring()
op_name = f"mo.mha.padded.{cache_strategy_str}"
parameters: dict[str, bool | int | str | DType] = {
"num_heads": kv_params.n_kv_heads_per_device,
"head_dim": kv_params.head_dim,
"mask_str": MHAMaskVariant.CAUSAL_MASK.value,
"score_mod_str": PositionalEncodingVariant.NO_POS.value,
}
return ops.inplace_custom(
op_name,
device=input.device,
values=[
input,
kv_collection,
layer_idx,
valid_lengths,
# NOTE: The scale argument to flash attention is constrained to float32.
ops.constant(scale, dtype=DType.float32, device=DeviceRef.CPU()),
],
out_types=[
TensorType(
dtype=input.dtype, shape=input.shape, device=input.device
)
],
parameters=parameters,
)[0].tensor
def flash_attention_gpu(
q: TensorValue,
k: TensorValue,
v: TensorValue,
mask_variant: MHAMaskVariant,
scale: float,
local_window_size: int = -1,
valid_length: Optional[TensorValue] = None,
) -> TensorValue:
"""Computes flash attention using GPU-optimized kernel.
Args:
q: Query tensor of shape [batch, seq_len, num_heads, head_dim]
k: Key tensor of shape [batch, seq_len, num_heads, head_dim]
v: Value tensor of shape [batch, seq_len, num_heads, head_dim]
mask_variant: The mask variant to use for attention
scale: Scaling factor for attention scores
local_window_size: Local window size for sliding window attention
valid_length: Optional tensor of shape [batch] with dtype uint32.
When provided, uses the padded kernel variant that respects
the valid sequence lengths for each batch element.
Returns:
Output tensor of shape [batch, seq_len, num_heads, head_dim]
"""
if q.dtype != k.dtype or q.dtype != v.dtype:
msg = (
"q, k, v must have matching dtypes. Got "
f"q.dtype={q.dtype}, k.dtype={k.dtype}, v.dtype={v.dtype}"
)
raise ValueError(msg)
expected_rank = 4
for name, tensor in [("q", q), ("k", k), ("v", v)]:
if tensor.rank != expected_rank:
msg = f"{name} must be rank {expected_rank}, got {tensor.rank}"
raise ValueError(msg)
# Validate head dimension matches across all inputs
head_dim = q.shape[-1]
if k.shape[-1] != head_dim or v.shape[-1] != head_dim:
msg = (
"All inputs must have same head_dim. Got "
f"q: {head_dim}, k: {k.shape[-1]}, v: {v.shape[-1]}"
)
raise ValueError(msg)
# Validate valid_length if provided
if valid_length is not None:
if valid_length.dtype != DType.uint32:
msg = (
f"valid_length must have dtype uint32, got {valid_length.dtype}"
)
raise ValueError(msg)
if valid_length.rank != 1:
msg = f"valid_length must be rank 1, got {valid_length.rank}"
raise ValueError(msg)
if valid_length.shape[0] != q.shape[0]:
msg = (
f"valid_length batch size ({valid_length.shape[0]}) must match "
f"q batch size ({q.shape[0]})"
)
raise ValueError(msg)
mha_mask_config = _MHA_MASK_CONFIG_DICT[mask_variant]
parameters: dict[str, int | str | DType] = {}
parameters["mask_str"] = mha_mask_config.attention_mask_variant.value
parameters["score_mod_str"] = (
mha_mask_config.positional_encoding_variant.value
)
parameters["local_window_size"] = local_window_size
op_name = "mo.mha.no_cache"
values = [q, k, v]
if valid_length is not None:
op_name = "mo.mha.padded.no_cache"
values.append(valid_length)
values.append(
ops.constant(scale, dtype=DType.float32, device=DeviceRef.CPU())
)
return ops.custom(
op_name,
values=values,
out_types=[
TensorType(
dtype=q.dtype,