forked from ROCm/aiter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_fused_qk_norm_rope_cache_quant.py
More file actions
3414 lines (3222 loc) · 108 KB
/
Copy pathtest_fused_qk_norm_rope_cache_quant.py
File metadata and controls
3414 lines (3222 loc) · 108 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 copy
import torch
from torch import Tensor
import aiter
from aiter.test_common import checkAllclose, perftest, benchmark
from aiter.utility.dtypes import get_dtype_fp8
from aiter.utility import dtypes
import argparse
import pandas as pd
def rms_norm_forward(x: Tensor, weight: Tensor, eps: float):
input_dtype = x.dtype
variance = x.float().pow(2).mean(-1, keepdim=True)
x = x * torch.rsqrt(variance + eps)
x = x.to(input_dtype)
return weight * x
def rms_norm_diffusers_forward(x: Tensor, weight: Tensor, eps: float):
input_dtype = x.dtype
variance = x.to(torch.float32).pow(2).mean(-1, keepdim=True)
hidden_states = x * torch.rsqrt(variance + eps)
if weight is not None:
if weight.dtype in [torch.float16, torch.bfloat16]:
hidden_states = hidden_states.to(weight.dtype)
hidden_states = hidden_states * weight
else:
hidden_states = hidden_states.to(input_dtype)
return hidden_states
def apply_interleaved_rope(x: torch.Tensor, mrope_section: list[int]) -> torch.Tensor:
"""Apply interleaved MRoPE to 3D rotary embeddings.
Reorganizes frequency layout from chunked [TTT...HHH...WWW] to
interleaved [THTHWHTHW...TT], preserving frequency continuity.
"""
x_t = x[0].clone()
x_t[..., 1 : mrope_section[1] * 3 : 3] = x[1, ..., 1 : mrope_section[1] * 3 : 3]
x_t[..., 2 : mrope_section[2] * 3 : 3] = x[2, ..., 2 : mrope_section[2] * 3 : 3]
return x_t
def apply_rotary_emb_torch(
x: Tensor,
cos: Tensor,
sin: Tensor,
is_neox_style: bool,
) -> Tensor:
cos = cos.unsqueeze(-2).to(x.dtype)
sin = sin.unsqueeze(-2).to(x.dtype)
if is_neox_style:
x1, x2 = torch.chunk(x, 2, dim=-1)
else:
x1 = x[..., ::2]
x2 = x[..., 1::2]
o1 = x1 * cos - x2 * sin
o2 = x2 * cos + x1 * sin
if is_neox_style:
return torch.cat((o1, o2), dim=-1)
else:
return torch.stack((o1, o2), dim=-1).flatten(-2)
def apply_rotary_emb_diffusers(
x: Tensor,
cos: Tensor,
sin: Tensor,
is_neox_style: bool,
) -> Tensor:
"""Diffusers / qwen-image-edit reference rope: cos/sin stay fp32, x is upcast
to fp32 for the multiply, output is cast back to x's original dtype.
Mirrors the semantics of `_apply_rope_complex` (complex multiply in fp32,
`.to(original_dtype)` on the result)."""
out_dtype = x.dtype
cos = cos.unsqueeze(-2).float()
sin = sin.unsqueeze(-2).float()
x = x.float()
if is_neox_style:
x1, x2 = torch.chunk(x, 2, dim=-1)
else:
x1 = x[..., ::2]
x2 = x[..., 1::2]
o1 = x1 * cos - x2 * sin
o2 = x2 * cos + x1 * sin
if is_neox_style:
out = torch.cat((o1, o2), dim=-1)
else:
out = torch.stack((o1, o2), dim=-1).flatten(-2)
return out.to(out_dtype)
def apply_rotary_emb_dispatch(
x: Tensor,
cos: Tensor,
sin: Tensor,
is_neox_style: bool,
rotary_dim: int = 0,
) -> Tensor:
"""
Args:
x: [num_tokens, num_heads, head_size]
cos: [num_tokens, rotary_dim // 2]
sin: [num_tokens, rotary_dim // 2]
is_neox_style: Whether to use the Neox-style or GPT-J-style rotary
positional embeddings.
rotary_dim: 0 means full rotary; otherwise only the first rotary_dim
channels are rotated.
"""
head_size = x.shape[-1]
rotary_dim_ = rotary_dim if rotary_dim > 0 else head_size
if rotary_dim_ < head_size:
x_rot = apply_rotary_emb_torch(x[..., :rotary_dim_], cos, sin, is_neox_style)
return torch.cat((x_rot, x[..., rotary_dim_:]), dim=-1)
return apply_rotary_emb_torch(x, cos, sin, is_neox_style)
def split_qkv(
qkv: Tensor,
num_heads_q: int,
num_heads_k: int,
num_heads_v: int,
head_size: int,
) -> tuple[Tensor, Tensor, Tensor]:
q_size = num_heads_q * head_size
k_size = num_heads_k * head_size
v_size = num_heads_v * head_size
qkv_2d = qkv.view(qkv.shape[0], q_size + k_size + v_size)
return (
qkv_2d[:, :q_size],
qkv_2d[:, q_size : q_size + k_size],
qkv_2d[:, q_size + k_size :],
)
def clone_qkv_inputs(
q: Tensor,
k: Tensor,
v: Tensor,
num_heads_q: int,
num_heads_k: int,
num_heads_v: int,
head_size: int,
) -> tuple[Tensor, Tensor, Tensor]:
# deepcopy preserves the original split-view aliasing/strides, so perf/warmup
# iterations do not mutate the caller's tensors in-place.
return copy.deepcopy((q, k, v))
@perftest()
def run_torch_qk_norm_rope_cache_quant_shuffle(
qkv: Tensor, # contiguous (num_tokens * (num_heads_q + num_heads_k + num_heads_v) * head_size)
qw: Tensor, # contiguous (head_size)
kw: Tensor, # contiguous (head_size)
cos_sin: Tensor, # contiguous (max_positions * rotary_dim), rotary_dim <= head_size
positions: Tensor, # contiguous (3 * num_tokens) or (num_tokens)
num_tokens: int,
num_heads_q: int,
num_heads_k: int,
num_heads_v: int,
head_size: int,
is_neox_style: bool,
eps: float,
k_cache: Tensor, # [num_blocks, num_heads_k, head_size // x, page_size, x]
v_cache: Tensor, # [num_blocks, num_heads_v, head_size, page_size]
k_scale: Tensor, # [num_blocks, page_size]
v_scale: Tensor, # [num_blocks, page_size]
slot_mapping: Tensor,
kv_cache_dtype: str,
):
q, k, v = split_qkv(qkv, num_heads_q, num_heads_k, num_heads_v, head_size)
q_by_head = q.view(num_tokens, num_heads_q, head_size)
q_by_head = rms_norm_forward(q_by_head, qw, eps)
q = q_by_head.view(q.shape)
k_by_head = k.view(num_tokens, num_heads_k, head_size)
k_by_head = rms_norm_forward(k_by_head, kw, eps)
k = k_by_head.view(k.shape)
rotary_dim = cos_sin.shape[-1]
cos_sin = cos_sin.view(cos_sin.shape[0], rotary_dim)
cos_sin = cos_sin[positions]
cos, sin = cos_sin.chunk(2, dim=-1)
q_shape = q.shape
q = q.view(num_tokens, -1, head_size)
q = apply_rotary_emb_dispatch(q, cos, sin, is_neox_style, rotary_dim)
q = q.reshape(q_shape)
k_shape = k.shape
k = k.view(num_tokens, -1, head_size)
k = apply_rotary_emb_dispatch(k, cos, sin, is_neox_style, rotary_dim)
v = v.view(num_tokens, -1, head_size)
from aiter import reshape_and_cache_with_pertoken_quant, reshape_and_cache
if kv_cache_dtype == "auto":
reshape_and_cache(
k,
v,
k_cache,
v_cache,
slot_mapping,
kv_cache_dtype,
None,
None,
asm_layout=True,
)
else:
reshape_and_cache_with_pertoken_quant(
k, v, k_cache, v_cache, k_scale, v_scale, slot_mapping, asm_layout=True
)
k = k.reshape(k_shape)
v = v.reshape(k_shape)
return q, k, v, k_cache, v_cache
@perftest()
def run_aiter_qk_norm_rope_cache_quant_shuffle(
q: Tensor,
k: Tensor,
v: Tensor,
qw: Tensor, # contiguous (head_size)
kw: Tensor, # contiguous (head_size)
cos_sin: Tensor, # contiguous (max_positions * head_size)
positions: Tensor, # contiguous (3 * num_tokens)
num_heads_q: int,
num_heads_k: int,
num_heads_v: int,
head_size: int,
is_neox_style: bool,
eps: float,
k_cache: Tensor,
v_cache: Tensor,
slot_mapping: Tensor,
kv_cache_dtype: str,
k_scale: Tensor,
v_scale: Tensor,
):
q, k, v = clone_qkv_inputs(
q, k, v, num_heads_q, num_heads_k, num_heads_v, head_size
)
aiter.fused_qk_norm_rope_cache_quant_shuffle(
q,
k,
v,
num_heads_q=num_heads_q,
num_heads_k=num_heads_k,
num_heads_v=num_heads_v,
head_dim=head_size,
eps=eps,
qw=qw,
kw=kw,
cos_sin_cache=cos_sin,
is_neox_style=is_neox_style,
pos_ids=positions,
k_cache=k_cache,
v_cache=v_cache,
slot_mapping=slot_mapping,
kv_cache_dtype=kv_cache_dtype,
k_scale=k_scale,
v_scale=v_scale,
)
return q, k, v, k_cache, v_cache
@benchmark()
def test_shuffle_contiguous_inputs_match_split_views():
"""Contiguous q/k/v inputs should match non-contiguous split views."""
dtype = torch.bfloat16
num_tokens = 11
num_heads_q = num_heads_k = num_heads_v = 2
head_size = 128
is_neox_style = False
eps = 1e-6
kv_cache_dtype = "auto"
num_blocks = 4
page_size = 16
max_positions = 4096
k_cache = torch.randn(
[num_blocks, page_size, num_heads_k, head_size],
dtype=dtype,
device="cuda",
)
v_cache = torch.randn(
[num_blocks, page_size, num_heads_v, head_size],
dtype=dtype,
device="cuda",
)
x = 16 // k_cache.element_size()
k_cache = (
k_cache.view([num_blocks, page_size, num_heads_k, head_size // x, x])
.permute(0, 2, 3, 1, 4)
.contiguous()
)
v_cache = v_cache.permute(0, 2, 3, 1).contiguous()
slot_mapping = torch.randperm(num_tokens, dtype=torch.int64, device="cuda")
k_scale = torch.zeros(
[num_blocks, num_heads_k, page_size], dtype=torch.float32, device="cuda"
)
v_scale = torch.zeros(
[num_blocks, num_heads_v, page_size], dtype=torch.float32, device="cuda"
)
qkv = torch.randn(
(num_tokens, (num_heads_q + num_heads_k + num_heads_v) * head_size),
dtype=dtype,
device="cuda",
)
qw = torch.randn(head_size, dtype=dtype, device="cuda")
kw = torch.randn(head_size, dtype=dtype, device="cuda")
cos_sin = torch.randn((max_positions, head_size), dtype=dtype, device="cuda")
positions = torch.randint(
0, max_positions, (num_tokens,), dtype=torch.int64, device="cuda"
)
k_cache_c = k_cache.clone()
v_cache_c = v_cache.clone()
k_scale_c = k_scale.clone()
v_scale_c = v_scale.clone()
qkv_c = qkv.clone()
q1_src, k1_src, v1_src = split_qkv(
qkv.clone(), num_heads_q, num_heads_k, num_heads_v, head_size
)
q1_src = q1_src.contiguous()
k1_src = k1_src.contiguous()
v1_src = v1_src.contiguous()
q2_src, k2_src, v2_src = split_qkv(
qkv_c, num_heads_q, num_heads_k, num_heads_v, head_size
)
assert not q2_src.is_contiguous()
assert not k2_src.is_contiguous()
assert not v2_src.is_contiguous()
(q1, k1, v1, kc1, vc1), _ = run_aiter_qk_norm_rope_cache_quant_shuffle(
q1_src,
k1_src,
v1_src,
qw,
kw,
cos_sin,
positions,
num_heads_q,
num_heads_k,
num_heads_v,
head_size,
is_neox_style,
eps,
k_cache,
v_cache,
slot_mapping,
kv_cache_dtype,
k_scale,
v_scale,
)
(q2, k2, v2, kc2, vc2), _ = run_aiter_qk_norm_rope_cache_quant_shuffle(
q2_src,
k2_src,
v2_src,
qw,
kw,
cos_sin,
positions,
num_heads_q,
num_heads_k,
num_heads_v,
head_size,
is_neox_style,
eps,
k_cache_c,
v_cache_c,
slot_mapping,
kv_cache_dtype,
k_scale_c,
v_scale_c,
)
checkAllclose(q1, q2, msg="q contiguous vs split-view", rtol=1e-2, atol=0.05)
checkAllclose(k1, k2, msg="k contiguous vs split-view", rtol=1e-2, atol=0.05)
checkAllclose(v1, v2, msg="v contiguous vs split-view", rtol=1e-2, atol=0.05)
checkAllclose(kc1.float(), kc2.float(), msg="k_cache", rtol=1e-2, atol=0.05)
checkAllclose(vc1.float(), vc2.float(), msg="v_cache", rtol=1e-2, atol=0.05)
checkAllclose(k_scale, k_scale_c, msg="k_scale", rtol=1e-2, atol=0.05)
checkAllclose(v_scale, v_scale_c, msg="v_scale", rtol=1e-2, atol=0.05)
@benchmark()
def test_shuffle_noncontiguous_split_views_match_contiguous_inputs():
"""Non-contiguous q/k/v split views should match equivalent contiguous inputs."""
dtype = torch.bfloat16
num_tokens = 11
num_heads_q = num_heads_k = num_heads_v = 2
head_size = 128
is_neox_style = False
eps = 1e-6
kv_cache_dtype = "auto"
num_blocks = 4
page_size = 16
max_positions = 4096
k_cache = torch.randn(
[num_blocks, page_size, num_heads_k, head_size],
dtype=dtype,
device="cuda",
)
v_cache = torch.randn(
[num_blocks, page_size, num_heads_v, head_size],
dtype=dtype,
device="cuda",
)
x = 16 // k_cache.element_size()
k_cache = (
k_cache.view([num_blocks, page_size, num_heads_k, head_size // x, x])
.permute(0, 2, 3, 1, 4)
.contiguous()
)
v_cache = v_cache.permute(0, 2, 3, 1).contiguous()
slot_mapping = torch.randperm(num_tokens, dtype=torch.int64, device="cuda")
k_scale = torch.zeros(
[num_blocks, num_heads_k, page_size], dtype=torch.float32, device="cuda"
)
v_scale = torch.zeros(
[num_blocks, num_heads_v, page_size], dtype=torch.float32, device="cuda"
)
qw = torch.randn(head_size, dtype=dtype, device="cuda")
kw = torch.randn(head_size, dtype=dtype, device="cuda")
cos_sin = torch.randn((max_positions, head_size), dtype=dtype, device="cuda")
positions = torch.randint(
0, max_positions, (num_tokens,), dtype=torch.int64, device="cuda"
)
qs = num_heads_q * head_size
ks = num_heads_k * head_size
vs = num_heads_v * head_size
total = qs + ks + vs
flat = torch.randn((num_tokens, total), dtype=dtype, device="cuda")
buf_ref = flat.clone()
k_cache_ref = k_cache.clone()
v_cache_ref = v_cache.clone()
k_scale_ref = k_scale.clone()
v_scale_ref = v_scale.clone()
q_ref_src, k_ref_src, v_ref_src = split_qkv(
buf_ref, num_heads_q, num_heads_k, num_heads_v, head_size
)
q_ref_src = q_ref_src.contiguous()
k_ref_src = k_ref_src.contiguous()
v_ref_src = v_ref_src.contiguous()
(q_ref, k_ref, v_ref, kc_ref, vc_ref), _ = (
run_aiter_qk_norm_rope_cache_quant_shuffle(
q_ref_src,
k_ref_src,
v_ref_src,
qw,
kw,
cos_sin,
positions,
num_heads_q,
num_heads_k,
num_heads_v,
head_size,
is_neox_style,
eps,
k_cache_ref,
v_cache_ref,
slot_mapping,
kv_cache_dtype,
k_scale_ref,
v_scale_ref,
)
)
buf = flat.clone()
k_cache_a = k_cache.clone()
v_cache_a = v_cache.clone()
k_scale_a = k_scale.clone()
v_scale_a = v_scale.clone()
qkv_2d = buf.view(num_tokens, total)
q_nc = qkv_2d[:, :qs]
k_nc = qkv_2d[:, qs : qs + ks]
v_nc = qkv_2d[:, qs + ks :]
assert not q_nc.is_contiguous()
assert not k_nc.is_contiguous()
assert not v_nc.is_contiguous()
aiter.fused_qk_norm_rope_cache_quant_shuffle(
q_nc,
k_nc,
v_nc,
num_heads_q=num_heads_q,
num_heads_k=num_heads_k,
num_heads_v=num_heads_v,
head_dim=head_size,
eps=eps,
qw=qw,
kw=kw,
cos_sin_cache=cos_sin,
is_neox_style=is_neox_style,
pos_ids=positions,
k_cache=k_cache_a,
v_cache=v_cache_a,
slot_mapping=slot_mapping,
kv_cache_dtype=kv_cache_dtype,
k_scale=k_scale_a,
v_scale=v_scale_a,
)
checkAllclose(q_nc, q_ref, msg="q split-view vs contiguous", rtol=1e-2, atol=0.05)
checkAllclose(k_nc, k_ref, msg="k split-view vs contiguous", rtol=1e-2, atol=0.05)
checkAllclose(v_nc, v_ref, msg="v split-view vs contiguous", rtol=1e-2, atol=0.05)
checkAllclose(
k_cache_a.float(), kc_ref.float(), msg="k_cache", rtol=1e-2, atol=0.05
)
checkAllclose(
v_cache_a.float(), vc_ref.float(), msg="v_cache", rtol=1e-2, atol=0.05
)
checkAllclose(k_scale_a, k_scale_ref, msg="k_scale", rtol=1e-2, atol=0.05)
checkAllclose(v_scale_a, v_scale_ref, msg="v_scale", rtol=1e-2, atol=0.05)
@benchmark()
def test_shuffle_3d_inputs_match_2d_inputs():
"""The operator should produce the same result for equivalent 2D and 3D q/k/v inputs."""
dtype = torch.bfloat16
num_tokens = 9
num_heads_q = num_heads_k = num_heads_v = 2
head_size = 128
is_neox_style = False
eps = 1e-6
kv_cache_dtype = "auto"
num_blocks = 3
page_size = 16
max_positions = 2048
def make_kv_caches():
kc = torch.randn(
[num_blocks, page_size, num_heads_k, head_size],
dtype=dtype,
device="cuda",
)
vc = torch.randn(
[num_blocks, page_size, num_heads_v, head_size],
dtype=dtype,
device="cuda",
)
x_ = 16 // kc.element_size()
kc = (
kc.view([num_blocks, page_size, num_heads_k, head_size // x_, x_])
.permute(0, 2, 3, 1, 4)
.contiguous()
)
vc = vc.permute(0, 2, 3, 1).contiguous()
return kc, vc
slot_mapping = torch.randperm(num_tokens, dtype=torch.int64, device="cuda")
qkv = torch.randn(
(num_tokens, (num_heads_q + num_heads_k + num_heads_v) * head_size),
dtype=dtype,
device="cuda",
)
qw = torch.randn(head_size, dtype=dtype, device="cuda")
kw = torch.randn(head_size, dtype=dtype, device="cuda")
cos_sin = torch.randn((max_positions, head_size), dtype=dtype, device="cuda")
positions = torch.randint(
0, max_positions, (num_tokens,), dtype=torch.int64, device="cuda"
)
qs = int(num_heads_q * head_size)
ks = int(num_heads_k * head_size)
vs = int(num_heads_v * head_size)
flat = qkv.view(num_tokens, qs + ks + vs)
q_src = flat[:, :qs].contiguous()
k_src = flat[:, qs : qs + ks].contiguous()
v_src = flat[:, qs + ks :].contiguous()
k_cache_init, v_cache_init = make_kv_caches()
k_cache_a, v_cache_a = k_cache_init.clone(), v_cache_init.clone()
k_scale_a = torch.zeros(
[num_blocks, num_heads_k, page_size], dtype=torch.float32, device="cuda"
)
v_scale_a = torch.zeros(
[num_blocks, num_heads_v, page_size], dtype=torch.float32, device="cuda"
)
q_a, k_a, v_a = q_src.clone(), k_src.clone(), v_src.clone()
aiter.fused_qk_norm_rope_cache_quant_shuffle(
q_a,
k_a,
v_a,
num_heads_q=num_heads_q,
num_heads_k=num_heads_k,
num_heads_v=num_heads_v,
head_dim=head_size,
eps=eps,
qw=qw,
kw=kw,
cos_sin_cache=cos_sin,
is_neox_style=is_neox_style,
pos_ids=positions,
k_cache=k_cache_a,
v_cache=v_cache_a,
slot_mapping=slot_mapping,
kv_cache_dtype=kv_cache_dtype,
k_scale=k_scale_a,
v_scale=v_scale_a,
)
k_cache_b, v_cache_b = k_cache_init.clone(), v_cache_init.clone()
k_scale_b = torch.zeros_like(k_scale_a)
v_scale_b = torch.zeros_like(v_scale_a)
q_b = q_src.clone().view(num_tokens, num_heads_q, head_size)
k_b = k_src.clone().view(num_tokens, num_heads_k, head_size)
v_b = v_src.clone().view(num_tokens, num_heads_v, head_size)
aiter.fused_qk_norm_rope_cache_quant_shuffle(
q_b,
k_b,
v_b,
num_heads_q=num_heads_q,
num_heads_k=num_heads_k,
num_heads_v=num_heads_v,
head_dim=head_size,
eps=eps,
qw=qw,
kw=kw,
cos_sin_cache=cos_sin,
is_neox_style=is_neox_style,
pos_ids=positions,
k_cache=k_cache_b,
v_cache=v_cache_b,
slot_mapping=slot_mapping,
kv_cache_dtype=kv_cache_dtype,
k_scale=k_scale_b,
v_scale=v_scale_b,
)
checkAllclose(q_a, q_b.view_as(q_a), msg="q 2d vs 3d", rtol=1e-2, atol=0.05)
checkAllclose(k_a, k_b.view_as(k_a), msg="k 2d vs 3d", rtol=1e-2, atol=0.05)
checkAllclose(v_a, v_b.view_as(v_a), msg="v 2d vs 3d", rtol=1e-2, atol=0.05)
checkAllclose(
k_cache_a.float(), k_cache_b.float(), msg="k_cache", rtol=1e-2, atol=0.05
)
checkAllclose(
v_cache_a.float(), v_cache_b.float(), msg="v_cache", rtol=1e-2, atol=0.05
)
checkAllclose(k_scale_a, k_scale_b, msg="k_scale", rtol=1e-2, atol=0.05)
checkAllclose(v_scale_a, v_scale_b, msg="v_scale", rtol=1e-2, atol=0.05)
@perftest(num_iters=2)
def run_torch_qk_norm_rope_cache_block_quant_shuffle(
qkv: Tensor, # contiguous (num_tokens * (num_heads_q + num_heads_k + num_heads_v) * head_size)
qw: Tensor, # contiguous (head_size)
kw: Tensor, # contiguous (head_size)
cos_sin: Tensor, # contiguous (max_positions * head_size)
positions: Tensor, # contiguous (3 * num_tokens) or (num_tokens)
num_tokens: int,
num_heads_q: int,
num_heads_k: int,
num_heads_v: int,
head_size: int,
is_neox_style: bool,
eps: float,
k_cache: Tensor, # [num_blocks, num_heads_k, head_size // x, block_size, x]
v_cache: Tensor, # [num_blocks, num_heads_v, block_size // x, head_size, x]
k_scale: Tensor, # [num_blocks, num_kv_heads]
v_scale: Tensor, # [num_blocks, num_kv_heads]
slot_mapping: Tensor,
kv_cache_dtype: str,
):
q_size = num_heads_q * head_size
k_size = num_heads_k * head_size
v_size = num_heads_v * head_size
qkv = qkv.view(num_tokens, q_size + k_size + v_size)
q, k, v = qkv.split([q_size, k_size, v_size], dim=-1)
q_by_head = q.view(num_tokens, num_heads_q, head_size)
q_by_head = rms_norm_forward(q_by_head, qw, eps)
q = q_by_head.view(q.shape)
k_by_head = k.view(num_tokens, num_heads_k, head_size)
k_by_head = rms_norm_forward(k_by_head, kw, eps)
k = k_by_head.view(k.shape)
cos_sin = cos_sin.view(cos_sin.shape[0], head_size)
cos_sin = cos_sin[positions]
cos, sin = cos_sin.chunk(2, dim=-1)
q_shape = q.shape
q = q.view(num_tokens, -1, head_size)
q = apply_rotary_emb_dispatch(q, cos, sin, is_neox_style)
q = q.reshape(q_shape)
k_shape = k.shape
k = k.view(num_tokens, -1, head_size)
k = apply_rotary_emb_dispatch(k, cos, sin, is_neox_style)
v = v.view(num_tokens, -1, head_size)
from aiter import reshape_and_cache
if kv_cache_dtype == "auto":
reshape_and_cache(
k,
v,
k_cache,
v_cache,
slot_mapping,
kv_cache_dtype,
None,
None,
asm_layout=True,
)
else:
# Block quant ref using pertoken_quant (same approach as test_kvcache_blockscale.py)
# k_cache: [num_blocks, num_heads_k, head_size // x, block_size, x]
# v_cache: [num_blocks, num_heads_v, block_size // x, head_size, x]
num_blocks = k_cache.shape[0]
block_size = k_cache.shape[-2] # page_size
x_val = k_cache.shape[-1]
cache_dtype = k_cache.dtype
# Step 1: Unflatten k_cache to [num_blocks, block_size, num_heads_k, head_size]
# and DEQUANTIZE using old scale (multiply raw fp8 values by scale)
# k_cache: [num_blocks, num_heads_k, head_size//x, block_size, x]
# -> permute(0, 3, 1, 2, 4) -> [num_blocks, block_size, num_heads_k, head_size//x, x]
# -> view [num_blocks, block_size, num_heads_k, head_size]
k_cache_flat = (
k_cache.float()
.permute(0, 3, 1, 2, 4)
.contiguous()
.view(num_blocks, block_size, num_heads_k, head_size)
)
# Dequantize: k_cache_flat *= k_scale[num_blocks, num_heads_k] (broadcast over block_size, head_size)
k_cache_flat = k_cache_flat * k_scale.view(num_blocks, 1, num_heads_k, 1)
k_cache_flat = k_cache_flat.view(-1, num_heads_k, head_size)
# v_cache: [num_blocks, num_heads_v, block_size//x, head_size, x]
# -> permute(0, 2, 4, 1, 3) -> [num_blocks, block_size//x, x, num_heads_v, head_size]
# -> view [num_blocks, block_size, num_heads_v, head_size]
v_cache_flat = (
v_cache.float()
.permute(0, 2, 4, 1, 3)
.contiguous()
.view(num_blocks, block_size, num_heads_v, head_size)
)
# Dequantize: v_cache_flat *= v_scale[num_blocks, num_heads_v]
v_cache_flat = v_cache_flat * v_scale.view(num_blocks, 1, num_heads_v, 1)
v_cache_flat = v_cache_flat.view(-1, num_heads_v, head_size)
# Step 2: Scatter K/V into dequantized cache
k_flat = k.view(-1, num_heads_k, head_size)
v_flat = v.view(-1, num_heads_v, head_size)
k_cache_flat[slot_mapping] = k_flat.float()
v_cache_flat[slot_mapping] = v_flat.float()
# Step 3: Reshape to [num_blocks, num_heads, block_size*head_size] and pertoken_quant
k_cache_for_quant = (
k_cache_flat.view(num_blocks, block_size, num_heads_k, head_size)
.permute(0, 2, 1, 3)
.contiguous()
.view(num_blocks, num_heads_k, -1)
)
k_cache_q, k_scale_new = aiter.pertoken_quant(
k_cache_for_quant,
scale_dtype=torch.float32,
quant_dtype=cache_dtype,
)
k_scale_new = k_scale_new.view(num_blocks, num_heads_k)
v_cache_for_quant = (
v_cache_flat.view(num_blocks, block_size, num_heads_v, head_size)
.permute(0, 2, 1, 3)
.contiguous()
.view(num_blocks, num_heads_v, -1)
)
v_cache_q, v_scale_new = aiter.pertoken_quant(
v_cache_for_quant,
scale_dtype=torch.float32,
quant_dtype=cache_dtype,
)
v_scale_new = v_scale_new.view(num_blocks, num_heads_v)
# Step 4: Reshape back to tiled layout
# k_cache_q: [num_blocks, num_heads_k, block_size*head_size]
# -> view [num_blocks, num_heads_k, block_size, head_size//x, x]
# -> permute(0, 1, 3, 2, 4) -> [num_blocks, num_heads_k, head_size//x, block_size, x]
k_cache.copy_(
k_cache_q.view(
num_blocks, num_heads_k, block_size, head_size // x_val, x_val
)
.permute(0, 1, 3, 2, 4)
.contiguous()
)
# v_cache_q: [num_blocks, num_heads_v, block_size*head_size]
# -> view [num_blocks, num_heads_v, block_size, head_size]
# -> view [num_blocks, num_heads_v, block_size//x, x, head_size]
# -> permute(0, 1, 2, 4, 3) -> [num_blocks, num_heads_v, block_size//x, head_size, x]
v_cache.copy_(
v_cache_q.view(
num_blocks, num_heads_v, block_size // x_val, x_val, head_size
)
.permute(0, 1, 2, 4, 3)
.contiguous()
)
k_scale.copy_(k_scale_new)
v_scale.copy_(v_scale_new)
k = k.reshape(k_shape)
v = v.reshape(k_shape)
return q, k, v, k_cache, v_cache
@perftest(num_iters=31, num_rotate_args=31)
def run_aiter_qk_norm_rope_cache_block_quant_shuffle(
qkv: Tensor, # contiguous (num_tokens * (num_heads_q + num_heads_k + num_heads_v) * head_size)
qw: Tensor, # contiguous (head_size)
kw: Tensor, # contiguous (head_size)
cos_sin: Tensor, # contiguous (max_positions * head_size)
positions: Tensor, # contiguous (3 * num_tokens)
num_tokens: int,
num_heads_q: int,
num_heads_k: int,
num_heads_v: int,
head_size: int,
is_neox_style: bool,
eps: float,
k_cache: Tensor,
v_cache: Tensor,
slot_mapping: Tensor,
cu_q_len: Tensor,
kv_cache_dtype: str,
k_scale: Tensor,
v_scale: Tensor,
max_tokens_per_batch: int = 0,
):
qkv = qkv.clone() # inplace op
aiter.fused_qk_norm_rope_cache_block_quant_shuffle(
qkv,
num_heads_q,
num_heads_k,
num_heads_v,
head_size,
eps,
qw,
kw,
cos_sin,
is_neox_style,
positions,
k_cache,
v_cache,
slot_mapping,
cu_q_len,
kv_cache_dtype,
k_scale,
v_scale,
max_tokens_per_batch,
)
q_size = num_heads_q * head_size
k_size = num_heads_k * head_size
v_size = num_heads_v * head_size
qkv = qkv.view(num_tokens, q_size + k_size + v_size)
q, k, v = qkv.split([q_size, k_size, v_size], dim=-1)
return q, k, v, k_cache, v_cache
@benchmark()
def test_qk_norm_rope_cache_quant(
dtype,
num_tokens,
num_heads_q,
num_heads_k,
num_heads_v,
head_size,
is_neox_style,
eps,
kv_cache_dtype,
num_blocks,
page_size,
max_positions: int = 10000,
rotary_dim: int = 0,
):
# Construct tensors inside the function
if kv_cache_dtype == "fp8_e4m3":
cache_dtype = get_dtype_fp8()
else:
cache_dtype = dtype
rotary_dim_ = rotary_dim if rotary_dim > 0 else head_size
assert rotary_dim_ <= head_size
assert rotary_dim_ % 2 == 0
k_cache = torch.randn(
[num_blocks, page_size, num_heads_k, head_size],
dtype=dtype,
device="cuda",
).to(cache_dtype)
v_cache = torch.randn(
[num_blocks, page_size, num_heads_v, head_size],
dtype=dtype,
device="cuda",
).to(cache_dtype)
x = 16 // k_cache.element_size()
k_cache = (
k_cache.view([num_blocks, page_size, num_heads_k, head_size // x, x])
.permute(0, 2, 3, 1, 4)
.contiguous()
)
v_cache = v_cache.permute(0, 2, 3, 1).contiguous()
slot_mapping = torch.randperm(num_tokens, dtype=torch.int64, device="cuda")
k_scale = torch.zeros(
[num_blocks, num_heads_k, page_size], dtype=torch.float32, device="cuda"
)
v_scale = torch.zeros(
[num_blocks, num_heads_v, page_size], dtype=torch.float32, device="cuda"
)
qkv = torch.randn(
(num_tokens, (num_heads_q + num_heads_k + num_heads_v) * head_size),
dtype=dtype,
device="cuda",
)
qw = torch.randn(head_size, dtype=dtype, device="cuda")
kw = torch.randn(head_size, dtype=dtype, device="cuda")
cos_sin = torch.randn((max_positions, rotary_dim_), dtype=dtype, device="cuda")
pos_shape = (num_tokens,)
positions = torch.randint(
0, max_positions, pos_shape, dtype=torch.int64, device="cuda"
)
k_scale_ref = k_scale.clone()
v_scale_ref = v_scale.clone()
(q_ref, k_ref, v_ref, k_cache_ref, v_cache_ref), avg_torch = (
run_torch_qk_norm_rope_cache_quant_shuffle(
qkv,
qw,
kw,
cos_sin,
positions,
num_tokens,
num_heads_q,
num_heads_k,
num_heads_v,
head_size,
is_neox_style,
eps,
k_cache,
v_cache,
k_scale_ref,
v_scale_ref,
slot_mapping,
kv_cache_dtype,
)
)
q_in, k_in, v_in = split_qkv(
qkv.clone(), num_heads_q, num_heads_k, num_heads_v, head_size
)
(q, k, v, k_cache, v_cache), avg_cu = run_aiter_qk_norm_rope_cache_quant_shuffle(
q_in,
k_in,
v_in,
qw,
kw,
cos_sin,
positions,
num_heads_q,
num_heads_k,
num_heads_v,
head_size,
is_neox_style,
eps,
k_cache,
v_cache,
slot_mapping,
kv_cache_dtype,
k_scale,
v_scale,
)
info = f"dtype:{dtype}, num_tokens:{num_tokens}, num_heads_q:{num_heads_q}, num_heads_k:{num_heads_k}, num_heads_v:{num_heads_v}, head_size:{head_size}, is_neox_style:{is_neox_style}"
if rotary_dim > 0:
info += f", rotary_dim:{rotary_dim_}"
msg = f"[perf] === {info} === torch avg: {avg_torch:<8.2f} us, cu avg: {avg_cu:<8.2f} us, uplift: {avg_torch / avg_cu - 1:<5.1%}"
checkAllclose(q_ref, q, msg="q", rtol=1e-2, atol=0.05)
checkAllclose(k_ref, k, msg="k", rtol=1e-2, atol=0.05)
checkAllclose(v_ref, v, msg=msg, rtol=1e-2, atol=0.05)
checkAllclose(