-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathFSA_topk_sparse_attention.py
More file actions
2000 lines (1797 loc) · 62.6 KB
/
Copy pathFSA_topk_sparse_attention.py
File metadata and controls
2000 lines (1797 loc) · 62.6 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
# Copyright 2025 Ran Yan.
#
# 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
import math
from typing import Any, Optional
import torch
import triton
import triton.language as tl
from nsa_ref.ops.topk_sparse_attention import (backward_sum_o_do,
reorder_topk_idx)
from nsa_ref.ops.utils import get_num_warps_stages, is_hopper_gpu
IS_HOPPER_GPU = is_hopper_gpu()
@triton.jit
def fused_fill_kernel(ptr_tile, ptr_m_i_cur_tiles, N, BLOCK_SIZE: tl.constexpr):
pid = tl.program_id(0)
offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = offsets < N
tl.store(ptr_tile + offsets, -1, mask=mask) # fill int32 with -1
tl.store(ptr_m_i_cur_tiles + offsets, float("-inf"), mask=mask)
def fused_fill(topk_idx_permuted_tile: torch.Tensor, m_i_cur_tiles):
numel = topk_idx_permuted_tile.numel()
BLOCK_SIZE = 1024
# Flatten for pointer access
tile_flat = topk_idx_permuted_tile.view(-1)
m_i_cur_tiles_flat = m_i_cur_tiles.view(-1)
grid = lambda meta: (triton.cdiv(numel, meta['BLOCK_SIZE']),)
fused_fill_kernel[grid](
tile_flat,
m_i_cur_tiles_flat,
numel,
BLOCK_SIZE=BLOCK_SIZE,
num_warps=1,
num_stages=3,
)
@triton.jit
def block_to_token_kernel(
topk_idx_ptr,
result_ptr,
N_token,
K,
min_block_id,
max_block_id,
padding_value,
ts_h,
ts_b,
ts_n,
rs_h,
rs_b,
rs_n,
num_q_loops: tl.constexpr,
BLOCK_K: tl.constexpr,
):
pid = tl.program_id(0) # token index i
pid_h = 0
offs = tl.arange(0, BLOCK_K) # [0, 1, ..., K-1]
offs_q = tl.arange(0, num_q_loops)
pid_j = pid * num_q_loops + offs_q
topk_idx_offset = pid_h * ts_h + pid_j[None, :] * K + offs[:, None]
block_ids = tl.load(
topk_idx_ptr + topk_idx_offset, mask=(pid_j < N_token)[None, :] & (offs < K)[:, None], other=padding_value
)
result_ptrs = result_ptr + pid_h * rs_h + block_ids * N_token + pid_j[None, :]
mask = (block_ids >= 0) & (block_ids != padding_value) & (pid_j < N_token)[None, :]
tl.store(result_ptrs, pid_j[None, :], mask=mask)
def build_block_to_token_triton(
result: torch.Tensor, topk_idx: torch.Tensor, min_block_id: int, max_block_id: int, padding_value: int = -1
):
"""
Args:
topk_idx: [num_heads, N_token, TopK], block indices per token, padded with padding_value for invalid blocks
num_blocks: int
padding_value: int
Returns:
result: [num_blocks, N_token], token indices per block, padded by padding_value
"""
assert topk_idx.ndim == 3
assert padding_value == -1
num_heads, N_token, TopK = topk_idx.shape
# 每个 token,每个head 一个 program
num_q_loops = 4
grid = (triton.cdiv(N_token, num_q_loops),)
BLOCK_K = triton.next_power_of_2(TopK)
block_to_token_kernel[grid](
topk_idx,
result,
N_token,
TopK,
min_block_id,
max_block_id,
padding_value,
topk_idx.stride(0),
topk_idx.stride(1),
topk_idx.stride(2),
result.stride(0),
result.stride(1),
result.stride(2),
num_q_loops,
BLOCK_K=BLOCK_K,
num_warps=2,
num_stages=3,
)
return result
@triton.jit
def reduce_kernel(
lse_ptr, # float32 [H, N]
m_ij_ptr, # float32 [H, B, N]
l_ij_first_ptr, # float32 [H, 1, N]
l_ij_rest_ptr, # float32 [H, B, N]
m_ij_last_ptr, # float32 [H, N]
o_ptr, # o: n x h x d
o_tiles_first_ptr, # o_tiles: n x h x 1 x d
o_tiles_rest_ptr, # o_tiles: n x h x b x d
acc_o_scales_first_ptr, # acc_o_scales: n x h x 1
acc_o_scales_rest_ptr, # acc_o_scales: n x h x b
t_ptr, # topk_idx: h x n x k
token_index_mapping_ptr,
start_head_id,
num_qz_loop,
TOPK,
total_len,
# stride
stride_lse_h,
stride_lse_n,
stride_m_ij_h,
stride_m_ij_b,
stride_m_ij_n,
stride_l_ij_fh,
stride_l_ij_fb,
stride_l_ij_fn,
stride_l_ij_rh,
stride_l_ij_rb,
stride_l_ij_rn,
stride_on,
stride_oh,
stride_od,
stride_otfh,
stride_otfb,
stride_otfn,
stride_otfd,
stride_otrh,
stride_otrb,
stride_otrn,
stride_otrd,
stride_acc_fh,
stride_acc_fb,
stride_acc_fn,
stride_acc_rh,
stride_acc_rb,
stride_acc_rn,
stride_th,
stride_tn,
stride_tk,
stride_tim_h,
stride_tim_b,
stride_tim_n,
# META parameters
BLOCK_SIZE_T: tl.constexpr,
BLOCK_SIZE_D: tl.constexpr,
):
pid_qy = tl.program_id(0)
pid_q = tl.program_id(1) # token
pid_q_j = pid_q + pid_qy * num_qz_loop
if pid_q_j >= total_len:
return
t_ptr_j = t_ptr + pid_q_j * stride_tn
off_d = tl.arange(0, BLOCK_SIZE_D)
o_ptrs = o_ptr + pid_q_j * stride_on + off_d
last_acc_o = tl.load(o_ptrs, mask=off_d < BLOCK_SIZE_D, other=0.0)
acc_o = tl.zeros((BLOCK_SIZE_D,), dtype=tl.float32)
acc_o += last_acc_o
lse_ptrs = (lse_ptr + pid_q_j * stride_lse_n,)
# Load lse
lse = tl.load(lse_ptrs, mask=pid_q_j < total_len, other=float("-inf"))
# the stride is 1 for m_ij_last
m_ij_last = tl.load(m_ij_last_ptr + pid_q_j)
for block_id in range(TOPK):
t = tl.load(t_ptr_j + block_id * stride_tk, mask=block_id < TOPK, other=-1)
if t != -1:
if t == 0:
real_block_pos = 0
l_ij_ptr = l_ij_first_ptr
o_tiles_ptr = o_tiles_first_ptr
acc_o_scales_ptr = acc_o_scales_first_ptr
stride_l_ij_b = stride_l_ij_fb
stride_l_ij_n = stride_l_ij_fn
stride_acc_b = stride_acc_fb
stride_acc_n = stride_acc_fn
stride_otb = stride_otfb
stride_otn = stride_otfn
else:
real_block_pos = t - 1
l_ij_ptr = l_ij_rest_ptr
o_tiles_ptr = o_tiles_rest_ptr
acc_o_scales_ptr = acc_o_scales_rest_ptr
stride_l_ij_b = stride_l_ij_rb
stride_l_ij_n = stride_l_ij_rn
stride_acc_b = stride_acc_rb
stride_acc_n = stride_acc_rn
stride_otb = stride_otrb
stride_otn = stride_otrn
# init pointers
token_index_mapping_ptrs = (
token_index_mapping_ptr + t.to(tl.int64) * stride_tim_b + (pid_q_j) * stride_tim_n
)
real_token_index = tl.load(token_index_mapping_ptrs)
m_ij = tl.load(
m_ij_ptr + t * stride_m_ij_b + pid_q_j * stride_m_ij_n, mask=pid_q_j < total_len, other=float("-inf")
)
l_ij = tl.load(
l_ij_ptr + real_block_pos * stride_l_ij_b + real_token_index * stride_l_ij_n,
mask=real_token_index < total_len,
other=0.0,
)
delta = lse - m_ij
log_delta = tl.exp2(delta) + l_ij
# Update lse
lse = m_ij + tl.log2(log_delta)
o_tiles_ptrs = (
o_tiles_ptr + real_block_pos.to(tl.int64) * stride_otb + (real_token_index) * stride_otn + off_d
)
acc_o_scales_ptrs = acc_o_scales_ptr + real_block_pos * stride_acc_b + (real_token_index) * stride_acc_n
o_tiles = tl.load(o_tiles_ptrs)
acc_o_scales_tiles = tl.load(acc_o_scales_ptrs)
acc_o = o_tiles + acc_o * acc_o_scales_tiles
# final scale
acc_o = acc_o * tl.exp2(m_ij_last - lse)
tl.store(o_ptrs, acc_o, mask=off_d < BLOCK_SIZE_D)
# Store back
tl.store(
lse_ptrs,
lse,
mask=pid_q_j < total_len,
)
@triton.jit
def qk_kernel(
q_ptr, # Q: n x h x d
k_ptr, # K: n x h x d
m_i_tiles_ptr, # m_i: h x b x n
selected_tokens_ptr, # selected_tokens: sum(valid_lens),
valid_lens_ptr, # valid_lens: (h x b),
valid_start_indices_ptr, # valid_start_indices: (h x b),
num_heads,
num_blocks,
# seqlens
cu_seqlens_q,
cu_seqlens_k,
# shape
HEAD_DIM,
# sm_scale
sm_scale,
num_q_blocks,
num_b_blocks,
# stride
stride_qn,
stride_qh,
stride_qd,
stride_kn,
stride_kh,
stride_kd,
stride_m_i_tiles_h,
stride_m_i_tiles_b,
stride_m_i_tiles_n,
# META parameters
BLOCK_SIZE_Q: tl.constexpr, # q block size
BLOCK_SIZE_K: tl.constexpr, # k block size
BLOCK_SIZE_D: tl.constexpr,
):
qk_scale = sm_scale * 1.44269504
# get batch id and head id
pid_block_grid = tl.program_id(0) // num_heads # block id
head_id = tl.program_id(0) % num_heads
pid_q = tl.program_id(1) # token
# get q k start and len after rmpad
k_len = tl.load(cu_seqlens_k + 1)
k_ptrs = tl.make_block_ptr(
base=k_ptr + head_id * stride_kh,
shape=(HEAD_DIM, k_len),
strides=(stride_kd, stride_kn),
offsets=(0, 0),
block_shape=(BLOCK_SIZE_D, BLOCK_SIZE_K),
order=(0, 1),
)
for bb in range(num_b_blocks):
pid_block = bb + pid_block_grid * num_b_blocks
start_id = tl.load(valid_start_indices_ptr + head_id * num_blocks + pid_block)
valid_tokens = tl.load(valid_lens_ptr + head_id * num_blocks + pid_block)
if pid_q * BLOCK_SIZE_Q < valid_tokens:
c = pid_block * BLOCK_SIZE_K
# load k
k = tl.load(tl.advance(k_ptrs, (0, c)), boundary_check=(1, 0), padding_option="zero")
off_k = tl.arange(0, BLOCK_SIZE_K)
off_d = tl.arange(0, BLOCK_SIZE_D)
for j in range(num_q_blocks):
pid_q_j = pid_q * num_q_blocks + j
# Enable early return
if pid_q_j * BLOCK_SIZE_Q < valid_tokens:
# one thread block for one KV block, a subset of selected tokens
st_offs = start_id + (pid_q_j * BLOCK_SIZE_Q + tl.arange(0, BLOCK_SIZE_Q))
# st should be in shape [BLOCK_SIZE_Q]
st_mask = (pid_q_j * BLOCK_SIZE_Q + tl.arange(0, BLOCK_SIZE_Q)) < valid_tokens
st = tl.load(selected_tokens_ptr + st_offs, mask=st_mask, other=-1)
# otherwise, st selects a set of q tokens, selected_tokens_ptr should be sorted
q_ptrs_off = st[:, None] * stride_qn + off_d[None, :] * stride_qd
q_ptrs = q_ptr + head_id * stride_qh + q_ptrs_off
# load q
q_mask = (st != -1)[:, None] & (off_d < HEAD_DIM)[None, :]
q = tl.load(q_ptrs, mask=q_mask, other=0)
# compute qk
qk = tl.zeros((BLOCK_SIZE_Q, BLOCK_SIZE_K), dtype=tl.float32)
qk += tl.where((st[:, None] >= c + off_k[None, :]), 0, float("-inf"))
# [BLOCK_SIZE_Q, HEAD_DIM] @ [HEAD_DIM, BLOCK_SIZE_K] -> [BLOCK_SIZE_Q, BLOCK_SIZE_K]
qk += tl.dot(q, k) * qk_scale
m_i = tl.max(qk, axis=1)
m_i_tiles_ptrs = (
m_i_tiles_ptr
+ head_id * stride_m_i_tiles_h
+ pid_block * stride_m_i_tiles_b
+ st * stride_m_i_tiles_n
)
tl.store(m_i_tiles_ptrs, m_i, mask=(st != -1))
@triton.jit
def forward_kernel_opt(
q_ptr,
k_ptr,
v_ptr, # V: n x h x d
o_tiles_ptr, # O: n x h x b x d
acc_o_scales_ptr, # acc_o_scales: h x b x n
m_ij_tiles_ptr,
l_ij_ptr, # h x b x n
token_index_mapping_ptr,
selected_tokens_ptr, # selected_tokens: sum(valid_lens),
valid_lens_ptr, # valid_lens: (h x b),
valid_start_indices_ptr, # valid_start_indices: (h x b),
min_block_id,
cur_max_valid_tokens,
num_heads,
num_blocks,
# seqlens
cu_seqlens_q,
cu_seqlens_k,
# shape
HEAD_DIM,
# sm_scale
sm_scale,
num_q_blocks,
# stride
stride_qn,
stride_qh,
stride_qd,
stride_kn,
stride_kh,
stride_kd,
stride_vn,
stride_vh,
stride_vd,
stride_oth,
stride_otb,
stride_otn,
stride_otd,
stride_acc_oh,
stride_acc_ob,
stride_acc_on,
stride_m_ij_tiles_h,
stride_m_ij_tiles_b,
stride_m_ij_tiles_n,
stride_l_ij_h,
stride_l_ij_b,
stride_l_ij_n,
stride_tim_h,
stride_tim_b,
stride_tim_n,
# META parameters
BLOCK_SIZE_Q: tl.constexpr, # q block size
BLOCK_SIZE_K: tl.constexpr, # k block size
BLOCK_SIZE_D: tl.constexpr,
):
# get batch id and head id
pid_block = tl.program_id(0) // num_heads # block id
head_id = tl.program_id(0) % num_heads
pid_q = tl.program_id(1) # token
# seq packing is not supported yet
q_start = 0
k_start = 0
k_len = tl.load(cu_seqlens_k + 1) - k_start
start_id = tl.load(valid_start_indices_ptr + head_id * num_blocks + pid_block)
valid_tokens = tl.load(valid_lens_ptr + head_id * num_blocks + pid_block)
if num_q_blocks * pid_q * BLOCK_SIZE_Q >= valid_tokens:
return
c = (min_block_id + pid_block) * BLOCK_SIZE_K
k_ptrs = tl.make_block_ptr(
base=k_ptr + k_start * stride_kn + head_id * stride_kh,
shape=(HEAD_DIM, k_len),
strides=(stride_kd, stride_kn),
offsets=(0, 0),
block_shape=(BLOCK_SIZE_D, BLOCK_SIZE_K),
order=(0, 1),
)
# load k
k = tl.load(tl.advance(k_ptrs, (0, c)), boundary_check=(1, 0), padding_option="zero")
v_ptrs = tl.make_block_ptr(
base=v_ptr + k_start * stride_vn + head_id * stride_vh,
shape=(k_len, HEAD_DIM),
strides=(stride_vn, stride_vd),
offsets=(0, 0),
block_shape=(BLOCK_SIZE_K, BLOCK_SIZE_D),
order=(1, 0),
)
# load v
v = tl.load(tl.advance(v_ptrs, (c, 0)), boundary_check=(0, 1), padding_option="zero")
off_k = tl.arange(0, BLOCK_SIZE_K)
off_d = tl.arange(0, BLOCK_SIZE_D)
for j in range(num_q_blocks):
pid_q_j = pid_q * num_q_blocks + j
if pid_q_j * BLOCK_SIZE_Q < valid_tokens:
# one thread block for one KV block, a subset of selected tokens
st_offs = start_id + (q_start + pid_q_j * BLOCK_SIZE_Q + tl.arange(0, BLOCK_SIZE_Q))
# st should be in shape [BLOCK_SIZE_Q]
st_mask = (pid_q_j * BLOCK_SIZE_Q + tl.arange(0, BLOCK_SIZE_Q)) < valid_tokens
st = tl.load(selected_tokens_ptr + st_offs, mask=st_mask, other=-1)
# otherwise, st selects a set of q tokens, selected_tokens_ptr should be sorted
q_ptrs_off = st[:, None] * stride_qn + off_d[None, :] * stride_qd
# load m_i
mask = st != -1
m_ij_tiles_ptrs = (
m_ij_tiles_ptr
+ head_id * stride_m_ij_tiles_h
+ (q_start + st) * stride_m_ij_tiles_n
+ (pid_block + min_block_id) * stride_m_ij_tiles_b
)
m_ij = tl.load(m_ij_tiles_ptrs, mask=mask, other=float("-inf"))
m_ij_tiles_prev_ptrs = (
m_ij_tiles_ptr
+ head_id * stride_m_ij_tiles_h
+ (q_start + st) * stride_m_ij_tiles_n
+ (pid_block + min_block_id - 1) * stride_m_ij_tiles_b
)
m_ij_prev = tl.load(m_ij_tiles_prev_ptrs, mask=mask & (pid_block + min_block_id > 0), other=float("-inf"))
m_i_minus_m_ij = m_ij_prev - m_ij
q_ptrs = q_ptr + q_start * stride_qn + head_id * stride_qh + q_ptrs_off
# load q
q_mask = mask[:, None] & (off_d < HEAD_DIM)[None, :]
q = tl.load(q_ptrs, mask=q_mask, other=0)
# compute qk
qk = tl.zeros((BLOCK_SIZE_Q, BLOCK_SIZE_K), dtype=tl.float32)
qk += tl.where((st[:, None] >= c + off_k[None, :]), 0, float("-inf"))
# [BLOCK_SIZE_Q, HEAD_DIM] @ [HEAD_DIM, BLOCK_SIZE_K] -> [BLOCK_SIZE_Q, BLOCK_SIZE_K]
qk_scale = sm_scale * 1.44269504
qk += tl.dot(q, k) * qk_scale
# init statistics
acc_o_buffer = tl.full((BLOCK_SIZE_Q, BLOCK_SIZE_D), 0, dtype=tl.float32)
# load m_ij and compute l_ij
p = tl.exp2(qk - m_ij[:, None])
l_ij = tl.sum(p, axis=1)
# load token index mapping
token_index_mapping_ptrs = (
token_index_mapping_ptr + (st) * stride_tim_n + (pid_block + min_block_id) * stride_tim_b
)
token_index_mapping = tl.load(token_index_mapping_ptrs, mask=mask, other=-1)
l_ij_ptrs = (
l_ij_ptr
+ head_id * stride_l_ij_h
+ (q_start + token_index_mapping) * stride_l_ij_n
+ (pid_block) * stride_l_ij_b
)
tl.store(l_ij_ptrs, l_ij, mask=mask)
# scale acc_o
if pid_block + min_block_id == 0:
acc_o_scale = tl.full((BLOCK_SIZE_Q,), 1.0, dtype=tl.float32)
else:
acc_o_scale = tl.exp2(m_i_minus_m_ij)
tl.store(
acc_o_scales_ptr
+ head_id * stride_acc_oh
+ (pid_block) * stride_acc_ob
+ (q_start + token_index_mapping) * stride_acc_on,
acc_o_scale,
mask=(st != -1),
)
p = p.to(v.dtype)
acc_o_buffer = tl.dot(p, v)
o_ptrs_off = token_index_mapping[:, None] * stride_otn + off_d[None, :] * stride_otd
o_ptrs = o_tiles_ptr + head_id * stride_oth + o_ptrs_off + (pid_block).to(tl.int64) * stride_otb
tl.store(o_ptrs, acc_o_buffer.to(o_tiles_ptr.dtype.element_ty), mask=q_mask)
def _topk_sparse_attention_fwd_opt(
q: torch.Tensor, # [total_len, num_heads, head_dim]
k: torch.Tensor, # [total_len, num_heads, head_dim]
v: torch.Tensor, # [total_len, num_heads, head_dim]
topk_idx: torch.Tensor, # [num_heads, total_len, topk]
block_size: int,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
sm_scale: float,
causal=True,
):
"""
TODO: Currently sequence packing is explicitly done in for loop, will merge in kernels.
"""
o = torch.empty_like(q)
total_len, num_heads, _ = q.shape
lse = torch.empty((num_heads, total_len), dtype=torch.float32, device=q.device)
permute_results = []
for i in range(len(cu_seqlens_q) - 1):
cu_seqlens_q_ = cu_seqlens_q[i: i + 2] - cu_seqlens_q[i]
cu_seqlens_k_ = cu_seqlens_k[i: i + 2] - cu_seqlens_k[i]
max_seqlen_q_ = cu_seqlens_q_[1] - cu_seqlens_q_[0]
max_seqlen_k_ = cu_seqlens_k_[1] - cu_seqlens_k_[0]
q_ = q[cu_seqlens_q[i]: cu_seqlens_q[i + 1]]
k_ = k[cu_seqlens_k[i]: cu_seqlens_k[i + 1]]
v_ = v[cu_seqlens_k[i]: cu_seqlens_k[i + 1]]
topk_idx_ = topk_idx[:, cu_seqlens_q[i]: cu_seqlens_q[i + 1]]
o_seq, lse_seq, permute_results_seq = _topk_sparse_attention_fwd_opt_per_seq(
q_,
k_,
v_,
topk_idx_,
block_size,
cu_seqlens_q_,
cu_seqlens_k_,
max_seqlen_q_,
max_seqlen_k_,
sm_scale,
causal,
)
o[cu_seqlens_q[i]: cu_seqlens_q[i + 1]] = o_seq
lse[:, cu_seqlens_q[i]: cu_seqlens_q[i + 1]] = lse_seq
permute_results.append(permute_results_seq)
return o, lse, permute_results
@triton.jit
def index_mapping_kernel(
token_index_mapping_ptr,
selected_tokens_ptr,
valid_lens_ptr,
valid_start_indices_ptr,
stride_im_h,
stride_im_b,
stride_im_n,
BLOCK_SIZE_K: tl.constexpr,
):
pid_b = tl.program_id(0)
pid_n = tl.program_id(1)
offs_q = tl.arange(0, BLOCK_SIZE_K)
offs_n = pid_n * BLOCK_SIZE_K + offs_q
start_id = tl.load(valid_start_indices_ptr + pid_b)
valid_tokens = tl.load(valid_lens_ptr + pid_b)
st_offs = start_id + offs_n
# st should be in shape [BLOCK_SIZE_K]
st_mask = offs_n < valid_tokens
st = tl.load(selected_tokens_ptr + st_offs, mask=st_mask, other=-1)
token_im_ptrs = token_index_mapping_ptr + pid_b * stride_im_b + st * stride_im_n
tl.store(token_im_ptrs, offs_n, mask=st_mask)
def index_mapping(token_index_mapping, valid_topk_idx_permuted_tile, valid_lens, valid_start_indices, num_blocks):
max_tokens = valid_lens.max()
BLOCK_SIZE_K = 1024
grid = (num_blocks, triton.cdiv(max_tokens, BLOCK_SIZE_K))
index_mapping_kernel[grid](
token_index_mapping,
valid_topk_idx_permuted_tile,
valid_lens,
valid_start_indices,
token_index_mapping.stride(0),
token_index_mapping.stride(1),
token_index_mapping.stride(2),
BLOCK_SIZE_K,
num_warps=2,
num_stages=3,
)
def online_softmax(
q_tile,
k_tile,
m_i_cur_tiles,
valid_topk_idx_permuted_tile,
valid_lens,
valid_start_indices,
compute_min_block_id,
cur_max_valid_tokens,
block_size,
num_blocks,
head_tile,
head_dim,
sm_scale,
cu_seqlens_q,
cu_seqlens_k,
):
# launch kernel
BLOCK_SIZE_Q = 128
BLOCK_SIZE_K = triton.next_power_of_2(block_size)
BLOCK_SIZE_D = triton.next_power_of_2(head_dim)
num_q_blocks = 8
num_b_blocks = 1
grid_qk = lambda META: (
triton.cdiv(num_blocks, num_b_blocks),
triton.cdiv(cur_max_valid_tokens, BLOCK_SIZE_Q * num_q_blocks),
)
qk_kernel[grid_qk](
q_tile,
k_tile,
m_i_cur_tiles,
valid_topk_idx_permuted_tile,
valid_lens,
valid_start_indices,
head_tile,
num_blocks,
cu_seqlens_q,
cu_seqlens_k,
head_dim,
sm_scale,
num_q_blocks,
num_b_blocks,
q_tile.stride(0),
q_tile.stride(1),
q_tile.stride(2),
k_tile.stride(0),
k_tile.stride(1),
k_tile.stride(2),
m_i_cur_tiles.stride(0),
m_i_cur_tiles.stride(1),
m_i_cur_tiles.stride(2),
BLOCK_SIZE_Q=BLOCK_SIZE_Q,
BLOCK_SIZE_K=BLOCK_SIZE_K,
BLOCK_SIZE_D=BLOCK_SIZE_D,
num_warps=8,
num_stages=3,
)
m_ij_tiles = m_i_cur_tiles.cummax(dim=1).values
m_ij_last = m_ij_tiles[:, -1]
return m_ij_tiles, m_ij_last
def qkv_kernel(
q_tile,
k_tile,
v_tile,
o_tiles,
acc_o_scales,
m_ij_tiles,
l_ij,
token_index_mapping,
valid_topk_idx_permuted_tile,
valid_lens,
valid_start_indices,
compute_min_block_id,
cur_max_valid_tokens,
head_tile,
compute_tile_size,
cu_seqlens_q,
cu_seqlens_k,
head_dim,
sm_scale,
block_size,
):
BLOCK_SIZE_Q = 128
BLOCK_SIZE_K = triton.next_power_of_2(block_size)
BLOCK_SIZE_D = triton.next_power_of_2(head_dim)
# a heuristic that avoids large grid size, and redudant KV loading
num_q_blocks = 8
grid_fwd = lambda META: (
compute_tile_size * head_tile,
triton.cdiv(cur_max_valid_tokens, BLOCK_SIZE_Q * num_q_blocks),
)
forward_kernel_opt[grid_fwd](
q_tile,
k_tile,
v_tile,
o_tiles,
acc_o_scales,
m_ij_tiles,
l_ij,
token_index_mapping,
valid_topk_idx_permuted_tile,
valid_lens,
valid_start_indices,
compute_min_block_id,
cur_max_valid_tokens,
head_tile,
compute_tile_size,
cu_seqlens_q,
cu_seqlens_k,
head_dim,
sm_scale,
num_q_blocks,
q_tile.stride(0),
q_tile.stride(1),
q_tile.stride(2),
k_tile.stride(0),
k_tile.stride(1),
k_tile.stride(2),
v_tile.stride(0),
v_tile.stride(1),
v_tile.stride(2),
o_tiles.stride(0),
o_tiles.stride(1),
o_tiles.stride(2),
o_tiles.stride(3),
acc_o_scales.stride(0),
acc_o_scales.stride(1),
acc_o_scales.stride(2),
m_ij_tiles.stride(0),
m_ij_tiles.stride(1),
m_ij_tiles.stride(2),
l_ij.stride(0),
l_ij.stride(1),
l_ij.stride(2),
token_index_mapping.stride(0),
token_index_mapping.stride(1),
token_index_mapping.stride(2),
BLOCK_SIZE_Q=BLOCK_SIZE_Q,
BLOCK_SIZE_K=BLOCK_SIZE_K,
BLOCK_SIZE_D=BLOCK_SIZE_D,
num_stages=3,
num_warps=4,
)
def reduce_output(
lse,
o,
o_tiles_first,
o_tiles_rest,
m_ij_tiles,
l_ij_first,
l_ij_rest,
m_ij_last,
acc_o_scales_first,
acc_o_scales_rest,
topk_idx_tile,
token_index_mapping,
h,
head_tile,
total_len,
TOPK,
head_dim,
):
num_qy_loop = 4
num_qz_loop = total_len // num_qy_loop
grid_reduce = lambda META: (
num_qy_loop + (total_len % num_qy_loop != 0),
num_qz_loop,
)
reduce_kernel[grid_reduce](
lse,
m_ij_tiles,
l_ij_first,
l_ij_rest,
m_ij_last,
o,
o_tiles_first,
o_tiles_rest,
acc_o_scales_first,
acc_o_scales_rest,
topk_idx_tile,
token_index_mapping,
h * head_tile,
num_qz_loop,
TOPK,
total_len,
lse.stride(0),
lse.stride(1),
m_ij_tiles.stride(0),
m_ij_tiles.stride(1),
m_ij_tiles.stride(2),
l_ij_first.stride(0),
l_ij_first.stride(1),
l_ij_first.stride(2),
l_ij_rest.stride(0),
l_ij_rest.stride(1),
l_ij_rest.stride(2),
o.stride(0),
o.stride(1),
o.stride(2),
o_tiles_first.stride(0),
o_tiles_first.stride(1),
o_tiles_first.stride(2),
o_tiles_first.stride(3),
o_tiles_rest.stride(0),
o_tiles_rest.stride(1),
o_tiles_rest.stride(2),
o_tiles_rest.stride(3),
acc_o_scales_first.stride(0),
acc_o_scales_first.stride(1),
acc_o_scales_first.stride(2),
acc_o_scales_rest.stride(0),
acc_o_scales_rest.stride(1),
acc_o_scales_rest.stride(2),
topk_idx_tile.stride(0),
topk_idx_tile.stride(1),
topk_idx_tile.stride(2),
token_index_mapping.stride(0),
token_index_mapping.stride(1),
token_index_mapping.stride(2),
BLOCK_SIZE_T=triton.next_power_of_2(TOPK),
BLOCK_SIZE_D=triton.next_power_of_2(head_dim),
num_warps=1,
num_stages=2,
)
def _topk_sparse_attention_fwd_opt_per_seq(
q: torch.Tensor, # [total_len, num_heads, head_dim]
k: torch.Tensor, # [total_len, num_kv_heads, head_dim]
v: torch.Tensor, # [total_len, num_kv_heads, head_dim]
topk_idx: torch.Tensor, # [num_heads, total_len, topk]
block_size: int,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
sm_scale: float,
causal=True,
):
# dtype check
assert k.dtype == q.dtype and v.dtype == q.dtype
assert cu_seqlens_q.dtype == torch.int32 and cu_seqlens_k.dtype == torch.int32
assert block_size in {32, 64, 128, 256}
# shape
total_len, num_heads, head_dim = q.shape
total_len, num_kv_heads, head_dim = k.shape
assert num_heads % num_kv_heads == 0
gqa_deg = num_heads // num_kv_heads
TOPK = topk_idx.shape[-1]
real_num_blocks = math.ceil(total_len / block_size)
num_blocks = max(real_num_blocks, TOPK)
head_tile = 1
reduce_tile_size = num_blocks - 1
valid_lens_all = torch.zeros(
(
num_kv_heads,
num_blocks,
),
dtype=torch.int32,
device=q.device,
)
for h in range(num_kv_heads):
topk_idx_tile = topk_idx[h * head_tile: (h + 1) * head_tile]
topk_idx_nonneg = topk_idx_tile[topk_idx_tile >= 0]
valid_lens = torch.bincount(topk_idx_nonneg.view(-1), minlength=num_blocks)
valid_lens_all[h * head_tile: (h + 1) * head_tile] = valid_lens
global_max_valid_tokens = valid_lens_all[:, 1:].max() if num_blocks > 1 else valid_lens_all.max()
o_full = torch.zeros_like(q)
lse_full = torch.full((num_heads, total_len), float("-inf"), dtype=torch.float32, device=q.device)
# New introduced buffers
topk_idx_permuted_tile = torch.full((head_tile, num_blocks, total_len), -1, dtype=torch.int32, device=q.device)
token_index_mapping = torch.full((head_tile, num_blocks, total_len), 0, dtype=torch.int32, device=q.device)
# first KV block is computed seaprately
o_tiles_first = torch.zeros((head_tile, 1, total_len, head_dim), dtype=torch.bfloat16, device=q.device)
o_tiles_rest = torch.zeros(
(head_tile, reduce_tile_size, global_max_valid_tokens, head_dim), dtype=torch.bfloat16, device=q.device
)
# Statistics buffers
# m_i_tiles: 历史最大, m_diff_tiles: 历史最大和当前最大的差值
# m_i_cur_tiles: 当前最大, # m_ij_tiles: 考虑当前和历史后的最大
m_i_cur_tiles: torch.Tensor = torch.full(
(head_tile, num_blocks, total_len), float("-inf"), dtype=torch.float32, device=q.device
)
# first KV block is reduced separately
l_ij_first = torch.full((head_tile, 1, total_len), 0, dtype=torch.float32, device=q.device)
acc_o_scales_first = torch.full((head_tile, 1, total_len), 1, dtype=torch.float32, device=q.device)
l_ij_rest = torch.full(
(head_tile, reduce_tile_size, global_max_valid_tokens), 0, dtype=torch.float32, device=q.device
)
acc_o_scales_rest = torch.full(
(head_tile, reduce_tile_size, global_max_valid_tokens), 1, dtype=torch.float32, device=q.device
)
permute_results = {}
permute_results['global_max_valid_tokens'] = global_max_valid_tokens
permute_results['num_blocks'] = num_blocks
permute_results['real_num_blocks'] = real_num_blocks
permute_results['valid_topk_idx_permuted_tile'] = []
permute_results['valid_lens_all'] = valid_lens_all
permute_results['valid_lens'] = []
permute_results['valid_start_indices'] = []
for h in range(num_heads // head_tile):
q_tile = q[:, h * head_tile: (h + 1) * head_tile]