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,1904 @@
1
+ import math
2
+ import warnings
3
+ from dataclasses import dataclass
4
+ from typing import Optional, Tuple
5
+
6
+ import torch
7
+ import torch.nn.functional as F
8
+ import triton
9
+ import triton.language as tl
10
+ from einops import reduce
11
+
12
+ from fla.ops.utils import chunk_local_cumsum
13
+ from fla.ops.utils.op import safe_exp
14
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
15
+
16
+ BLOCK_K = 64
17
+
18
+
19
+ @triton.heuristics(
20
+ {
21
+ "IS_VARLEN": lambda args: args["cu_seqlens"] is not None,
22
+ "USE_INITIAL_STATE": lambda args: args["h0"] is not None,
23
+ "STORE_FINAL_STATE": lambda args: args["ht"] is not None,
24
+ }
25
+ )
26
+ @triton.autotune(
27
+ configs=[
28
+ triton.Config({"BK": BLOCK_K}, num_warps=num_warps, num_stages=num_stages)
29
+ for num_warps in [4]
30
+ for num_stages in [2, 3, 4]
31
+ ],
32
+ key=["H", "K", "V"],
33
+ )
34
+ @triton.jit(do_not_specialize=["T"])
35
+ def chunkwise_fwd_kernel(
36
+ q,
37
+ k,
38
+ v,
39
+ g,
40
+ level_scales,
41
+ llut,
42
+ o,
43
+ h0,
44
+ ht,
45
+ offsets,
46
+ new_offsets,
47
+ cu_seqlens,
48
+ T,
49
+ H: tl.constexpr,
50
+ K: tl.constexpr,
51
+ V: tl.constexpr,
52
+ L: tl.constexpr,
53
+ BT: tl.constexpr,
54
+ BK: tl.constexpr,
55
+ L_IN: tl.constexpr,
56
+ L_OUT: tl.constexpr,
57
+ MIN_LEVEL: tl.constexpr,
58
+ MAX_LEVEL: tl.constexpr,
59
+ IS_VARLEN: tl.constexpr,
60
+ USE_INITIAL_STATE: tl.constexpr,
61
+ STORE_FINAL_STATE: tl.constexpr,
62
+ ):
63
+ p_llut = tl.make_block_ptr(llut, (BT, BT), (BT, 1), (0, 0), (BT, BT), (1, 0))
64
+ b_llut = tl.load(p_llut, boundary_check=(0, 1))
65
+ # parallel over sequences and heads
66
+ i_k = tl.program_id(0)
67
+ i_nh = tl.program_id(1)
68
+ i_n, i_h = i_nh // H, i_nh % H
69
+
70
+ if IS_VARLEN:
71
+ bos, eos = (
72
+ tl.load(cu_seqlens + i_n).to(tl.int32),
73
+ tl.load(cu_seqlens + i_n + 1).to(tl.int32),
74
+ )
75
+ T = eos - bos
76
+ else:
77
+ bos, eos = i_n * T, i_n * T + T
78
+
79
+ o_i = tl.arange(0, BT)
80
+
81
+ # For hierarchical masking
82
+ num_intra_levels = (tl.log2(float(BT))).to(tl.int32) + 1
83
+ i_idx = o_i[:, None] # BT x 1
84
+ j_idx = o_i[None, :] # 1 x BT
85
+
86
+ # This is not great.
87
+ # See issue: https://github.com/triton-lang/triton/discussions/1313
88
+ KV_0_CREATED = MIN_LEVEL <= 1 and MAX_LEVEL >= 0
89
+ KV_1_CREATED = MIN_LEVEL <= 2 and MAX_LEVEL >= 0
90
+ KV_2_CREATED = MIN_LEVEL <= 3 and MAX_LEVEL >= 1
91
+ KV_3_CREATED = MIN_LEVEL <= 4 and MAX_LEVEL >= 2
92
+ KV_4_CREATED = MIN_LEVEL <= 5 and MAX_LEVEL >= 3
93
+ KV_5_CREATED = MIN_LEVEL <= 6 and MAX_LEVEL >= 4
94
+ KV_6_CREATED = MIN_LEVEL <= 7 and MAX_LEVEL >= 5
95
+ KV_7_CREATED = MIN_LEVEL <= 8 and MAX_LEVEL >= 6
96
+ KV_8_CREATED = MIN_LEVEL <= 9 and MAX_LEVEL >= 7
97
+ KV_9_CREATED = MIN_LEVEL <= 10 and MAX_LEVEL >= 8
98
+ KV_10_CREATED = MIN_LEVEL <= 11 and MAX_LEVEL >= 9
99
+ KV_11_CREATED = MIN_LEVEL <= 12 and MAX_LEVEL >= 10
100
+
101
+ kv_0 = tl.zeros([BK, V], dtype=tl.float32)
102
+ kv_1 = tl.zeros([BK, V], dtype=tl.float32)
103
+ kv_2 = tl.zeros([BK, V], dtype=tl.float32)
104
+ kv_3 = tl.zeros([BK, V], dtype=tl.float32)
105
+ kv_4 = tl.zeros([BK, V], dtype=tl.float32)
106
+ kv_5 = tl.zeros([BK, V], dtype=tl.float32)
107
+ kv_6 = tl.zeros([BK, V], dtype=tl.float32)
108
+ kv_7 = tl.zeros([BK, V], dtype=tl.float32)
109
+ kv_8 = tl.zeros([BK, V], dtype=tl.float32)
110
+ kv_9 = tl.zeros([BK, V], dtype=tl.float32)
111
+ kv_10 = tl.zeros([BK, V], dtype=tl.float32)
112
+ kv_11 = tl.zeros([BK, V], dtype=tl.float32)
113
+
114
+ offset = 0 # total number to cached tokens
115
+ first_chunk_index = 0 # next chunk index to compute
116
+ if USE_INITIAL_STATE:
117
+ offset = tl.load(offsets + i_n)
118
+
119
+ first_chunk_index = offset // BT
120
+
121
+ if KV_0_CREATED and (first_chunk_index & 1 > 0):
122
+ p_kv_0 = tl.make_block_ptr(
123
+ h0 + ((i_n * L_IN + 0) * H + i_h) * K * V,
124
+ (K, V),
125
+ (V, 1),
126
+ (i_k * BK, 0),
127
+ (BK, V),
128
+ (1, 0),
129
+ )
130
+ kv_0 = tl.load(p_kv_0, boundary_check=(0, 1))
131
+ if KV_1_CREATED and (first_chunk_index & 2 > 0):
132
+ p_kv_1 = tl.make_block_ptr(
133
+ h0 + ((i_n * L_IN + 1) * H + i_h) * K * V,
134
+ (K, V),
135
+ (V, 1),
136
+ (i_k * BK, 0),
137
+ (BK, V),
138
+ (1, 0),
139
+ )
140
+ kv_1 = tl.load(p_kv_1, boundary_check=(0, 1))
141
+ if KV_2_CREATED and (first_chunk_index & 4 > 0):
142
+ p_kv_2 = tl.make_block_ptr(
143
+ h0 + ((i_n * L_IN + 2) * H + i_h) * K * V,
144
+ (K, V),
145
+ (V, 1),
146
+ (i_k * BK, 0),
147
+ (BK, V),
148
+ (1, 0),
149
+ )
150
+ kv_2 = tl.load(p_kv_2, boundary_check=(0, 1))
151
+ if KV_3_CREATED and (first_chunk_index & 8 > 0):
152
+ p_kv_3 = tl.make_block_ptr(
153
+ h0 + ((i_n * L_IN + 3) * H + i_h) * K * V,
154
+ (K, V),
155
+ (V, 1),
156
+ (i_k * BK, 0),
157
+ (BK, V),
158
+ (1, 0),
159
+ )
160
+ kv_3 = tl.load(p_kv_3, boundary_check=(0, 1))
161
+ if KV_4_CREATED and (first_chunk_index & 16 > 0):
162
+ p_kv_4 = tl.make_block_ptr(
163
+ h0 + ((i_n * L_IN + 4) * H + i_h) * K * V,
164
+ (K, V),
165
+ (V, 1),
166
+ (i_k * BK, 0),
167
+ (BK, V),
168
+ (1, 0),
169
+ )
170
+ kv_4 = tl.load(p_kv_4, boundary_check=(0, 1))
171
+ if KV_5_CREATED and (first_chunk_index & 32 > 0):
172
+ p_kv_5 = tl.make_block_ptr(
173
+ h0 + ((i_n * L_IN + 5) * H + i_h) * K * V,
174
+ (K, V),
175
+ (V, 1),
176
+ (i_k * BK, 0),
177
+ (BK, V),
178
+ (1, 0),
179
+ )
180
+ kv_5 = tl.load(p_kv_5, boundary_check=(0, 1))
181
+ if KV_6_CREATED and (first_chunk_index & 64 > 0):
182
+ p_kv_6 = tl.make_block_ptr(
183
+ h0 + ((i_n * L_IN + 6) * H + i_h) * K * V,
184
+ (K, V),
185
+ (V, 1),
186
+ (i_k * BK, 0),
187
+ (BK, V),
188
+ (1, 0),
189
+ )
190
+ kv_6 = tl.load(p_kv_6, boundary_check=(0, 1))
191
+ if KV_7_CREATED and (first_chunk_index & 128 > 0):
192
+ p_kv_7 = tl.make_block_ptr(
193
+ h0 + ((i_n * L_IN + 7) * H + i_h) * K * V,
194
+ (K, V),
195
+ (V, 1),
196
+ (i_k * BK, 0),
197
+ (BK, V),
198
+ (1, 0),
199
+ )
200
+ kv_7 = tl.load(p_kv_7, boundary_check=(0, 1))
201
+ if KV_8_CREATED and (first_chunk_index & 256 > 0):
202
+ p_kv_8 = tl.make_block_ptr(
203
+ h0 + ((i_n * L_IN + 8) * H + i_h) * K * V,
204
+ (K, V),
205
+ (V, 1),
206
+ (i_k * BK, 0),
207
+ (BK, V),
208
+ (1, 0),
209
+ )
210
+ kv_8 = tl.load(p_kv_8, boundary_check=(0, 1))
211
+ if KV_9_CREATED and (first_chunk_index & 512 > 0):
212
+ p_kv_9 = tl.make_block_ptr(
213
+ h0 + ((i_n * L_IN + 9) * H + i_h) * K * V,
214
+ (K, V),
215
+ (V, 1),
216
+ (i_k * BK, 0),
217
+ (BK, V),
218
+ (1, 0),
219
+ )
220
+ kv_9 = tl.load(p_kv_9, boundary_check=(0, 1))
221
+ if KV_10_CREATED and (first_chunk_index & 1024 > 0):
222
+ p_kv_10 = tl.make_block_ptr(
223
+ h0 + ((i_n * L_IN + 10) * H + i_h) * K * V,
224
+ (K, V),
225
+ (V, 1),
226
+ (i_k * BK, 0),
227
+ (BK, V),
228
+ (1, 0),
229
+ )
230
+ kv_10 = tl.load(p_kv_10, boundary_check=(0, 1))
231
+ if KV_11_CREATED and (first_chunk_index & 2048 > 0):
232
+ p_kv_11 = tl.make_block_ptr(
233
+ h0 + ((i_n * L_IN + 11) * H + i_h) * K * V,
234
+ (K, V),
235
+ (V, 1),
236
+ (i_k * BK, 0),
237
+ (BK, V),
238
+ (1, 0),
239
+ )
240
+ kv_11 = tl.load(p_kv_11, boundary_check=(0, 1))
241
+
242
+ NT = tl.cdiv(T, BT)
243
+ output_offset = -1 * (offset % BT)
244
+ for i_t in range(NT):
245
+ b_h_ptrs = level_scales + ((bos + i_t * BT + i_idx) * H + i_h) * L + b_llut
246
+ b_h = tl.load(b_h_ptrs, mask=i_idx >= j_idx)
247
+
248
+ p_g = tl.make_block_ptr(g + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,))
249
+ p_q = tl.make_block_ptr(
250
+ q + bos * K, (T, K), (K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0)
251
+ )
252
+ p_k = tl.make_block_ptr(
253
+ k + bos * K, (K, T), (1, K), (i_k * BK, i_t * BT), (BK, BT), (0, 1)
254
+ )
255
+ p_v = tl.make_block_ptr(
256
+ v + (bos * H + i_h) * V,
257
+ (T, V),
258
+ (H * V, 1),
259
+ (i_t * BT, 0),
260
+ (BT, V),
261
+ (1, 0),
262
+ )
263
+ p_o = tl.make_block_ptr(
264
+ o + ((bos * H + i_h) * (K // BK) + i_k) * V,
265
+ (T, V),
266
+ (H * (K // BK) * V, 1),
267
+ (i_t * BT + output_offset, 0),
268
+ (BT, V),
269
+ (1, 0),
270
+ )
271
+
272
+ b_g = tl.load(p_g, boundary_check=(0,))
273
+ b_q = tl.load(p_q, boundary_check=(0, 1))
274
+ b_k = tl.load(p_k, boundary_check=(0, 1))
275
+
276
+ b_s = (tl.dot(b_q, b_k) * safe_exp(b_g[:, None] - b_g[None, :])).to(
277
+ b_q.dtype
278
+ ) * b_h
279
+
280
+ b_v = tl.load(p_v, boundary_check=(0, 1))
281
+ b_o = tl.zeros((BT, V), dtype=tl.float32)
282
+ if MIN_LEVEL == 0:
283
+ b_o += tl.dot(b_s, b_v)
284
+
285
+ chunk_index = (
286
+ first_chunk_index + i_t
287
+ ) # index of the chunk over the entire sequence, including the offset
288
+
289
+ if MIN_LEVEL <= 0 and MAX_LEVEL >= 0:
290
+ if chunk_index & 1:
291
+ p_l = tl.make_block_ptr(
292
+ level_scales + (bos * H + i_h) * L,
293
+ (T, L),
294
+ (H * L, 1),
295
+ (i_t * BT, num_intra_levels),
296
+ (BT, 1),
297
+ (1, 0),
298
+ )
299
+ b_l = tl.load(p_l, boundary_check=(0, 1))
300
+ b_o += tl.dot((b_l * b_q), kv_0.to(b_q.dtype)) * tl.exp(b_g)[:, None]
301
+ if MIN_LEVEL <= 1 and MAX_LEVEL >= 1:
302
+ if chunk_index & 2:
303
+ p_l = tl.make_block_ptr(
304
+ level_scales + (bos * H + i_h) * L,
305
+ (T, L),
306
+ (H * L, 1),
307
+ (i_t * BT, num_intra_levels + 1),
308
+ (BT, 1),
309
+ (1, 0),
310
+ )
311
+ b_l = tl.load(p_l, boundary_check=(0, 1))
312
+ b_o += tl.dot((b_l * b_q), kv_1.to(b_q.dtype)) * tl.exp(b_g)[:, None]
313
+ if MIN_LEVEL <= 2 and MAX_LEVEL >= 2:
314
+ if chunk_index & 4:
315
+ p_l = tl.make_block_ptr(
316
+ level_scales + (bos * H + i_h) * L,
317
+ (T, L),
318
+ (H * L, 1),
319
+ (i_t * BT, num_intra_levels + 2),
320
+ (BT, 1),
321
+ (1, 0),
322
+ )
323
+ b_l = tl.load(p_l, boundary_check=(0, 1))
324
+ b_o += tl.dot((b_l * b_q), kv_2.to(b_q.dtype)) * tl.exp(b_g)[:, None]
325
+ if MIN_LEVEL <= 3 and MAX_LEVEL >= 3:
326
+ if chunk_index & 8:
327
+ p_l = tl.make_block_ptr(
328
+ level_scales + (bos * H + i_h) * L,
329
+ (T, L),
330
+ (H * L, 1),
331
+ (i_t * BT, num_intra_levels + 3),
332
+ (BT, 1),
333
+ (1, 0),
334
+ )
335
+ b_l = tl.load(p_l, boundary_check=(0, 1))
336
+ b_o += tl.dot((b_l * b_q), kv_3.to(b_q.dtype)) * tl.exp(b_g)[:, None]
337
+ if MIN_LEVEL <= 4 and MAX_LEVEL >= 4:
338
+ if chunk_index & 16:
339
+ p_l = tl.make_block_ptr(
340
+ level_scales + (bos * H + i_h) * L,
341
+ (T, L),
342
+ (H * L, 1),
343
+ (i_t * BT, num_intra_levels + 4),
344
+ (BT, 1),
345
+ (1, 0),
346
+ )
347
+ b_l = tl.load(p_l, boundary_check=(0, 1))
348
+ b_o += tl.dot((b_l * b_q), kv_4.to(b_q.dtype)) * tl.exp(b_g)[:, None]
349
+ if MIN_LEVEL <= 5 and MAX_LEVEL >= 5:
350
+ if chunk_index & 32:
351
+ p_l = tl.make_block_ptr(
352
+ level_scales + (bos * H + i_h) * L,
353
+ (T, L),
354
+ (H * L, 1),
355
+ (i_t * BT, num_intra_levels + 5),
356
+ (BT, 1),
357
+ (1, 0),
358
+ )
359
+ b_l = tl.load(p_l, boundary_check=(0, 1))
360
+ b_o += tl.dot((b_l * b_q), kv_5.to(b_q.dtype)) * tl.exp(b_g)[:, None]
361
+ if MIN_LEVEL <= 6 and MAX_LEVEL >= 6:
362
+ if chunk_index & 64:
363
+ p_l = tl.make_block_ptr(
364
+ level_scales + (bos * H + i_h) * L,
365
+ (T, L),
366
+ (H * L, 1),
367
+ (i_t * BT, num_intra_levels + 6),
368
+ (BT, 1),
369
+ (1, 0),
370
+ )
371
+ b_l = tl.load(p_l, boundary_check=(0, 1))
372
+ b_o += tl.dot((b_l * b_q), kv_6.to(b_q.dtype)) * tl.exp(b_g)[:, None]
373
+ if MIN_LEVEL <= 7 and MAX_LEVEL >= 7:
374
+ if chunk_index & 128: # 8192 - 16384
375
+ p_l = tl.make_block_ptr(
376
+ level_scales + (bos * H + i_h) * L,
377
+ (T, L),
378
+ (H * L, 1),
379
+ (i_t * BT, num_intra_levels + 7),
380
+ (BT, 1),
381
+ (1, 0),
382
+ )
383
+ b_l = tl.load(p_l, boundary_check=(0, 1))
384
+ b_o += tl.dot((b_l * b_q), kv_7.to(b_q.dtype)) * tl.exp(b_g)[:, None]
385
+ if MIN_LEVEL <= 8 and MAX_LEVEL >= 8:
386
+ if chunk_index & 256:
387
+ p_l = tl.make_block_ptr(
388
+ level_scales + (bos * H + i_h) * L,
389
+ (T, L),
390
+ (H * L, 1),
391
+ (i_t * BT, num_intra_levels + 8),
392
+ (BT, 1),
393
+ (1, 0),
394
+ )
395
+ b_l = tl.load(p_l, boundary_check=(0, 1))
396
+ b_o += tl.dot((b_l * b_q), kv_8.to(b_q.dtype)) * tl.exp(b_g)[:, None]
397
+ if MIN_LEVEL <= 9 and MAX_LEVEL >= 9:
398
+ if chunk_index & 512:
399
+ p_l = tl.make_block_ptr(
400
+ level_scales + (bos * H + i_h) * L,
401
+ (T, L),
402
+ (H * L, 1),
403
+ (i_t * BT, num_intra_levels + 9),
404
+ (BT, 1),
405
+ (1, 0),
406
+ )
407
+ b_l = tl.load(p_l, boundary_check=(0, 1))
408
+ b_o += tl.dot((b_l * b_q), kv_9.to(b_q.dtype)) * tl.exp(b_g)[:, None]
409
+ if MIN_LEVEL <= 10 and MAX_LEVEL >= 10:
410
+ if chunk_index & 1024:
411
+ p_l = tl.make_block_ptr(
412
+ level_scales + (bos * H + i_h) * L,
413
+ (T, L),
414
+ (H * L, 1),
415
+ (i_t * BT, num_intra_levels + 10),
416
+ (BT, 1),
417
+ (1, 0),
418
+ )
419
+ b_l = tl.load(p_l, boundary_check=(0, 1))
420
+ b_o += tl.dot((b_l * b_q), kv_10.to(b_q.dtype)) * tl.exp(b_g)[:, None]
421
+ if MIN_LEVEL <= 11 and MAX_LEVEL >= 11:
422
+ if chunk_index & 2048:
423
+ p_l = tl.make_block_ptr(
424
+ level_scales + (bos * H + i_h) * L,
425
+ (T, L),
426
+ (H * L, 1),
427
+ (i_t * BT, num_intra_levels + 11),
428
+ (BT, 1),
429
+ (1, 0),
430
+ )
431
+ b_l = tl.load(p_l, boundary_check=(0, 1))
432
+ b_o += tl.dot((b_l * b_q), kv_11.to(b_q.dtype)) * tl.exp(b_g)[:, None]
433
+
434
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
435
+
436
+ if i_t < NT - 1 or T % BT == 0:
437
+ # Only apply the state update if the last chunk is a full chunk.
438
+ # Otherwise, it needs to be included in the next kernel call.
439
+
440
+ # update the recurrent states
441
+ last_idx = min((i_t + 1) * BT, T) - 1
442
+ b_g_last = tl.load(g + bos * H + last_idx * H + i_h)
443
+ if KV_0_CREATED:
444
+ kv_0 *= tl.exp(b_g_last)
445
+ if KV_1_CREATED:
446
+ kv_1 *= tl.exp(b_g_last)
447
+ if KV_2_CREATED:
448
+ kv_2 *= tl.exp(b_g_last)
449
+ if KV_3_CREATED:
450
+ kv_3 *= tl.exp(b_g_last)
451
+ if KV_4_CREATED:
452
+ kv_4 *= tl.exp(b_g_last)
453
+ if KV_5_CREATED:
454
+ kv_5 *= tl.exp(b_g_last)
455
+ if KV_6_CREATED:
456
+ kv_6 *= tl.exp(b_g_last)
457
+ if KV_7_CREATED:
458
+ kv_7 *= tl.exp(b_g_last)
459
+ if KV_8_CREATED:
460
+ kv_8 *= tl.exp(b_g_last)
461
+ if KV_9_CREATED:
462
+ kv_9 *= tl.exp(b_g_last)
463
+ if KV_10_CREATED:
464
+ kv_10 *= tl.exp(b_g_last)
465
+ if KV_11_CREATED:
466
+ kv_11 *= tl.exp(b_g_last)
467
+
468
+ b_v = (b_v * tl.exp(b_g_last - b_g)[:, None]).to(b_v.dtype)
469
+ if MIN_LEVEL <= 1:
470
+ kv_0 += tl.dot(b_k, b_v)
471
+ elif MIN_LEVEL == 2:
472
+ kv_1 += tl.dot(b_k, b_v)
473
+ elif MIN_LEVEL == 3:
474
+ kv_2 += tl.dot(b_k, b_v)
475
+ elif MIN_LEVEL == 4:
476
+ kv_3 += tl.dot(b_k, b_v)
477
+ elif MIN_LEVEL == 5:
478
+ kv_4 += tl.dot(b_k, b_v)
479
+ elif MIN_LEVEL == 6:
480
+ kv_5 += tl.dot(b_k, b_v)
481
+ elif MIN_LEVEL == 7:
482
+ kv_6 += tl.dot(b_k, b_v)
483
+ elif MIN_LEVEL == 8:
484
+ kv_7 += tl.dot(b_k, b_v)
485
+ elif MIN_LEVEL == 9:
486
+ kv_8 += tl.dot(b_k, b_v)
487
+ elif MIN_LEVEL == 10:
488
+ kv_9 += tl.dot(b_k, b_v)
489
+ elif MIN_LEVEL == 11:
490
+ kv_10 += tl.dot(b_k, b_v)
491
+
492
+ check_value = (~chunk_index & (chunk_index + 1)) - 1
493
+
494
+ if MIN_LEVEL <= 1 and MAX_LEVEL >= 0:
495
+ if check_value & 1:
496
+ kv_1 += kv_0
497
+ kv_0 = tl.zeros([BK, V], dtype=tl.float32)
498
+ if MIN_LEVEL <= 2 and MAX_LEVEL >= 1:
499
+ if check_value & 2:
500
+ kv_2 += kv_1
501
+ kv_1 = tl.zeros([BK, V], dtype=tl.float32)
502
+ if MIN_LEVEL <= 3 and MAX_LEVEL >= 2:
503
+ if check_value & 4:
504
+ kv_3 += kv_2
505
+ kv_2 = tl.zeros([BK, V], dtype=tl.float32)
506
+ if MIN_LEVEL <= 4 and MAX_LEVEL >= 3:
507
+ if check_value & 8:
508
+ kv_4 += kv_3
509
+ kv_3 = tl.zeros([BK, V], dtype=tl.float32)
510
+ if MIN_LEVEL <= 5 and MAX_LEVEL >= 4:
511
+ if check_value & 16:
512
+ kv_5 += kv_4
513
+ kv_4 = tl.zeros([BK, V], dtype=tl.float32)
514
+ if MIN_LEVEL <= 6 and MAX_LEVEL >= 5:
515
+ if check_value & 32:
516
+ kv_6 += kv_5
517
+ kv_5 = tl.zeros([BK, V], dtype=tl.float32)
518
+ if MIN_LEVEL <= 7 and MAX_LEVEL >= 6:
519
+ if check_value & 64:
520
+ kv_7 += kv_6
521
+ kv_6 = tl.zeros([BK, V], dtype=tl.float32)
522
+ if MIN_LEVEL <= 8 and MAX_LEVEL >= 7:
523
+ if check_value & 128:
524
+ kv_8 += kv_7
525
+ kv_7 = tl.zeros([BK, V], dtype=tl.float32)
526
+ if MIN_LEVEL <= 9 and MAX_LEVEL >= 8:
527
+ if check_value & 256:
528
+ kv_9 += kv_8
529
+ kv_8 = tl.zeros([BK, V], dtype=tl.float32)
530
+ if MIN_LEVEL <= 10 and MAX_LEVEL >= 9:
531
+ if check_value & 512:
532
+ kv_10 += kv_9
533
+ kv_9 = tl.zeros([BK, V], dtype=tl.float32)
534
+ if MIN_LEVEL <= 11 and MAX_LEVEL >= 10:
535
+ if check_value & 1024:
536
+ kv_11 += kv_10
537
+ kv_10 = tl.zeros([BK, V], dtype=tl.float32)
538
+
539
+ chunk_index = offset // BT + T // BT
540
+
541
+ if STORE_FINAL_STATE:
542
+ if (MIN_LEVEL <= 0 and MAX_LEVEL >= 0) and (chunk_index & 1 > 0):
543
+ p_kv = tl.make_block_ptr(
544
+ ht + ((i_n * L_OUT + 0) * H + i_h) * K * V,
545
+ (K, V),
546
+ (V, 1),
547
+ (i_k * BK, 0),
548
+ (BK, V),
549
+ (1, 0),
550
+ )
551
+ tl.store(p_kv, kv_0, boundary_check=(0, 1))
552
+ if (MIN_LEVEL <= 1 and MAX_LEVEL >= 1) and (chunk_index & 2 > 0):
553
+ p_kv = tl.make_block_ptr(
554
+ ht + ((i_n * L_OUT + 1) * H + i_h) * K * V,
555
+ (K, V),
556
+ (V, 1),
557
+ (i_k * BK, 0),
558
+ (BK, V),
559
+ (1, 0),
560
+ )
561
+ tl.store(p_kv, kv_1, boundary_check=(0, 1))
562
+ if (MIN_LEVEL <= 2 and MAX_LEVEL >= 2) and (chunk_index & 4 > 0):
563
+ p_kv = tl.make_block_ptr(
564
+ ht + ((i_n * L_OUT + 2) * H + i_h) * K * V,
565
+ (K, V),
566
+ (V, 1),
567
+ (i_k * BK, 0),
568
+ (BK, V),
569
+ (1, 0),
570
+ )
571
+ tl.store(p_kv, kv_2, boundary_check=(0, 1))
572
+ if (MIN_LEVEL <= 3 and MAX_LEVEL >= 3) and (chunk_index & 8 > 0):
573
+ p_kv = tl.make_block_ptr(
574
+ ht + ((i_n * L_OUT + 3) * H + i_h) * K * V,
575
+ (K, V),
576
+ (V, 1),
577
+ (i_k * BK, 0),
578
+ (BK, V),
579
+ (1, 0),
580
+ )
581
+ tl.store(p_kv, kv_3, boundary_check=(0, 1))
582
+ if (MIN_LEVEL <= 4 and MAX_LEVEL >= 4) and (chunk_index & 16 > 0):
583
+ p_kv = tl.make_block_ptr(
584
+ ht + ((i_n * L_OUT + 4) * H + i_h) * K * V,
585
+ (K, V),
586
+ (V, 1),
587
+ (i_k * BK, 0),
588
+ (BK, V),
589
+ (1, 0),
590
+ )
591
+ tl.store(p_kv, kv_4, boundary_check=(0, 1))
592
+ if (MIN_LEVEL <= 5 and MAX_LEVEL >= 5) and (chunk_index & 32 > 0):
593
+ p_kv = tl.make_block_ptr(
594
+ ht + ((i_n * L_OUT + 5) * H + i_h) * K * V,
595
+ (K, V),
596
+ (V, 1),
597
+ (i_k * BK, 0),
598
+ (BK, V),
599
+ (1, 0),
600
+ )
601
+ tl.store(p_kv, kv_5, boundary_check=(0, 1))
602
+ if (MIN_LEVEL <= 6 and MAX_LEVEL >= 6) and (chunk_index & 64 > 0):
603
+ p_kv = tl.make_block_ptr(
604
+ ht + ((i_n * L_OUT + 6) * H + i_h) * K * V,
605
+ (K, V),
606
+ (V, 1),
607
+ (i_k * BK, 0),
608
+ (BK, V),
609
+ (1, 0),
610
+ )
611
+ tl.store(p_kv, kv_6, boundary_check=(0, 1))
612
+ if (MIN_LEVEL <= 7 and MAX_LEVEL >= 7) and (chunk_index & 128 > 0):
613
+ p_kv = tl.make_block_ptr(
614
+ ht + ((i_n * L_OUT + 7) * H + i_h) * K * V,
615
+ (K, V),
616
+ (V, 1),
617
+ (i_k * BK, 0),
618
+ (BK, V),
619
+ (1, 0),
620
+ )
621
+ tl.store(p_kv, kv_7, boundary_check=(0, 1))
622
+ if (MIN_LEVEL <= 8 and MAX_LEVEL >= 8) and (chunk_index & 256 > 0):
623
+ p_kv = tl.make_block_ptr(
624
+ ht + ((i_n * L_OUT + 8) * H + i_h) * K * V,
625
+ (K, V),
626
+ (V, 1),
627
+ (i_k * BK, 0),
628
+ (BK, V),
629
+ (1, 0),
630
+ )
631
+ tl.store(p_kv, kv_8, boundary_check=(0, 1))
632
+ if (MIN_LEVEL <= 9 and MAX_LEVEL >= 9) and (chunk_index & 512 > 0):
633
+ p_kv = tl.make_block_ptr(
634
+ ht + ((i_n * L_OUT + 9) * H + i_h) * K * V,
635
+ (K, V),
636
+ (V, 1),
637
+ (i_k * BK, 0),
638
+ (BK, V),
639
+ (1, 0),
640
+ )
641
+ tl.store(p_kv, kv_9, boundary_check=(0, 1))
642
+ if (MIN_LEVEL <= 10 and MAX_LEVEL >= 10) and (chunk_index & 1024 > 0):
643
+ p_kv = tl.make_block_ptr(
644
+ ht + ((i_n * L_OUT + 10) * H + i_h) * K * V,
645
+ (K, V),
646
+ (V, 1),
647
+ (i_k * BK, 0),
648
+ (BK, V),
649
+ (1, 0),
650
+ )
651
+ tl.store(p_kv, kv_10, boundary_check=(0, 1))
652
+ if (MIN_LEVEL <= 11 and MAX_LEVEL >= 11) and (chunk_index & 2048 > 0):
653
+ p_kv = tl.make_block_ptr(
654
+ ht + ((i_n * L_OUT + 11) * H + i_h) * K * V,
655
+ (K, V),
656
+ (V, 1),
657
+ (i_k * BK, 0),
658
+ (BK, V),
659
+ (1, 0),
660
+ )
661
+ tl.store(p_kv, kv_11, boundary_check=(0, 1))
662
+
663
+ tl.store(new_offsets + i_n, (offset // BT) * BT + T)
664
+
665
+
666
+ @triton.heuristics({
667
+ "IS_VARLEN": lambda args: args["cu_seqlens"] is not None,
668
+ })
669
+ @triton.jit(do_not_specialize=["T"])
670
+ def copy_input_kernel(
671
+ q,
672
+ k,
673
+ v,
674
+ g,
675
+ level_scales,
676
+ cu_seqlens,
677
+ q_prev,
678
+ k_prev,
679
+ v_prev,
680
+ g_prev,
681
+ level_scales_prev,
682
+ offsets,
683
+ q_new,
684
+ k_new,
685
+ v_new,
686
+ g_new,
687
+ level_scales_new,
688
+ T,
689
+ H: tl.constexpr,
690
+ K: tl.constexpr,
691
+ V: tl.constexpr,
692
+ L: tl.constexpr,
693
+ BT: tl.constexpr,
694
+ IS_VARLEN: tl.constexpr,
695
+ ):
696
+ # parallel over sequences and heads
697
+ i_nh = tl.program_id(0)
698
+ i_n, i_h = i_nh // H, i_nh % H
699
+
700
+ if IS_VARLEN:
701
+ bos, eos = (
702
+ tl.load(cu_seqlens + i_n).to(tl.int32),
703
+ tl.load(cu_seqlens + i_n + 1).to(tl.int32),
704
+ )
705
+ T = eos - bos
706
+ else:
707
+ bos, eos = i_n * T, i_n * T + T
708
+
709
+ offset = tl.load(offsets + i_n)
710
+ input_offset = -1 * (offset % BT)
711
+
712
+ NT = tl.cdiv(T, BT)
713
+
714
+ for i_t in range(NT):
715
+ p_g = tl.make_block_ptr(
716
+ g + bos * H + i_h, (T,), (H,), (i_t * BT + input_offset,), (BT,), (0,)
717
+ )
718
+ p_q = tl.make_block_ptr(
719
+ q + bos * K, (T, K), (K, 1), (i_t * BT + input_offset, 0), (BT, K), (1, 0)
720
+ )
721
+ p_k = tl.make_block_ptr(
722
+ k + bos * K, (T, K), (K, 1), (i_t * BT + input_offset, 0), (BT, K), (1, 0)
723
+ )
724
+ p_v = tl.make_block_ptr(
725
+ v + (bos * H + i_h) * V,
726
+ (T, V),
727
+ (H * V, 1),
728
+ (i_t * BT + input_offset, 0),
729
+ (BT, V),
730
+ (1, 0),
731
+ )
732
+ p_g_new = tl.make_block_ptr(
733
+ g_new + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,)
734
+ )
735
+ p_q_new = tl.make_block_ptr(
736
+ q_new + bos * K, (T, K), (K, 1), (i_t * BT, 0), (BT, K), (1, 0)
737
+ )
738
+ p_k_new = tl.make_block_ptr(
739
+ k_new + bos * K, (T, K), (K, 1), (i_t * BT, 0), (BT, K), (1, 0)
740
+ )
741
+ p_v_new = tl.make_block_ptr(
742
+ v_new + (bos * H + i_h) * V,
743
+ (T, V),
744
+ (H * V, 1),
745
+ (i_t * BT, 0),
746
+ (BT, V),
747
+ (1, 0),
748
+ )
749
+
750
+ b_g = tl.load(p_g, boundary_check=(0,))
751
+ b_q = tl.load(p_q, boundary_check=(0, 1))
752
+ b_k = tl.load(p_k, boundary_check=(0, 1))
753
+ b_v = tl.load(p_v, boundary_check=(0, 1))
754
+
755
+ if i_t == 0:
756
+ p_g_prev = tl.make_block_ptr(
757
+ g_prev + i_n * BT * H + i_h, (BT,), (H,), (0,), (BT,), (0,)
758
+ )
759
+ p_q_prev = tl.make_block_ptr(
760
+ q_prev + i_n * BT * K, (BT, K), (K, 1), (0, 0), (BT, K), (1, 0)
761
+ )
762
+ p_k_prev = tl.make_block_ptr(
763
+ k_prev + i_n * BT * K, (BT, K), (K, 1), (0, 0), (BT, K), (1, 0)
764
+ )
765
+ p_v_prev = tl.make_block_ptr(
766
+ v_prev + (i_n * BT * H + i_h) * V,
767
+ (BT, V),
768
+ (H * V, 1),
769
+ (0, 0),
770
+ (BT, V),
771
+ (1, 0),
772
+ )
773
+
774
+ b_g += tl.load(p_g_prev, boundary_check=(0,))
775
+ b_q += tl.load(p_q_prev, boundary_check=(0, 1))
776
+ b_k += tl.load(p_k_prev, boundary_check=(0, 1))
777
+ b_v += tl.load(p_v_prev, boundary_check=(0, 1))
778
+
779
+ tl.store(p_g_new, b_g, boundary_check=(0,))
780
+ tl.store(p_q_new, b_q, boundary_check=(0, 1))
781
+ tl.store(p_k_new, b_k, boundary_check=(0, 1))
782
+ tl.store(p_v_new, b_v, boundary_check=(0, 1))
783
+
784
+ for i in range(L):
785
+ p_l = tl.make_block_ptr(
786
+ level_scales + (bos * H + i_h) * L,
787
+ (T, L),
788
+ (H * L, 1),
789
+ (i_t * BT + input_offset, i),
790
+ (BT, 1),
791
+ (1, 0),
792
+ )
793
+ p_l_new = tl.make_block_ptr(
794
+ level_scales_new + (bos * H + i_h) * L,
795
+ (T, L),
796
+ (H * L, 1),
797
+ (i_t * BT, i),
798
+ (BT, 1),
799
+ (1, 0),
800
+ )
801
+ b_l = tl.load(p_l, boundary_check=(0,))
802
+ if i_t == 0:
803
+ p_l_prev = tl.make_block_ptr(
804
+ level_scales_prev + (i_n * BT * H + i_h) * L,
805
+ (BT, L),
806
+ (H * L, 1),
807
+ (0, i),
808
+ (BT, 1),
809
+ (1, 0),
810
+ )
811
+ b_l += tl.load(p_l_prev, boundary_check=(0,))
812
+ tl.store(p_l_new, b_l, boundary_check=(0,))
813
+
814
+
815
+ @triton.heuristics(
816
+ {
817
+ "IS_VARLEN": lambda args: args["cu_seqlens"] is not None,
818
+ }
819
+ )
820
+ @triton.jit(do_not_specialize=["T"])
821
+ def copy_last_chunk_kernel(
822
+ q,
823
+ k,
824
+ v,
825
+ g,
826
+ level_scales,
827
+ cu_seqlens,
828
+ q_prev,
829
+ k_prev,
830
+ v_prev,
831
+ g_prev,
832
+ level_scales_prev,
833
+ offsets,
834
+ T,
835
+ H: tl.constexpr,
836
+ K: tl.constexpr,
837
+ V: tl.constexpr,
838
+ L: tl.constexpr,
839
+ BT: tl.constexpr,
840
+ IS_VARLEN: tl.constexpr,
841
+ ):
842
+ # parallel over sequences and heads
843
+ i_nh = tl.program_id(0)
844
+ i_n, i_h = i_nh // H, i_nh % H
845
+
846
+ if IS_VARLEN:
847
+ bos, eos = (
848
+ tl.load(cu_seqlens + i_n).to(tl.int32),
849
+ tl.load(cu_seqlens + i_n + 1).to(tl.int32),
850
+ )
851
+ T = eos - bos
852
+ else:
853
+ bos, eos = i_n * T, i_n * T + T
854
+
855
+ seq_offset = (T // BT) * BT
856
+
857
+ p_g = tl.make_block_ptr(g + bos * H + i_h, (T,), (H,), (seq_offset,), (BT,), (0,))
858
+ p_q = tl.make_block_ptr(
859
+ q + bos * K, (T, K), (K, 1), (seq_offset, 0), (BT, K), (1, 0)
860
+ )
861
+ p_k = tl.make_block_ptr(
862
+ k + bos * K, (T, K), (K, 1), (seq_offset, 0), (BT, K), (1, 0)
863
+ )
864
+ p_v = tl.make_block_ptr(
865
+ v + (bos * H + i_h) * V,
866
+ (T, V),
867
+ (H * V, 1),
868
+ (seq_offset, 0),
869
+ (BT, V),
870
+ (1, 0),
871
+ )
872
+ p_g_prev = tl.make_block_ptr(
873
+ g_prev + i_n * BT * H + i_h, (BT,), (H,), (0,), (BT,), (0,)
874
+ )
875
+ p_q_prev = tl.make_block_ptr(
876
+ q_prev + i_n * BT * K, (BT, K), (K, 1), (0, 0), (BT, K), (1, 0)
877
+ )
878
+ p_k_prev = tl.make_block_ptr(
879
+ k_prev + i_n * BT * K, (BT, K), (K, 1), (0, 0), (BT, K), (1, 0)
880
+ )
881
+ p_v_prev = tl.make_block_ptr(
882
+ v_prev + (i_n * BT * H + i_h) * V, (BT, V), (H * V, 1), (0, 0), (BT, V), (1, 0)
883
+ )
884
+
885
+ tl.store(p_g_prev, tl.load(p_g, boundary_check=(0,)), boundary_check=(0,))
886
+ tl.store(p_q_prev, tl.load(p_q, boundary_check=(0, 1)), boundary_check=(0, 1))
887
+ tl.store(p_k_prev, tl.load(p_k, boundary_check=(0, 1)), boundary_check=(0, 1))
888
+ tl.store(p_v_prev, tl.load(p_v, boundary_check=(0, 1)), boundary_check=(0, 1))
889
+
890
+ for i in range(L):
891
+ p_l = tl.make_block_ptr(
892
+ level_scales + (bos * H + i_h) * L,
893
+ (T, L),
894
+ (H * L, 1),
895
+ (seq_offset, i),
896
+ (BT, 1),
897
+ (1, 0),
898
+ )
899
+ p_l_prev = tl.make_block_ptr(
900
+ level_scales_prev + (i_n * BT * H + i_h) * L,
901
+ (BT, L),
902
+ (H * L, 1),
903
+ (0, i),
904
+ (BT, 1),
905
+ (1, 0),
906
+ )
907
+ tl.store(p_l_prev, tl.load(p_l, boundary_check=(0,)), boundary_check=(0,))
908
+
909
+
910
+ @triton.heuristics({"IS_VARLEN": lambda args: args["cu_seqlens"] is not None})
911
+ @triton.autotune(
912
+ configs=[
913
+ triton.Config({"BK": BK}, num_warps=num_warps, num_stages=num_stages)
914
+ for BK in [32, 64, 128]
915
+ for num_warps in [4]
916
+ for num_stages in [2, 3, 4]
917
+ ],
918
+ key=["H", "K", "V"],
919
+ restore_value=["dh", "dg_last"],
920
+ )
921
+ @triton.jit(do_not_specialize=["T"])
922
+ def chunkwise_bwd_kernel_dhg(
923
+ do,
924
+ q,
925
+ g,
926
+ l,
927
+ h_l,
928
+ dh,
929
+ dg_last,
930
+ ell,
931
+ T,
932
+ cu_seqlens,
933
+ H: tl.constexpr,
934
+ K: tl.constexpr,
935
+ V: tl.constexpr,
936
+ L: tl.constexpr,
937
+ BT: tl.constexpr,
938
+ BK: tl.constexpr,
939
+ NT: tl.constexpr,
940
+ IS_VARLEN: tl.constexpr,
941
+ ):
942
+ # parallel over batches and heads
943
+ i_k = tl.program_id(0)
944
+ i_nh = tl.program_id(1)
945
+ i_n, i_h = i_nh // H, i_nh % H
946
+
947
+ if IS_VARLEN:
948
+ bos, eos = (
949
+ tl.load(cu_seqlens + i_n).to(tl.int32),
950
+ tl.load(cu_seqlens + i_n + 1).to(tl.int32),
951
+ )
952
+ T = eos - bos
953
+ else:
954
+ bos, eos = i_n * T, i_n * T + T
955
+
956
+ b_dh = tl.zeros([BK, V], dtype=tl.float32)
957
+
958
+ num_intra_levels = (tl.log2(float(BT))).to(tl.int32) + 1
959
+
960
+ for i_t in range(tl.cdiv(T, BT) - 1, -1, -1):
961
+ p_dh = tl.make_block_ptr(
962
+ dh + ((i_n * NT + i_t) * H + i_h) * K * V,
963
+ (K, V),
964
+ (V, 1),
965
+ (i_k * BK, 0),
966
+ (BK, V),
967
+ (1, 0),
968
+ )
969
+ b_dh_old = tl.load(p_dh, boundary_check=(0, 1))
970
+
971
+ if (i_t & (1 << ell)) == 0: # store the chunk
972
+ tl.store(
973
+ p_dh, b_dh.to(p_dh.dtype.element_ty) + b_dh_old, boundary_check=(0, 1)
974
+ )
975
+ # if you are about the transition to compute, reset to zeros
976
+ if i_t > 0 and ((i_t - 1) & (1 << ell)) > 0:
977
+ b_dh = tl.zeros([BK, V], dtype=tl.float32)
978
+ if i_t & (1 << ell):
979
+ p_h = tl.make_block_ptr(
980
+ h_l + ((i_n * NT + i_t) * H + i_h) * K * V,
981
+ (K, V),
982
+ (V, 1),
983
+ (i_k * BK, 0),
984
+ (BK, V),
985
+ (1, 0),
986
+ )
987
+
988
+ b_h = tl.load(p_h, boundary_check=(0, 1))
989
+ p_dg_last = dg_last + i_n * NT * H + i_t * H + i_h
990
+ tl.atomic_add(p_dg_last, tl.sum(b_h * (b_dh + b_dh_old)))
991
+ last_idx = min((i_t + 1) * BT, T) - 1
992
+ b_g_last = tl.exp(tl.load(g + bos * H + last_idx * H + i_h))
993
+ b_dh *= b_g_last
994
+ if i_t & (1 << ell): # compute this chunk
995
+ p_g = tl.make_block_ptr(
996
+ g + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,)
997
+ )
998
+ p_q = tl.make_block_ptr(
999
+ q + bos * K, (K, T), (1, K), (i_k * BK, i_t * BT), (BK, BT), (0, 1)
1000
+ )
1001
+ p_do = tl.make_block_ptr(
1002
+ do + (bos * H + i_h) * V,
1003
+ (T, V),
1004
+ (H * V, 1),
1005
+ (i_t * BT, 0),
1006
+ (BT, V),
1007
+ (1, 0),
1008
+ )
1009
+ p_l = tl.make_block_ptr(
1010
+ l + (bos * H + i_h) * L + num_intra_levels + ell,
1011
+ (T,),
1012
+ (H * L,),
1013
+ (i_t * BT,),
1014
+ (BT,),
1015
+ (0,),
1016
+ )
1017
+ b_l = tl.load(p_l, boundary_check=(0,))
1018
+ b_g = tl.load(p_g, boundary_check=(0,))
1019
+ b_q = tl.load(p_q, boundary_check=(0, 1))
1020
+ b_q = (b_q * (tl.exp(b_g) * b_l)[None, :]).to(b_q.dtype)
1021
+ b_do = tl.load(p_do, boundary_check=(0, 1))
1022
+
1023
+ b_s = tl.dot(b_q, b_do).to(b_q.dtype)
1024
+ b_dh += b_s
1025
+
1026
+
1027
+ @triton.heuristics({"IS_VARLEN": lambda args: args["cu_seqlens"] is not None})
1028
+ @triton.autotune(
1029
+ configs=[
1030
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
1031
+ for num_warps in [4]
1032
+ for num_stages in [2, 3, 4]
1033
+ ],
1034
+ key=["H", "K", "V"],
1035
+ restore_value=["dq", "dg"],
1036
+ )
1037
+ @triton.jit(do_not_specialize=["T"])
1038
+ def chunkwise_bwd_kernel_hdqgl(
1039
+ do,
1040
+ q,
1041
+ k,
1042
+ v,
1043
+ g,
1044
+ l,
1045
+ h_l,
1046
+ dq,
1047
+ dg,
1048
+ dl,
1049
+ ell,
1050
+ T,
1051
+ cu_seqlens,
1052
+ H: tl.constexpr,
1053
+ K: tl.constexpr,
1054
+ V: tl.constexpr,
1055
+ L: tl.constexpr,
1056
+ BT: tl.constexpr,
1057
+ NT: tl.constexpr,
1058
+ IS_VARLEN: tl.constexpr,
1059
+ ):
1060
+ # parallel over batches and heads
1061
+ i_nh = tl.program_id(0)
1062
+ i_n, i_h = i_nh // H, i_nh % H
1063
+
1064
+ if IS_VARLEN:
1065
+ bos, eos = (
1066
+ tl.load(cu_seqlens + i_n).to(tl.int32),
1067
+ tl.load(cu_seqlens + i_n + 1).to(tl.int32),
1068
+ )
1069
+ T = eos - bos
1070
+ else:
1071
+ bos, eos = i_n * T, i_n * T + T
1072
+
1073
+ b_h = tl.zeros([V, K], dtype=tl.float32)
1074
+
1075
+ num_intra_levels = (tl.log2(float(BT))).to(tl.int32) + 1
1076
+
1077
+ for i_t in range(tl.cdiv(T, BT)):
1078
+ p_g = tl.make_block_ptr(g + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,))
1079
+ if i_t & (1 << ell): # compute and store derivatives
1080
+ p_do = tl.make_block_ptr(
1081
+ do + (bos * H + i_h) * V,
1082
+ (T, V),
1083
+ (H * V, 1),
1084
+ (i_t * BT, 0),
1085
+ (BT, V),
1086
+ (1, 0),
1087
+ )
1088
+ p_q = tl.make_block_ptr(
1089
+ q + bos * K, (T, K), (K, 1), (i_t * BT, 0), (BT, K), (1, 0)
1090
+ )
1091
+ p_l = tl.make_block_ptr(
1092
+ l + (bos * H + i_h) * L + num_intra_levels + ell,
1093
+ (T,),
1094
+ (H * L,),
1095
+ (i_t * BT,),
1096
+ (BT,),
1097
+ (0,),
1098
+ )
1099
+ p_dq = tl.make_block_ptr(
1100
+ dq + (bos * H + i_h) * K,
1101
+ (T, K),
1102
+ (H * K, 1),
1103
+ (i_t * BT, 0),
1104
+ (BT, K),
1105
+ (1, 0),
1106
+ )
1107
+ p_dg = tl.make_block_ptr(
1108
+ dg + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,)
1109
+ )
1110
+ p_dl = tl.make_block_ptr(
1111
+ dl + (bos * H + i_h) * L + num_intra_levels + ell,
1112
+ (T,),
1113
+ (H * L,),
1114
+ (i_t * BT,),
1115
+ (BT,),
1116
+ (0,),
1117
+ )
1118
+ p_h = tl.make_block_ptr(
1119
+ h_l + ((i_n * NT + i_t) * H + i_h) * K * V,
1120
+ (V, K),
1121
+ (1, V),
1122
+ (0, 0),
1123
+ (V, K),
1124
+ (0, 1),
1125
+ )
1126
+
1127
+ b_do = tl.load(p_do, boundary_check=(0, 1))
1128
+ b_q = tl.load(p_q, boundary_check=(0, 1))
1129
+ b_g = tl.load(p_g, boundary_check=(0,))
1130
+ b_l = tl.load(p_l, boundary_check=(0,))
1131
+
1132
+ b_dlq = tl.exp(b_g)[:, None] * tl.dot(b_do, b_h.to(b_do.dtype))
1133
+
1134
+ b_dl = tl.sum(b_dlq * b_q, axis=1)
1135
+ b_dg = b_l * b_dl
1136
+
1137
+ tl.store(p_h, b_h, boundary_check=(0, 1))
1138
+ b_dq_old = tl.load(p_dq, boundary_check=(0, 1))
1139
+ tl.store(
1140
+ p_dq,
1141
+ (b_l[:, None] * b_dlq).to(p_dq.dtype.element_ty) + b_dq_old,
1142
+ boundary_check=(0, 1),
1143
+ )
1144
+ tl.store(p_dl, b_dl.to(p_dl.dtype.element_ty), boundary_check=(0,))
1145
+ b_dg_old = tl.load(p_dg, boundary_check=(0,))
1146
+ tl.store(
1147
+ p_dg, b_dg.to(p_dg.dtype.element_ty) + b_dg_old, boundary_check=(0,)
1148
+ )
1149
+ if ((i_t + 1) & (1 << ell)) == 0:
1150
+ b_h = tl.zeros([V, K], dtype=tl.float32)
1151
+
1152
+ last_idx = min((i_t + 1) * BT, T) - 1
1153
+ b_g_last = tl.load(g + bos * H + last_idx * H + i_h)
1154
+ b_h *= tl.exp(b_g_last)
1155
+ if (i_t & (1 << ell)) == 0: # update the state
1156
+ p_k = tl.make_block_ptr(
1157
+ k + bos * K, (T, K), (K, 1), (i_t * BT, 0), (BT, K), (1, 0)
1158
+ )
1159
+ p_v = tl.make_block_ptr(
1160
+ v + (bos * H + i_h) * V,
1161
+ (V, T),
1162
+ (1, H * V),
1163
+ (0, i_t * BT),
1164
+ (V, BT),
1165
+ (0, 1),
1166
+ )
1167
+ b_g = tl.load(p_g, boundary_check=(0,))
1168
+ b_k = tl.load(p_k, boundary_check=(0, 1))
1169
+ b_v = tl.load(p_v, boundary_check=(0, 1))
1170
+ b_k = (b_k * tl.exp(b_g_last - b_g)[:, None]).to(b_k.dtype)
1171
+ b_h += tl.dot(b_v, b_k)
1172
+
1173
+
1174
+ @triton.heuristics({"IS_VARLEN": lambda args: args["cu_seqlens"] is not None})
1175
+ @triton.autotune(
1176
+ configs=[
1177
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
1178
+ for num_warps in [4]
1179
+ for num_stages in [2, 3, 4]
1180
+ ],
1181
+ key=["H", "K", "V"],
1182
+ restore_value=["dk", "dg", "dg_last"],
1183
+ )
1184
+ @triton.jit(do_not_specialize=["T"])
1185
+ def chunkwise_bwd_kernel_dkg(
1186
+ dh,
1187
+ k,
1188
+ v,
1189
+ g,
1190
+ dg_last,
1191
+ dk,
1192
+ dg,
1193
+ cu_seqlens,
1194
+ T,
1195
+ H: tl.constexpr,
1196
+ K: tl.constexpr,
1197
+ V: tl.constexpr,
1198
+ L: tl.constexpr,
1199
+ BT: tl.constexpr,
1200
+ NT: tl.constexpr,
1201
+ IS_VARLEN: tl.constexpr,
1202
+ ):
1203
+ i_t, i_nh = tl.program_id(0), tl.program_id(1)
1204
+ i_n, i_h = i_nh // H, i_nh % H
1205
+
1206
+ if IS_VARLEN:
1207
+ bos, eos = (
1208
+ tl.load(cu_seqlens + i_n).to(tl.int32),
1209
+ tl.load(cu_seqlens + i_n + 1).to(tl.int32),
1210
+ )
1211
+ T = eos - bos
1212
+ else:
1213
+ bos, eos = i_n * T, i_n * T + T
1214
+
1215
+ o_i = tl.arange(0, BT)
1216
+
1217
+ p_dh = tl.make_block_ptr(
1218
+ dh + ((i_n * NT + i_t) * H + i_h) * K * V,
1219
+ (V, K),
1220
+ (1, V),
1221
+ (0, 0),
1222
+ (V, K),
1223
+ (0, 1),
1224
+ )
1225
+ p_g = tl.make_block_ptr(g + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,))
1226
+ p_k = tl.make_block_ptr(k + bos * K, (T, K), (K, 1), (i_t * BT, 0), (BT, K), (1, 0))
1227
+ p_v = tl.make_block_ptr(
1228
+ v + (bos * H + i_h) * V,
1229
+ (T, V),
1230
+ (H * V, 1),
1231
+ (i_t * BT, 0),
1232
+ (BT, V),
1233
+ (1, 0),
1234
+ )
1235
+ p_dk = tl.make_block_ptr(
1236
+ dk + (bos * H + i_h) * K, (T, K), (H * K, 1), (i_t * BT, 0), (BT, K), (1, 0)
1237
+ )
1238
+ p_dg = tl.make_block_ptr(dg + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,))
1239
+
1240
+ b_dh = tl.load(p_dh, boundary_check=(0, 1))
1241
+ b_g = tl.load(p_g, boundary_check=(0,))
1242
+ b_v = tl.load(p_v, boundary_check=(0, 1))
1243
+ b_k = tl.load(p_k, boundary_check=(0, 1))
1244
+ last_idx = min((i_t + 1) * BT, T) - 1
1245
+ b_g_last = tl.load(g + bos * H + last_idx * H + i_h)
1246
+ p_dg_last = dg_last + i_n * NT * H + i_t * H + i_h
1247
+ b_dg_last = tl.load(p_dg_last)
1248
+
1249
+ b_dg_last *= tl.exp(b_g_last)
1250
+ b_dk = safe_exp(b_g_last - b_g)[:, None] * tl.dot(b_v, b_dh).to(b_v.dtype)
1251
+ b_dg = tl.load(p_dg, boundary_check=(0,))
1252
+ b_dg -= tl.sum(b_k * b_dk, axis=1)
1253
+ b_dg_last += tl.sum(b_dk * b_k)
1254
+
1255
+ b_dg = tl.where(o_i < BT - 1, b_dg, b_dg + b_dg_last)
1256
+
1257
+ tl.store(p_dg, b_dg, boundary_check=(0,))
1258
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
1259
+
1260
+
1261
+ @triton.heuristics({"IS_VARLEN": lambda args: args["cu_seqlens"] is not None})
1262
+ @triton.autotune(
1263
+ configs=[
1264
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
1265
+ for num_warps in [4]
1266
+ for num_stages in [2, 3, 4]
1267
+ ],
1268
+ key=["H", "K", "V"],
1269
+ restore_value=["dv"],
1270
+ )
1271
+ @triton.jit(do_not_specialize=["T"])
1272
+ def chunkwise_bwd_kernel_dv(
1273
+ dh,
1274
+ k,
1275
+ g,
1276
+ dv,
1277
+ T,
1278
+ cu_seqlens,
1279
+ H: tl.constexpr,
1280
+ K: tl.constexpr,
1281
+ V: tl.constexpr,
1282
+ L: tl.constexpr,
1283
+ BT: tl.constexpr,
1284
+ NT: tl.constexpr,
1285
+ IS_VARLEN: tl.constexpr,
1286
+ ):
1287
+ i_t, i_nh = tl.program_id(0), tl.program_id(1)
1288
+ i_n, i_h = i_nh // H, i_nh % H
1289
+
1290
+ if IS_VARLEN:
1291
+ bos, eos = (
1292
+ tl.load(cu_seqlens + i_n).to(tl.int32),
1293
+ tl.load(cu_seqlens + i_n + 1).to(tl.int32),
1294
+ )
1295
+ T = eos - bos
1296
+ else:
1297
+ bos, eos = i_n * T, i_n * T + T
1298
+
1299
+ p_dh = tl.make_block_ptr(
1300
+ dh + ((i_n * NT + i_t) * H + i_h) * K * V,
1301
+ (K, V),
1302
+ (V, 1),
1303
+ (0, 0),
1304
+ (K, V),
1305
+ (1, 0),
1306
+ )
1307
+ p_g = tl.make_block_ptr(g + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,))
1308
+ p_k = tl.make_block_ptr(k + bos * K, (T, K), (K, 1), (i_t * BT, 0), (BT, K), (1, 0))
1309
+ p_dv = tl.make_block_ptr(
1310
+ dv + (bos * H + i_h) * V, (T, V), (H * V, 1), (i_t * BT, 0), (BT, V), (1, 0)
1311
+ )
1312
+
1313
+ last_idx = min((i_t + 1) * BT, T) - 1
1314
+ b_g_last = tl.load(g + bos * H + last_idx * H + i_h)
1315
+
1316
+ b_dh = tl.load(p_dh, boundary_check=(0, 1))
1317
+ b_g = tl.load(p_g, boundary_check=(0,))
1318
+ b_k = tl.load(p_k, boundary_check=(0, 1))
1319
+ b_dv = safe_exp(-b_g + b_g_last)[:, None] * tl.dot(b_k, b_dh).to(b_k.dtype)
1320
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
1321
+
1322
+
1323
+ @triton.heuristics({"IS_VARLEN": lambda args: args["cu_seqlens"] is not None})
1324
+ @triton.autotune(
1325
+ configs=[
1326
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
1327
+ for num_warps in [4]
1328
+ for num_stages in [2, 3, 4]
1329
+ ],
1330
+ key=["H", "K", "V"],
1331
+ restore_value=["dl", "dq", "dk", "dv", "dg"],
1332
+ )
1333
+ @triton.jit(do_not_specialize=["T"])
1334
+ def chunkwise_bwd_kernel_diag(
1335
+ do,
1336
+ q,
1337
+ k,
1338
+ v,
1339
+ g,
1340
+ l,
1341
+ llut,
1342
+ mask,
1343
+ dq,
1344
+ dk,
1345
+ dv,
1346
+ dg,
1347
+ dl,
1348
+ cu_seqlens,
1349
+ T,
1350
+ H: tl.constexpr,
1351
+ K: tl.constexpr,
1352
+ V: tl.constexpr,
1353
+ L: tl.constexpr,
1354
+ BT: tl.constexpr,
1355
+ IS_VARLEN: tl.constexpr,
1356
+ ):
1357
+ p_llut = tl.make_block_ptr(llut, (BT, BT), (BT, 1), (0, 0), (BT, BT), (1, 0))
1358
+ b_llut = tl.load(p_llut, boundary_check=(0, 1))
1359
+ i_t, i_nh = tl.program_id(0), tl.program_id(1)
1360
+ i_n, i_h = i_nh // H, i_nh % H
1361
+
1362
+ if IS_VARLEN:
1363
+ bos, eos = (
1364
+ tl.load(cu_seqlens + i_n).to(tl.int32),
1365
+ tl.load(cu_seqlens + i_n + 1).to(tl.int32),
1366
+ )
1367
+ T = eos - bos
1368
+ else:
1369
+ bos, eos = i_n * T, i_n * T + T
1370
+
1371
+ o_i = tl.arange(0, BT)
1372
+ i_idx = o_i[:, None] # BT x 1
1373
+ j_idx = o_i[None, :] # 1 x BT
1374
+
1375
+ b_h_ptrs = l + ((bos + i_t * BT + i_idx) * H + i_h) * L + b_llut
1376
+ b_h = tl.load(b_h_ptrs, mask=i_idx >= j_idx)
1377
+
1378
+ p_g = tl.make_block_ptr(g + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,))
1379
+ p_q = tl.make_block_ptr(q + bos * K, (K, T), (1, K), (0, i_t * BT), (K, BT), (0, 1))
1380
+ p_k = tl.make_block_ptr(k + bos * K, (T, K), (K, 1), (i_t * BT, 0), (BT, K), (1, 0))
1381
+ p_v = tl.make_block_ptr(
1382
+ v + (bos * H + i_h) * V, (V, T), (1, H * V), (0, i_t * BT), (V, BT), (0, 1)
1383
+ )
1384
+ p_do = tl.make_block_ptr(
1385
+ do + (bos * H + i_h) * V, (T, V), (H * V, 1), (i_t * BT, 0), (BT, V), (1, 0)
1386
+ )
1387
+ p_dg = tl.make_block_ptr(dg + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,))
1388
+ p_dq = tl.make_block_ptr(
1389
+ dq + (bos * H + i_h) * K, (T, K), (H * K, 1), (i_t * BT, 0), (BT, K), (1, 0)
1390
+ )
1391
+ p_dk = tl.make_block_ptr(
1392
+ dk + (bos * H + i_h) * K, (T, K), (H * K, 1), (i_t * BT, 0), (BT, K), (1, 0)
1393
+ )
1394
+ p_dv = tl.make_block_ptr(
1395
+ dv + (bos * H + i_h) * V, (T, V), (H * V, 1), (i_t * BT, 0), (BT, V), (1, 0)
1396
+ )
1397
+
1398
+ b_g = tl.load(p_g, boundary_check=(0,))
1399
+ b_q = tl.load(p_q, boundary_check=(0, 1))
1400
+ b_k = tl.load(p_k, boundary_check=(0, 1))
1401
+ b_v = tl.load(p_v, boundary_check=(0, 1))
1402
+ b_do = tl.load(p_do, boundary_check=(0, 1))
1403
+ b_dq = tl.load(p_dq, boundary_check=(0, 1))
1404
+ b_dk = tl.load(p_dk, boundary_check=(0, 1))
1405
+ b_dv = tl.load(p_dv, boundary_check=(0, 1))
1406
+ b_dg = tl.load(p_dg, boundary_check=(0,))
1407
+
1408
+ b_s = (tl.dot(b_k, b_q)).to(b_q.dtype)
1409
+ b_a = safe_exp(b_g[:, None] - b_g[None, :])
1410
+ b_dv += tl.dot((b_s * tl.trans(b_a * b_h)).to(b_do.dtype), b_do)
1411
+ b_ds = tl.dot(b_do, b_v) * b_a
1412
+ b_dl = b_ds * tl.trans(b_s)
1413
+ b_dg += tl.sum(b_dl * b_h, axis=1)
1414
+ b_dg -= tl.sum(b_dl * b_h, axis=0)
1415
+ b_ds = (b_ds * b_h).to(b_k.dtype)
1416
+ b_dq += tl.dot(b_ds, b_k)
1417
+ b_dk += tl.trans(tl.dot(b_q, b_ds))
1418
+
1419
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
1420
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
1421
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
1422
+ tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0,))
1423
+
1424
+ num_intra_levels = (tl.log2(float(BT))).to(tl.int32) + 1
1425
+
1426
+ for i in range(num_intra_levels):
1427
+ p_mask = tl.make_block_ptr(mask + i * (BT * BT), (BT, BT), (BT, 1), (0, 0), (BT, BT), (1, 0))
1428
+ b_mask = tl.load(p_mask, boundary_check=(0, 1))
1429
+ dl_i = tl.sum(tl.where(b_mask == 1, b_dl, 0), axis=1)
1430
+ p_dl_i = tl.make_block_ptr(dl + (bos * H + i_h) * L + i, (T,), (H * L,), (i_t * BT,), (BT,), (0,))
1431
+ tl.store(p_dl_i, dl_i, boundary_check=(0,))
1432
+
1433
+
1434
+ def construct_binary_level_mask(level, T):
1435
+ if level == 0:
1436
+ return torch.diag(torch.ones(T, dtype=torch.bool))
1437
+
1438
+ indices = torch.cartesian_prod(torch.arange(T), torch.arange(T))
1439
+
1440
+ mask = torch.where(
1441
+ torch.logical_and(
1442
+ torch.logical_and(
1443
+ indices[:, 0] % (1 << level) >= (1 << (level - 1)),
1444
+ indices[:, 1] + (1 << (level - 1))
1445
+ >= indices[:, 0] - (indices[:, 0] % (1 << (level - 1))),
1446
+ ),
1447
+ indices[:, 1] < indices[:, 0] - (indices[:, 0] % (1 << (level - 1))),
1448
+ ).view(T, T),
1449
+ 1,
1450
+ 0,
1451
+ )
1452
+
1453
+ return mask
1454
+
1455
+
1456
+ def level_lut(BT, device):
1457
+ lut = torch.zeros((BT, BT), dtype=torch.int32, device=device)
1458
+ for level in range(1, ceil_log(BT, 2) + 1):
1459
+ mask = construct_binary_level_mask(level, BT).to(device)
1460
+ lut = torch.where(mask.to(torch.bool), level, lut)
1461
+ return lut
1462
+
1463
+
1464
+ def masks(BT, device):
1465
+ masks = []
1466
+ for level in range(0, ceil_log(BT, 2) + 1):
1467
+ mask = construct_binary_level_mask(level, BT).to(device).to(torch.int32)
1468
+ masks.append(mask)
1469
+ return torch.stack(masks)
1470
+
1471
+
1472
+ def ceil_div(x: int, y: int) -> int:
1473
+ return math.ceil(x / y)
1474
+
1475
+
1476
+ def ceil_log(x: int, b: int) -> int:
1477
+ return math.ceil(math.log(x, b))
1478
+
1479
+
1480
+ @dataclass
1481
+ class LogLinearAttentionState:
1482
+ ht: torch.Tensor
1483
+ offsets: torch.Tensor
1484
+ q_prev: torch.Tensor
1485
+ k_prev: torch.Tensor
1486
+ v_prev: torch.Tensor
1487
+ g_prev: torch.Tensor
1488
+ level_scales_prev: torch.Tensor
1489
+
1490
+
1491
+ class ChunkLogLinearAttentionFunction(torch.autograd.Function):
1492
+
1493
+ @staticmethod
1494
+ @input_guard
1495
+ @autocast_custom_fwd
1496
+ def forward(
1497
+ ctx,
1498
+ q,
1499
+ k,
1500
+ v,
1501
+ g,
1502
+ level_scales,
1503
+ initial_state,
1504
+ output_final_state,
1505
+ cu_seqlens,
1506
+ ):
1507
+ B, T, G, K = k.shape
1508
+ _, _, H, V = v.shape
1509
+ _, _, _, L = level_scales.shape
1510
+
1511
+ if G != 1:
1512
+ raise ValueError("Group dimension must be 1.")
1513
+
1514
+ if not math.log2(V).is_integer():
1515
+ raise ValueError(
1516
+ "Head dimension must be a power of two. Please pad the head dimension to the next power of two."
1517
+ )
1518
+
1519
+ if K % BLOCK_K != 0:
1520
+ raise ValueError(f"State dimension must be divisible by {BLOCK_K}.")
1521
+
1522
+ if triton.__version__ > "3.2.0":
1523
+ warnings.warn("Triton>3.2.0 detected, which is known to have worse performance. "
1524
+ "For optimal performance, it is recommended to install Triton==3.2.0 (if possible).")
1525
+
1526
+ BT = 64 # chunk size
1527
+
1528
+ h0 = initial_state.ht if initial_state is not None else None
1529
+ offsets = initial_state.offsets if initial_state is not None else None
1530
+
1531
+ if cu_seqlens is None:
1532
+ NT = ceil_div(T + (torch.max(offsets) if offsets is not None else 0), BT)
1533
+ MAX_LEVEL = ceil_log(NT, 2) - 1
1534
+ else:
1535
+ NT = max(
1536
+ [
1537
+ ceil_div(
1538
+ cu_seqlens[i + 1]
1539
+ - cu_seqlens[i]
1540
+ + (offsets[i] if offsets is not None else 0),
1541
+ BT,
1542
+ )
1543
+ for i in range(len(cu_seqlens) - 1)
1544
+ ]
1545
+ )
1546
+ MAX_LEVEL = ceil_log(NT, 2) - 1
1547
+ B = len(cu_seqlens) - 1
1548
+
1549
+ if MAX_LEVEL > 10:
1550
+ raise ValueError("Sequence length must be less than 2**17")
1551
+
1552
+ S0 = B if cu_seqlens is None else 1
1553
+ o = torch.zeros(
1554
+ (S0, T, H, (K // BLOCK_K), V),
1555
+ dtype=v.dtype,
1556
+ device=v.device,
1557
+ )
1558
+
1559
+ if initial_state is not None:
1560
+ if cu_seqlens is not None:
1561
+ cu_seqlens = cu_seqlens + F.pad(torch.cumsum(offsets % BT), (1, 0))
1562
+ else:
1563
+ assert (offsets == offsets[0]).all()
1564
+ T += offsets[0].item() % BT
1565
+ S1 = cu_seqlens[-1] if cu_seqlens is not None else T
1566
+ q_new = torch.zeros((S0, S1, G, K), dtype=q.dtype, device=q.device)
1567
+ k_new = torch.zeros((S0, S1, G, K), dtype=k.dtype, device=k.device)
1568
+ v_new = torch.zeros((S0, S1, H, V), dtype=v.dtype, device=v.device)
1569
+ g_new = torch.zeros((S0, S1, H), dtype=g.dtype, device=g.device)
1570
+ level_scales_new = torch.zeros((S0, S1, H, L), dtype=level_scales.dtype, device=level_scales.device)
1571
+
1572
+ copy_input_kernel[(B * H,)](
1573
+ q=q,
1574
+ k=k,
1575
+ v=v,
1576
+ g=g,
1577
+ level_scales=level_scales,
1578
+ cu_seqlens=cu_seqlens,
1579
+ q_prev=initial_state.q_prev,
1580
+ k_prev=initial_state.k_prev,
1581
+ v_prev=initial_state.v_prev,
1582
+ g_prev=initial_state.g_prev,
1583
+ level_scales_prev=initial_state.level_scales_prev,
1584
+ q_new=q_new,
1585
+ k_new=k_new,
1586
+ v_new=v_new,
1587
+ g_new=g_new,
1588
+ level_scales_new=level_scales_new,
1589
+ offsets=offsets,
1590
+ T=T,
1591
+ H=H,
1592
+ K=K,
1593
+ V=V,
1594
+ L=L,
1595
+ BT=BT,
1596
+ )
1597
+ q = q_new
1598
+ k = k_new
1599
+ v = v_new
1600
+ g = g_new
1601
+ level_scales = level_scales_new
1602
+
1603
+ # Store one extra level (MAX_LEVEL + 2) in case the length is multiple of 2
1604
+ ht = (
1605
+ torch.zeros((B, MAX_LEVEL + 2, H, K, V), dtype=torch.float, device=v.device)
1606
+ if output_final_state
1607
+ else None
1608
+ )
1609
+
1610
+ new_offsets = torch.zeros((B,), dtype=torch.int32, device=v.device)
1611
+ g = chunk_local_cumsum(g, chunk_size=BT, cu_seqlens=cu_seqlens)
1612
+
1613
+ def grid(meta):
1614
+ return (triton.cdiv(K, meta["BK"]), B * H)
1615
+
1616
+ l_in = h0.shape[1] if initial_state is not None else None
1617
+ l_out = ht.shape[1] if output_final_state else None
1618
+
1619
+ ctx.llut = level_lut(BT, v.device)
1620
+
1621
+ chunkwise_fwd_kernel[grid](
1622
+ q=q,
1623
+ k=k,
1624
+ v=v,
1625
+ g=g,
1626
+ level_scales=level_scales,
1627
+ llut=ctx.llut,
1628
+ o=o,
1629
+ h0=h0,
1630
+ ht=ht,
1631
+ offsets=offsets,
1632
+ new_offsets=new_offsets,
1633
+ cu_seqlens=cu_seqlens,
1634
+ T=T,
1635
+ H=H,
1636
+ K=K,
1637
+ V=V,
1638
+ L=L,
1639
+ BT=BT,
1640
+ L_IN=l_in,
1641
+ L_OUT=l_out,
1642
+ MIN_LEVEL=0,
1643
+ MAX_LEVEL=MAX_LEVEL,
1644
+ )
1645
+
1646
+ ctx.save_for_backward(q, k, v, g, level_scales, initial_state, cu_seqlens)
1647
+ ctx.chunk_size = BT
1648
+
1649
+ if output_final_state:
1650
+ q_prev = torch.zeros((B, BT, G, K), dtype=q.dtype, device=q.device)
1651
+ k_prev = torch.zeros((B, BT, G, K), dtype=k.dtype, device=k.device)
1652
+ v_prev = torch.zeros((B, BT, H, V), dtype=v.dtype, device=v.device)
1653
+ g_prev = torch.zeros((B, BT, H), dtype=g.dtype, device=g.device)
1654
+ level_scales_prev = torch.zeros((B, BT, H, L), dtype=level_scales.dtype, device=level_scales.device)
1655
+
1656
+ copy_last_chunk_kernel[(B * H,)](
1657
+ q=q,
1658
+ k=k,
1659
+ v=v,
1660
+ g=g,
1661
+ level_scales=level_scales,
1662
+ cu_seqlens=cu_seqlens,
1663
+ q_prev=q_prev,
1664
+ k_prev=k_prev,
1665
+ v_prev=v_prev,
1666
+ g_prev=g_prev,
1667
+ level_scales_prev=level_scales_prev,
1668
+ offsets=new_offsets,
1669
+ T=T,
1670
+ H=H,
1671
+ K=K,
1672
+ V=V,
1673
+ L=L,
1674
+ BT=BT,
1675
+ )
1676
+
1677
+ final_state = LogLinearAttentionState(
1678
+ ht=ht,
1679
+ offsets=new_offsets,
1680
+ q_prev=q_prev,
1681
+ k_prev=k_prev,
1682
+ v_prev=v_prev,
1683
+ g_prev=g_prev,
1684
+ level_scales_prev=level_scales_prev,
1685
+ )
1686
+ return o.sum(dim=-2), final_state
1687
+
1688
+ return o.sum(dim=-2), None
1689
+
1690
+ @staticmethod
1691
+ @input_guard
1692
+ @autocast_custom_bwd
1693
+ def backward(ctx, do, dht):
1694
+ if triton.__version__ < "3.1.0":
1695
+ raise ValueError("Triton>=3.1.0 is required")
1696
+
1697
+ q, k, v, g, level_scales, initial_state, cu_seqlens = ctx.saved_tensors
1698
+ chunk_size = ctx.chunk_size
1699
+ llut = ctx.llut
1700
+ mask = masks(chunk_size, v.device)
1701
+
1702
+ if initial_state is not None:
1703
+ raise NotImplementedError(
1704
+ "Backward pass is not implemented for log-linear attention with a prefilled kernel."
1705
+ )
1706
+
1707
+ B, T, G, K = k.shape
1708
+ assert G == 1, "Multi-head attention is not supported"
1709
+ _, _, H, V = v.shape
1710
+ _, _, _, L = level_scales.shape
1711
+ BT = chunk_size
1712
+ if cu_seqlens is not None:
1713
+ NT = max(
1714
+ [
1715
+ ceil_div(cu_seqlens[i + 1] - cu_seqlens[i], BT)
1716
+ for i in range(len(cu_seqlens) - 1)
1717
+ ]
1718
+ )
1719
+ else:
1720
+ NT = ceil_div(T, BT)
1721
+
1722
+ if cu_seqlens is not None:
1723
+ B = len(cu_seqlens) - 1
1724
+
1725
+ dh = torch.zeros((B, NT, H, K, V), dtype=v.dtype, device=v.device)
1726
+ dq = torch.zeros((B if cu_seqlens is None else 1, T, H, K), dtype=v.dtype, device=v.device)
1727
+ dk = torch.zeros((B if cu_seqlens is None else 1, T, H, K), dtype=v.dtype, device=v.device)
1728
+ dv = torch.zeros_like(v)
1729
+ dg = torch.zeros(g.shape, dtype=torch.float, device=v.device)
1730
+ dl = torch.zeros(level_scales.shape, dtype=torch.float, device=v.device)
1731
+ h_l = torch.zeros((B, NT, H, K, V), dtype=torch.float, device=v.device)
1732
+ dg_last = torch.zeros((B, NT, H), dtype=torch.float, device=v.device)
1733
+ do = do.to(v.dtype)
1734
+
1735
+ grid = (B * H,)
1736
+
1737
+ def grid_f(meta):
1738
+ return (triton.cdiv(K, meta["BK"]), B * H)
1739
+
1740
+ grid_t = (NT, B * H)
1741
+
1742
+ num_inter_chunk_levels = ceil_log(NT, 2)
1743
+ for ell in range(num_inter_chunk_levels - 1, -1, -1):
1744
+ chunkwise_bwd_kernel_hdqgl[grid](
1745
+ do=do,
1746
+ q=q,
1747
+ k=k,
1748
+ v=v,
1749
+ g=g,
1750
+ l=level_scales,
1751
+ h_l=h_l,
1752
+ dq=dq,
1753
+ dg=dg,
1754
+ dl=dl,
1755
+ cu_seqlens=cu_seqlens,
1756
+ ell=ell,
1757
+ T=T,
1758
+ H=H,
1759
+ K=K,
1760
+ V=V,
1761
+ L=L,
1762
+ BT=BT,
1763
+ NT=NT,
1764
+ )
1765
+ chunkwise_bwd_kernel_dhg[grid_f](
1766
+ do=do,
1767
+ q=q,
1768
+ g=g,
1769
+ l=level_scales,
1770
+ h_l=h_l,
1771
+ dh=dh,
1772
+ dg_last=dg_last,
1773
+ cu_seqlens=cu_seqlens,
1774
+ ell=ell,
1775
+ T=T,
1776
+ H=H,
1777
+ K=K,
1778
+ V=V,
1779
+ L=L,
1780
+ BT=BT,
1781
+ NT=NT,
1782
+ )
1783
+
1784
+ chunkwise_bwd_kernel_dkg[grid_t](
1785
+ dh=dh,
1786
+ k=k,
1787
+ v=v,
1788
+ g=g,
1789
+ dg_last=dg_last,
1790
+ dk=dk,
1791
+ dg=dg,
1792
+ cu_seqlens=cu_seqlens,
1793
+ T=T,
1794
+ H=H,
1795
+ K=K,
1796
+ V=V,
1797
+ L=L,
1798
+ BT=BT,
1799
+ NT=NT,
1800
+ )
1801
+
1802
+ chunkwise_bwd_kernel_dv[grid_t](
1803
+ dh=dh,
1804
+ k=k,
1805
+ g=g,
1806
+ dv=dv,
1807
+ cu_seqlens=cu_seqlens,
1808
+ T=T,
1809
+ H=H,
1810
+ K=K,
1811
+ V=V,
1812
+ L=L,
1813
+ BT=BT,
1814
+ NT=NT,
1815
+ )
1816
+
1817
+ chunkwise_bwd_kernel_diag[grid_t](
1818
+ do=do,
1819
+ q=q,
1820
+ k=k,
1821
+ v=v,
1822
+ g=g,
1823
+ l=level_scales,
1824
+ llut=llut,
1825
+ mask=mask,
1826
+ dq=dq,
1827
+ dk=dk,
1828
+ dv=dv,
1829
+ dg=dg,
1830
+ dl=dl,
1831
+ cu_seqlens=cu_seqlens,
1832
+ T=T,
1833
+ H=H,
1834
+ K=K,
1835
+ V=V,
1836
+ L=L,
1837
+ BT=BT,
1838
+ )
1839
+
1840
+ dg = chunk_local_cumsum(dg, chunk_size=chunk_size, reverse=True, cu_seqlens=cu_seqlens).to(g.dtype)
1841
+
1842
+ dq = reduce(dq, "b t (g h) k -> b t g k", "sum", g=G, h=H // G)
1843
+ dk = reduce(dk, "b t (g h) k -> b t g k", "sum", g=G, h=H // G)
1844
+ return dq, dk, dv, dg, dl, None, None, None
1845
+
1846
+
1847
+ @torch.compiler.disable
1848
+ def chunk_log_linear_attn(
1849
+ q: torch.Tensor,
1850
+ k: torch.Tensor,
1851
+ v: torch.Tensor,
1852
+ g: torch.Tensor,
1853
+ level_scales: torch.Tensor,
1854
+ initial_state: Optional[LogLinearAttentionState] = None,
1855
+ output_final_state: bool = False,
1856
+ cu_seqlens: Optional[torch.LongTensor] = None,
1857
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
1858
+ r"""
1859
+ Args:
1860
+ q (torch.Tensor):
1861
+ queries of shape `[B, T, H, K]`.
1862
+ k (torch.Tensor):
1863
+ keys of shape `[B, T, H, K]`.
1864
+ v (torch.Tensor):
1865
+ values of shape `[B, T, H, V]`.
1866
+ g (torch.Tensor):
1867
+ Forget gates of shape `[B, T, H]`.
1868
+ level_scales (torch.Tensor):
1869
+ Scales for each level of shape `[B, T, H, L]`.
1870
+ initial_state (Optional[LogLinearAttentionState]):
1871
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
1872
+ For equal-length input sequences, `N` equals the batch size `B`.
1873
+ Default: `None`.
1874
+ output_final_state (Optional[bool]):
1875
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
1876
+ cu_seqlens (torch.LongTensor):
1877
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
1878
+ consistent with the FlashAttention API.
1879
+
1880
+ Returns:
1881
+ o (torch.Tensor):
1882
+ Outputs of shape `[B, T, H, V]`.
1883
+ final_state (torch.Tensor):
1884
+ Final state of type `LogLinearAttentionState` if `output_final_state=True` else `None`.
1885
+
1886
+ """
1887
+ if cu_seqlens is not None:
1888
+ if q.shape[0] != 1:
1889
+ raise ValueError(
1890
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
1891
+ f"Please flatten variable-length inputs before processing."
1892
+ )
1893
+
1894
+ o, final_state = ChunkLogLinearAttentionFunction.apply(
1895
+ q,
1896
+ k,
1897
+ v,
1898
+ g,
1899
+ level_scales,
1900
+ initial_state,
1901
+ output_final_state,
1902
+ cu_seqlens,
1903
+ )
1904
+ return o, final_state