-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathinterface.py
More file actions
2011 lines (1909 loc) · 76.9 KB
/
Copy pathinterface.py
File metadata and controls
2011 lines (1909 loc) · 76.9 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
# SPDX-FileCopyrightText: Copyright (c) 2026 MiniMax
# SPDX-License-Identifier: MIT
"""Sparse attention interface.
Current delivery scope:
- head dimension is supported only for D=128
Public API:
sparse_atten_func(...)
sparse_decode_atten_func(...)
SparseDecodePagedAttentionWrapper
Internal forward core:
_sparse_atten_csr_varlen_forward(...)
Preprocessing (external, done once):
q2k_indices [head_kv, total_q, topK] -> sparse_index_utils.build_k2q_csr()
-> k2q_row_ptr [head_kv, total_rows + 1] int32
-> k2q_q_indices [head_kv, total_q * topK] int32
"""
import math
import os
from typing import Optional
import cutlass
import cutlass.cute as cute
import torch
from cutlass import Float32, Int32
from cutlass.cute.runtime import from_dlpack
from src.sm100.fwd.combine import combine
from src.sm100.fwd.atten_fwd import SparseAttentionForwardSm100
from src.sm100.fwd.atten_fwd_nvfp4_kv import SparseAttentionForwardNvfp4KvSm100
from src.sm100.prepare_scheduler import (
SparseAttentionSchedule,
prepare_sparse_fwd_schedule_and_split,
)
from src.sm100.decode_schedule import (
DecodeAttentionSchedule,
prepare_decode_schedule,
)
from src.common.cute_dsl_utils import to_cute_tensor as to_cute_tensor_kvouter
from src.common.tma_utils import (
create_q_gather4_tma_desc,
)
_compile_cache: dict = {}
_TEMPERATURE_LSE_FAST_PATH_ABS_TOL = 1e-12
_SUPPORTED_SPARSE_TOPK = (4, 8, 16, 32)
_SUPPORTED_FWD_DTYPES = (torch.bfloat16, torch.float8_e4m3fn)
_SUPPORTED_FWD_MMA_DTYPES = (torch.bfloat16, torch.float8_e4m3fn)
_SUPPORTED_DECODE_QHEAD_PER_KV = 16
def _normalize_partial_dtype(partial_dtype: torch.dtype) -> torch.dtype:
supported = {torch.float32, torch.bfloat16, torch.float16, torch.float8_e4m3fn}
if partial_dtype not in supported:
raise TypeError(
"partial_dtype must be one of torch.float32 / torch.bfloat16 / "
"torch.float16 / torch.float8_e4m3fn, "
f"got {partial_dtype}"
)
return partial_dtype
def _normalize_forward_mma_dtype(dtype: Optional[torch.dtype], fallback: torch.dtype, name: str) -> torch.dtype:
dtype = fallback if dtype is None else dtype
if dtype not in _SUPPORTED_FWD_MMA_DTYPES:
raise TypeError(
f"{name} must be one of torch.bfloat16 / torch.float8_e4m3fn, got {dtype}"
)
return dtype
def _resolve_forward_mma_dtypes(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
qk_dtype: Optional[torch.dtype],
pv_dtype: Optional[torch.dtype],
) -> tuple[torch.dtype, torch.dtype]:
qk_dtype = _normalize_forward_mma_dtype(qk_dtype, q.dtype, "qk_dtype")
if pv_dtype is None:
# Preserve the historical fp8 KV-cache path: BF16 Q with FP8 K/V
# stages both K and V as BF16 compute operands.
if (
q.dtype == torch.bfloat16
and k.dtype == torch.float8_e4m3fn
and v.dtype == torch.float8_e4m3fn
):
pv_dtype = torch.bfloat16
else:
pv_dtype = v.dtype
pv_dtype = _normalize_forward_mma_dtype(pv_dtype, pv_dtype, "pv_dtype")
if q.dtype != qk_dtype:
raise ValueError(
"qk_dtype must match q storage dtype; Q fp8->bf16 staging is not supported"
)
if k.dtype != qk_dtype:
if not (k.dtype == torch.float8_e4m3fn and qk_dtype == torch.bfloat16):
raise ValueError(
"unsupported K storage/qk_dtype combination; only fp8 K -> bf16 QK staging is supported"
)
if v.dtype != pv_dtype:
if not (v.dtype == torch.float8_e4m3fn and pv_dtype == torch.bfloat16):
raise ValueError(
"unsupported V storage/pv_dtype combination; only fp8 V -> bf16 PV staging is supported"
)
return qk_dtype, pv_dtype
def _to_cute_tensor_meta(t: torch.Tensor, assumed_align: int = 4):
tensor = from_dlpack(t.detach(), assumed_align=assumed_align, enable_tvm_ffi=True)
return tensor.mark_layout_dynamic(leading_dim=0)
def _torch_dtype_to_cutlass_dtype(dtype: torch.dtype):
if dtype == torch.bfloat16:
return cutlass.BFloat16
if dtype == torch.float16:
return cutlass.Float16
if dtype == torch.float8_e4m3fn:
return cutlass.Float8E4M3FN
raise TypeError(
f"Only torch.bfloat16, torch.float16, torch.float8_e4m3fn supported, got {dtype}"
)
def _prepare_paged_kv_for_tma(k, v, blk_kv: int):
page_size = int(k.shape[2])
if page_size != blk_kv:
raise ValueError(f"Sparse Page Attention requires page_size == blk_kv, got {page_size} vs {blk_kv}")
return k, v
def _validate_cu_seqlens(
cu_seqlens: torch.Tensor,
*,
name: str,
device: torch.device,
) -> None:
if cu_seqlens.device != device:
raise ValueError(f"{name} must be on the same device as q")
if cu_seqlens.dtype != torch.int32:
raise TypeError(f"{name} must be torch.int32")
if cu_seqlens.ndim != 1:
raise ValueError(f"{name} must have shape [B + 1]")
if cu_seqlens.shape[0] < 1:
raise ValueError(f"{name} must have at least one element")
if not cu_seqlens.is_contiguous():
raise ValueError(f"{name} must be contiguous")
def _csr_row_capacity(k2q_row_ptr: torch.Tensor) -> int:
return int(k2q_row_ptr.shape[1] - 1)
def _validate_csr_varlen_inputs(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k2q_row_ptr: torch.Tensor,
k2q_q_indices: torch.Tensor,
topK: int,
blk_kv: int,
page_table: Optional[torch.Tensor],
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
seqused_k: Optional[torch.Tensor],
) -> tuple[int, int]:
if q.ndim != 3:
raise ValueError("CSR sparse forward requires q to have shape [total_q, Hq, D]")
if q.dtype not in _SUPPORTED_FWD_DTYPES:
raise TypeError(
"CSR sparse forward supports only torch.bfloat16 and "
f"torch.float8_e4m3fn Q/K/V, got {q.dtype}"
)
if q.device != k.device or q.device != v.device:
raise ValueError("q, k, v must be on the same device")
mixed_fp8_kv_bf16_q = (
q.dtype == torch.bfloat16
and k.dtype == torch.float8_e4m3fn
and v.dtype == torch.float8_e4m3fn
)
if not mixed_fp8_kv_bf16_q and (q.dtype != k.dtype or q.dtype != v.dtype):
raise ValueError(
"q, k, v must have the same dtype, except q=bf16 with fp8_e4m3 K/V cache"
)
if q.shape[-1] != k.shape[-1] or q.shape[-1] != v.shape[-1]:
raise ValueError("q, k, v must have the same head dimension")
dim = q.shape[-1]
if dim != 128:
raise NotImplementedError(
f"CSR sparse forward currently supports only D=128, got D={dim}"
)
if page_table is None:
if k.shape[-2] != v.shape[-2] or k.shape[-1] != v.shape[-1]:
raise ValueError("k and v must have the same [Hkv, D] tail dimensions")
head_kv = k.shape[-2]
else:
if k.ndim != 4 or v.ndim != 4:
raise ValueError(
"Sparse Page Attention requires k and v to have shape "
"[num_pages, Hkv, page_size, D]"
)
if k.shape[1] != v.shape[1] or k.shape[-1] != v.shape[-1]:
raise ValueError(
"Sparse Page Attention k and v must have the same Hkv and D"
)
head_kv = k.shape[1]
if (
q.device != k2q_row_ptr.device
or q.device != k2q_q_indices.device
):
raise ValueError("CSR metadata must be on the same device as q")
if (
k2q_row_ptr.dtype != torch.int32
or k2q_q_indices.dtype != torch.int32
):
raise TypeError("CSR metadata tensors must be torch.int32")
if k2q_row_ptr.ndim != 2 or k2q_q_indices.ndim != 2:
raise ValueError("k2q_row_ptr and k2q_q_indices must be rank-2")
_validate_cu_seqlens(cu_seqlens_q, name="cu_seqlens_q", device=q.device)
_validate_cu_seqlens(cu_seqlens_k, name="cu_seqlens_k", device=q.device)
if cu_seqlens_k.shape != cu_seqlens_q.shape:
raise ValueError("cu_seqlens_k must have shape [B + 1] matching cu_seqlens_q")
batch = int(cu_seqlens_q.shape[0] - 1)
total_q = q.shape[0]
head_q = q.shape[1]
if head_q % head_kv != 0:
raise ValueError("q.shape[1] must be divisible by Hkv")
qhead_per_kv = head_q // head_kv
if qhead_per_kv not in (1, 2, 4, 8, 16):
raise NotImplementedError(
"CSR forward is currently supported only for qhead_per_kv in {1, 2, 4, 8, 16}"
)
if k2q_row_ptr.shape[0] != head_kv or k2q_q_indices.shape[0] != head_kv:
raise ValueError("CSR metadata head dimension must match KV head count")
if k2q_q_indices.shape[1] < total_q * topK:
raise ValueError(
f"k2q_q_indices.shape[1] ({k2q_q_indices.shape[1]}) must be >= total_q * topK ({total_q * topK})"
)
if k2q_row_ptr.shape[1] < 1:
raise ValueError("k2q_row_ptr must contain at least one row pointer column")
if page_table is None:
if seqused_k is not None:
raise ValueError("seqused_k is only supported together with page_table")
total_k = k.shape[0]
if k.ndim != 3 or v.ndim != 3:
raise ValueError("Sparse Attention requires k and v to have shape [total_k, Hkv, D]")
if k.shape != (total_k, head_kv, q.shape[-1]) or v.shape != (total_k, head_kv, q.shape[-1]):
raise ValueError("Sparse Attention k and v must match [total_k, Hkv, D]")
else:
if page_table.device != q.device:
raise ValueError("page_table must be on the same device as q")
if page_table.dtype != torch.int32:
raise TypeError("page_table must be torch.int32")
if page_table.ndim != 2 or page_table.shape[0] != batch:
raise ValueError("page_table must have shape [B, max_num_pages_per_seq]")
if page_table.stride(-1) != 1:
raise ValueError("page_table must be contiguous in the last dimension")
if k.ndim != 4 or v.ndim != 4:
raise ValueError(
"Sparse Page Attention requires k and v to have shape "
"[num_pages, Hkv, page_size, D]"
)
if k.shape != v.shape:
raise ValueError(f"k and v must have the same shape, got {k.shape} and {v.shape}")
if k.shape[1] != head_kv or k.shape[3] != q.shape[-1]:
raise ValueError(
"Sparse Page Attention k and v must match "
"[num_pages, Hkv, page_size, D]"
)
page_size = int(k.shape[2])
if page_size != blk_kv:
raise ValueError(
f"Unsupported Sparse Page Attention page_size={page_size} for blk_kv={blk_kv}; "
"require page_size == blk_kv"
)
if seqused_k is not None:
if seqused_k.device != q.device:
raise ValueError("seqused_k must be on the same device as q")
if seqused_k.dtype != torch.int32:
raise TypeError("seqused_k must be torch.int32")
if seqused_k.shape != (batch,):
raise ValueError("seqused_k must have shape [B]")
if not seqused_k.is_contiguous():
raise ValueError("seqused_k must be contiguous")
if topK not in _SUPPORTED_SPARSE_TOPK:
raise ValueError(
f"CSR sparse forward supports topK in {_SUPPORTED_SPARSE_TOPK}, got {topK}"
)
return batch, head_kv
def _validate_csr_varlen_nvfp4_kv_inputs(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_scale_128x4: torch.Tensor,
v_scale_128x4: torch.Tensor,
k_global_scale: Optional[torch.Tensor],
v_global_scale: Optional[torch.Tensor],
k2q_row_ptr: torch.Tensor,
k2q_q_indices: torch.Tensor,
topK: int,
blk_kv: int,
page_table: Optional[torch.Tensor],
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
seqused_k: Optional[torch.Tensor],
) -> tuple[int, int]:
if q.ndim != 3:
raise ValueError("KVFP4 CSR sparse forward requires q to have shape [total_q, Hq, D]")
if q.dtype not in (torch.bfloat16, torch.float8_e4m3fn):
raise TypeError(f"KVFP4 CSR sparse forward requires BF16 or FP8 E4M3 q, got {q.dtype}")
if q.shape[-1] != 128:
raise NotImplementedError(
f"KVFP4 CSR sparse forward currently supports only D=128, got {q.shape[-1]}"
)
if k.dtype != torch.uint8 or v.dtype != torch.uint8:
raise TypeError(f"KVFP4 k/v must be torch.uint8, got {k.dtype} and {v.dtype}")
if k_scale_128x4.dtype != torch.uint8 or v_scale_128x4.dtype != torch.uint8:
raise TypeError(
"KVFP4 block scales must be torch.uint8 E4M3 tensors, got "
f"{k_scale_128x4.dtype} and {v_scale_128x4.dtype}"
)
if k_global_scale is not None and k_global_scale.dtype != torch.float32:
raise TypeError("KVFP4 K global scale must be a torch.float32 tensor or None")
if v_global_scale is not None and v_global_scale.dtype != torch.float32:
raise TypeError("KVFP4 V global scale must be a torch.float32 tensor or None")
tensors = (
k,
v,
k_scale_128x4,
v_scale_128x4,
k2q_row_ptr,
k2q_q_indices,
cu_seqlens_q,
cu_seqlens_k,
)
optional_tensors = tuple(t for t in (k_global_scale, v_global_scale) if t is not None)
if any(t.device != q.device for t in tensors + optional_tensors):
raise ValueError("KVFP4 inputs and metadata must be on the same device as q")
if k.shape != v.shape:
raise ValueError(f"KVFP4 k and v must have the same shape, got {k.shape} and {v.shape}")
packed_dim = q.shape[-1] // 2
scale_cols = q.shape[-1] // 16
if k_scale_128x4.ndim != 2 or v_scale_128x4.ndim != 2:
raise ValueError("KVFP4 block scales must be rank-2 128x4 tiled tensors")
if k_scale_128x4.shape[1] < scale_cols or v_scale_128x4.shape[1] < scale_cols:
raise ValueError(
"KVFP4 block scales must have at least D/16 columns; "
f"need {scale_cols}, got {k_scale_128x4.shape[1]} and {v_scale_128x4.shape[1]}"
)
if k_global_scale is not None and k_global_scale.numel() < 1:
raise ValueError("KVFP4 K global scale must contain at least one element")
if v_global_scale is not None and v_global_scale.numel() < 1:
raise ValueError("KVFP4 V global scale must contain at least one element")
if page_table is None:
if seqused_k is not None:
raise ValueError("seqused_k is only supported together with page_table")
if k.ndim != 3:
raise ValueError("KVFP4 Sparse Attention requires k/v shape [total_k, Hkv, D/2]")
if k.shape[-1] != packed_dim:
raise ValueError(f"KVFP4 packed K/V last dimension must be D/2={packed_dim}")
total_k = int(k.shape[0])
head_kv = int(k.shape[1])
required_scale_rows = total_k * head_kv
else:
if k.ndim != 4:
raise ValueError(
"KVFP4 Sparse Page Attention requires k/v shape "
"[num_pages, Hkv, page_size, D/2]"
)
if k.shape[-1] != packed_dim:
raise ValueError(f"KVFP4 packed K/V last dimension must be D/2={packed_dim}")
page_size = int(k.shape[2])
if page_size != int(blk_kv):
raise ValueError(
f"KVFP4 Sparse Page Attention requires page_size == blk_kv, got {page_size} vs {blk_kv}"
)
head_kv = int(k.shape[1])
required_scale_rows = int(k.shape[0]) * head_kv * page_size
if page_table.device != q.device:
raise ValueError("page_table must be on the same device as q")
if page_table.dtype != torch.int32:
raise TypeError("page_table must be torch.int32")
if page_table.ndim != 2:
raise ValueError("page_table must have shape [B, max_num_pages_per_seq]")
if page_table.stride(-1) != 1:
raise ValueError("page_table must be contiguous in the last dimension")
if seqused_k is not None:
if seqused_k.device != q.device:
raise ValueError("seqused_k must be on the same device as q")
if seqused_k.dtype != torch.int32:
raise TypeError("seqused_k must be torch.int32")
if not seqused_k.is_contiguous():
raise ValueError("seqused_k must be contiguous")
padded_scale_rows = ((required_scale_rows + 127) // 128) * 128
padded_scale_cols = ((scale_cols + 3) // 4) * 4
for name, scale in (("k_scale_128x4", k_scale_128x4), ("v_scale_128x4", v_scale_128x4)):
if scale.shape[0] < padded_scale_rows or scale.shape[1] < padded_scale_cols:
raise ValueError(
f"{name} is too small for 128x4 layout: got {tuple(scale.shape)}, "
f"need at least {(padded_scale_rows, padded_scale_cols)}"
)
if k2q_row_ptr.device != q.device or k2q_q_indices.device != q.device:
raise ValueError("CSR metadata must be on the same device as q")
if k2q_row_ptr.dtype != torch.int32 or k2q_q_indices.dtype != torch.int32:
raise TypeError("CSR metadata tensors must be torch.int32")
if k2q_row_ptr.ndim != 2 or k2q_q_indices.ndim != 2:
raise ValueError("k2q_row_ptr and k2q_q_indices must be rank-2")
_validate_cu_seqlens(cu_seqlens_q, name="cu_seqlens_q", device=q.device)
_validate_cu_seqlens(cu_seqlens_k, name="cu_seqlens_k", device=q.device)
if cu_seqlens_k.shape != cu_seqlens_q.shape:
raise ValueError("cu_seqlens_k must have shape [B + 1] matching cu_seqlens_q")
batch = int(cu_seqlens_q.shape[0] - 1)
if page_table is not None and page_table.shape[0] != batch:
raise ValueError("page_table must have shape [B, max_num_pages_per_seq]")
if seqused_k is not None and seqused_k.shape != (batch,):
raise ValueError("seqused_k must have shape [B]")
head_q = int(q.shape[1])
if head_q % head_kv != 0:
raise ValueError("q.shape[1] must be divisible by Hkv")
qhead_per_kv = head_q // head_kv
if qhead_per_kv not in (1, 2, 4, 8, 16):
raise NotImplementedError(
"KVFP4 CSR forward is currently supported only for qhead_per_kv in {1, 2, 4, 8, 16}"
)
if k2q_row_ptr.shape[0] != head_kv or k2q_q_indices.shape[0] != head_kv:
raise ValueError("CSR metadata head dimension must match KV head count")
if k2q_q_indices.shape[1] < q.shape[0] * topK:
raise ValueError(
f"k2q_q_indices.shape[1] ({k2q_q_indices.shape[1]}) must be >= total_q * topK ({q.shape[0] * topK})"
)
if k2q_row_ptr.shape[1] < 1:
raise ValueError("k2q_row_ptr must contain at least one row pointer column")
if topK not in _SUPPORTED_SPARSE_TOPK:
raise ValueError(
f"KVFP4 CSR sparse forward supports topK in {_SUPPORTED_SPARSE_TOPK}, got {topK}"
)
return batch, head_kv
def _validate_sparse_decode_inputs(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
q2k_indices: Optional[torch.Tensor],
*,
page_table: torch.Tensor,
seqused_k: torch.Tensor,
seqlen_q: int,
max_seqlen_k: int,
blk_kv: int,
causal: bool,
) -> tuple[int, int]:
if q.ndim != 3:
raise ValueError("decode attention requires q to have shape [total_q, Hq, D]")
if k.ndim != 4 or v.ndim != 4:
raise ValueError(
"decode attention requires paged k/v with shape [num_pages, Hkv, page_size, D]"
)
if q.device != k.device or q.device != v.device:
raise ValueError("decode q, k, and v must be on the same device")
if q.dtype != torch.float8_e4m3fn or k.dtype != q.dtype or v.dtype != q.dtype:
raise TypeError(
"decode attention currently supports only torch.float8_e4m3fn Q/K/V"
)
if k.shape != v.shape:
raise ValueError(f"decode k and v must have the same shape, got {k.shape} and {v.shape}")
if q.shape[-1] != 128 or k.shape[-1] != 128:
raise NotImplementedError(
f"decode attention currently supports only D=128, got q={q.shape[-1]} k={k.shape[-1]}"
)
if not bool(causal):
raise NotImplementedError("decode attention currently supports only causal=True")
page_size = int(k.shape[2])
if page_size != int(blk_kv):
raise ValueError(f"decode attention requires page_size == blk_kv, got {page_size} vs {blk_kv}")
head_kv = int(k.shape[1])
head_q = int(q.shape[1])
if head_q % head_kv != 0:
raise ValueError("decode q.shape[1] must be divisible by Hkv")
qhead_per_kv = head_q // head_kv
if qhead_per_kv != _SUPPORTED_DECODE_QHEAD_PER_KV:
raise NotImplementedError(
"decode attention currently supports only "
f"qhead_per_kv={_SUPPORTED_DECODE_QHEAD_PER_KV}, got {qhead_per_kv}"
)
if page_table is None:
raise ValueError("decode attention requires page_table")
if page_table.device != q.device:
raise ValueError("decode page_table must be on the same device as q")
if page_table.dtype != torch.int32:
raise TypeError("decode page_table must be torch.int32")
if page_table.ndim != 2:
raise ValueError("decode page_table must have shape [B, max_num_pages_per_seq]")
batch = int(page_table.shape[0])
if page_table.stride(-1) != 1:
raise ValueError("decode page_table must be contiguous in the last dimension")
if seqused_k is None:
raise ValueError("decode attention requires seqused_k")
if seqused_k.device != q.device:
raise ValueError("decode seqused_k must be on the same device as q")
if seqused_k.dtype != torch.int32:
raise TypeError("decode seqused_k must be torch.int32")
if seqused_k.shape != (batch,):
raise ValueError("decode seqused_k must have shape [B]")
if not seqused_k.is_contiguous():
raise ValueError("decode seqused_k must be contiguous")
seqlen_q = int(seqlen_q)
max_seqlen_k = int(max_seqlen_k)
if seqlen_q <= 0 or max_seqlen_k <= 0:
raise ValueError("decode seqlen_q and max_seqlen_k must be positive")
if int(q.shape[0]) != batch * seqlen_q:
raise ValueError("decode q.shape[0] must equal batch * seqlen_q")
if q2k_indices is not None:
if q2k_indices.device != q.device:
raise ValueError("decode q2k_indices must be on the same device as q")
if q2k_indices.dtype != torch.int32:
raise TypeError("decode q2k_indices must be torch.int32")
if q2k_indices.ndim != 3:
raise ValueError("decode q2k_indices must have shape [Hkv, total_q, topK]")
if q2k_indices.shape[0] != head_kv or q2k_indices.shape[1] != q.shape[0]:
raise ValueError("decode q2k_indices must match [Hkv, total_q, topK]")
if not q2k_indices.is_contiguous():
raise ValueError("decode q2k_indices must be contiguous")
return batch, head_kv
def _validate_schedule_common(
schedule: SparseAttentionSchedule,
*,
device: torch.device,
) -> None:
if schedule.scheduler_metadata is None:
raise ValueError("schedule.scheduler_metadata is required")
if schedule.work_count is None:
raise ValueError("schedule.work_count is required")
metadata = schedule.scheduler_metadata
work_count = schedule.work_count
if metadata.device != device or work_count.device != device:
raise ValueError("schedule tensors must be on the same device as q")
if metadata.dtype != torch.int32 or work_count.dtype != torch.int32:
raise TypeError("schedule.scheduler_metadata and schedule.work_count must be torch.int32")
if metadata.ndim != 2 or metadata.shape[1] != 6:
raise ValueError("schedule.scheduler_metadata must have shape [capacity, 6]")
if work_count.shape != (1,):
raise ValueError("schedule.work_count must have shape [1]")
if not metadata.is_contiguous() or not work_count.is_contiguous():
raise ValueError("schedule.scheduler_metadata and schedule.work_count must be contiguous")
def _validate_fwd_schedule(
schedule: SparseAttentionSchedule,
*,
q: torch.Tensor,
k2q_q_indices: torch.Tensor,
head_kv: int,
) -> None:
_validate_schedule_common(schedule, device=q.device)
if schedule.qsplit_indices is None:
raise ValueError("schedule.qsplit_indices is required for forward")
if schedule.split_counts is None:
raise ValueError("schedule.split_counts is required for forward")
qsplit = schedule.qsplit_indices
split_counts = schedule.split_counts
if qsplit.device != q.device or split_counts.device != q.device:
raise ValueError("forward schedule tensors must be on the same device as q")
if qsplit.dtype != torch.int32 or split_counts.dtype != torch.int32:
raise TypeError("schedule.qsplit_indices and schedule.split_counts must be torch.int32")
if qsplit.shape != k2q_q_indices.shape:
raise ValueError("schedule.qsplit_indices shape must match k2q_q_indices")
total_q = q.shape[0]
if split_counts.shape != (total_q, head_kv):
raise ValueError(
"schedule.split_counts must have shape "
f"({total_q}, {head_kv}), got {tuple(split_counts.shape)}"
)
if not qsplit.is_contiguous() or not split_counts.is_contiguous():
raise ValueError("schedule.qsplit_indices and schedule.split_counts must be contiguous")
def sparse_atten_func(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k2q_row_ptr: torch.Tensor,
k2q_q_indices: torch.Tensor,
topK: int,
*,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
blk_kv: int = 128,
causal: bool = False,
softmax_scale: Optional[float] = None,
lse_temperature_scale: float = 1.0,
return_temperature_lse: bool = False,
partial_dtype: torch.dtype = torch.bfloat16,
return_softmax_lse: bool = False,
page_table: Optional[torch.Tensor] = None,
seqused_k: Optional[torch.Tensor] = None,
schedule: Optional[SparseAttentionSchedule] = None,
usable_SM_count: int = -1,
qk_dtype: Optional[torch.dtype] = None,
pv_dtype: Optional[torch.dtype] = None,
):
"""Run SM100 CSR block-sparse varlen attention.
This is the public forward-only sparse attention API. It consumes
query-to-key block selections converted to CSR metadata by
``build_k2q_csr`` and supports both dense KV layout and paged KV layout.
Parameters
----------
q : torch.Tensor
Shape ``[total_q, Hq, 128]`` on CUDA. Supported dtypes are BF16 and
FP8 E4M3.
k : torch.Tensor
Dense layout ``[total_k, Hkv, 128]`` or paged layout
``[num_pages, Hkv, blk_kv, 128]``. For BF16 Q with FP8 K/V cache, K
may be FP8 E4M3 while QK compute uses BF16 staging.
v : torch.Tensor
Same layout and head count as ``k``.
k2q_row_ptr : torch.Tensor
CSR row pointers with shape ``[Hkv, total_rows + 1]`` and dtype int32.
k2q_q_indices : torch.Tensor
CSR query indices with shape ``[Hkv, >= total_q * topK]`` and dtype
int32.
topK : int
Number of selected KV blocks per query. Supported values are
``4, 8, 16, 32``.
cu_seqlens_q : torch.Tensor
Shape ``[batch_size + 1]``, dtype int32. Prefix sums of Q lengths.
cu_seqlens_k : torch.Tensor
Shape ``[batch_size + 1]``, dtype int32. Prefix sums of KV lengths.
max_seqlen_q : int
Maximum Q sequence length in the batch.
max_seqlen_k : int
Maximum KV sequence length in the batch.
blk_kv : int, optional
KV block size. Paged KV requires ``k.shape[2] == blk_kv``.
causal : bool, optional
Whether to apply causal masking.
softmax_scale : float, optional
Softmax scale. Defaults to ``1 / sqrt(128)``.
lse_temperature_scale : float, optional
Extra divisor used only for temperature-scaled LSE output.
return_temperature_lse : bool, optional
If True, also return LSE computed with logits scaled by
``softmax_scale / lse_temperature_scale``. Requires
``return_softmax_lse=True``.
partial_dtype : torch.dtype, optional
Accumulation dtype for per-block partial O. Supported values are
FP32, BF16, FP16, and FP8 E4M3.
return_softmax_lse : bool, optional
If True, return ``(out, softmax_lse)`` or
``(out, softmax_lse, temperature_lse)``.
page_table : torch.Tensor, optional
Paged-KV physical page table with shape
``[batch_size, max_num_pages_per_seq]`` and dtype int32.
seqused_k : torch.Tensor, optional
Shape ``[batch_size]``, dtype int32. Effective KV length per request
for paged causal attention.
schedule : SparseAttentionSchedule, optional
Prebuilt sparse forward schedule. If omitted, the schedule is built
during the call.
usable_SM_count : int, optional
Maximum number of SMs used by the scheduler. ``-1`` uses all SMs.
qk_dtype : torch.dtype, optional
Compile-time MMA operand dtype for QK. Defaults to Q storage dtype,
except supported FP8 K/V cache staging modes.
pv_dtype : torch.dtype, optional
Compile-time MMA operand dtype for PV. Defaults to V storage dtype,
except supported FP8 K/V cache staging modes.
Returns
-------
torch.Tensor or tuple[torch.Tensor, torch.Tensor]
Output shape ``[total_q, Hq, 128]`` with BF16 dtype. Optional LSE
outputs have shape ``[total_q, Hq]`` and dtype float32.
Notes
-----
``Hq / Hkv`` must be one of ``1, 2, 4, 8, 16``. Current kernels support
head dimension 128 only.
"""
if softmax_scale is None:
softmax_scale = q.shape[-1] ** -0.5
lse_temperature_scale = float(lse_temperature_scale)
if not math.isfinite(lse_temperature_scale) or lse_temperature_scale <= 0.0:
raise ValueError(
f"lse_temperature_scale must be finite and > 0, got {lse_temperature_scale}"
)
return_temperature_lse = bool(return_temperature_lse)
if return_temperature_lse and not return_softmax_lse:
raise ValueError("return_temperature_lse=True requires return_softmax_lse=True")
partial_dtype = _normalize_partial_dtype(partial_dtype)
qk_dtype, pv_dtype = _resolve_forward_mma_dtypes(q, k, v, qk_dtype, pv_dtype)
if cu_seqlens_q is None or cu_seqlens_k is None:
raise ValueError(
"sparse_atten_func requires CSR varlen metadata: pass cu_seqlens_q and cu_seqlens_k"
)
batch, head_kv = _validate_csr_varlen_inputs(
q,
k,
v,
k2q_row_ptr,
k2q_q_indices,
topK,
blk_kv,
page_table,
cu_seqlens_q,
cu_seqlens_k,
seqused_k,
)
max_seqlen_q = int(max_seqlen_q)
max_seqlen_k = int(max_seqlen_k)
return _sparse_atten_csr_varlen_forward(
q.contiguous(),
k.contiguous(),
v.contiguous(),
k2q_row_ptr.contiguous(),
k2q_q_indices.contiguous(),
int(topK),
int(blk_kv),
bool(causal),
float(softmax_scale),
lse_temperature_scale,
return_temperature_lse,
partial_dtype,
bool(return_softmax_lse),
cu_seqlens_q.contiguous(),
cu_seqlens_k.contiguous(),
None if page_table is None else page_table.contiguous(),
None if seqused_k is None else seqused_k.contiguous(),
schedule,
int(usable_SM_count),
int(batch),
int(head_kv),
int(max_seqlen_q),
int(max_seqlen_k),
qk_dtype,
pv_dtype,
)
def sparse_atten_nvfp4_kv_func(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_scale_128x4: torch.Tensor,
v_scale_128x4: torch.Tensor,
k_global_scale: Optional[torch.Tensor],
v_global_scale: Optional[torch.Tensor],
k2q_row_ptr: torch.Tensor,
k2q_q_indices: torch.Tensor,
topK: int,
*,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
blk_kv: int = 128,
causal: bool = False,
softmax_scale: Optional[float] = None,
lse_temperature_scale: float = 1.0,
return_temperature_lse: bool = False,
partial_dtype: torch.dtype = torch.bfloat16,
return_softmax_lse: bool = False,
page_table: Optional[torch.Tensor] = None,
seqused_k: Optional[torch.Tensor] = None,
schedule: Optional[SparseAttentionSchedule] = None,
):
"""Run SM100 CSR sparse attention with packed NVFP4 K/V.
Parameters
----------
q : torch.Tensor
Shape ``[total_q, Hq, 128]`` on CUDA. Supported dtypes are BF16 and
FP8 E4M3.
k : torch.Tensor
Packed NVFP4 K data. Dense layout is ``[total_k, Hkv, 64]``; paged
layout is ``[num_pages, Hkv, blk_kv, 64]``. Dtype must be uint8
because each byte packs two FP4 values.
v : torch.Tensor
Packed NVFP4 V data with the same shape as ``k``.
k_scale_128x4 : torch.Tensor
K block scales in cuBLAS/cuDNN 128x4 tiled storage. Dtype uint8
containing FP8 E4M3 scale values.
v_scale_128x4 : torch.Tensor
V block scales in the same 128x4 tiled storage.
k_global_scale : torch.Tensor, optional
FP32 tensor/global dequant scale for K. May be ``None``.
v_global_scale : torch.Tensor, optional
FP32 tensor/global dequant scale for V. May be ``None``. The V global
scale is applied in the combine stage.
k2q_row_ptr : torch.Tensor
CSR row pointers with shape ``[Hkv, total_rows + 1]`` and dtype int32.
k2q_q_indices : torch.Tensor
CSR query indices with shape ``[Hkv, >= total_q * topK]`` and dtype
int32.
topK : int
Number of selected KV blocks per query. Supported values are
``4, 8, 16, 32``.
cu_seqlens_q, cu_seqlens_k : torch.Tensor
Shape ``[batch_size + 1]``, dtype int32. Prefix sums of Q and KV
lengths.
max_seqlen_q, max_seqlen_k : int
Maximum Q and KV sequence lengths in the batch.
blk_kv : int, optional
KV block/page size. Paged KV requires ``k.shape[2] == blk_kv``.
causal : bool, optional
Whether to apply causal masking.
softmax_scale : float, optional
Softmax scale. Defaults to ``1 / sqrt(128)``.
lse_temperature_scale : float, optional
Extra divisor used only for temperature-scaled LSE output.
return_temperature_lse : bool, optional
If True, also return temperature-scaled LSE. Requires
``return_softmax_lse=True``.
partial_dtype : torch.dtype, optional
Accumulation dtype for per-block partial O.
return_softmax_lse : bool, optional
If True, return LSE together with the output.
page_table : torch.Tensor, optional
Paged-KV physical page table with shape
``[batch_size, max_num_pages_per_seq]`` and dtype int32.
seqused_k : torch.Tensor, optional
Effective KV length per request for paged causal attention.
schedule : SparseAttentionSchedule, optional
Prebuilt sparse forward schedule.
Returns
-------
torch.Tensor or tuple[torch.Tensor, torch.Tensor]
Output shape ``[total_q, Hq, 128]`` with BF16 dtype. Optional LSE
outputs have shape ``[total_q, Hq]`` and dtype float32.
"""
if softmax_scale is None:
softmax_scale = q.shape[-1] ** -0.5
lse_temperature_scale = float(lse_temperature_scale)
if not math.isfinite(lse_temperature_scale) or lse_temperature_scale <= 0.0:
raise ValueError(
f"lse_temperature_scale must be finite and > 0, got {lse_temperature_scale}"
)
return_temperature_lse = bool(return_temperature_lse)
if return_temperature_lse and not return_softmax_lse:
raise ValueError("return_temperature_lse=True requires return_softmax_lse=True")
partial_dtype = _normalize_partial_dtype(partial_dtype)
if cu_seqlens_q is None or cu_seqlens_k is None:
raise ValueError(
"sparse_atten_nvfp4_kv_func requires CSR varlen metadata: pass cu_seqlens_q and cu_seqlens_k"
)
batch, head_kv = _validate_csr_varlen_nvfp4_kv_inputs(
q,
k,
v,
k_scale_128x4,
v_scale_128x4,
k_global_scale,
v_global_scale,
k2q_row_ptr,
k2q_q_indices,
topK,
blk_kv,
page_table,
cu_seqlens_q,
cu_seqlens_k,
seqused_k,
)
total_q, head_q, dim = q.shape
max_num_kv_blocks = _csr_row_capacity(k2q_row_ptr)
temperature_lse_fast_path = (
return_temperature_lse
and math.isclose(
float(lse_temperature_scale),
1.0,
rel_tol=0.0,
abs_tol=_TEMPERATURE_LSE_FAST_PATH_ABS_TOL,
)
)
kernel_return_temperature_lse = (
return_temperature_lse and not temperature_lse_fast_path
)
O_partial = torch.empty(
topK, total_q, head_q, dim, dtype=partial_dtype, device=q.device
)
LSE_partial = torch.empty(
topK, total_q, head_q, dtype=torch.float32, device=q.device
)
LSE_temperature_partial = (
torch.empty(topK, total_q, head_q, dtype=torch.float32, device=q.device)
if kernel_return_temperature_lse
else None
)
O_out = torch.empty(total_q, head_q, dim, dtype=torch.bfloat16, device=q.device)
LSE_out = torch.empty(total_q, head_q, dtype=torch.float32, device=q.device)
LSE_temperature_out = (
torch.empty_like(LSE_out) if kernel_return_temperature_lse else None
)
if schedule is None:
k2q_qsplit_indices = torch.empty_like(k2q_q_indices)
split_counts = torch.zeros(
(total_q, head_kv),
dtype=torch.int32,
device=q.device,
)
else:
_validate_fwd_schedule(
schedule,
q=q,
k2q_q_indices=k2q_q_indices,
head_kv=head_kv,
)
k2q_qsplit_indices = schedule.qsplit_indices
split_counts = schedule.split_counts
schedule = _call_sparse_forward_sm100_csr_varlen_nvfp4_kv(
q.contiguous(),
k.contiguous(),
v.contiguous(),
k_scale_128x4.contiguous(),
v_scale_128x4.contiguous(),
None if k_global_scale is None else k_global_scale.contiguous(),
None if v_global_scale is None else v_global_scale.contiguous(),
k2q_row_ptr.contiguous(),
k2q_q_indices.contiguous(),
k2q_qsplit_indices.contiguous(),
split_counts.contiguous(),
cu_seqlens_q.contiguous(),
cu_seqlens_k.contiguous(),
None if page_table is None else page_table.contiguous(),
None if seqused_k is None else seqused_k.contiguous(),
O_partial,
LSE_partial,
LSE_temperature_partial,
float(softmax_scale),
lse_temperature_scale,
kernel_return_temperature_lse,
max_num_kv_blocks,
int(blk_kv),
head_kv,
int(max_seqlen_q),
causal=bool(causal),
schedule=schedule,
)
combine(
O_partial,
LSE_partial,
O_out,
LSE_out,
lse_temperature_partial=LSE_temperature_partial,
lse_temperature_out=LSE_temperature_out,
cu_seqlens=cu_seqlens_q,
split_counts=split_counts,
output_scale=v_global_scale,
use_pdl=True,
)
if temperature_lse_fast_path:
LSE_temperature_out = LSE_out
if return_softmax_lse:
if return_temperature_lse:
return O_out, LSE_out, LSE_temperature_out
return O_out, LSE_out
return O_out
def sparse_decode_atten_func(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
q2k_indices: Optional[torch.Tensor] = None,
*,
page_table: torch.Tensor,