forked from ROCm/aiter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_batch_prefill.py
More file actions
3798 lines (3379 loc) · 124 KB
/
Copy pathtest_batch_prefill.py
File metadata and controls
3798 lines (3379 loc) · 124 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-License-Identifier: MIT
# Copyright (C) 2024-2026, Advanced Micro Devices, Inc. All rights reserved.
import ctypes
import itertools
import math
import os
import weakref
import pytest
import torch
import pandas as pd
import aiter
from aiter import dtypes
from aiter import per_tensor_quant
from einops import rearrange, repeat
import argparse
from aiter.test_common import (
perftest,
)
def skip_test_if(condition: bool, reason: str) -> bool:
"""
Skip the test if condition is True.
Works in both pytest and direct python execution:
- pytest session: calls pytest.skip()
- direct python: prints message and returns True
Usage:
if skip_test_if(causal and kv_len < qo_len, "reason"):
return
Returns:
True if test should be skipped (caller should return early)
"""
if not condition:
return False
# PYTEST_CURRENT_TEST is only set when pytest is actively running tests,
# not when pytest is just imported. This is the reliable way to detect
# if we're inside a pytest session.
if "PYTEST_CURRENT_TEST" in os.environ:
pytest.skip(reason)
print(f"SKIP: {reason}")
return True
def get_vector_size(dtype) -> int:
"""Calculate vector size for a given dtype (16 bytes / element_size)."""
return 16 // torch.tensor([], dtype=dtype).element_size()
def get_rocm_version():
"""
Get ROCm version from PyTorch.
Returns:
tuple (major, minor) or None if not using ROCm
Example:
>>> get_rocm_version()
(7, 2) # ROCm 7.2
"""
if not torch.version.hip:
return None
try:
# torch.version.hip returns string like "6.2.41133" or "6.2.41133-rocm6.2.2"
hip_version = torch.version.hip
parts = hip_version.split(".")
if len(parts) >= 2:
return (int(parts[0]), int(parts[1]))
except (ValueError, AttributeError):
pass
return None
def get_gpu_arch():
"""
Get GPU architecture (gcnArchName).
Returns:
str like "gfx942", "gfx950", etc., or None if cannot determine
Example:
>>> get_gpu_arch()
"gfx950"
"""
if not torch.cuda.is_available():
return None
try:
# Get device properties
props = torch.cuda.get_device_properties(0)
# gcnArchName property contains architecture like "gfx942:sramecc+:xnack-"
if hasattr(props, "gcnArchName"):
arch_name = props.gcnArchName
# Extract base architecture (e.g., "gfx950" from "gfx950:sramecc+:xnack-")
if ":" in arch_name:
return arch_name.split(":")[0]
return arch_name
except (AttributeError, RuntimeError):
pass
return None
def should_skip_rocm72_issue(causal, logits_soft_cap):
"""
Check if test should be skipped due to ROCm 7.2 + gfx950 compiler issue.
FIXME: ROCm 7.2 on gfx950 has a compiler bug with causal=True + logits_soft_cap=0.0
configuration. This workaround should be removed once the compiler is fixed.
Args:
causal: Whether causal masking is enabled
logits_soft_cap: Soft cap value for logits
Returns:
True if test should be skipped on current ROCm version + GPU architecture
"""
# Only check if the problematic configuration is used
if not (causal and logits_soft_cap == 0.0):
return False
# Check ROCm version
rocm_version = get_rocm_version()
if rocm_version is None:
return False # Not ROCm, no need to skip
# Check GPU architecture
gpu_arch = get_gpu_arch()
if gpu_arch is None:
return False # Cannot determine GPU, no need to skip
# Only skip on ROCm 7.2.x + gfx950
major, minor = rocm_version
if (major, minor) == (7, 2) and gpu_arch == "gfx950":
return True
return False
def check_common_skip_conditions(
is_input_fp8: bool,
return_lse: bool = False,
) -> bool:
"""
Check common skip conditions shared across test functions.
Returns True if test should be skipped.
"""
# FP8 is inference-only, no backward pass needed, so LSE is not required
if skip_test_if(
is_input_fp8 and return_lse,
"FP8 is inference-only, LSE not needed for backward pass",
):
return True
return False
def check_layout_skip_conditions(
kvcache_layout: str,
head_dim: int,
page_size: int,
k_vector_size: int,
k_vector_size_fp8: int,
is_input_fp8: bool,
contiguous_kv: bool,
) -> bool:
"""
Check layout-specific skip conditions.
Returns True if test should be skipped.
"""
if kvcache_layout == "vectorized":
if skip_test_if(
page_size % k_vector_size != 0 or head_dim % k_vector_size != 0,
"Vectorized layout requires page/head dim divisible by vector size",
):
return True
if skip_test_if(
is_input_fp8
and (
page_size % k_vector_size_fp8 != 0 or head_dim % k_vector_size_fp8 != 0
),
"FP8 vectorized layout requires page/head dim divisible by vector size",
):
return True
return False
def get_tolerances(dtype, is_fp8: bool = False) -> tuple[float, float]:
"""Return (rtol, atol) tolerances based on dtype and FP8 mode."""
if is_fp8:
return 2e-2, 1e-2
if dtype == torch.float16:
return 1e-3, 1e-3
return 2e-2, 1e-2
def build_q_tensor_for_test(
qo_lens,
batch_size: int,
qo_len: int,
num_qo_heads: int,
head_dim: int,
dtype,
q_init_min: float,
q_init_max: float,
is_input_fp8: bool,
):
"""Build Q tensor, handling both FP8 and non-FP8 cases."""
# Use actual sum of qo_lens as total_q_tokens for correct shape
total_q_tokens = torch.sum(qo_lens).item()
if is_input_fp8:
return torch.rand(
total_q_tokens, num_qo_heads, head_dim, device="cuda", dtype=dtype
)
return build_q_tensor(
total_q_tokens, num_qo_heads, head_dim, dtype, q_init_min, q_init_max
)
def extract_kv_caches(kv_cache: dict, contiguous_kv: bool):
"""Extract K and V reference tensors from KV cache dict."""
if contiguous_kv:
return split_kv_pages(kv_cache["kv_data"])
return kv_cache["kv_data"][:, 0], kv_cache["kv_data"][:, 1]
def verify_fp8_output(out_fp8, o_ref, threshold: float = 0.055):
"""Verify FP8 kernel output against reference."""
max_diff = (out_fp8 - o_ref).abs().max().item()
assert max_diff < threshold, (
f"FP8 kernel vs reference difference too large: "
f"{max_diff} (threshold: {threshold})"
)
def construct_local_mask(
seqlen_q,
seqlen_k,
window_size=(-1, -1), # -1 means infinite window size
query_padding_mask=None,
key_padding_mask=None,
device=None,
key_leftpad=None,
):
row_idx = rearrange(
torch.arange(seqlen_q, device=device, dtype=torch.long), "s -> s 1"
)
col_idx = torch.arange(seqlen_k, device=device, dtype=torch.long)
if key_leftpad is not None:
key_leftpad = rearrange(key_leftpad, "b -> b 1 1 1")
col_idx = repeat(col_idx, "s -> b 1 1 s", b=key_leftpad.shape[0])
col_idx = torch.where(col_idx >= key_leftpad, col_idx - key_leftpad, 2**32)
sk = (
seqlen_k
if key_padding_mask is None
else rearrange(key_padding_mask.sum(-1), "b -> b 1 1 1")
)
sq = (
seqlen_q
if query_padding_mask is None
else rearrange(query_padding_mask.sum(-1), "b -> b 1 1 1")
)
if window_size[0] < 0:
return col_idx > row_idx + sk - sq + window_size[1]
else:
sk = torch.full_like(col_idx, seqlen_k) if key_padding_mask is None else sk
return torch.logical_or(
col_idx > torch.minimum(row_idx + sk - sq + window_size[1], sk),
col_idx < row_idx + sk - sq - window_size[0],
)
def ref_masked_attention(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
causal: bool = False,
window_left: int = -1,
logits_soft_cap: float = 0.0,
return_lse: bool = False,
) -> torch.Tensor:
"""
Reference implementation of masked attention.
Args:
query: [seqlen_q, num_heads, head_dim]
key: [seqlen_k, num_heads, head_dim]
value: [seqlen_k, num_heads, head_dim]
causal: whether to use causal mask
window_left: left window size for sliding window attention
logits_soft_cap: soft cap for logits (0.0 = disabled)
return_lse: whether to return log-sum-exp values
Returns:
If return_lse=False: output [seqlen_q, num_heads, head_dim]
If return_lse=True: (output, lse) where lse is [num_heads, seqlen_q]
"""
if causal:
window_size = (window_left, 0)
else:
window_size = (-1, -1)
head_dim = query.shape[2]
seqlen_q = query.shape[0]
seqlen_k = key.shape[0]
scale = 1.0 / math.sqrt(head_dim)
# Compute scaled attention scores: [num_heads, seqlen_q, seqlen_k]
attn_weights = scale * torch.einsum("qhd,khd->hqk", query.float(), key.float())
if 0 < logits_soft_cap:
mode = int(os.environ.get("CK_TILE_ATTENTION_LOGITS_SOFT_CAP_DEFAULT", 0))
if mode == 0:
attn_weights = logits_soft_cap * torch.tanh(attn_weights / logits_soft_cap)
else:
attn_weights = attn_weights / (
1.0 + torch.abs(attn_weights / logits_soft_cap)
)
if window_size[0] >= 0 or window_size[1] >= 0:
local_mask = construct_local_mask(
seqlen_q,
seqlen_k,
window_size,
device=query.device,
)
attn_weights.masked_fill_(local_mask, float("-inf"))
# Compute LSE before softmax using torch.logsumexp
# This correctly handles fully-masked rows (all -inf) by returning -inf instead of nan
if return_lse:
# attn_weights: [num_heads, seqlen_q, seqlen_k]
lse = torch.logsumexp(attn_weights, dim=-1) # [H, Q]
attn_weights = torch.softmax(attn_weights, dim=-1)
if window_size[0] >= 0 or window_size[1] >= 0:
attn_weights = attn_weights.masked_fill(
torch.all(local_mask, dim=-1, keepdim=True), 0.0
)
out = torch.einsum("hqk,khd->qhd", attn_weights, value.float())
if return_lse:
return out.to(query), lse.float()
return out.to(query)
def make_scaled_rand(min_val, max_val, *shape, dtype, device="cuda"):
x = torch.randn(*shape, device=device, dtype=dtype)
x = (x - x.min()) / (x.max() - x.min())
return min_val + (max_val - min_val) * x
def convert_lens_to_indptr(lens):
return torch.cumsum(torch.cat((torch.tensor([0]), lens)), dim=0).int()
def build_qo_lens(batch_size, qo_len, randomize=True):
if randomize and batch_size > 1:
return torch.randint(1, qo_len + 1, (batch_size,)).int()
return torch.full((batch_size,), qo_len).int()
def build_kv_lens(batch_size, kv_len, qo_lens, randomize=True, ensure_at_least_q=True):
if randomize and batch_size > 1:
kv_lens = torch.randint(1, kv_len + 1, (batch_size,)).int()
return torch.maximum(qo_lens, kv_lens) if ensure_at_least_q else kv_lens
return torch.full((batch_size,), kv_len).int()
def build_q_tensor(
total_q_tokens, num_qo_heads, head_dim, dtype, q_init_min, q_init_max
):
return make_scaled_rand(
q_init_min,
q_init_max,
total_q_tokens,
num_qo_heads,
head_dim,
dtype=dtype,
).to(0)
def build_paged_kv_cache(
batch_size,
kv_len,
page_size,
num_kv_heads,
head_dim,
kv_lens,
kv_init_min,
kv_init_max,
dtype,
use_uniform=False,
contiguous_kv=True,
):
max_num_pages_per_seq = (kv_len + page_size - 1) // page_size
total_num_pages = max_num_pages_per_seq * batch_size
kv_shape = [total_num_pages, 2, page_size, num_kv_heads, head_dim]
if contiguous_kv:
if use_uniform:
kv_data_fp32 = torch.rand(*kv_shape, device="cuda", dtype=torch.float32)
if kv_init_min is not None and kv_init_max is not None:
kv_data_fp32 = kv_init_min + (kv_init_max - kv_init_min) * kv_data_fp32
else:
kv_data_fp32 = make_scaled_rand(
kv_init_min, kv_init_max, *kv_shape, dtype=torch.float32
).to(0)
kv_data = kv_data_fp32.to(dtype)
else:
kv_shape_nc = [kv_shape[0]]
for dim in kv_shape[1:]:
kv_shape_nc.append(2)
kv_shape_nc.append(dim)
if use_uniform:
kv_data_fp32 = torch.rand(*kv_shape_nc, device="cuda", dtype=torch.float32)
if kv_init_min is not None and kv_init_max is not None:
kv_data_fp32 = kv_init_min + (kv_init_max - kv_init_min) * kv_data_fp32
else:
kv_data_fp32 = make_scaled_rand(
kv_init_min, kv_init_max, *kv_shape_nc, dtype=torch.float32
).to(0)
kv_data = kv_data_fp32.to(dtype)
kv_data = kv_data[:, 1, :, 1, :, 1, :, 1, :]
kv_data_fp32 = kv_data_fp32[:, 1, :, 1, :, 1, :, 1, :]
kv_num_used_pages = (kv_lens + page_size - 1) // page_size
kv_indptr_cpu = convert_lens_to_indptr(kv_num_used_pages)
kv_indices_cpu = torch.nn.functional.pad(
torch.randperm(total_num_pages).int(), (0, 128), value=0
)
kv_last_page_len_cpu = ((kv_lens - 1) % page_size + 1).int()
return {
"kv_data_fp32": kv_data_fp32,
"kv_data": kv_data,
"kv_indptr_cpu": kv_indptr_cpu,
"kv_indices_cpu": kv_indices_cpu,
"kv_last_page_len_cpu": kv_last_page_len_cpu,
"max_num_pages_per_seq": max_num_pages_per_seq,
"total_num_pages": total_num_pages,
}
def split_kv_pages(kv_data):
chunks = torch.chunk(kv_data, 2, dim=1)
k_cache_ref = chunks[0].squeeze(1).contiguous()
v_cache_ref = chunks[1].squeeze(1).contiguous()
return k_cache_ref, v_cache_ref
def apply_kv_layout(
k_cache_ref,
v_cache_ref,
num_kv_heads,
head_dim,
page_size,
k_vector_size,
layout,
):
if layout == "vectorized":
return vectorize_kv_cache(
k_cache_ref,
v_cache_ref,
num_kv_heads,
head_dim,
page_size,
k_vector_size,
)
if layout == "linear":
return k_cache_ref.contiguous(), v_cache_ref.contiguous()
raise ValueError(f"Unsupported KV layout: {layout}")
def build_block_table(kv_indptr_cpu, kv_indices_cpu, batch_size, max_num_pages_per_seq):
block_table_cpu = torch.zeros(
(batch_size, max_num_pages_per_seq), dtype=torch.int32
)
for i in range(batch_size):
start = kv_indptr_cpu[i].item()
end = kv_indptr_cpu[i + 1].item()
block_table_cpu[i, : (end - start)] = kv_indices_cpu[start:end]
return block_table_cpu
def build_reference_output(
q,
q_indptr_cpu,
kv_data_fp32,
kv_indices_cpu,
kv_indptr_cpu,
kv_last_page_len_cpu,
num_kv_heads,
head_dim,
dtype,
causal,
logits_soft_cap,
return_lse=False,
):
"""
Build reference output (and optionally LSE) for batch prefill.
Args:
return_lse: If True, also return LSE values.
Returns:
If return_lse=False: output tensor [total_q, num_heads, head_dim]
If return_lse=True: (output, lse) where lse is [total_q, num_heads]
"""
o_ref_list = []
lse_ref_list = []
for i in range(len(q_indptr_cpu) - 1):
perm_dims = [0, 1, 2, 3]
perm_dims_last = [0, 1, 2]
qi = q[q_indptr_cpu[i] : q_indptr_cpu[i + 1]]
used_kv_indices = kv_indices_cpu[kv_indptr_cpu[i] : kv_indptr_cpu[i + 1]]
last_k = kv_data_fp32[used_kv_indices[-1], 0, : kv_last_page_len_cpu[i], :]
last_v = kv_data_fp32[used_kv_indices[-1], 1, : kv_last_page_len_cpu[i], :]
ki = torch.cat(
[
kv_data_fp32[used_kv_indices[:-1], 0]
.permute(*perm_dims)
.reshape(-1, num_kv_heads, head_dim),
last_k.permute(*perm_dims_last).reshape(-1, num_kv_heads, head_dim),
],
dim=0,
).to(dtype)
vi = torch.cat(
[
kv_data_fp32[used_kv_indices[:-1], 1]
.permute(*perm_dims)
.reshape(-1, num_kv_heads, head_dim),
last_v.permute(*perm_dims_last).reshape(-1, num_kv_heads, head_dim),
],
dim=0,
).to(dtype)
if qi.shape[1] != num_kv_heads:
assert qi.shape[1] % num_kv_heads == 0
ratio = qi.shape[1] // num_kv_heads
ki = ki.repeat_interleave(ratio, dim=1)
vi = vi.repeat_interleave(ratio, dim=1)
result = ref_masked_attention(
qi,
ki,
vi,
causal=causal,
logits_soft_cap=logits_soft_cap,
return_lse=return_lse,
)
if return_lse:
o_ref_list.append(result[0])
# ref_masked_attention returns lse as [num_heads, seqlen_q]
# kernel also returns [num_heads, total_q], so no transpose needed
lse_ref_list.append(result[1])
else:
o_ref_list.append(result)
if return_lse:
# Concatenate along the seqlen dimension (dim=1 for [num_heads, seqlen_q])
return torch.cat(o_ref_list, dim=0), torch.cat(lse_ref_list, dim=1)
return torch.cat(o_ref_list, dim=0)
def assert_output_matches_reference(out, q_indptr_cpu, o_ref, rtol, atol):
for i in range(len(q_indptr_cpu) - 1):
start = q_indptr_cpu[i]
end = q_indptr_cpu[i + 1]
torch.testing.assert_close(
out[start:end], o_ref[start:end], rtol=rtol, atol=atol
)
def assert_lse_matches_reference(
lse_kernel: torch.Tensor,
lse_ref: torch.Tensor,
rtol: float = 1e-3,
atol: float = 1e-3,
):
"""
Compare kernel LSE output against reference LSE.
Both should be [total_q, num_heads] and float32.
Uses same tolerance logic as CK's fmha_fwd_runner.hpp.
"""
assert (
lse_kernel.shape == lse_ref.shape
), f"LSE shape mismatch: kernel={lse_kernel.shape}, ref={lse_ref.shape}"
assert (
lse_kernel.dtype == torch.float32
), f"Kernel LSE should be float32, got {lse_kernel.dtype}"
assert (
lse_ref.dtype == torch.float32
), f"Reference LSE should be float32, got {lse_ref.dtype}"
# CK's check_err with allow_infinity_ref=true
torch.testing.assert_close(
lse_kernel,
lse_ref,
rtol=rtol,
atol=atol,
)
@pytest.mark.parametrize("input_dtype", ["bf16", "fp8"])
@pytest.mark.parametrize("batch_size", [1, 3, 7])
@pytest.mark.parametrize(
"qo_len,kv_len",
[
(1024, 1024),
(1023, 1024),
(1024, 1023),
(2048, 2048),
],
)
@pytest.mark.parametrize("num_qo_heads,num_kv_heads", [(6, 1), (3, 1)])
@pytest.mark.parametrize("head_dim", [128])
@pytest.mark.parametrize("causal", [False, True])
@pytest.mark.parametrize("logits_soft_cap", [0.0, 30.0])
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
@pytest.mark.parametrize("q_init_min,q_init_max", [(-10, 10)])
@pytest.mark.parametrize("kv_init_min,kv_init_max", [(-5, 5)])
@pytest.mark.parametrize("kv_dim", [4, 3])
@pytest.mark.parametrize("contiguous_kv", [True, False])
@pytest.mark.parametrize("return_lse", [False, True])
@pytest.mark.parametrize("seed", [19378])
def test_batch_prefill_page_size_1_linear_sglang(
input_dtype,
batch_size,
kv_len,
qo_len,
num_qo_heads,
num_kv_heads,
head_dim,
causal,
logits_soft_cap,
dtype,
q_init_min,
q_init_max,
kv_init_min,
kv_init_max,
kv_dim,
contiguous_kv,
return_lse,
seed,
):
if seed is not None:
torch.manual_seed(seed)
is_input_fp8 = input_dtype == dtypes.fp8 or input_dtype == "fp8"
k_vector_size = get_vector_size(dtype)
k_vector_size_fp8 = get_vector_size(dtypes.fp8)
page_size = 1
# Skip conditions
if check_common_skip_conditions(is_input_fp8, return_lse):
return
if check_layout_skip_conditions(
"linear",
head_dim,
page_size,
k_vector_size,
k_vector_size_fp8,
is_input_fp8,
contiguous_kv,
):
return
if skip_test_if(
should_skip_rocm72_issue(causal, logits_soft_cap),
"ROCm 7.2 + gfx950 compiler issue with causal=True + logits_soft_cap=0.0",
):
return
# Build test tensors
qo_lens = build_qo_lens(batch_size, qo_len, randomize=True)
q_indptr_cpu = convert_lens_to_indptr(qo_lens)
q = build_q_tensor_for_test(
qo_lens,
batch_size,
qo_len,
num_qo_heads,
head_dim,
dtype,
q_init_min,
q_init_max,
is_input_fp8,
)
kv_lens = build_kv_lens(batch_size, kv_len, qo_lens, randomize=True)
kv_cache = build_paged_kv_cache(
batch_size,
kv_len,
page_size,
num_kv_heads,
head_dim,
kv_lens,
None if is_input_fp8 else kv_init_min,
None if is_input_fp8 else kv_init_max,
dtype,
use_uniform=is_input_fp8,
contiguous_kv=contiguous_kv,
)
# Move to GPU
q_indptr_gpu = q_indptr_cpu.to(0)
kv_indptr_gpu = kv_cache["kv_indptr_cpu"].to(0)
kv_indices_gpu = kv_cache["kv_indices_cpu"].to(0)
kv_last_page_len_gpu = kv_cache["kv_last_page_len_cpu"].to(0)
k_cache_ref, v_cache_ref = extract_kv_caches(kv_cache, contiguous_kv)
max_qo_len = torch.max(qo_lens).item()
max_kv_len = torch.max(kv_lens).item()
# Build reference output (shared between FP8 and non-FP8)
ref_result = build_reference_output(
q,
q_indptr_cpu,
kv_cache["kv_data_fp32"],
kv_cache["kv_indices_cpu"],
kv_cache["kv_indptr_cpu"],
kv_cache["kv_last_page_len_cpu"],
num_kv_heads,
head_dim,
dtype,
causal,
logits_soft_cap,
return_lse=return_lse,
)
if return_lse:
o_ref, lse_ref = ref_result
else:
o_ref = ref_result
lse_ref = None
if is_input_fp8:
q_quant, q_descale = per_tensor_quant(q, quant_dtype=dtypes.fp8)
k_cache_quant, k_descale = per_tensor_quant(
k_cache_ref.to(dtype), quant_dtype=dtypes.fp8
)
v_cache_quant, v_descale = per_tensor_quant(
v_cache_ref.to(dtype), quant_dtype=dtypes.fp8
)
# Apply layout based on kv_dim
if kv_dim == 3:
k_cache_fp8 = k_cache_quant.squeeze(1).contiguous()
v_cache_fp8 = v_cache_quant.squeeze(1).contiguous()
k_cache_ref_layout = k_cache_ref.squeeze(1).contiguous()
v_cache_ref_layout = v_cache_ref.squeeze(1).contiguous()
else:
k_cache_fp8, v_cache_fp8 = apply_kv_layout(
k_cache_quant,
v_cache_quant,
num_kv_heads,
head_dim,
page_size,
k_vector_size_fp8,
"linear",
)
k_cache_ref_layout, v_cache_ref_layout = apply_kv_layout(
k_cache_ref.to(dtype),
v_cache_ref.to(dtype),
num_kv_heads,
head_dim,
page_size,
k_vector_size,
"linear",
)
# Note: FP8 is inference-only, LSE not needed
out_fp8 = aiter.mha_batch_prefill_func(
q_quant,
k_cache_fp8,
v_cache_fp8,
q_indptr_gpu,
kv_indptr_gpu,
kv_indices_gpu,
max_qo_len,
max_kv_len,
causal=causal,
logits_soft_cap=logits_soft_cap,
q_descale=q_descale,
k_descale=k_descale,
v_descale=v_descale,
kv_last_page_lens=kv_last_page_len_gpu,
)
out_ref = aiter.mha_batch_prefill_func(
q,
k_cache_ref_layout,
v_cache_ref_layout,
q_indptr_gpu,
kv_indptr_gpu,
kv_indices_gpu,
max_qo_len,
max_kv_len,
causal=causal,
logits_soft_cap=logits_soft_cap,
kv_last_page_lens=kv_last_page_len_gpu,
)
# Causal + kv_len < qo_len: rows with few valid K positions amplify
# FP8 quantization error (not averaged over many attention targets).
# Larger head_dim accumulates more rounding error in dot products
# (CK's own FP8BF16 atol is 0.18 for reference).
fp8_threshold = 0.06 if causal and kv_len < qo_len else 0.055
if head_dim > 128:
fp8_threshold = max(fp8_threshold, 0.06)
verify_fp8_output(out_fp8, o_ref, threshold=fp8_threshold)
rtol, atol = get_tolerances(dtype, is_fp8=True)
torch.testing.assert_close(out_ref, o_ref, rtol=rtol, atol=atol)
else:
# Prepare KV cache based on kv_dim and contiguity
if kv_dim == 3:
k_cache = k_cache_ref.squeeze(1)
v_cache = v_cache_ref.squeeze(1)
if contiguous_kv:
k_cache = k_cache.contiguous()
v_cache = v_cache.contiguous()
elif contiguous_kv:
k_cache, v_cache = apply_kv_layout(
k_cache_ref,
v_cache_ref,
num_kv_heads,
head_dim,
page_size,
k_vector_size,
"linear",
)
else:
k_cache, v_cache = k_cache_ref, v_cache_ref
# Verify contiguity expectations
assert k_cache.is_contiguous() == contiguous_kv
assert v_cache.is_contiguous() == contiguous_kv
kernel_result = aiter.mha_batch_prefill_func(
q,
k_cache,
v_cache,
q_indptr_gpu,
kv_indptr_gpu,
kv_indices_gpu,
max_qo_len,
max_kv_len,
causal=causal,
logits_soft_cap=logits_soft_cap,
kv_last_page_lens=kv_last_page_len_gpu,
return_lse=return_lse,
)
if return_lse:
out, lse_kernel = kernel_result
else:
out = kernel_result
lse_kernel = None
rtol, atol = get_tolerances(dtype)
assert_output_matches_reference(out, q_indptr_cpu, o_ref, rtol, atol)
# Compare LSE if requested
if return_lse:
assert_lse_matches_reference(lse_kernel, lse_ref)
@pytest.mark.parametrize("kvcache_layout", ["linear", "vectorized"])
@pytest.mark.parametrize("table_layout", ["sglang", "vllm"])
@pytest.mark.parametrize("input_dtype", ["bf16", "fp8"])
@pytest.mark.parametrize("batch_size", [1, 3, 7])
@pytest.mark.parametrize(
"qo_len,kv_len",
[
(128, 128),
(1024, 1024),
(1023, 1024),
(1024, 1023),
(2048, 2048),
(8192, 8192),
],
)
@pytest.mark.parametrize("page_size", [16, 1024])
@pytest.mark.parametrize("num_qo_heads,num_kv_heads", [(8, 1), (16, 1)])
@pytest.mark.parametrize("head_dim", [128, 256])
@pytest.mark.parametrize("causal", [False, True])
@pytest.mark.parametrize("logits_soft_cap", [0.0, 30.0])
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
@pytest.mark.parametrize("q_init_min,q_init_max", [(-10, 10)])
@pytest.mark.parametrize("kv_init_min,kv_init_max", [(-5, 5)])
@pytest.mark.parametrize("contiguous_kv", [True, False])
@pytest.mark.parametrize("return_lse", [False, True])
@pytest.mark.parametrize("seed", [19378])
def test_batch_prefill(
kvcache_layout,
table_layout,
input_dtype,
batch_size,
qo_len,
kv_len,
page_size,
num_qo_heads,
num_kv_heads,
head_dim,
causal,
logits_soft_cap,
dtype,
q_init_min,
q_init_max,
kv_init_min,
kv_init_max,
contiguous_kv,
return_lse,
seed,
profile=False,
):
if seed is not None:
torch.manual_seed(seed)
is_input_fp8 = input_dtype == dtypes.fp8 or input_dtype == "fp8"
k_vector_size = get_vector_size(dtype)
k_vector_size_fp8 = get_vector_size(dtypes.fp8)
# Skip conditions
if check_common_skip_conditions(is_input_fp8, return_lse):
return {"status": "skipped"}
if check_layout_skip_conditions(
kvcache_layout,
head_dim,
page_size,
k_vector_size,
k_vector_size_fp8,
is_input_fp8,
contiguous_kv,
):
return {"status": "skipped"}
if skip_test_if(
should_skip_rocm72_issue(causal, logits_soft_cap),
"ROCm 7.2 + gfx950 compiler issue with causal=True + logits_soft_cap=0.0",
):
return {"status": "skipped"}
# Build test tensors
qo_lens = build_qo_lens(batch_size, qo_len, randomize=True)
q_indptr_cpu = convert_lens_to_indptr(qo_lens)
q = build_q_tensor_for_test(
qo_lens,
batch_size,
qo_len,
num_qo_heads,
head_dim,
dtype,
q_init_min,
q_init_max,
is_input_fp8,
)
kv_lens = build_kv_lens(batch_size, kv_len, qo_lens, randomize=True)
kv_cache = build_paged_kv_cache(
batch_size,
kv_len,
page_size,
num_kv_heads,
head_dim,
kv_lens,
None if is_input_fp8 else kv_init_min,
None if is_input_fp8 else kv_init_max,
dtype,
use_uniform=is_input_fp8,
contiguous_kv=contiguous_kv,
)
# Move to GPU
q_indptr_gpu = q_indptr_cpu.to(0)
kv_indptr_gpu = kv_cache["kv_indptr_cpu"].to(0)
kv_indices_gpu = kv_cache["kv_indices_cpu"].to(0)
kv_last_page_len_gpu = kv_cache["kv_last_page_len_cpu"].to(0)
k_cache_ref, v_cache_ref = extract_kv_caches(kv_cache, contiguous_kv)
max_qo_len = torch.max(qo_lens).item()
max_kv_len = torch.max(kv_lens).item()
# Build vLLM-style block table if needed
block_table_gpu = None
seqlen_k_gpu = None
if table_layout == "vllm":
block_table_cpu = build_block_table(
kv_cache["kv_indptr_cpu"],
kv_cache["kv_indices_cpu"],
batch_size,
kv_cache["max_num_pages_per_seq"],