fla-core 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. fla/__init__.py +4 -0
  2. fla/modules/__init__.py +33 -0
  3. fla/modules/activations.py +548 -0
  4. fla/modules/convolution.py +1143 -0
  5. fla/modules/feature_map.py +300 -0
  6. fla/modules/fused_bitlinear.py +632 -0
  7. fla/modules/fused_cross_entropy.py +419 -0
  8. fla/modules/fused_kl_div.py +324 -0
  9. fla/modules/fused_linear_cross_entropy.py +620 -0
  10. fla/modules/fused_norm_gate.py +1253 -0
  11. fla/modules/grpo.py +411 -0
  12. fla/modules/l2norm.py +285 -0
  13. fla/modules/l2warp.py +38 -0
  14. fla/modules/layernorm.py +1433 -0
  15. fla/modules/layernorm_gated.py +528 -0
  16. fla/modules/mlp.py +132 -0
  17. fla/modules/parallel.py +42 -0
  18. fla/modules/rotary.py +500 -0
  19. fla/modules/token_shift.py +543 -0
  20. fla/ops/__init__.py +53 -0
  21. fla/ops/abc/__init__.py +7 -0
  22. fla/ops/abc/chunk.py +1117 -0
  23. fla/ops/abc/naive.py +96 -0
  24. fla/ops/attn/__init__.py +7 -0
  25. fla/ops/attn/decoding.py +182 -0
  26. fla/ops/attn/parallel.py +730 -0
  27. fla/ops/based/__init__.py +9 -0
  28. fla/ops/based/fused_chunk.py +373 -0
  29. fla/ops/based/naive.py +72 -0
  30. fla/ops/based/parallel.py +408 -0
  31. fla/ops/comba/__init__.py +7 -0
  32. fla/ops/comba/chunk.py +342 -0
  33. fla/ops/comba/fused_recurrent.py +332 -0
  34. fla/ops/comba/utils.py +172 -0
  35. fla/ops/comba/wy_fast.py +423 -0
  36. fla/ops/common/__init__.py +1 -0
  37. fla/ops/common/chunk_delta_h.py +527 -0
  38. fla/ops/common/chunk_h.py +384 -0
  39. fla/ops/common/chunk_h_parallel.py +551 -0
  40. fla/ops/common/chunk_h_split.py +596 -0
  41. fla/ops/common/chunk_o.py +681 -0
  42. fla/ops/common/chunk_scaled_dot_kkt.py +305 -0
  43. fla/ops/common/fused_chunk.py +629 -0
  44. fla/ops/common/fused_recurrent.py +567 -0
  45. fla/ops/delta_rule/__init__.py +11 -0
  46. fla/ops/delta_rule/chunk.py +311 -0
  47. fla/ops/delta_rule/fused_chunk.py +6 -0
  48. fla/ops/delta_rule/fused_recurrent.py +535 -0
  49. fla/ops/delta_rule/naive.py +120 -0
  50. fla/ops/delta_rule/parallel.py +403 -0
  51. fla/ops/delta_rule/wy_fast.py +294 -0
  52. fla/ops/forgetting_attn/__init__.py +7 -0
  53. fla/ops/forgetting_attn/parallel.py +64 -0
  54. fla/ops/gated_delta_product/__init__.py +5 -0
  55. fla/ops/gated_delta_product/chunk.py +305 -0
  56. fla/ops/gated_delta_product/chunk_deltaproduct_h.py +502 -0
  57. fla/ops/gated_delta_product/chunk_deltaproduct_o.py +154 -0
  58. fla/ops/gated_delta_product/chunk_ref.py +68 -0
  59. fla/ops/gated_delta_product/naive.py +36 -0
  60. fla/ops/gated_delta_rule/__init__.py +7 -0
  61. fla/ops/gated_delta_rule/chunk.py +340 -0
  62. fla/ops/gated_delta_rule/fused_recurrent.py +351 -0
  63. fla/ops/gated_delta_rule/wy_fast.py +296 -0
  64. fla/ops/generalized_delta_rule/__init__.py +9 -0
  65. fla/ops/generalized_delta_rule/dplr/__init__.py +7 -0
  66. fla/ops/generalized_delta_rule/dplr/chunk.py +362 -0
  67. fla/ops/generalized_delta_rule/dplr/chunk_A_bwd.py +367 -0
  68. fla/ops/generalized_delta_rule/dplr/chunk_A_fwd.py +198 -0
  69. fla/ops/generalized_delta_rule/dplr/chunk_h_bwd.py +175 -0
  70. fla/ops/generalized_delta_rule/dplr/chunk_h_fwd.py +175 -0
  71. fla/ops/generalized_delta_rule/dplr/chunk_o_bwd.py +430 -0
  72. fla/ops/generalized_delta_rule/dplr/chunk_o_fwd.py +125 -0
  73. fla/ops/generalized_delta_rule/dplr/fused_recurrent.py +268 -0
  74. fla/ops/generalized_delta_rule/dplr/naive.py +96 -0
  75. fla/ops/generalized_delta_rule/dplr/wy_fast_bwd.py +164 -0
  76. fla/ops/generalized_delta_rule/dplr/wy_fast_fwd.py +284 -0
  77. fla/ops/generalized_delta_rule/iplr/__init__.py +7 -0
  78. fla/ops/generalized_delta_rule/iplr/chunk.py +492 -0
  79. fla/ops/generalized_delta_rule/iplr/fused_recurrent.py +452 -0
  80. fla/ops/generalized_delta_rule/iplr/naive.py +69 -0
  81. fla/ops/generalized_delta_rule/iplr/wy_fast.py +300 -0
  82. fla/ops/gla/__init__.py +11 -0
  83. fla/ops/gla/chunk.py +1298 -0
  84. fla/ops/gla/fused_chunk.py +642 -0
  85. fla/ops/gla/fused_recurrent.py +111 -0
  86. fla/ops/gla/naive.py +41 -0
  87. fla/ops/gsa/__init__.py +9 -0
  88. fla/ops/gsa/chunk.py +1133 -0
  89. fla/ops/gsa/fused_recurrent.py +536 -0
  90. fla/ops/gsa/naive.py +69 -0
  91. fla/ops/hgrn/__init__.py +9 -0
  92. fla/ops/hgrn/chunk.py +282 -0
  93. fla/ops/hgrn/fused_recurrent.py +308 -0
  94. fla/ops/hgrn/naive.py +63 -0
  95. fla/ops/lightning_attn/__init__.py +9 -0
  96. fla/ops/lightning_attn/chunk.py +84 -0
  97. fla/ops/lightning_attn/fused_recurrent.py +84 -0
  98. fla/ops/linear_attn/__init__.py +11 -0
  99. fla/ops/linear_attn/chunk.py +76 -0
  100. fla/ops/linear_attn/fused_chunk.py +61 -0
  101. fla/ops/linear_attn/fused_recurrent.py +35 -0
  102. fla/ops/linear_attn/naive.py +64 -0
  103. fla/ops/linear_attn/utils.py +10 -0
  104. fla/ops/log_linear_attn/__init__.py +7 -0
  105. fla/ops/log_linear_attn/chunk.py +1904 -0
  106. fla/ops/log_linear_attn/naive.py +50 -0
  107. fla/ops/mesa_net/__init__.py +5 -0
  108. fla/ops/mesa_net/chunk.py +371 -0
  109. fla/ops/mesa_net/chunk_cg_solver_bwd.py +162 -0
  110. fla/ops/mesa_net/chunk_cg_solver_fwd.py +186 -0
  111. fla/ops/mesa_net/chunk_h_fwd.py +170 -0
  112. fla/ops/mesa_net/chunk_h_kk_intra_bwd.py +191 -0
  113. fla/ops/mesa_net/chunk_h_kv_intra_bwd.py +209 -0
  114. fla/ops/mesa_net/chunk_h_kv_intra_bwd_separate.py +300 -0
  115. fla/ops/mesa_net/decoding_one_step.py +175 -0
  116. fla/ops/mesa_net/naive.py +131 -0
  117. fla/ops/nsa/__init__.py +9 -0
  118. fla/ops/nsa/compression.py +536 -0
  119. fla/ops/nsa/naive.py +103 -0
  120. fla/ops/nsa/parallel.py +879 -0
  121. fla/ops/nsa/utils.py +92 -0
  122. fla/ops/path_attn/__init__.py +7 -0
  123. fla/ops/path_attn/cumprod_householder_bwd.py +140 -0
  124. fla/ops/path_attn/cumprod_householder_fwd.py +119 -0
  125. fla/ops/path_attn/intra_chunk_preprocess_bwd.py +140 -0
  126. fla/ops/path_attn/intra_chunk_preprocess_bwd_prepare.py +208 -0
  127. fla/ops/path_attn/intra_chunk_preprocess_fwd.py +168 -0
  128. fla/ops/path_attn/parallel.py +270 -0
  129. fla/ops/path_attn/parallel_path_bwd_inter_dkv.py +189 -0
  130. fla/ops/path_attn/parallel_path_bwd_inter_dqh.py +200 -0
  131. fla/ops/path_attn/parallel_path_bwd_intra.py +172 -0
  132. fla/ops/path_attn/parallel_path_fwd.py +195 -0
  133. fla/ops/path_attn/prepare_k_cache.py +74 -0
  134. fla/ops/path_attn/transform_q.py +108 -0
  135. fla/ops/rebased/__init__.py +7 -0
  136. fla/ops/rebased/naive.py +27 -0
  137. fla/ops/rebased/parallel.py +464 -0
  138. fla/ops/retention/__init__.py +13 -0
  139. fla/ops/retention/chunk.py +77 -0
  140. fla/ops/retention/fused_chunk.py +78 -0
  141. fla/ops/retention/fused_recurrent.py +33 -0
  142. fla/ops/retention/naive.py +15 -0
  143. fla/ops/retention/parallel.py +71 -0
  144. fla/ops/rwkv4/__init__.py +7 -0
  145. fla/ops/rwkv4/fused_recurrent.py +472 -0
  146. fla/ops/rwkv6/__init__.py +9 -0
  147. fla/ops/rwkv6/chunk.py +1300 -0
  148. fla/ops/rwkv6/chunk_naive.py +43 -0
  149. fla/ops/rwkv6/fused_recurrent.py +673 -0
  150. fla/ops/rwkv6/recurrent_naive.py +103 -0
  151. fla/ops/rwkv7/__init__.py +10 -0
  152. fla/ops/rwkv7/channel_mixing.py +323 -0
  153. fla/ops/rwkv7/chunk.py +78 -0
  154. fla/ops/rwkv7/fused_addcmul.py +293 -0
  155. fla/ops/rwkv7/fused_k_update.py +346 -0
  156. fla/ops/rwkv7/fused_recurrent.py +334 -0
  157. fla/ops/rwkv7/gate_output_correction.py +244 -0
  158. fla/ops/simple_gla/__init__.py +13 -0
  159. fla/ops/simple_gla/chunk.py +303 -0
  160. fla/ops/simple_gla/fused_chunk.py +108 -0
  161. fla/ops/simple_gla/fused_recurrent.py +112 -0
  162. fla/ops/simple_gla/naive.py +114 -0
  163. fla/ops/simple_gla/parallel.py +722 -0
  164. fla/ops/titans/__init__.py +7 -0
  165. fla/ops/titans/log_impl.py +153 -0
  166. fla/ops/titans/naive.py +375 -0
  167. fla/ops/ttt/__init__.py +9 -0
  168. fla/ops/ttt/chunk.py +1441 -0
  169. fla/ops/ttt/fused_chunk.py +831 -0
  170. fla/ops/ttt/naive.py +126 -0
  171. fla/ops/utils/__init__.py +58 -0
  172. fla/ops/utils/constant.py +6 -0
  173. fla/ops/utils/cumsum.py +465 -0
  174. fla/ops/utils/index.py +133 -0
  175. fla/ops/utils/logcumsumexp.py +52 -0
  176. fla/ops/utils/logsumexp.py +80 -0
  177. fla/ops/utils/matmul.py +245 -0
  178. fla/ops/utils/op.py +62 -0
  179. fla/ops/utils/pack.py +208 -0
  180. fla/ops/utils/pooling.py +207 -0
  181. fla/ops/utils/softmax.py +106 -0
  182. fla/ops/utils/solve_tril.py +381 -0
  183. fla/utils.py +462 -0
  184. fla_core-0.3.2.dist-info/METADATA +575 -0
  185. fla_core-0.3.2.dist-info/RECORD +188 -0
  186. fla_core-0.3.2.dist-info/WHEEL +5 -0
  187. fla_core-0.3.2.dist-info/licenses/LICENSE +21 -0
  188. fla_core-0.3.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,879 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ import warnings
