forked from NVIDIA/TensorRT-LLM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfused_multihead_attention.cpp
More file actions
2205 lines (1994 loc) · 89 KB
/
Copy pathfused_multihead_attention.cpp
File metadata and controls
2205 lines (1994 loc) · 89 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) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include <float.h>
#include <fmha/hopper/tma_types.h>
#include <fmha/paged_kv_cache.h>
#include <fstream>
#include <fused_multihead_attention_api.h>
#include <iostream>
#include <math.h>
#include <numeric>
#include <string>
#include <vector>
using Launch_params = bert::Fused_multihead_attention_launch_params;
using Attention_mask_type = fmha::Attention_mask_type;
using Attention_input_layout = fmha::Attention_input_layout;
using Kv_block_array = fmha::Kv_block_array;
////////////////////////////////////////////////////////////////////////////////////////////////////
void run_softmax_fp32(void* dst, void const* src, void const* mask, void const* attention_sinks, void* softmax_sum_d,
void* cu_q_seqlens_d, int s_inner, int s_outer, int b, int h, float softcapping_scale_bmm1, int warps_n,
bool has_alibi);
////////////////////////////////////////////////////////////////////////////////////////////////////
void run_softmax_e4m3(void* dst, void const* src, void const* mask, void const* attention_sinks, void* softmax_sum_d,
void* cu_q_seqlens_d, int s_inner, int s_outer, int b, int h, float scale_softmax, float softcapping_scale_bmm1,
int warps_n, bool has_alibi);
////////////////////////////////////////////////////////////////////////////////////////////////////
void run_softmax_fp16(void* dst, void const* src, void const* mask, void const* attention_sinks, void* softmax_sum_d,
void* cu_q_seqlens_d, int s_inner, int s_outer, int b, int h, float softcapping_scale_bmm1, int warps_n,
bool has_alibi);
////////////////////////////////////////////////////////////////////////////////////////////////////
void run_softmax_bf16(void* dst, void const* src, void const* mask, void const* attention_sinks, void* softmax_sum_d,
void* cu_q_seqlens_d, int s_inner, int s_outer, int b, int h, float softcapping_scale_bmm1, int warps_n,
bool has_alibi);
////////////////////////////////////////////////////////////////////////////////////////////////////
void run_softmax_int8(void* dst, void const* src, void const* mask, void const* attention_sinks, void* softmax_sum_d,
void* cu_q_seqlens_d, int s_inner, int s_outer, int b, int h, float scale_i2f, float scale_f2i,
float softcapping_scale_bmm1, int warps_n, bool has_alibi);
////////////////////////////////////////////////////////////////////////////////////////////////////
void run_conversion_int32_to_int8(void* dst, void const* src, int s, int b, int h, int d, float scale);
////////////////////////////////////////////////////////////////////////////////////////////////////
void run_conversion_fp32_to_fp16(void* dst, void const* src, int s, int b, int h, int d);
////////////////////////////////////////////////////////////////////////////////////////////////////
void run_conversion_fp32_to_bf16(void* dst, void const* src, int s, int b, int h, int d);
////////////////////////////////////////////////////////////////////////////////////////////////////
void run_conversion_fp32_to_e4m3(void* dst, void const* src, int s, int b, int h, int d, float scale_o);
////////////////////////////////////////////////////////////////////////////////////////////////////
void run_sage_quant(unsigned int batch_size, unsigned int head_num, unsigned int head_size, unsigned int max_seq_len,
// device var
void const* q, void const* k, void const* v, int stride_q, int stride_k, int stride_v, int const* cu_seqlens_q,
int const* cu_seqlens_kv, int block_size_q, int block_size_k, int block_size_v,
// output
void* quant_q, void* quant_k, void* quant_v, float* scales_q, float* scales_k, float* scales_v);
////////////////////////////////////////////////////////////////////////////////////////////////////
void ground_truth(RefBMM& bmm1, RefBMM& bmm2, const Data_type data_type, const Data_type acc_type,
float const scale_bmm1, float const scale_softmax, float const scale_bmm2, float const softcapping_scale_bmm1,
void* qkv_d, void* vt_d, void* mask_d, void* attention_sinks_d, void* p_d, void* s_d, void* tmp_d, void* o_d,
void* softmax_sum_d, void* cu_q_seqlens_d, const size_t b, const size_t s, const size_t h, const size_t d,
const size_t dv, int const runs, int const warps_m, int const warps_n, bool const has_alibi)
{
cudaStream_t stream = 0;
// The stride between rows of the QKV matrix.
size_t qkv_stride = get_size_in_bytes(d, data_type);
// 1st GEMMd.
uint32_t alpha, beta = 0u;
for (int ii = 0; ii < runs; ++ii)
{
// If we run the INT8 kernel, defer the scaling of P to softmax.
set_alpha(alpha, data_type == DATA_TYPE_INT8 ? 1.f : scale_bmm1, acc_type);
// P = Q x K'
bmm1(static_cast<char*>(qkv_d) + 0 * qkv_stride, static_cast<char*>(qkv_d) + 1 * qkv_stride, p_d, &alpha, &beta,
stream);
// Softmax.
if (data_type == DATA_TYPE_FP16 && acc_type == DATA_TYPE_FP16)
{
run_softmax_fp16(s_d, p_d, mask_d, attention_sinks_d, softmax_sum_d, cu_q_seqlens_d, s, s, b, h,
softcapping_scale_bmm1, warps_n, has_alibi);
}
else if (data_type == DATA_TYPE_BF16 && acc_type == DATA_TYPE_FP32)
{
run_softmax_bf16(s_d, p_d, mask_d, attention_sinks_d, softmax_sum_d, cu_q_seqlens_d, s, s, b, h,
softcapping_scale_bmm1, warps_n, has_alibi);
}
else if (data_type == DATA_TYPE_FP16 && acc_type == DATA_TYPE_FP32)
{
run_softmax_fp32(s_d, p_d, mask_d, attention_sinks_d, softmax_sum_d, cu_q_seqlens_d, s, s, b, h,
softcapping_scale_bmm1, warps_n, has_alibi);
}
else if (data_type == DATA_TYPE_E4M3 && acc_type == DATA_TYPE_FP32)
{
run_softmax_e4m3(s_d, p_d, mask_d, attention_sinks_d, softmax_sum_d, cu_q_seqlens_d, s, s, b, h,
scale_softmax, softcapping_scale_bmm1, warps_n, has_alibi);
}
else if (data_type == DATA_TYPE_INT8 && acc_type == DATA_TYPE_INT32)
{
run_softmax_int8(s_d, p_d, mask_d, attention_sinks_d, softmax_sum_d, cu_q_seqlens_d, s, s, b, h, scale_bmm1,
scale_softmax, softcapping_scale_bmm1, warps_n, has_alibi);
}
else
{
assert(false && "Reference Softmax: Unsupported type config");
}
// 2nd GEMM.
set_alpha(alpha, 1.f, acc_type);
void* out_d = o_d;
// We may have to do a final conversion.
if (data_type != acc_type)
{
out_d = tmp_d;
}
// O = S x V
bmm2(static_cast<char*>(s_d),
static_cast<char*>(vt_d), // static_cast<char *>(qkv_d) + 2 * qkv_stride,
out_d, &alpha, &beta, stream);
// Conversion to output type.
if (data_type == DATA_TYPE_FP16 && acc_type == DATA_TYPE_FP16)
{
// Noop.
}
else if (data_type == DATA_TYPE_FP16 && acc_type == DATA_TYPE_FP32)
{
run_conversion_fp32_to_fp16(o_d, out_d, s, b, h, dv);
}
else if (data_type == DATA_TYPE_BF16 && acc_type == DATA_TYPE_FP32)
{
run_conversion_fp32_to_bf16(o_d, out_d, s, b, h, dv);
}
else if (data_type == DATA_TYPE_E4M3 && acc_type == DATA_TYPE_FP32)
{
run_conversion_fp32_to_e4m3(o_d, out_d, s, b, h, dv, scale_bmm2);
}
else if (data_type == DATA_TYPE_INT8 && acc_type == DATA_TYPE_INT32)
{
// quantize output in second step
run_conversion_int32_to_int8(o_d, out_d, s, b, h, dv, scale_bmm2);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static inline void set_params(bert::Fused_multihead_attention_params_v1& params,
// types
Data_type data_type, Data_type acc_type,
// sizes
const size_t b, const size_t s, const size_t h, const size_t d, const size_t packed_mask_stride,
// device pointers
void* qkv_d, void* packed_mask_d, void* o_d, void* p_d, void* s_d,
// scale factors
float const scale_bmm1, float const scale_softmax, float const scale_bmm2,
// flags
bool const has_alibi)
{
memset(¶ms, 0, sizeof(params));
// Set the pointers.
params.qkv_ptr = qkv_d;
params.qkv_stride_in_bytes = get_size_in_bytes(b * h * 3 * d, data_type);
// params.qkv_stride_in_bytes = get_size_in_bytes(h * 3 * d, data_type);
params.packed_mask_ptr = packed_mask_d;
// params.packed_mask_stride_in_bytes = mmas_m * threads_per_cta * sizeof(uint32_t);
params.packed_mask_stride_in_bytes = packed_mask_stride * sizeof(uint32_t);
params.o_ptr = o_d;
params.o_stride_in_bytes = get_size_in_bytes(b * h * d, data_type);
params.has_alibi = has_alibi;
params.alibi_params = fmha::AlibiParams(h);
#if defined(STORE_P)
params.p_ptr = p_d;
params.p_stride_in_bytes = get_size_in_bytes(b * h * s, acc_type);
#endif // defined(STORE_P)
#if defined(STORE_S)
params.s_ptr = s_d;
params.s_stride_in_bytes = get_size_in_bytes(b * h * s, data_type);
#endif // defined(STORE_S)
// Set the dimensions.
params.b = b;
params.h = h;
params.s = s;
params.d = d;
// Set the different scale values.
Data_type scale_type1 = (data_type == DATA_TYPE_FP16) || (data_type == DATA_TYPE_BF16) ? acc_type : DATA_TYPE_FP32;
Data_type scale_type2 = (data_type == DATA_TYPE_FP16) || (data_type == DATA_TYPE_BF16) ? data_type : DATA_TYPE_FP32;
set_alpha(params.scale_bmm1, scale_bmm1, scale_type1);
set_alpha(params.scale_softmax, scale_softmax, scale_type1);
set_alpha(params.scale_bmm2, scale_bmm2, scale_type2);
// Do we enable the trick to replace I2F with FP math in the 2nd GEMM?
if (data_type == DATA_TYPE_INT8)
{
params.enable_i2f_trick
= -double(1 << 22) * double(scale_bmm2) <= -128.f && double(1 << 22) * double(scale_bmm2) >= 127.f;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static inline void set_params(bert::Fused_multihead_attention_params_v2& params, const Launch_params launch_params,
// types
Data_type data_type, Data_type acc_type, Data_type output_dtype,
// attention input layout
Attention_input_layout input_layout,
// sizes
const size_t b, const size_t s_q, const size_t s_kv, const size_t h, const size_t h_kv, const size_t d,
const size_t dv, const size_t total, const size_t num_grouped_heads, const size_t sliding_window_size,
const size_t chunked_attention_size,
// paged kv cache block size.
const size_t tokens_per_block,
// device pointers
void* qkv_packed_d,
// contiguous q.
void* q_d,
// separate k.
void* k_d,
// separate v.
void* v_d,
// contiguous kv.
void* kv_d,
// start address of the paged kv pool.
void* paged_kv_pool_ptr,
// offsets for different blocks in terms of the start address.
int32_t* paged_block_offsets,
// mask input.
void* packed_mask_d, void* cu_mask_rows_d,
// attention sinks.
void* attention_sinks_d, void* cu_kv_seqlens_d, void* cu_q_seqlens_d, void* o_packed_d, void* p_d, void* s_d,
void* softmax_stats_d, void* scale_bmm2_d,
// scale factors
float const scale_bmm1, float const scale_softmax, float const scale_bmm2, float const softcapping_scale_bmm1,
// flags
bool const use_int8_scale_max, bool const interleaved, bool const is_s_padded, bool const has_alibi,
float const skip_softmax_threshold_scale_factor)
{
memset(¶ms, 0, sizeof(params));
params.o_ptr = o_packed_d;
params.o_stride_in_bytes = get_size_in_bytes(h * dv, output_dtype);
if (interleaved)
{
params.q_stride_in_bytes = total;
params.o_stride_in_bytes = total;
}
if (input_layout == Attention_input_layout::PACKED_QKV)
{
// For grouped- or multi-query attention (h denotes num_q_heads; h' denotes h_kv):
// qkv_layout = [b, s, [q_hd, k_h'd, v_h'd]]
// qkv_stride = (h+2*h')d * bytes_per_elt
// Otherwise:
// qkv_layout = [b, s, 3, h, d] or [b, s, h, 3, d]
// qkv_stride = 3hd * bytes_per_elt
params.qkv_ptr = qkv_packed_d;
params.q_stride_in_bytes = params.k_stride_in_bytes = params.v_stride_in_bytes
= get_size_in_bytes(h * d + h_kv * d + h_kv * dv, data_type);
}
else
{
// Layout [B, S, H, D].
params.q_ptr = q_d;
params.q_stride_in_bytes = get_size_in_bytes(h * d, data_type);
if (input_layout == Attention_input_layout::CONTIGUOUS_Q_KV)
{
// Layout [B, S, 2, H, D].
params.kv_ptr = kv_d;
params.k_stride_in_bytes = params.v_stride_in_bytes = get_size_in_bytes(h_kv * (d + dv), data_type);
}
else if (input_layout == Attention_input_layout::Q_PAGED_KV)
{
int max_blocks_per_sequence = (s_kv + tokens_per_block - 1) / tokens_per_block;
params.paged_kv_cache = Kv_block_array(b, max_blocks_per_sequence, tokens_per_block,
get_size_in_bytes(tokens_per_block * h_kv * std::gcd(d, dv), data_type), paged_kv_pool_ptr);
params.paged_kv_cache.mBlockOffsets = paged_block_offsets;
params.k_stride_in_bytes = get_size_in_bytes(tokens_per_block * d, data_type);
params.v_stride_in_bytes = get_size_in_bytes(tokens_per_block * dv, data_type);
}
else if (input_layout == Attention_input_layout::SEPARATE_Q_K_V)
{
// Layout [B, S, H_kv, D].
params.k_ptr = k_d;
// Layout [B, S, H_kv, Dv].
params.v_ptr = v_d;
params.k_stride_in_bytes = get_size_in_bytes(h_kv * d, data_type);
params.v_stride_in_bytes = get_size_in_bytes(h_kv * dv, data_type);
}
}
// Packed mask.
params.packed_mask_ptr = packed_mask_d;
// The N dimension has to be aligned.
params.packed_mask_stride_in_bytes = (align_to(int64_t(s_kv), int64_t(fmha::FLASH_ATTEN_MASK_N_ALIGNMENT))) / 8;
// Attention sinks.
params.attention_sinks = reinterpret_cast<float*>(attention_sinks_d);
assert((attention_sinks_d == nullptr || launch_params.flash_attention)
&& "attention sinks are only supported with flash attention");
#if defined(STORE_P)
params.p_ptr = p_d;
params.p_stride_in_bytes = get_size_in_bytes(b * h * s_kv, acc_type);
#endif // defined(STORE_P)
#if defined(STORE_S)
params.s_ptr = s_d;
params.s_stride_in_bytes = get_size_in_bytes(b * h * s_kv, data_type);
#endif // defined(STORE_S)
params.softmax_stats_ptr = softmax_stats_d;
params.softmax_stats_stride_in_bytes = get_size_in_bytes(h * 2, DATA_TYPE_FP32);
// Set the dimensions.
params.b = b;
params.h = h;
params.s = s_q;
params.d = d;
params.dv = dv;
params.num_grouped_heads = num_grouped_heads;
params.sliding_window_size = sliding_window_size;
assert((chunked_attention_size == 0 || (chunked_attention_size & (chunked_attention_size - 1)) == 0)
&& "chunked_attention_size has to be a power of 2");
params.log2_chunked_attention_size = chunked_attention_size > 0 ? std::log2(chunked_attention_size) : 0;
// cumulative q or kv sequence lengths.
params.cu_q_seqlens = static_cast<int*>(cu_q_seqlens_d);
params.cu_kv_seqlens = static_cast<int*>(cu_kv_seqlens_d);
// cumulative mask sequence lengths.
params.cu_mask_rows = static_cast<int*>(cu_mask_rows_d);
// Set the different scale values.
Data_type scale_type1 = (data_type == DATA_TYPE_FP16) || (data_type == DATA_TYPE_BF16) ? acc_type : DATA_TYPE_FP32;
Data_type scale_softmax_type = scale_type1;
Data_type scale_type2 = (data_type == DATA_TYPE_FP16) || (data_type == DATA_TYPE_BF16) ? data_type : DATA_TYPE_FP32;
if (data_type == DATA_TYPE_E4M3)
{
scale_type1 = acc_type;
scale_type2 = acc_type;
}
// Fuse 1.0f / softcapping_scale into scale_bmm1.
bool const enable_attn_logit_softcapping = softcapping_scale_bmm1 != 0.f;
float fused_scale_bmm1 = enable_attn_logit_softcapping ? scale_bmm1 / softcapping_scale_bmm1 : scale_bmm1;
// use specialized hopper kernels without alibi support.
// alibi or softcapping_scale cannot utilize the exp2f with fused_scale optimization.
if (launch_params.warp_specialization && !has_alibi && !enable_attn_logit_softcapping)
{
set_alpha(params.scale_bmm1, fused_scale_bmm1 * float(M_LOG2E), DATA_TYPE_FP32);
}
else
{
set_alpha(params.scale_bmm1, fused_scale_bmm1, scale_type1);
}
set_alpha(params.scale_softmax, scale_softmax, scale_softmax_type);
set_alpha(params.scale_bmm2, scale_bmm2, scale_type2);
params.scale_bmm2_d = reinterpret_cast<uint32_t*>(scale_bmm2_d);
params.softcapping_scale_bmm1 = softcapping_scale_bmm1;
FMHA_CHECK_CUDA(cudaMemcpy(params.scale_bmm2_d, ¶ms.scale_bmm2, sizeof(uint32_t), cudaMemcpyHostToDevice));
// attention type, h_kv < h if MQA or GQA
params.h_kv = h_kv;
assert(h % h_kv == 0 && "MQA/GQA needs h to be divisible by h_kv!");
params.h_q_per_kv = h / h_kv;
params.has_alibi = has_alibi;
params.alibi_params = fmha::AlibiParams(h);
// Set flags
params.is_s_padded = is_s_padded;
params.use_int8_scale_max = use_int8_scale_max;
// Do we enable the trick to replace I2F with FP math in the 2nd GEMM?
if (data_type == DATA_TYPE_INT8)
{
params.enable_i2f_trick
= -double(1 << 22) * double(scale_bmm2) <= -128.f && double(1 << 22) * double(scale_bmm2) >= 127.f;
}
// Skip-softmax attention
params.skip_softmax_threshold_scale_factor = skip_softmax_threshold_scale_factor;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static inline void determine_launch_params(Launch_params& launch_params, Data_type data_type, int sm, const size_t s,
const size_t d, const Attention_mask_type attention_mask_type, const Attention_input_layout input_layout,
bool const interleaved, bool const ignore_b1opt, bool const force_unroll, bool const use_tma,
bool const force_non_flash_attention, bool const force_non_warp_specialization,
bool const force_non_granular_tiling, bool const force_fp32_acc, float const skip_softmax_threshold_scale_factor,
// device props
const cudaDeviceProp props)
{
// Set launch params to choose kernels
launch_params.ignore_b1opt = ignore_b1opt;
launch_params.force_unroll = force_unroll;
launch_params.force_fp32_acc = force_fp32_acc;
launch_params.interleaved = interleaved;
launch_params.attention_mask_type = attention_mask_type;
launch_params.attention_input_layout = input_layout;
// Set SM count and L2 cache size (used to determine launch blocks/grids to maximum performance)
launch_params.multi_processor_count = props.multiProcessorCount;
launch_params.device_l2_cache_size = props.l2CacheSize;
// threshold for adopting flash attention or warp_specialized kernels.
launch_params.flash_attention
= (data_type == DATA_TYPE_FP16 || data_type == DATA_TYPE_BF16 || data_type == DATA_TYPE_E4M3)
&& (s >= 16 && d >= 16) && !force_non_flash_attention;
// enable warp_speialized kernels when s >= 512 on hopper
// note that warp_speialized kernels need flash attention + tma
launch_params.warp_specialization
= (data_type == DATA_TYPE_FP16 || data_type == DATA_TYPE_BF16 || data_type == DATA_TYPE_E4M3) && sm == 90
&& launch_params.flash_attention && !force_non_warp_specialization;
// warp specialization kernels on hopper need tma
launch_params.use_tma = use_tma || launch_params.warp_specialization;
// use granular tiling on Ampere-style flash attention
launch_params.use_granular_tiling
= !force_non_granular_tiling && launch_params.flash_attention && !launch_params.warp_specialization && sm >= 80;
if (launch_params.use_granular_tiling && (data_type == DATA_TYPE_E4M3 && sm == 80))
{
printf(
"Fallback to non-granular-tiling kernels as tiled e4m3 kernels"
"are not supported on Ada currently.\n");
launch_params.use_granular_tiling = false;
}
// Enable skip softmax attention or not.
launch_params.enable_skip_softmax = skip_softmax_threshold_scale_factor > 0.f;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
// The device. Reset on destruction
CudaDevice device;
int sm = device.sm;
cudaDeviceProp props = device.props;
GpuTimer timer;
// The batch size.
size_t b = 128;
// The number of heads.
size_t h = 16;
// The dimension of the Q, K and V vectors.
size_t d = 64;
// The dimension of V if set to non-zero, otherwise dimension of V equals to that of Q
size_t dv = 0;
// The length of the sequence.
size_t s = 384;
// Number of grouped heads in the seqlen dimension.
size_t num_grouped_heads = 1;
// Sliding Window Attention
// Only pay attention to [max(0, query_idx - sliding_window_size), query_idx].
size_t sliding_window_size = size_t(INT_MAX);
// The chunked-attention size.
size_t chunked_attention_size = 0;
// The data type of the kernel.
Data_type data_type = DATA_TYPE_FP16;
// The type of the intermediate P matrix.
Data_type acc_type = DATA_TYPE_FP16;
// The type of the output.
Data_type output_dtype = DATA_TYPE_FP16;
// Is the output type set ?
bool is_output_dtype_set = false;
// The scaling factors.
float scale_bmm1 = 0.f, scale_softmax = 0.f, scale_bmm2 = 0.25f;
// The number of runs.
int runs = 1, warm_up_runs = 0;
// Do we use 1s for Q, K, V.
bool use_1s_q = false, use_1s_k = false, use_1s_v = false;
// The range of the different inputs.
int range_q = 5, range_k = 3, range_v = 5;
// The scale.
float scale_q = 0.f, scale_k = 0.f, scale_v = 0.f;
// The threshold for dropout. By default, drop 10%.
float dropout = 0.1f;
// Do we skip the checks.
bool skip_checks = false;
// The tolerance when checking results.
float epsilon = -1.f; // data_type == DATA_TYPE_FP16 ? 0.015f : 0.f;
// Use causal mask / padding_mask / sliding_or_chunked_causal mask / custom_mask input.
Attention_mask_type attention_mask_type = Attention_mask_type::PADDING;
// Use padded format for input QKV tensor & output O tensor.
// Instead of variable lengths [total, h, 3, d] where total = b1*s1 + b2*s2 + ... bn*sn,
// use padded length [b, max_s, h, 3, d] where max_s is the maximum expected seq len
bool is_s_padded = false;
// minimum sequence length for sampling variable seqlens
uint32_t min_s = -1;
// run interleaved kernels and transpose input and output accordingly
bool interleaved = false;
bool ignore_b1opt = false;
bool force_unroll = false;
// used by kernels that have different acc data types (like hmma, qmma)
bool force_fp32_acc = false;
bool force_non_flash_attention = false;
// enable warp specialization kernels on sm 90
bool force_non_warp_specialization = (sm != 90);
bool use_int8_scale_max = false;
bool verbose = true;
bool save_softmax = false;
// use granular tiling
// supported only by Ampere-based Flash Attention at this moment
bool force_non_granular_tiling = false;
// set all sequence lengths to min(s, min_s)
bool fix_s = false;
bool v1 = false;
// use TMA or not. ignored if not in SM90
bool use_tma = false;
// use alibi.
bool has_alibi = false;
// Use softcapping_scale_bmm1 (scale * __tanhf(x / scale)).
float softcapping_scale_bmm1 = 0.f;
// In multi-query or grouped-query attention (MQA/GQA), several Q heads are associated with one KV head
bool multi_query_attention = false;
size_t h_kv = 0;
// The attention input layout.
Attention_input_layout input_layout = Attention_input_layout::PACKED_QKV;
// TRTLLM uses 64 by default in paged kv cache.
size_t tokens_per_block = 64;
// Attention that has different q and kv lengths.
size_t s_q = 0;
// different q and kv sequence lengths.
bool different_q_kv_lengths = false;
// SageAttention block sizes
int sage_block_size_q = 0, sage_block_size_k = 0, sage_block_size_v = 0;
// Use attention sinks (added to the denominator of softmax)
bool use_attention_sinks = false;
// Skip-softmax attention
float skip_softmax_threshold_scale_factor = 0;
// Read the parameters from the command-line.
for (int ii = 1; ii < argc; ++ii)
{
if (!strcmp(argv[ii], "-1s"))
{
use_1s_k = use_1s_q = use_1s_v = true;
}
else if (!strcmp(argv[ii], "-1s-k"))
{
use_1s_k = true;
}
else if (!strcmp(argv[ii], "-1s-q"))
{
use_1s_q = true;
}
else if (!strcmp(argv[ii], "-1s-v"))
{
use_1s_v = true;
}
else if (!strcmp(argv[ii], "-b") && ++ii < argc)
{
b = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-d") && ++ii < argc)
{
d = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-dv") && ++ii < argc)
{
dv = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-s-q") && ++ii < argc)
{
s_q = strtol(argv[ii], nullptr, 10);
different_q_kv_lengths = true;
}
else if (!strcmp(argv[ii], "-dropout") && ++ii < argc)
{
dropout = (float) strtod(argv[ii], nullptr);
}
else if (!strcmp(argv[ii], "-epsilon") && ++ii < argc)
{
epsilon = (float) strtod(argv[ii], nullptr);
}
else if (!strcmp(argv[ii], "-h") && ++ii < argc)
{
h = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-int8"))
{
data_type = DATA_TYPE_INT8;
acc_type = DATA_TYPE_INT32;
}
else if (!strcmp(argv[ii], "-fp16"))
{
data_type = DATA_TYPE_FP16;
acc_type = DATA_TYPE_FP16;
}
else if (!strcmp(argv[ii], "-fp16-fp32"))
{
data_type = DATA_TYPE_FP16;
acc_type = DATA_TYPE_FP32;
force_fp32_acc = true;
}
else if (!strcmp(argv[ii], "-bf16"))
{
data_type = DATA_TYPE_BF16;
acc_type = DATA_TYPE_FP32;
force_fp32_acc = true;
}
else if (!strcmp(argv[ii], "-e4m3"))
{
data_type = DATA_TYPE_E4M3;
// Technically not the acc type.
acc_type = DATA_TYPE_FP32;
force_fp32_acc = true;
}
else if (!strcmp(argv[ii], "-e4m3-fp16"))
{ // Ada QMMA only
data_type = DATA_TYPE_E4M3;
// Technically not the acc type.
acc_type = DATA_TYPE_FP16;
}
else if (!strcmp(argv[ii], "-e4m3-fp32"))
{
data_type = DATA_TYPE_E4M3;
// Technically not the acc type.
acc_type = DATA_TYPE_FP32;
force_fp32_acc = true;
}
else if (!strcmp(argv[ii], "-fp16-output"))
{
output_dtype = DATA_TYPE_FP16;
is_output_dtype_set = true;
}
else if (!strcmp(argv[ii], "-bf16-output"))
{
output_dtype = DATA_TYPE_BF16;
is_output_dtype_set = true;
}
else if (!strcmp(argv[ii], "-num-grouped-heads") && ++ii < argc)
{
num_grouped_heads = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-range-k") && ++ii < argc)
{
range_k = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-range-q") && ++ii < argc)
{
range_q = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-range-v") && ++ii < argc)
{
range_v = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-runs") && ++ii < argc)
{
runs = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-s") && ++ii < argc)
{
s = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-sliding-window-size") && ++ii < argc)
{
sliding_window_size = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-chunked-attention-size") && ++ii < argc)
{
chunked_attention_size = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-scale-bmm1") && ++ii < argc)
{
scale_bmm1 = (float) strtod(argv[ii], nullptr);
}
else if (!strcmp(argv[ii], "-scale-bmm2") && ++ii < argc)
{
scale_bmm2 = (float) strtod(argv[ii], nullptr);
}
else if (!strcmp(argv[ii], "-scale-k") && ++ii < argc)
{
scale_k = (float) strtod(argv[ii], nullptr);
}
else if (!strcmp(argv[ii], "-scale-softmax") && ++ii < argc)
{
scale_softmax = (float) strtod(argv[ii], nullptr);
}
else if (!strcmp(argv[ii], "-scale-q") && ++ii < argc)
{
scale_q = (float) strtod(argv[ii], nullptr);
}
else if (!strcmp(argv[ii], "-scale-v") && ++ii < argc)
{
scale_v = (float) strtod(argv[ii], nullptr);
}
else if (!strcmp(argv[ii], "-skip-checks"))
{
skip_checks = true;
}
else if (!strcmp(argv[ii], "-warm-up-runs") && ++ii < argc)
{
warm_up_runs = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-min-s") && ++ii < argc)
{
min_s = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-il"))
{
interleaved = true;
}
else if (!strcmp(argv[ii], "-causal-mask"))
{
attention_mask_type = Attention_mask_type::CAUSAL;
}
else if (!strcmp(argv[ii], "-sliding-or-chunked-causal-mask"))
{
attention_mask_type = Attention_mask_type::SLIDING_OR_CHUNKED_CAUSAL;
}
else if (!strcmp(argv[ii], "-custom-mask"))
{
attention_mask_type = Attention_mask_type::CUSTOM_MASK;
}
else if (!strcmp(argv[ii], "-multi-query-attention") || !strcmp(argv[ii], "-mqa"))
{
h_kv = 1;
multi_query_attention = true; // subset of GQA
}
else if ((!strcmp(argv[ii], "-grouped-query-attention") || !strcmp(argv[ii], "-gqa")) && ++ii < argc)
{
h_kv = strtol(argv[ii], nullptr, 10);
multi_query_attention = true;
}
else if (!strcmp(argv[ii], "-contiguous-q-kv"))
{
input_layout = Attention_input_layout::CONTIGUOUS_Q_KV;
}
else if (!strcmp(argv[ii], "-paged-kv"))
{
input_layout = Attention_input_layout::Q_PAGED_KV;
}
else if (!strcmp(argv[ii], "-separate-q-k-v"))
{
input_layout = Attention_input_layout::SEPARATE_Q_K_V;
}
else if (!strcmp(argv[ii], "-tokens-per-block") && ++ii < argc)
{
tokens_per_block = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-pad-s"))
{
is_s_padded = true;
}
else if (!strcmp(argv[ii], "-ignore-b1opt"))
{
ignore_b1opt = true;
}
else if (!strcmp(argv[ii], "-force-unroll"))
{
force_unroll = true;
}
else if (!strcmp(argv[ii], "-force-non-flash-attention"))
{
force_non_flash_attention = true;
force_non_warp_specialization = true;
}
else if (!strcmp(argv[ii], "-force-flash-attention"))
{
fprintf(stderr,
"Deprecation warning: -force-flash-attention is no longer valid; use "
"-force-non-flash-attention instead, as Flash Attention is enabled by default.\n");
}
else if (!strcmp(argv[ii], "-force-non-warp-specialization"))
{
force_non_warp_specialization = true;
}
else if (!strcmp(argv[ii], "-force-non-granular-tiling") || !strcmp(argv[ii], "-force-non-tiled"))
{
force_non_granular_tiling = true;
}
else if (!strcmp(argv[ii], "-fix-s"))
{
fix_s = true;
}
else if (!strcmp(argv[ii], "-scale-max"))
{
use_int8_scale_max = true;
}
else if (!strcmp(argv[ii], "-v") && ++ii < argc)
{
int v = strtol(argv[ii], nullptr, 10);
verbose = v != 0;
}
else if (!strcmp(argv[ii], "-v1"))
{
v1 = true;
}
else if (!strcmp(argv[ii], "-use-tma"))
{
use_tma = true;
// flash attention + tma + non_warp_specialized kernels are not supported
// use non_flash_attention + tma + non_warp_specialized instead
if (force_non_warp_specialization)
{
force_non_flash_attention = true;
}
}
else if (!strcmp(argv[ii], "-alibi"))
{
has_alibi = true;
}
else if (!strcmp(argv[ii], "-softcapping-scale-bmm1") && ++ii < argc)
{
softcapping_scale_bmm1 = (float) strtod(argv[ii], nullptr);
}
else if (!strcmp(argv[ii], "-save-softmax"))
{
save_softmax = true;
}
else if (!strcmp(argv[ii], "-sage-block-q") && ++ii < argc)
{
sage_block_size_q = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-sage-block-k") && ++ii < argc)
{
sage_block_size_k = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-sage-block-v") && ++ii < argc)
{
sage_block_size_v = strtol(argv[ii], nullptr, 10);
}
else if (!strcmp(argv[ii], "-use-attention-sinks"))
{
use_attention_sinks = true;
}
else if (!strcmp(argv[ii], "-skip-softmax-threshold-scale-factor") && ++ii < argc)
{
skip_softmax_threshold_scale_factor = strtof(argv[ii], nullptr);
}
else
{
fprintf(stderr, "Unrecognized option: %s. Aborting!\n", argv[ii]);
return -1;
}
}
if (save_softmax == true)
{
bool is_MLA = (d == 192 && dv == 128);
if (((!is_MLA) && input_layout != Attention_input_layout::CONTIGUOUS_Q_KV)
|| (is_MLA && input_layout != Attention_input_layout::SEPARATE_Q_K_V))
{
fprintf(stderr,
"For normal attention, Only '--contiguous-q-kv' layout supports "
"'-save-softmax'. For MLA only '-separate-q-k-v' layout supports "
"'-save-softmax'.\n");
exit(1);
}
}
// Sanitize
if (min_s == -1)
min_s = s;
min_s = std::min<uint32_t>(s, min_s);
h_kv = multi_query_attention ? h_kv : h;
// Check if the options are valid.
if (different_q_kv_lengths)
{
assert(input_layout != Attention_input_layout::PACKED_QKV
&& "Packed QKV input layout is not supported with different q and kv lengths.");
assert(s >= s_q && "q seqlen has to be smaller than or equal to the kv seqlen !");
}
else
{
s_q = s;
}
// Sliding window attention (only pay attention to sliding-window-size long previous tokens).
if (sliding_window_size < s)
{
assert(
chunked_attention_size == 0 && "chunked_attention_size should not be used when sliding_window_size is set");
attention_mask_type = Attention_mask_type::SLIDING_OR_CHUNKED_CAUSAL;
}
// Chunked attention.
if (chunked_attention_size > 0)
{
assert((chunked_attention_size & (chunked_attention_size - 1)) == 0
&& "chunked_attention_size has to be a power of 2");
attention_mask_type = Attention_mask_type::SLIDING_OR_CHUNKED_CAUSAL;
}
// Set the norm.
if (scale_bmm1 == 0.f)
{
scale_bmm1 = 1.f / sqrtf((float) d);
}
// Set the output type if not set by user.
if (!is_output_dtype_set)
{
output_dtype = data_type;
}
// Force the softmax scale to 1.f for the FP16 kernel.
if (data_type == DATA_TYPE_FP16)
{
scale_softmax = 1.f;
}
else if (data_type == DATA_TYPE_INT8 && scale_softmax == 0.f)
{
scale_softmax = std::max(512.f, (float) s);
}
else if (data_type == DATA_TYPE_E4M3 && scale_softmax == 0.f)
{
scale_softmax = 1.f; // For E4M3 this is hardcoded as the largest power-of-2 below E4M3_MAX
}
// Sage Attention uses the e4m3 data type
if (sage_block_size_q > 0 || sage_block_size_k > 0 || sage_block_size_v > 0)
{
scale_softmax = 1.f;
scale_bmm2 = 1.f;
force_fp32_acc = true;
acc_type = DATA_TYPE_FP32;
}
// Define the scaling factor for the different inputs.
if (scale_q == 0.f)
{
scale_q = 1.f;
}
if (scale_k == 0.f)
{
scale_k = 1.f;
}
if (scale_v == 0.f)