-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathtest_sparse_atten.py
More file actions
3875 lines (3599 loc) · 131 KB
/
Copy pathtest_sparse_atten.py
File metadata and controls
3875 lines (3599 loc) · 131 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
"""Interface-level sparse attention tests and benchmark harness.
This file intentionally keeps correctness coverage and ad-hoc benchmarking in
one module. Tests only exercise the public `sparse_atten_func` interface:
- sparse attention: forward numerical checks
- page attention: forward numerical checks
Examples:
pytest -q test_sparse_atten.py
python test_sparse_atten.py benchmark
python test_sparse_atten.py benchmark --customer-case both --backend both --q2k-pattern both --causal
python test_sparse_atten.py benchmark --paged --causal --page-size 128 --seqused-trim 17
"""
from __future__ import annotations
import argparse
import math
import sys
import types
from contextlib import contextmanager
from typing import Optional
import pytest
import torch
import interface as sparse_interface
from interface import sparse_atten_func, sparse_atten_nvfp4_kv_func
from sparse_index_utils import build_k2q_csr, build_k2q_csr_torch_reference
from src.sm100.prepare_scheduler import (
prepare_sparse_fwd_schedule_and_split,
)
# The Triton reference backend was removed for the open-source release.
# Tests below validate the CuTe-DSL kernels against PyTorch references only.
TRITON_REFERENCE_AVAILABLE = False
pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
DEFAULT_B = 1
DEFAULT_SQ = 32768
DEFAULT_SKV = 32768
DEFAULT_TOPK = 16
DEFAULT_HEAD_KV = 4
DEFAULT_QHEAD_PER_KV = 16
DEFAULT_DIM = 128
DEFAULT_BLK_KV = 128
DEFAULT_WARMUP = 5
DEFAULT_ITERS = 20
DEFAULT_SEED = 42
BLK_KV = DEFAULT_BLK_KV
DECODE_BATCH = 32
DECODE_SEQLEN_Q = 8
DECODE_HEAD_KV = 4
DECODE_QHEAD_PER_KV = 16
DECODE_DIM = 128
DECODE_KV_TOKEN_SWEEP = tuple(2**exp for exp in range(3, 21))
@contextmanager
def _nvtx_range(message: str):
torch.cuda.nvtx.range_push(message)
try:
yield
finally:
torch.cuda.nvtx.range_pop()
def _nvtx_token(text: object) -> str:
return "".join(ch if ch.isalnum() or ch == "_" else "_" for ch in str(text))
class Q2KPattern:
SINK = "sink"
UNIFORM = "uniform"
BOTH = "both"
class BenchmarkBackend:
CUTE = "cute"
TRITON = "triton"
BOTH = "both"
CUSTOMER_BENCHMARK_CASES = {
"ring48k": {
"name": "bs1_nhq16_hkv1_seq48k_ring_attn",
"batch": 1,
"seqlen_q": 48 * 1024,
"seqlen_k": 48 * 1024,
"head_kv": 1,
"qhead_per_kv": 16,
},
"ulysses384k": {
"name": "bs1_nhq2_hkv1_seq384k_ulysses",
"batch": 1,
"seqlen_q": 384 * 1024,
"seqlen_k": 384 * 1024,
"head_kv": 1,
"qhead_per_kv": 2,
},
}
CUSTOMER_QHEAD_SWEEP_CASES = {
f"qhead{qhead}": {
"name": f"bs1_nhq{qhead}_hkv1_seq{(768 // qhead)}k_qhead_sweep",
"batch": 1,
"seqlen_q": 768 * 1024 // qhead,
"seqlen_k": 768 * 1024 // qhead,
"head_kv": 1,
"qhead_per_kv": qhead,
}
for qhead in (1, 2, 4, 8, 16)
}
# ---------------------------------------------------------------------------
# Reference helpers
# ---------------------------------------------------------------------------
def _bottom_right_causal_visible_blocks(
q_pos: torch.Tensor,
*,
seqlen_q: int,
seqlen_k: int,
blk_kv: int,
) -> torch.Tensor:
num_kv_blocks = (seqlen_k + blk_kv - 1) // blk_kv
causal_k_limit = q_pos + (seqlen_k - seqlen_q)
return (causal_k_limit // blk_kv + 1).clamp(min=0, max=num_kv_blocks).to(torch.int32)
def _randn_qkv(shape: tuple[int, ...], *, dtype: torch.dtype, device: str | torch.device = "cuda") -> torch.Tensor:
if dtype == torch.float8_e4m3fn:
return torch.randn(shape, dtype=torch.float32, device=device).to(dtype)
return torch.randn(shape, dtype=dtype, device=device)
def generate_test_data(
batch: int,
seqlen_q: int,
seqlen_k: int,
head_q: int,
head_kv: int,
dim: int,
topk: int,
*,
blk_kv: int = BLK_KV,
causal: bool = False,
dtype: torch.dtype = torch.bfloat16,
device: str = "cuda",
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Generate dense Q/K/V plus sparse q->kv block indices."""
assert seqlen_k % blk_kv == 0, f"seqlen_k ({seqlen_k}) must be divisible by blk_kv ({blk_kv})"
assert head_q % head_kv == 0, f"head_q ({head_q}) must be divisible by head_kv ({head_kv})"
num_kv_blocks = seqlen_k // blk_kv
assert topk <= num_kv_blocks, f"topk ({topk}) must be <= num_kv_blocks ({num_kv_blocks})"
q = _randn_qkv((batch, seqlen_q, head_q, dim), dtype=dtype, device=device)
k = _randn_qkv((batch, seqlen_k, head_kv, dim), dtype=dtype, device=device)
v = _randn_qkv((batch, seqlen_k, head_kv, dim), dtype=dtype, device=device)
if not causal:
q2k_indices = torch.stack(
[
torch.stack(
[
torch.stack(
[torch.randperm(num_kv_blocks, device=device)[:topk] for _ in range(seqlen_q)]
)
for _ in range(head_kv)
]
)
for _ in range(batch)
]
).to(torch.int32)
return q, k, v, q2k_indices
q2k_indices = torch.full((batch, head_kv, seqlen_q, topk), -1, dtype=torch.int32, device=device)
for b in range(batch):
for h in range(head_kv):
for q_idx in range(seqlen_q):
visible_blocks = max(
0,
min((q_idx + seqlen_k - seqlen_q) // blk_kv + 1, num_kv_blocks),
)
if visible_blocks == 0:
continue
if visible_blocks <= topk:
chosen = torch.arange(visible_blocks, device=device, dtype=torch.int32)
else:
chosen = torch.randperm(visible_blocks, device=device, dtype=torch.int32)[:topk]
chosen, _ = chosen.sort()
q2k_indices[b, h, q_idx, : chosen.numel()] = chosen
return q, k, v, q2k_indices
def sparse_attention_ref(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
q2k_indices: torch.Tensor,
*,
blk_kv: int = BLK_KV,
causal: bool = False,
softmax_scale: Optional[float] = None,
lse_temperature_scale: Optional[float] = None,
upcast: bool = True,
seqused_k: Optional[torch.Tensor] = None,
p_dtype: Optional[torch.dtype] = None,
o_partial_dtype: Optional[torch.dtype] = None,
) -> tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Golden sparse attention reference via explicit mask construction."""
batch, seqlen_q, head_q, dim = q.shape
seqlen_k = k.shape[1]
head_kv = k.shape[2]
qhead_per_kv = head_q // head_kv
num_kv_blocks = seqlen_k // blk_kv
if softmax_scale is None:
softmax_scale = 1.0 / math.sqrt(dim)
if seqused_k is not None:
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 [batch]")
q_t = q.float() if upcast else q
k_t = k.float() if upcast else k
v_t = v.float() if upcast else v
block_mask = torch.zeros(batch, head_kv, seqlen_q, num_kv_blocks, dtype=torch.bool, device=q.device)
valid_q2k = q2k_indices >= 0
safe_q2k = torch.where(valid_q2k, q2k_indices, torch.zeros_like(q2k_indices))
flat_mask = block_mask.view(-1, num_kv_blocks)
flat_valid = valid_q2k.view(-1, valid_q2k.shape[-1])
flat_idx = safe_q2k.view(-1, safe_q2k.shape[-1]).long()
row_idx = torch.arange(flat_mask.shape[0], device=q.device).unsqueeze(1)
flat_mask[row_idx.expand_as(flat_idx)[flat_valid], flat_idx[flat_valid]] = True
token_mask = block_mask.repeat_interleave(blk_kv, dim=3)
if qhead_per_kv > 1:
token_mask = token_mask.repeat_interleave(qhead_per_kv, dim=1)
k_t = k_t.repeat_interleave(qhead_per_kv, dim=2)
v_t = v_t.repeat_interleave(qhead_per_kv, dim=2)
scores = torch.einsum("bshd,bthd->bhst", q_t * softmax_scale, k_t)
if seqused_k is not None:
kv_pos = torch.arange(seqlen_k, device=q.device, dtype=torch.int32)
valid_k_mask = kv_pos.unsqueeze(0) < seqused_k.view(batch, 1)
token_mask = token_mask & valid_k_mask[:, None, None, :]
if causal:
q_pos = torch.arange(seqlen_q, device=q.device, dtype=torch.int32)
kv_pos = torch.arange(seqlen_k, device=q.device, dtype=torch.int32)
causal_seqlen_k = (
seqused_k
if seqused_k is not None
else torch.full((batch,), seqlen_k, device=q.device, dtype=torch.int32)
)
causal_limit = q_pos.unsqueeze(0) + (causal_seqlen_k.view(batch, 1) - seqlen_q)
causal_mask = kv_pos.view(1, 1, seqlen_k) <= causal_limit.unsqueeze(-1)
token_mask = token_mask & causal_mask.unsqueeze(1)
scores = scores.masked_fill(~token_mask, float("-inf"))
lse = torch.logsumexp(scores, dim=-1).transpose(1, 2).contiguous()
lse_temperature_out = (
torch.logsumexp(scores * (1.0 / float(lse_temperature_scale)), dim=-1)
.transpose(1, 2)
.contiguous()
if lse_temperature_scale is not None
else None
)
row_has_value = token_mask.any(dim=-1, keepdim=True)
scores_for_softmax = torch.where(row_has_value, scores, torch.zeros_like(scores))
if o_partial_dtype is not None:
# Split-K reference that mirrors the kernel: each topK split runs PV
# independently, quantizes the partial output, and combine accumulates
# scaled partials. This is what the kernel actually does when
# O_partial dtype < fp32. Re-use scratch buffers across splits to
# avoid topK x O(batch*head*sq*sk) peak memory.
# Wrap in no_grad: this split-K reference is forward-only and should
# avoid retaining per-split graphs.
with torch.no_grad():
out = torch.zeros(
batch, seqlen_q, head_q, dim, dtype=torch.float32, device=q.device
)
split_block_mask_buf = torch.zeros_like(block_mask)
split_flat_mask_buf = split_block_mask_buf.view(-1, num_kv_blocks)
flat_rows = torch.arange(split_flat_mask_buf.shape[0], device=q.device)
for split in range(q2k_indices.shape[-1]):
split_block_mask_buf.zero_()
split_indices = q2k_indices[..., split]
split_valid = split_indices >= 0
split_flat_idx = torch.where(
split_valid, split_indices, torch.zeros_like(split_indices)
).view(-1).long()
split_flat_valid = split_valid.view(-1)
split_flat_mask_buf[flat_rows[split_flat_valid], split_flat_idx[split_flat_valid]] = True
# Build per-split token mask without keeping repeat_interleave
# intermediates alive past one statement.
split_token_mask = split_block_mask_buf.repeat_interleave(blk_kv, dim=3)
if qhead_per_kv > 1:
split_token_mask = split_token_mask.repeat_interleave(qhead_per_kv, dim=1)
split_token_mask &= token_mask
# split_scores is a transient 6.4 GB-class tensor; reuse by
# copying scores once and applying mask in-place.
split_scores = scores.clone()
split_scores.masked_fill_(~split_token_mask, float("-inf"))
split_lse = torch.logsumexp(split_scores, dim=-1)
split_has_value = split_token_mask.any(dim=-1, keepdim=True)
del split_token_mask
split_scores.masked_fill_(~split_has_value, 0.0)
split_attn = torch.softmax(split_scores, dim=-1)
split_attn.masked_fill_(~split_has_value, 0.0)
del split_scores, split_has_value
if p_dtype is not None:
split_attn = split_attn.to(p_dtype).float()
out_partial = torch.einsum("bhst,bthd->bshd", split_attn, v_t)
del split_attn
out_partial = out_partial.to(o_partial_dtype).float()
split_lse_t = split_lse.transpose(1, 2).contiguous()
del split_lse
scale = torch.exp(split_lse_t - lse)
scale = torch.where(
torch.isfinite(split_lse_t), scale, torch.zeros_like(scale)
)
del split_lse_t
out.add_(scale.unsqueeze(-1) * out_partial)
del scale, out_partial
del split_block_mask_buf, flat_rows
elif p_dtype == torch.float8_e4m3fn:
# The SM100 fp8 forward path quantizes unnormalized P to e4m3 before
# PV, then applies 1 / row_sum in the epilogue.
row_max = scores_for_softmax.max(dim=-1, keepdim=True).values
exp_scores = torch.exp(scores_for_softmax - row_max)
exp_scores = torch.where(
token_mask & row_has_value,
exp_scores,
torch.zeros_like(exp_scores),
)
row_sum = exp_scores.sum(dim=-1, keepdim=True)
p_unnorm = exp_scores.to(p_dtype).float()
out = torch.einsum("bhst,bthd->bshd", p_unnorm, v_t)
out = out / torch.where(
row_sum.transpose(1, 2) > 0,
row_sum.transpose(1, 2),
torch.ones_like(row_sum.transpose(1, 2)),
)
else:
attn = torch.where(
row_has_value,
torch.softmax(scores_for_softmax, dim=-1),
torch.zeros_like(scores),
)
if p_dtype is not None:
attn = attn.to(p_dtype).float()
out = torch.einsum("bhst,bthd->bshd", attn, v_t)
if lse_temperature_out is not None:
return out, lse, lse_temperature_out
return out, lse
def pack_paged_kv(
k: torch.Tensor,
v: torch.Tensor,
*,
page_size: int,
page_table_mode: str = "identity",
max_pages_per_seq: Optional[int] = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Pack dense [B, Skv, H, D] KV into paged [num_pages, H, page_size, D]."""
if k.shape != v.shape:
raise ValueError("k and v must have the same shape")
if page_table_mode not in {"identity", "shuffle"}:
raise ValueError(f"Unsupported page_table_mode={page_table_mode!r}")
batch, seqlen_k, head_kv, dim = k.shape
logical_pages = (seqlen_k + page_size - 1) // page_size
max_pages_per_seq = logical_pages if max_pages_per_seq is None else max_pages_per_seq
if max_pages_per_seq < logical_pages:
raise ValueError("max_pages_per_seq must cover the logical KV length")
total_pages = batch * max_pages_per_seq
device = k.device
page_table = torch.arange(total_pages, device=device, dtype=torch.int32).view(batch, max_pages_per_seq)
if page_table_mode == "shuffle":
perm = torch.randperm(total_pages, device=device, dtype=torch.int64)
page_table = perm.to(torch.int32).view(batch, max_pages_per_seq)
k_paged = torch.zeros(total_pages, head_kv, page_size, dim, dtype=k.dtype, device=device)
v_paged = torch.zeros_like(k_paged)
for b in range(batch):
for logical_page in range(logical_pages):
physical_page = int(page_table[b, logical_page].item())
src_start = logical_page * page_size
src_end = min(src_start + page_size, seqlen_k)
page_len = src_end - src_start
if page_len > 0:
k_paged[physical_page, :, :page_len].copy_(
k[b, src_start:src_end].transpose(0, 1)
)
v_paged[physical_page, :, :page_len].copy_(
v[b, src_start:src_end].transpose(0, 1)
)
return k_paged, v_paged, page_table
def _install_flash_attn3_stub_for_te_import() -> None:
"""Install a minimal import stub for TE builds that import FA3 attention."""
package = sys.modules.get("flash_attn_3", types.ModuleType("flash_attn_3"))
interface = sys.modules.get(
"flash_attn_3.flash_attn_interface",
types.ModuleType("flash_attn_3.flash_attn_interface"),
)
def _unavailable(*args, **kwargs):
raise RuntimeError("flash_attn_3 attention stub is import-only")
for name in (
"flash_attn_func",
"flash_attn_varlen_func",
"flash_attn_with_kvcache",
"_flash_attn_forward",
"_flash_attn_backward",
):
setattr(interface, name, _unavailable)
package.flash_attn_interface = interface
sys.modules.setdefault("flash_attn_3", package)
sys.modules.setdefault("flash_attn_3.flash_attn_interface", interface)
def _make_synthetic_nvfp4_tensor(
shape: tuple[int, ...],
*,
global_scale_value: float = 1.0,
) -> object:
"""Create deterministic packed NVFP4 data with unit block/global scales."""
from quantize import Nvfp4QuantizedTensor
if shape[-1] % 16 != 0:
raise ValueError("NVFP4 synthetic shape requires D divisible by 16")
rows = math.prod(int(dim) for dim in shape[:-1])
scale_cols = int(shape[-1]) // 16
padded_rows = ((rows + 127) // 128) * 128
padded_cols = ((scale_cols + 3) // 4) * 4
data = torch.randint(
0,
256,
(*shape[:-1], shape[-1] // 2),
device="cuda",
dtype=torch.uint8,
)
scale_128x4 = torch.full(
(padded_rows, padded_cols),
0x38,
device="cuda",
dtype=torch.uint8,
)
global_scale = torch.full(
(1,),
float(global_scale_value),
device="cuda",
dtype=torch.float32,
)
return Nvfp4QuantizedTensor(
data=data,
scale_128x4=scale_128x4,
global_scale=global_scale,
logical_scale_shape=(rows, scale_cols),
original_shape=shape,
)
def _quantize_bf16_to_nvfp4_or_skip(x: torch.Tensor) -> object:
_install_flash_attn3_stub_for_te_import()
from quantize import quantize_bf16_to_nvfp4_128x4
try:
return quantize_bf16_to_nvfp4_128x4(x)
except RuntimeError as exc:
pytest.skip(str(exc))
def _dequant_nvfp4_to_bf16(qx: object, *, include_global_scale: bool = True) -> torch.Tensor:
from quantize import dequantize_nvfp4_128x4_to_bf16
return dequantize_nvfp4_128x4_to_bf16(
qx,
include_global_scale=include_global_scale,
)
def _get_sparse_decode_atten_func_for_test():
wrapper_cls = getattr(sparse_interface, "SparseDecodePagedAttentionWrapper", None)
if wrapper_cls is None:
pytest.skip("SparseDecodePagedAttentionWrapper is not implemented yet")
return wrapper_cls(blk_kv=BLK_KV, causal=True)
def _get_sparse_decode_atten_func_for_benchmark():
wrapper_cls = getattr(sparse_interface, "SparseDecodePagedAttentionWrapper", None)
if wrapper_cls is None:
raise RuntimeError("SparseDecodePagedAttentionWrapper is not implemented yet")
return wrapper_cls(blk_kv=BLK_KV, causal=True)
# ---------------------------------------------------------------------------
# Input preparation
# ---------------------------------------------------------------------------
def _cat_cu_seqlens(lengths: tuple[int, ...], *, device: str = "cuda") -> torch.Tensor:
cu = [0]
for length in lengths:
cu.append(cu[-1] + length)
return torch.tensor(cu, device=device, dtype=torch.int32)
def _sample_q_lens(batch: int, max_seqlen_q: int, *, seed: int) -> tuple[int, ...]:
if batch < 1:
raise ValueError("batch must be >= 1")
if max_seqlen_q < 1:
raise ValueError("max_seqlen_q must be >= 1")
if batch == 1:
return (max_seqlen_q,)
generator = torch.Generator(device="cpu")
generator.manual_seed(seed)
lengths = torch.randint(1, max_seqlen_q + 1, (batch,), generator=generator, dtype=torch.int64)
lengths[0] = max_seqlen_q
if torch.all(lengths == max_seqlen_q):
lengths[-1] = max(1, max_seqlen_q - 1)
return tuple(int(length.item()) for length in lengths)
def _sample_k_lens(
batch: int,
max_seqlen_kv: int,
*,
blk_kv: int,
seed: int,
) -> tuple[int, ...]:
if batch < 1:
raise ValueError("batch must be >= 1")
if max_seqlen_kv < blk_kv or max_seqlen_kv % blk_kv != 0:
raise ValueError("max_seqlen_kv must be a positive multiple of blk_kv")
if batch == 1:
return (max_seqlen_kv,)
generator = torch.Generator(device="cpu")
generator.manual_seed(seed)
max_blocks = max_seqlen_kv // blk_kv
num_blocks = torch.randint(1, max_blocks + 1, (batch,), generator=generator, dtype=torch.int64)
num_blocks[0] = max_blocks
if torch.all(num_blocks == max_blocks):
num_blocks[-1] = max(1, max_blocks - 1)
lengths = num_blocks * blk_kv
return tuple(int(length.item()) for length in lengths)
def _parse_dtype(raw: str) -> torch.dtype:
if raw == "bf16":
return torch.bfloat16
if raw == "fp8":
return torch.float8_e4m3fn
raise ValueError(f"unsupported dtype {raw!r}")
def _parse_partial_dtype(raw: str) -> torch.dtype:
if raw == "fp32":
return torch.float32
if raw == "bf16":
return torch.bfloat16
if raw == "fp16":
return torch.float16
if raw == "fp8":
return torch.float8_e4m3fn
raise ValueError(f"unsupported partial dtype {raw!r}")
def _build_pattern_q2k(
*,
q_lens: tuple[int, ...],
k_lens: tuple[int, ...],
head_kv: int,
topk: int,
blk_kv: int,
causal: bool,
pattern: str,
device: str = "cuda",
) -> torch.Tensor:
if pattern not in {Q2KPattern.SINK, Q2KPattern.UNIFORM}:
raise ValueError(f"unsupported q2k pattern: {pattern}")
total_q = sum(q_lens)
q2k = torch.full((head_kv, total_q, topk), -1, dtype=torch.int32, device=device)
slots = torch.arange(topk, device=device, dtype=torch.int32)
head_hash = torch.arange(head_kv, device=device, dtype=torch.int64).view(-1, 1)
q_cursor = 0
for seqlen_q, seqlen_k in zip(q_lens, k_lens):
num_kv_blocks = (seqlen_k + blk_kv - 1) // blk_kv
if num_kv_blocks < 1:
raise ValueError("each sequence needs at least one KV block")
q_local = torch.arange(seqlen_q, device=device, dtype=torch.int32)
if causal:
visible_blocks = _bottom_right_causal_visible_blocks(
q_local,
seqlen_q=seqlen_q,
seqlen_k=seqlen_k,
blk_kv=blk_kv,
)
else:
visible_blocks = torch.full((seqlen_q,), num_kv_blocks, dtype=torch.int32, device=device)
budget = visible_blocks.clamp(max=topk)
latest = visible_blocks - 1
if pattern == Q2KPattern.UNIFORM:
if causal:
first = latest - budget + 1
idx = first[:, None] + slots[None, :]
else:
idx = torch.remainder(q_local[:, None] // blk_kv + slots[None, :], num_kv_blocks)
idx = torch.where(slots[None, :] < budget[:, None], idx, torch.full_like(idx, -1))
q2k[:, q_cursor : q_cursor + seqlen_q, :] = idx[None, :, :]
q_cursor += seqlen_q
continue
sink = torch.zeros((head_kv, seqlen_q), dtype=torch.int32, device=device)
q2k[:, q_cursor : q_cursor + seqlen_q, 0] = torch.where(
budget.view(1, -1) > 0,
sink,
torch.full_like(sink, -1),
)
if topk > 1:
current = latest.view(1, -1).expand(head_kv, -1)
q2k[:, q_cursor : q_cursor + seqlen_q, 1] = torch.where(
budget.view(1, -1) > 1,
current,
torch.full_like(current, -1),
)
if topk > 2:
q_hash = q_local.to(torch.int64).view(1, -1)
n_prev = (latest.to(torch.int64) - 1).clamp(min=1).view(1, -1)
valid_prev = (latest > 1).view(1, -1)
for slot in range(2, topk):
valid = (budget > slot).view(1, -1) & valid_prev
base = torch.remainder(
q_hash * 1103515245 + head_hash * 12345 + slot * 2654435761,
2147483647,
)
candidate = 1 + torch.remainder(base, n_prev)
previous = q2k[:, q_cursor : q_cursor + seqlen_q, :slot].to(torch.int64)
for _ in range(slot):
duplicate = (previous == candidate.unsqueeze(-1)).any(dim=-1) & valid
if not duplicate.any():
break
candidate = torch.where(
duplicate,
1 + torch.remainder(candidate, n_prev),
candidate,
)
q2k[:, q_cursor : q_cursor + seqlen_q, slot] = torch.where(
valid,
candidate.to(torch.int32),
torch.full_like(candidate, -1, dtype=torch.int32),
)
q_cursor += seqlen_q
return q2k
def _format_q2k_fanout(q2k: torch.Tensor) -> str:
valid = q2k[q2k >= 0]
if valid.numel() == 0:
return "valid=0"
fanout = torch.bincount(valid.flatten(), minlength=int(valid.max().item()) + 1)
fanout_f = fanout.float()
return (
f"valid={valid.numel()} "
f"kv_block0={int(fanout[0].item())} "
f"max={int(fanout.max().item())} "
f"mean={fanout_f.mean().item():.1f} "
f"p50={fanout_f.median().item():.1f} "
f"sink_share={fanout[0].item() / valid.numel() * 100:.2f}% "
f"max/mean={fanout_f.max().item() / fanout_f.mean().item():.2f}x"
)
def _format_csr_pattern(
k2q_row_ptr: torch.Tensor,
*,
k_lens: tuple[int, ...],
blk_kv: int,
topk: int,
) -> str:
counts = (k2q_row_ptr[:, 1:] - k2q_row_ptr[:, :-1]).to(torch.float32)
valid_rows_per_batch = tuple((k_len + blk_kv - 1) // blk_kv for k_len in k_lens)
sink_rows = [
batch_idx
for batch_idx, rows in enumerate(valid_rows_per_batch)
if rows > 0
]
if counts.numel() == 0 or counts.sum().item() == 0:
return "inferred=empty valid=0"
total = counts.sum().item()
sink_entries = counts[:, sink_rows].sum().item() if sink_rows else 0.0
sink_share = sink_entries / total
uniform_share = len(sink_rows) / counts.shape[1] if counts.shape[1] > 0 else 0.0
sink_threshold = max(2.0 * uniform_share, 0.5 / max(topk, 1))
inferred = Q2KPattern.SINK if sink_share >= sink_threshold else Q2KPattern.UNIFORM
p50 = counts.flatten().median().item()
mean = counts.mean().item()
max_count = counts.max().item()
return (
f"inferred={inferred} "
f"sink_entries={int(sink_entries)} "
f"sink_share={sink_share * 100:.2f}% "
f"uniform_row_share={uniform_share * 100:.2f}% "
f"max={int(max_count)} "
f"mean={mean:.1f} "
f"p50={p50:.1f} "
f"max/mean={max_count / mean:.2f}x"
)
def _build_sparse_inputs(
*,
q_lens: tuple[int, ...],
k_lens: tuple[int, ...],
head_kv: int,
qhead_per_kv: int,
dim: int,
topk: int,
blk_kv: int,
causal: bool,
dtype: torch.dtype,
q2k_pattern: Optional[str] = None,
) -> dict[str, torch.Tensor | float]:
qs: list[torch.Tensor] = []
ks: list[torch.Tensor] = []
vs: list[torch.Tensor] = []
q2ks: list[torch.Tensor] = []
for seqlen_q, seqlen_k in zip(q_lens, k_lens):
if q2k_pattern is None:
q, k, v, q2k = generate_test_data(
batch=1,
seqlen_q=seqlen_q,
seqlen_k=seqlen_k,
head_q=head_kv * qhead_per_kv,
head_kv=head_kv,
dim=dim,
topk=topk,
blk_kv=blk_kv,
causal=causal,
dtype=dtype,
)
qs.append(q.squeeze(0))
ks.append(k.squeeze(0))
vs.append(v.squeeze(0))
q2ks.append(q2k.squeeze(0))
else:
qs.append(_randn_qkv((seqlen_q, head_kv * qhead_per_kv, dim), dtype=dtype, device="cuda"))
ks.append(_randn_qkv((seqlen_k, head_kv, dim), dtype=dtype, device="cuda"))
vs.append(_randn_qkv((seqlen_k, head_kv, dim), dtype=dtype, device="cuda"))
q = torch.cat(qs, dim=0)
k = torch.cat(ks, dim=0)
v = torch.cat(vs, dim=0)
q2k = (
torch.cat(q2ks, dim=1)
if q2k_pattern is None
else _build_pattern_q2k(
q_lens=q_lens,
k_lens=k_lens,
head_kv=head_kv,
topk=topk,
blk_kv=blk_kv,
causal=causal,
pattern=q2k_pattern,
)
)
cu_seqlens_q = _cat_cu_seqlens(q_lens)
cu_seqlens_k = _cat_cu_seqlens(k_lens)
max_seqlen_q = max(q_lens)
max_seqlen_k = max(k_lens)
k2q_row_ptr, k2q_q_indices, schedule = build_k2q_csr(
q2k,
cu_seqlens_q,
cu_seqlens_k,
blk_kv,
total_k=k.shape[0],
max_seqlen_k=max_seqlen_k,
max_seqlen_q=max_seqlen_q,
total_rows=sum((length + blk_kv - 1) // blk_kv for length in k_lens),
qhead_per_kv=qhead_per_kv,
return_schedule=True,
)
return {
"q": q,
"k": k,
"v": v,
"q2k": q2k,
"k2q_row_ptr": k2q_row_ptr,
"k2q_q_indices": k2q_q_indices,
"schedule": schedule,
"cu_seqlens_q": cu_seqlens_q,
"cu_seqlens_k": cu_seqlens_k,
"q_lens": q_lens,
"k_lens": k_lens,
"max_seqlen_q": max_seqlen_q,
"max_seqlen_k": max_seqlen_k,
"blk_kv": blk_kv,
"softmax_scale": 1.0 / math.sqrt(dim),
}
def _force_empty_kv_tile(
q2k: torch.Tensor,
q_lens: tuple[int, ...],
k_lens: tuple[int, ...],
*,
topk: int,
blk_kv: int,
causal: bool,
) -> tuple[tuple[slice, ...], tuple[slice, ...]]:
head_kv = q2k.shape[0]
q_cursor = 0
k_cursor = 0
empty_blocks: list[slice] = []
active_blocks: list[slice] = []
for seqlen_q, seqlen_k in zip(q_lens, k_lens):
num_kv_blocks = seqlen_k // blk_kv
if num_kv_blocks < 2:
raise ValueError("check_empty=True requires at least 2 KV blocks per sequence")
slots = torch.arange(topk, device=q2k.device, dtype=torch.int32).unsqueeze(0)
chosen = torch.where(slots == 0, torch.zeros_like(slots), slots + 1)
if causal:
visible_blocks = _bottom_right_causal_visible_blocks(
torch.arange(seqlen_q, device=q2k.device, dtype=torch.int32),
seqlen_q=seqlen_q,
seqlen_k=seqlen_k,
blk_kv=blk_kv,
)
else:
visible_blocks = torch.full(
(seqlen_q,),
num_kv_blocks,
device=q2k.device,
dtype=torch.int32,
)
valid = chosen < visible_blocks.unsqueeze(1)
q2k_seq = torch.where(
valid.unsqueeze(0),
chosen.unsqueeze(0).expand(head_kv, -1, -1),
torch.full((head_kv, seqlen_q, topk), -1, dtype=torch.int32, device=q2k.device),
)
q2k[:, q_cursor : q_cursor + seqlen_q] = q2k_seq
active_blocks.append(slice(k_cursor, k_cursor + blk_kv))
empty_blocks.append(slice(k_cursor + blk_kv, k_cursor + 2 * blk_kv))
q_cursor += seqlen_q
k_cursor += seqlen_k
return tuple(empty_blocks), tuple(active_blocks)
def _build_paged_inputs(
*,
batch: int,
seqlen_q: int,
seqlen_kv: int,
head_kv: int,
qhead_per_kv: int,
dim: int,
topk: int,
blk_kv: int,
causal: bool,
page_size: int,
seqused_trim: int,
dtype: torch.dtype,
page_table_mode: str = "shuffle",
q2k_pattern: Optional[str] = None,
) -> dict[str, torch.Tensor | float]:
q_lens = _sample_q_lens(batch, seqlen_q, seed=29)
k_lens = _sample_k_lens(batch, seqlen_kv, blk_kv=blk_kv, seed=31)
qs: list[torch.Tensor] = []
ks: list[torch.Tensor] = []
vs: list[torch.Tensor] = []
q2ks: list[torch.Tensor] = []
for q_len, k_len in zip(q_lens, k_lens):
if q2k_pattern is None:
q, k, v, q2k = generate_test_data(
batch=1,
seqlen_q=q_len,
seqlen_k=k_len,
head_q=head_kv * qhead_per_kv,
head_kv=head_kv,
dim=dim,
topk=topk,
blk_kv=blk_kv,
causal=causal,
dtype=dtype,
)
qs.append(q.squeeze(0))
ks.append(k.squeeze(0))
vs.append(v.squeeze(0))
q2ks.append(q2k.squeeze(0))
else:
qs.append(_randn_qkv((q_len, head_kv * qhead_per_kv, dim), dtype=dtype, device="cuda"))
ks.append(_randn_qkv((k_len, head_kv, dim), dtype=dtype, device="cuda"))
vs.append(_randn_qkv((k_len, head_kv, dim), dtype=dtype, device="cuda"))
q = torch.cat(qs, dim=0)
k_ref = torch.cat(ks, dim=0)
v_ref = torch.cat(vs, dim=0)
q2k = (
torch.cat(q2ks, dim=1)
if q2k_pattern is None
else _build_pattern_q2k(
q_lens=q_lens,
k_lens=k_lens,
head_kv=head_kv,
topk=topk,
blk_kv=blk_kv,
causal=causal,
pattern=q2k_pattern,
)
)
cu_seqlens_q = _cat_cu_seqlens(q_lens)
k_dense = torch.zeros(batch, seqlen_kv, head_kv, dim, dtype=dtype, device=q.device)
v_dense = torch.zeros_like(k_dense)
for batch_idx, (k_seq, v_seq, k_len) in enumerate(zip(ks, vs, k_lens)):
k_dense[batch_idx, :k_len].copy_(k_seq)
v_dense[batch_idx, :k_len].copy_(v_seq)
k_paged, v_paged, page_table = pack_paged_kv(
k_dense,
v_dense,
page_size=page_size,
page_table_mode=page_table_mode,
max_pages_per_seq=(seqlen_kv + page_size - 1) // page_size,
)
effective_k_lens = tuple(
max(1, k_len - min(seqused_trim, k_len - 1))
for k_len in k_lens
)
q2k_csr = q2k
if effective_k_lens != k_lens:
q2k_csr = q2k.clone()
q_cursor = 0
for q_len, effective_k_len in zip(q_lens, effective_k_lens):
max_effective_block = (effective_k_len + blk_kv - 1) // blk_kv
q_slice = slice(q_cursor, q_cursor + q_len)
invalid = q2k_csr[:, q_slice, :] >= max_effective_block
q2k_csr[:, q_slice, :] = torch.where(
invalid,
torch.full_like(q2k_csr[:, q_slice, :], -1),
q2k_csr[:, q_slice, :],
)
q_cursor += q_len
cu_seqlens_k = _cat_cu_seqlens(effective_k_lens)
max_seqlen_q = max(q_lens)
max_seqlen_k = max(effective_k_lens)
k2q_row_ptr, k2q_q_indices, schedule = build_k2q_csr(
q2k_csr,
cu_seqlens_q,
cu_seqlens_k,
blk_kv,
total_k=sum(effective_k_lens),
max_seqlen_k=max_seqlen_k,
max_seqlen_q=max_seqlen_q,
total_rows=sum(
(length + blk_kv - 1) // blk_kv for length in effective_k_lens
),
qhead_per_kv=qhead_per_kv,
return_schedule=True,
)
paged_capacity = int(page_table.shape[1]) * page_size
seqused_k = None
if any(k_len != paged_capacity for k_len in effective_k_lens):
seqused_k = torch.tensor(
effective_k_lens,
device=q.device,
dtype=torch.int32,
)
return {
"q": q,
"k_paged": k_paged,
"v_paged": v_paged,