5
+ from typing import Optional, Union
6
+
7
+ import torch
8
+ import triton
9
+ import triton.language as tl
10
+
11
+ from fla.ops.attn.parallel import parallel_attn_bwd_preprocess
12
+ from fla.ops.nsa.compression import parallel_nsa_compression
13
+ from fla.ops.nsa.utils import _bitonic_merge
14
+ from fla.ops.utils import prepare_chunk_indices, prepare_chunk_offsets, prepare_lens, prepare_token_indices
15
+ from fla.ops.utils.op import exp, log
16
+ from fla.ops.utils.pooling import mean_pooling
17
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, check_shared_mem, contiguous
18
+
19
+ try:
20
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
21
+ except ImportError:
22
+ warnings.warn(
23
+ "Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`",
24
+ category=ImportWarning
25
+ )
26
+ flash_attn_func = None
27
+
28
+
29
+ @triton.heuristics({
30
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
31
+ })
32
+ @triton.autotune(
33
+ configs=[
34
+ triton.Config({}, num_warps=num_warps)
35
+ for num_warps in [1, 2, 4]
36
+ ],
37
+ key=['BS', 'BK'],
38
+ )
39
+ @triton.jit
40
+ def parallel_nsa_kernel_topk(
41
+ q,
42
+ k,
43
+ lse,
44
+ scale,
45
+ block_indices,
46
+ cu_seqlens,
47
+ token_indices,
48
+ chunk_offsets,
49
+ T,
50
+ H: tl.constexpr,
51
+ HQ: tl.constexpr,
52
+ G: tl.constexpr,
53
+ K: tl.constexpr,
54
+ S: tl.constexpr,
55
+ BC: tl.constexpr,
56
+ BS: tl.constexpr,
57
+ BK: tl.constexpr,
58
+ IS_VARLEN: tl.constexpr,
59
+ ):
60
+ i_t, i_bh = tl.program_id(0), tl.program_id(1)
61
+ i_b, i_h = i_bh // H, i_bh % H
62
+
63
+ if IS_VARLEN:
64
+ i_n, i_t = tl.load(token_indices + i_t * 2).to(tl.int32), tl.load(token_indices + i_t * 2 + 1).to(tl.int32)
65
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
66
+ T = eos - bos
67
+ boc = tl.load(chunk_offsets + i_n).to(tl.int32)
68
+ else:
69
+ bos, eos = i_b * T, i_b * T + T
70
+ boc = i_b * tl.cdiv(T, BS)
71
+
72
+ p_q = tl.make_block_ptr(q + (bos + i_t) * HQ*K, (HQ, K), (K, 1), (i_h * G, 0), (G, BK), (1, 0))
73
+
74
+ # the Q block is kept in the shared memory throughout the whole kernel
75
+ # [G, BK]
76
+ b_q = tl.load(p_q, boundary_check=(0, 1))
77
+ b_q = (b_q * scale).to(b_q.dtype)
78
+
79
+ # the number of compression representations in total
80
+ TC = tl.cdiv(T, BS)
81
+ # the number of compression representations required to iterate over
82
+ # incomplete compression blocks are not included
83
+ NC = (i_t + 1) // BS
84
+ ################################
85
+ # 1. lse computation
86
+ ################################
87
+ if lse is not None:
88
+ b_lse = tl.load(lse + (bos + i_t) * HQ + i_h * G + tl.arange(0, G))
89
+ else:
90
+ # max scores for the current block
91
+ b_m = tl.full([G], float('-inf'), dtype=tl.float32)
92
+ # lse = log(acc) + m
93
+ b_acc = tl.zeros([G], dtype=tl.float32)
94
+ for i_c in range(0, NC, BC):
95
+ o_c = i_c + tl.arange(0, BC)
96
+
97
+ p_k = tl.make_block_ptr(k + (boc * H + i_h) * K, (K, TC), (1, H*K), (0, i_c), (BK, BC), (0, 1))
98
+ # [BK, BC]
99
+ b_k = tl.load(p_k, boundary_check=(0, 1))
100
+
101
+ # [G, BC]
102
+ b_s = tl.dot(b_q, b_k)
103
+ b_s = tl.where((o_c < NC)[None, :], b_s, float('-inf'))
104
+
105
+ # [G]
106
+ b_m, b_mp = tl.maximum(b_m, tl.max(b_s, 1)), b_m
107
+ b_r = exp(b_mp - b_m)
108
+ # [G, BC]
109
+ b_p = exp(b_s - b_m[:, None])
110
+ # [G]
111
+ b_acc = b_acc * b_r + tl.sum(b_p, 1)
112
+
113
+ b_mp = b_m
114
+ if NC == 0:
115
+ b_lse = tl.zeros([G], dtype=tl.float32)
116
+ else:
117
+ b_lse = b_m + log(b_acc)
118
+
119
+ ################################
120
+ # 2. topk selection
121
+ ################################
122
+ # [BC]
123
+ b_i = tl.full([BC], -1, dtype=tl.float32)
124
+ o_i = tl.zeros([BC], dtype=tl.int32)
125
+ m_i = tl.arange(0, BC) < BC//2
126
+
127
+ IC = i_t // BS
128
+ for i_c in range(0, tl.cdiv(i_t + 1, BS), BC):
129
+ o_c = i_c + tl.arange(0, BC)
130
+
131
+ p_k = tl.make_block_ptr(k + (boc * H + i_h) * K, (K, TC), (1, H*K), (0, i_c), (BK, BC), (0, 1))
132
+ # [BK, BC]
133
+ b_k = tl.load(p_k, boundary_check=(0, 1))
134
+ # [G, BC]
135
+ b_s = tl.dot(b_q, b_k)
136
+ b_s = tl.where(o_c < IC, b_s, float('-inf'))
137
+ # [G, BC]
138
+ # the 1st and the last 2 blocks are always selected
139
+ b_p = tl.where((o_c == 0) | ((o_c == IC - 1) | (o_c == IC)), 1., exp(b_s - b_lse[:, None]))
140
+ # the importance scores of the current block
141
+ # [BC]
142
+ b_i, b_ip = tl.sum(b_p, 0), b_i
143
+ # blocks with index < 0 will be skipped
144
+ o_i, o_ip = tl.where(o_c <= IC, o_c, -1), o_i
145
+
146
+ n_dims: tl.constexpr = tl.standard._log2(b_i.shape[0])
147
+ for i in tl.static_range(1, n_dims):
148
+ b_i, o_i = _bitonic_merge(b_i, o_i.to(tl.int32), i, 2, n_dims)
149
+
150
+ if i_c != 0:
151
+ b_i, o_i = _bitonic_merge(b_i, o_i.to(tl.int32), n_dims, False, n_dims)
152
+ b_i_new = b_ip * m_i + b_i * (1 - m_i)
153
+ o_i_new = o_ip * m_i + o_i * (1 - m_i)
154
+ b_i, o_i = _bitonic_merge(b_i_new, o_i_new.to(tl.int32), n_dims, True, n_dims)
155
+ else:
156
+ b_i, o_i = _bitonic_merge(b_i, o_i.to(tl.int32), n_dims, True, n_dims)
157
+
158
+ m_top = tl.arange(0, BC//S) == 0
159
+ b_top = tl.sum(m_top[:, None] * tl.reshape(o_i, [BC//S, S]), 0)
160
+
161
+ p_b = tl.make_block_ptr(block_indices + (bos + i_t) * H*S, (H*S,), (1,), (i_h * S,), (S,), (0,))
162
+ tl.store(p_b, b_top.to(p_b.dtype.element_ty))
163
+
164
+
165
+ @triton.heuristics({
166
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
167
+ 'USE_BLOCK_COUNTS': lambda args: isinstance(args['block_counts'], torch.Tensor),
168
+ })
169
+ @triton.autotune(
170
+ configs=[
171
+ triton.Config({}, num_warps=num_warps)
172
+ for num_warps in [1, 2, 4]
173
+ ],
174
+ key=['BS', 'BK', 'BV'],
175
+ )
176
+ @triton.jit
177
+ def parallel_nsa_fwd_kernel(
178
+ q,
179
+ k,
180
+ v,
181
+ o,
182
+ lse,
183
+ scale,
184
+ block_indices,
185
+ block_counts,
186
+ cu_seqlens,
187
+ token_indices,
188
+ T,
189
+ H: tl.constexpr,
190
+ HQ: tl.constexpr,
191
+ G: tl.constexpr,
192
+ K: tl.constexpr,
193
+ V: tl.constexpr,
194
+ S: tl.constexpr,
195
+ BS: tl.constexpr,
196
+ BK: tl.constexpr,
197
+ BV: tl.constexpr,
198
+ IS_VARLEN: tl.constexpr,
199
+ USE_BLOCK_COUNTS: tl.constexpr
200
+ ):
201
+ i_t, i_v, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
202
+ i_b, i_h = i_bh // H, i_bh % H
203
+
204
+ if IS_VARLEN:
205
+ i_n, i_t = tl.load(token_indices + i_t * 2).to(tl.int32), tl.load(token_indices + i_t * 2 + 1).to(tl.int32)
206
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
207
+ T = eos - bos
208
+ else:
209
+ bos, eos = i_b * T, i_b * T + T
210
+
211
+ k += (bos * H + i_h) * K
212
+ v += (bos * H + i_h) * V
213
+ block_indices += (bos + i_t) * H*S + i_h * S
214
+
215
+ if USE_BLOCK_COUNTS:
216
+ NS = tl.load(block_counts + (bos + i_t) * H + i_h)
217
+ else:
218
+ NS = S
219
+
220
+ p_q = tl.make_block_ptr(q + (bos + i_t) * HQ*K, (HQ, K), (K, 1), (i_h * G, 0), (G, BK), (1, 0))
221
+ # the Q block is kept in the shared memory throughout the whole kernel
222
+ # [G, BK]
223
+ b_q = tl.load(p_q, boundary_check=(0, 1))
224
+ b_q = (b_q * scale).to(b_q.dtype)
225
+
226
+ p_o = tl.make_block_ptr(o + (bos + i_t) * HQ*V, (HQ, V), (V, 1), (i_h * G, i_v * BV), (G, BV), (1, 0))
227
+ p_lse = lse + (bos + i_t) * HQ + i_h * G + tl.arange(0, G)
228
+ # [G, BV]
229
+ b_o = tl.zeros([G, BV], dtype=tl.float32)
230
+
231
+ b_m = tl.full([G], float('-inf'), dtype=tl.float32)
232
+ b_acc = tl.zeros([G], dtype=tl.float32)
233
+ for i in range(NS):
234
+ i_s = tl.load(block_indices + i).to(tl.int32) * BS
235
+ if i_s <= i_t and i_s >= 0:
236
+ p_k = tl.make_block_ptr(k, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
237
+ p_v = tl.make_block_ptr(v, (T, V), (H*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
238
+ # [BK, BS]
239
+ b_k = tl.load(p_k, boundary_check=(0, 1))
240
+ # [BS, BV]
241
+ b_v = tl.load(p_v, boundary_check=(0, 1))
242
+ # [G, BS]
243
+ b_s = tl.dot(b_q, b_k)
244
+ b_s = tl.where((i_t >= (i_s + tl.arange(0, BS)))[None, :], b_s, float('-inf'))
245
+
246
+ # [G]
247
+ b_m, b_mp = tl.maximum(b_m, tl.max(b_s, 1)), b_m
248
+ b_r = exp(b_mp - b_m)
249
+ # [G, BS]
250
+ b_p = exp(b_s - b_m[:, None])
251
+ # [G]
252
+ b_acc = b_acc * b_r + tl.sum(b_p, 1)
253
+ # [G, BV]
254
+ b_o = b_o * b_r[:, None] + tl.dot(b_p.to(b_q.dtype), b_v)
255
+
256
+ b_mp = b_m
257
+ b_o = b_o / b_acc[:, None]
258
+ b_m += log(b_acc)
259
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
260
+ tl.store(p_lse, b_m.to(p_lse.dtype.element_ty))
261
+
262
+
263
+ @triton.heuristics({
264
+ 'USE_BLOCK_COUNTS': lambda args: isinstance(args['block_counts'], torch.Tensor)
265
+ })
266
+ @triton.jit(do_not_specialize=['T'])
267
+ def parallel_nsa_kernel_mask(
268
+ block_indices,
269
+ block_counts,
270
+ block_mask,
271
+ T,
272
+ H: tl.constexpr,
273
+ S: tl.constexpr,
274
+ BS: tl.constexpr,
275
+ NS: tl.constexpr,
276
+ USE_BLOCK_COUNTS: tl.constexpr
277
+ ):
278
+ i_t, i_b, i_hs = tl.program_id(0), tl.program_id(1), tl.program_id(2)
279
+ i_h, i_s = i_hs // S, i_hs % S
280
+
281
+ b_i = tl.load(block_indices + i_b * T * H * S + i_t * H * S + i_h * S + i_s)
282
+ if USE_BLOCK_COUNTS:
283
+ b_m = b_i * BS <= i_t and i_s < tl.load(block_counts + i_b * T * H + i_t * H + i_h)
284
+ else:
285
+ b_m = b_i * BS <= i_t
286
+
287
+ if b_i < NS and b_i >= 0:
288
+ tl.store(block_mask + i_b * T * H * NS + i_t * H * NS + i_h * NS + b_i, b_m.to(block_mask.dtype.element_ty))
289
+
290
+
291
+ @triton.heuristics({
292
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
293
+ 'USE_BLOCK_COUNTS': lambda args: isinstance(args['block_counts'], torch.Tensor)
294
+ })
295
+ @triton.autotune(
296
+ configs=[
297
+ triton.Config({}, num_warps=num_warps)
298
+ for num_warps in [1, 2, 4]
299
+ ],
300
+ key=['BS', 'BK', 'BV'],
301
+ )
302
+ @triton.jit(do_not_specialize=['T'])
303
+ def parallel_nsa_bwd_kernel_dq(
304
+ q,
305
+ k,
306
+ v,
307
+ lse,
308
+ delta,
309
+ do,
310
+ dq,
311
+ scale,
312
+ block_indices,
313
+ block_counts,
314
+ cu_seqlens,
315
+ token_indices,
316
+ T,
317
+ B: tl.constexpr,
318
+ H: tl.constexpr,
319
+ HQ: tl.constexpr,
320
+ G: tl.constexpr,
321
+ K: tl.constexpr,
322
+ V: tl.constexpr,
323
+ S: tl.constexpr,
324
+ BS: tl.constexpr,
325
+ BK: tl.constexpr,
326
+ BV: tl.constexpr,
327
+ IS_VARLEN: tl.constexpr,
328
+ USE_BLOCK_COUNTS: tl.constexpr
329
+ ):
330
+ i_t, i_v, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
331
+ i_b, i_h = i_bh // H, i_bh % H
332
+
333
+ all = B * T
334
+ if IS_VARLEN:
335
+ i_n, i_t = tl.load(token_indices + i_t * 2).to(tl.int32), tl.load(token_indices + i_t * 2 + 1).to(tl.int32)
336
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
337
+ T = eos - bos
338
+ else:
339
+ bos, eos = i_b * T, i_b * T + T
340
+
341
+ q += (bos + i_t) * HQ*K
342
+ do += (bos + i_t) * HQ*V
343
+ lse += (bos + i_t) * HQ
344
+ delta += (bos + i_t) * HQ
345
+ dq += (i_v * all + bos + i_t) * HQ*K
346
+ block_indices += (bos + i_t) * H*S + i_h * S
347
+
348
+ if USE_BLOCK_COUNTS:
349
+ NS = tl.load(block_counts + (bos + i_t) * H + i_h)
350
+ else:
351
+ NS = S
352
+
353
+ k += (bos * H + i_h) * K
354
+ v += (bos * H + i_h) * V
355
+
356
+ p_q = tl.make_block_ptr(q, (HQ, K), (K, 1), (i_h * G, 0), (G, BK), (1, 0))
357
+ p_dq = tl.make_block_ptr(dq, (HQ, K), (K, 1), (i_h * G, 0), (G, BK), (1, 0))
358
+
359
+ # [G, BK]
360
+ b_q = tl.load(p_q, boundary_check=(0, 1))
361
+ b_q = (b_q * scale).to(b_q.dtype)
362
+
363
+ p_do = tl.make_block_ptr(do, (HQ, V), (V, 1), (i_h * G, i_v * BV), (G, BV), (1, 0))
364
+ p_lse = lse + i_h * G + tl.arange(0, G)
365
+ p_delta = delta + i_h * G + tl.arange(0, G)
366
+
367
+ # [G, BV]
368
+ b_do = tl.load(p_do, boundary_check=(0, 1))
369
+ # [G]
370
+ b_lse = tl.load(p_lse)
371
+ b_delta = tl.load(p_delta)
372
+
373
+ # [G, BK]
374
+ b_dq = tl.zeros([G, BK], dtype=tl.float32)
375
+ for i in range(NS):
376
+ i_s = tl.load(block_indices + i).to(tl.int32) * BS
377
+ if i_s <= i_t and i_s >= 0:
378
+ p_k = tl.make_block_ptr(k, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
379
+ p_v = tl.make_block_ptr(v, (V, T), (1, H*V), (i_v * BV, i_s), (BV, BS), (0, 1))
380
+ # [BK, BS]
381
+ b_k = tl.load(p_k, boundary_check=(0, 1))
382
+ # [BV, BS]
383
+ b_v = tl.load(p_v, boundary_check=(0, 1))
384
+
385
+ # [G, BS]
386
+ b_s = tl.dot(b_q, b_k)
387
+ b_p = exp(b_s - b_lse[:, None])
388
+ b_p = tl.where((i_t >= (i_s + tl.arange(0, BS)))[None, :], b_p, 0)
389
+
390
+ # [G, BV] @ [BV, BS] -> [G, BS]
391
+ b_dp = tl.dot(b_do, b_v)
392
+ b_ds = b_p * (b_dp.to(tl.float32) - b_delta[:, None])
393
+ # [G, BS] @ [BS, BK] -> [G, BK]
394
+ b_dq += tl.dot(b_ds.to(b_k.dtype), tl.trans(b_k))
395
+ b_dq *= scale
396
+
397
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
398
+
399
+
400
+ @triton.heuristics({
401
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
402
+ })
403
+ @triton.autotune(
404
+ configs=[
405
+ triton.Config({}, num_warps=num_warps)
406
+ for num_warps in [1, 2, 4]
407
+ ],
408
+ key=['BS', 'BK', 'BV'],
409
+ )
410
+ @triton.jit(do_not_specialize=['T'])
411
+ def parallel_nsa_bwd_kernel_dkv(
412
+ q,
413
+ k,
414
+ v,
415
+ lse,
416
+ delta,
417
+ do,
418
+ dk,
419
+ dv,
420
+ block_mask,
421
+ cu_seqlens,
422
+ chunk_indices,
423
+ scale,
424
+ T,
425
+ B: tl.constexpr,
426
+ H: tl.constexpr,
427
+ HQ: tl.constexpr,
428
+ G: tl.constexpr,
429
+ K: tl.constexpr,
430
+ V: tl.constexpr,
431
+ M: tl.constexpr,
432
+ BS: tl.constexpr,
433
+ BK: tl.constexpr,
434
+ BV: tl.constexpr,
435
+ IS_VARLEN: tl.constexpr
436
+ ):
437
+ i_v, i_s, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
438
+ i_b, i_h = i_bh // H, i_bh % H
439
+
440
+ all = B * T
441
+ if IS_VARLEN:
442
+ i_n, i_s = tl.load(chunk_indices + i_s * 2).to(tl.int32), tl.load(chunk_indices + i_s * 2 + 1).to(tl.int32)
443
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
444
+ T = eos - bos
445
+ else:
446
+ bos, eos = i_b * T, i_b * T + T
447
+
448
+ p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_s * BS, 0), (BS, BK), (1, 0))
449
+ p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_s * BS, i_v * BV), (BS, BV), (1, 0))
450
+ p_dk = tl.make_block_ptr(dk + (i_v * all * H + bos * H + i_h) * K, (T, K), (H*K, 1), (i_s * BS, 0), (BS, BK), (1, 0))
451
+ p_dv = tl.make_block_ptr(dv + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_s * BS, i_v * BV), (BS, BV), (1, 0))
452
+
453
+ # [BS, BK]
454
+ b_k = tl.load(p_k, boundary_check=(0, 1))
455
+ b_dk = tl.zeros([BS, BK], dtype=tl.float32)
456
+ # [BS, BV]
457
+ b_v = tl.load(p_v, boundary_check=(0, 1))
458
+ b_dv = tl.zeros([BS, BV], dtype=tl.float32)
459
+
460
+ for i in range(i_s * BS, T):
461
+ b_m = tl.load(block_mask + (bos + i) * H*M + i_h * M + i_s)
462
+ if b_m:
463
+ p_q = tl.make_block_ptr(q + (bos + i) * HQ*K, (HQ, K), (K, 1), (i_h * G, 0), (G, BK), (1, 0))
464
+ # [G, BK]
465
+ b_q = tl.load(p_q, boundary_check=(0, 1))
466
+ b_q = (b_q * scale).to(b_q.dtype)
467
+
468
+ p_do = tl.make_block_ptr(do + (bos + i) * HQ*V, (HQ, V), (V, 1), (i_h * G, i_v * BV), (G, BV), (1, 0))
469
+ p_lse = lse + (bos + i) * HQ + i_h * G + tl.arange(0, G)
470
+ p_delta = delta + (bos + i) * HQ + i_h * G + tl.arange(0, G)
471
+ # [G, BV]
472
+ b_do = tl.load(p_do, boundary_check=(0, 1))
473
+ # [G]
474
+ b_lse = tl.load(p_lse)
475
+ b_delta = tl.load(p_delta)
476
+ # [BS, G]
477
+ b_s = tl.dot(b_k, tl.trans(b_q))
478
+ b_p = exp(b_s - b_lse[None, :])
479
+ b_p = tl.where((i >= (i_s * BS + tl.arange(0, BS)))[:, None], b_p, 0)
480
+ # [BS, G] @ [G, BV] -> [BS, BV]
481
+ b_dv += tl.dot(b_p.to(b_do.dtype), b_do)
482
+ # [BS, BV] @ [BV, G] -> [BS, G]
483
+ b_dp = tl.dot(b_v, tl.trans(b_do))
484
+ # [BS, G]
485
+ b_ds = b_p * (b_dp - b_delta[None, :])
486
+ # [BS, G] @ [G, BK] -> [BS, BK]
487
+ b_dk += tl.dot(b_ds.to(b_q.dtype), b_q)
488
+
489
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
490
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
491
+
492
+
493
+ def parallel_nsa_topk(
494
+ q: torch.Tensor,
495
+ k: torch.Tensor,
496
+ lse: torch.Tensor,
497
+ block_counts: Union[torch.LongTensor, int],
498
+ block_size: int = 64,
499
+ scale: float = None,
500
+ cu_seqlens: Optional[torch.LongTensor] = None,
501
+ ) -> torch.LongTensor:
502
+ B, T, HQ, K = q.shape
503
+ H = k.shape[2]
504
+ G = HQ // H
505
+ # the number of selected blocks for each token
506
+ S = block_counts if isinstance(block_counts, int) else block_counts.max().item()
507
+ S = triton.next_power_of_2(S)
508
+ # here we set BC = BS, but beware that they can be chosen separately if required
509
+ BC = BS = block_size
510
+ BK = max(triton.next_power_of_2(K), 16)
511
+ assert BC >= 2 * S, f"BC ({BC}) must be greater than or equal to 2 * S ({S})"
512
+
513
+ block_indices = torch.zeros(B, T, H, S, dtype=torch.int32, device=q.device)
514
+ token_indices = prepare_token_indices(cu_seqlens) if cu_seqlens is not None else None
515
+ chunk_offsets = prepare_chunk_offsets(cu_seqlens, BS) if cu_seqlens is not None else None
516
+ grid = (T, B * H)
517
+ # the 1st and the last 2 blocks are always selected
518
+ parallel_nsa_kernel_topk[grid](
519
+ q=q,
520
+ k=k,
521
+ lse=lse,
522
+ scale=scale,
523
+ block_indices=block_indices,
524
+ cu_seqlens=cu_seqlens,
525
+ token_indices=token_indices,
526
+ chunk_offsets=chunk_offsets,
527
+ T=T,
528
+ H=H,
529
+ HQ=HQ,
530
+ G=G,
531
+ K=K,
532
+ S=S,
533
+ BC=BC,
534
+ BS=BS,
535
+ BK=BK
536
+ )
537
+ return block_indices
538
+
539
+
540
+ def parallel_nsa_fwd(
541
+ q: torch.Tensor,
542
+ k: torch.Tensor,
543
+ v: torch.Tensor,
544
+ block_indices: torch.LongTensor,
545
+ block_counts: Union[torch.LongTensor, int],
546
+ block_size: int,
547
+ scale: float,
548
+ cu_seqlens: Optional[torch.LongTensor] = None,
549
+ token_indices: Optional[torch.LongTensor] = None,
550
+ ):
551
+ B, T, H, K, V, S = *k.shape, v.shape[-1], block_indices.shape[-1]
552
+ HQ = q.shape[2]
553
+ G = HQ // H
554
+ BS = block_size
555
+ if check_shared_mem('hopper', q.device.index):
556
+ BK = min(256, triton.next_power_of_2(K))
557
+ BV = min(256, triton.next_power_of_2(V))
558
+ else:
559
+ BK = min(128, triton.next_power_of_2(K))
560
+ BV = min(128, triton.next_power_of_2(V))
561
+ NK = triton.cdiv(K, BK)
562
+ NV = triton.cdiv(V, BV)
563
+ assert NK == 1, "The key dimension can not be larger than 256"
564
+
565
+ grid = (T, NV, B * H)
566
+ o = torch.empty(B, T, HQ, V, dtype=v.dtype, device=q.device)
567
+ lse = torch.empty(B, T, HQ, dtype=torch.float, device=q.device)
568
+
569
+ parallel_nsa_fwd_kernel[grid](
570
+ q=q,
571
+ k=k,
572
+ v=v,
573
+ o=o,
574
+ lse=lse,
575
+ scale=scale,
576
+ block_indices=block_indices,
577
+ block_counts=block_counts,
578
+ cu_seqlens=cu_seqlens,
579
+ token_indices=token_indices,
580
+ T=T,
581
+ H=H,
582
+ HQ=HQ,
583
+ G=G,
584
+ K=K,
585
+ V=V,
586
+ S=S,
587
+ BS=BS,
588
+ BK=BK,
589
+ BV=BV,
590
+ )
591
+ return o, lse
592
+
593
+
594
+ def parallel_nsa_block_mask(
595
+ block_indices: torch.LongTensor,
596
+ block_counts: Union[torch.LongTensor, int],
597
+ cu_seqlens: torch.LongTensor,
598
+ block_size: int,
599
+ ):
600
+ B, T, H, S = block_indices.shape
601
+ BS = block_size
602
+ if cu_seqlens is not None:
603
+ NS = triton.cdiv(prepare_lens(cu_seqlens).max().item(), BS)
604
+ else:
605
+ NS = triton.cdiv(T, BS)
606
+ block_mask = torch.zeros(B, T, H, NS, dtype=torch.bool, device=block_indices.device)
607
+
608
+ parallel_nsa_kernel_mask[(T, B, H*S)](
609
+ block_indices=block_indices,
610
+ block_counts=block_counts,
611
+ block_mask=block_mask,
612
+ T=T,
613
+ H=H,
614
+ S=S,
615
+ BS=BS,
616
+ NS=NS
617
+ )
618
+ return block_mask
619
+
620
+
621
+ def parallel_nsa_bwd(
622
+ q: torch.Tensor,
623
+ k: torch.Tensor,
624
+ v: torch.Tensor,
625
+ o: torch.Tensor,
626
+ lse: torch.Tensor,
627
+ do: torch.Tensor,
628
+ block_indices: torch.Tensor,
629
+ block_counts: Union[torch.LongTensor, int],
630
+ block_size: int = 64,
631
+ scale: float = None,
632
+ cu_seqlens: Optional[torch.LongTensor] = None,
633
+ token_indices: Optional[torch.LongTensor] = None,
634
+ ):
635
+ B, T, H, K, V, S = *k.shape, v.shape[-1], block_indices.shape[-1]
636
+ HQ = q.shape[2]
637
+ G = HQ // H
638
+ BS = block_size
639
+ BK = max(triton.next_power_of_2(K), 16)
640
+ BV = min(128, max(triton.next_power_of_2(v.shape[-1]), 16))
641
+ NV = triton.cdiv(V, BV)
642
+
643
+ delta = parallel_attn_bwd_preprocess(o, do)
644
+
645
+ dq = torch.empty(NV, *q.shape, dtype=q.dtype if NV == 1 else torch.float, device=q.device)
646
+ grid = (T, NV, B * H)
647
+ parallel_nsa_bwd_kernel_dq[grid](
648
+ q=q,
649
+ k=k,
650
+ v=v,
651
+ lse=lse,
652
+ delta=delta,
653
+ do=do,
654
+ dq=dq,
655
+ block_indices=block_indices,
656
+ block_counts=block_counts,
657
+ cu_seqlens=cu_seqlens,
658
+ token_indices=token_indices,
659
+ scale=scale,
660
+ T=T,
661
+ B=B,
662
+ H=H,
663
+ HQ=HQ,
664
+ G=G,
665
+ K=K,
666
+ V=V,
667
+ S=S,
668
+ BS=BS,
669
+ BK=BK,
670
+ BV=BV
671
+ )
672
+ dq = dq.sum(0)
673
+
674
+ if cu_seqlens is not None:
675
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BS)
676
+ NS = len(chunk_indices)
677
+ else:
678
+ chunk_indices = None
679
+ NS = triton.cdiv(T, BS)
680
+
681
+ # [B, T, H, M]
682
+ block_mask = parallel_nsa_block_mask(block_indices, block_counts, cu_seqlens, block_size)
683
+ dk = torch.empty(NV, *k.shape, dtype=k.dtype if NV == 1 else torch.float, device=q.device)
684
+ dv = torch.empty(v.shape, dtype=v.dtype, device=q.device)
685
+
686
+ grid = (NV, NS, B * H)
687
+ parallel_nsa_bwd_kernel_dkv[grid](
688
+ q=q,
689
+ k=k,
690
+ v=v,
691
+ lse=lse,
692
+ delta=delta,
693
+ do=do,
694
+ dk=dk,
695
+ dv=dv,
696
+ block_mask=block_mask,
697
+ cu_seqlens=cu_seqlens,
698
+ chunk_indices=chunk_indices,
699
+ scale=scale,
700
+ T=T,
701
+ B=B,
702
+ H=H,
703
+ HQ=HQ,
704
+ G=G,
705
+ K=K,
706
+ V=V,
707
+ M=block_mask.shape[-1],
708
+ BS=BS,
709
+ BK=BK,
710
+ BV=BV
711
+ )
712
+ dk = dk.sum(0)
713
+ return dq, dk, dv
714
+
715
+
716
+ @torch.compile
717
+ class ParallelNSAFunction(torch.autograd.Function):
718
+
719
+ @staticmethod
720
+ @contiguous
721
+ @autocast_custom_fwd
722
+ def forward(ctx, q, k, v, block_indices, block_counts, block_size, scale, cu_seqlens):
723
+ ctx.dtype = q.dtype
724
+
725
+ # 2-d sequence indices denoting the cu_seqlens of tokens in each sequence
726
+ # for example, if the passed `cu_seqlens` is [0, 2, 6],
727
+ # then there are 2 and 4 tokens in the 1st and 2nd sequences respectively, and `token_indices` will be
728
+ # [[0, 0], [0, 1], [1, 0], [1, 1], [1, 2], [1, 3]]
729
+ token_indices = prepare_token_indices(cu_seqlens) if cu_seqlens is not None else None
730
+
731
+ o, lse = parallel_nsa_fwd(
732
+ q=q,
733
+ k=k,
734
+ v=v,
735
+ block_indices=block_indices,
736
+ block_counts=block_counts,
737
+ block_size=block_size,
738
+ scale=scale,
739
+ cu_seqlens=cu_seqlens,
740
+ token_indices=token_indices
741
+ )
742
+ ctx.save_for_backward(q, k, v, o, lse)
743
+ ctx.block_indices = block_indices
744
+ ctx.block_counts = block_counts
745
+ ctx.cu_seqlens = cu_seqlens
746
+ ctx.token_indices = token_indices
747
+ ctx.block_size = block_size
748
+ ctx.scale = scale
749
+ return o.to(q.dtype)
750
+
751
+ @staticmethod
752
+ @contiguous
753
+ @autocast_custom_bwd
754
+ def backward(ctx, do):
755
+ q, k, v, o, lse = ctx.saved_tensors
756
+ dq, dk, dv = parallel_nsa_bwd(
757
+ q=q,
758
+ k=k,
759
+ v=v,
760
+ o=o,
761
+ lse=lse,
762
+ do=do,
763
+ block_indices=ctx.block_indices,
764
+ block_counts=ctx.block_counts,
765
+ block_size=ctx.block_size,
766
+ scale=ctx.scale,
767
+ cu_seqlens=ctx.cu_seqlens,
768
+ token_indices=ctx.token_indices
769
+ )
770
+ return dq.to(q), dk.to(k), dv.to(v), None, None, None, None, None, None, None, None
771
+
772
+
773
+ def parallel_nsa(
774
+ q: torch.Tensor,
775
+ k: torch.Tensor,
776
+ v: torch.Tensor,
777
+ g_cmp: Optional[torch.Tensor] = None,
778
+ g_slc: Optional[torch.Tensor] = None,
779
+ g_swa: Optional[torch.Tensor] = None,
780
+ block_indices: Optional[torch.LongTensor] = None,
781
+ block_counts: Union[torch.LongTensor, int] = 16,
782
+ block_size: int = 64,
783
+ window_size: int = 0,
784
+ scale: Optional[float] = None,
785
+ cu_seqlens: Optional[torch.LongTensor] = None,
786
+ ) -> torch.Tensor:
787
+ r"""
788
+ Args:
789
+ q (torch.Tensor):
790
+ queries of shape `[B, T, HQ, K]`.
791
+ k (torch.Tensor):
792
+ keys of shape `[B, T, H, K]`.
793
+ GQA is enforced here. The ratio of query heads (HQ) to key/value heads (H) must be a power of 2 and >=16.
794
+ v (torch.Tensor):
795
+ values of shape `[B, T, H, V]`.
796
+ g_cmp (torch.Tensor):
797
+ Gate score for compressed attention of shape `[B, T, HQ]`.
798
+ g_slc (torch.Tensor):
799
+ Gate score for selected attention of shape `[B, T, HQ]`.
800
+ g_swa (torch.Tensor):
801
+ Gate score for sliding attentionof shape `[B, T, HQ]`.
802
+ block_indices (torch.LongTensor):
803
+ Block indices of shape `[B, T, H, S]`.
804
+ `S` is the number of selected blocks for each query token, which is set to 16 in the paper.
805
+ If `g_cmp` is provided, the passed `block_indices` will be ignored.
806
+ block_counts (Optional[Union[torch.LongTensor, int]]):
807
+ Number of selected blocks for each query.
808
+ If a tensor is provided, with shape `[B, T, H]`,
809
+ each query can select the same number of blocks.
810
+ If not provided, it will default to 16.
811
+ block_size (int):
812
+ Selected block size. Default: 64.
813
+ window_size (int):
814
+ Sliding window size. Default: 0.
815
+ scale (Optional[float]):
816
+ Scale factor for attention scores.
817
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
818
+ cu_seqlens (torch.LongTensor):
819
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
820
+ consistent with the FlashAttention API.
821
+
822
+ Returns:
823
+ o (torch.Tensor):
824
+ Outputs of shape `[B, T, HQ, V]`.
825
+ """
826
+ assert block_counts is not None, "block counts must be provided for selection"
827
+ if scale is None:
828
+ scale = k.shape[-1] ** -0.5
829
+ if cu_seqlens is not None:
830
+ assert q.shape[0] == 1, "batch size must be 1 when cu_seqlens are provided"
831
+ assert q.shape[2] % (k.shape[2] * 16) == 0, "Group size must be a multiple of 16 in NSA"
832
+
833
+ k_cmp, v_cmp = mean_pooling(k, block_size, cu_seqlens), mean_pooling(v, block_size, cu_seqlens)
834
+ o_cmp, lse_cmp = None, None
835
+ if g_cmp is not None:
836
+ o_cmp, lse_cmp = parallel_nsa_compression(
837
+ q=q,
838
+ k=k_cmp,
839
+ v=v_cmp,
840
+ block_size=block_size,
841
+ scale=scale,
842
+ cu_seqlens=cu_seqlens
843
+ )
844
+ if block_indices is not None:
845
+ warnings.warn("`block_indices` will be ignored when `g_cmp` is provided")
846
+ block_indices = parallel_nsa_topk(
847
+ q=q,
848
+ k=k_cmp,
849
+ lse=lse_cmp,
850
+ block_counts=block_counts,
851
+ block_size=block_size,
852
+ scale=scale,
853
+ cu_seqlens=cu_seqlens
854
+ )
855
+ o = o_slc = ParallelNSAFunction.apply(q, k, v, block_indices, block_counts, block_size, scale, cu_seqlens)
856
+ if g_slc is not None:
857
+ o = o_slc * g_slc.unsqueeze(-1)
858
+ if o_cmp is not None:
859
+ o = torch.addcmul(o, o_cmp, g_cmp.unsqueeze(-1))
860
+ if window_size > 0:
861
+ if cu_seqlens is not None:
862
+ max_seqlen = q.shape[1]
863
+ o_swa = flash_attn_varlen_func(
864
+ q.squeeze(0), k.squeeze(0), v.squeeze(0),
865
+ cu_seqlens_q=cu_seqlens,
866
+ cu_seqlens_k=cu_seqlens,
867
+ max_seqlen_q=max_seqlen,
868
+ max_seqlen_k=max_seqlen,
869
+ causal=True,
870
+ window_size=(window_size-1, 0)
871
+ ).unsqueeze(0)
872
+ else:
873
+ o_swa = flash_attn_func(
874
+ q, k, v,
875
+ causal=True,
876
+ window_size=(window_size-1, 0)
877
+ )
878
+ o = torch.addcmul(o, o_swa, g_swa.unsqueeze(-1))
879
+ return o