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,629 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from typing import Optional, Tuple
5
+
6
+ import torch
7
+ import triton
8
+ import triton.language as tl
9
+
10
+ from fla.ops.utils import chunk_local_cumsum
11
+ from fla.ops.utils.op import exp
12
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, check_shared_mem, input_guard, is_nvidia_hopper
13
+
14
+ BKV_LIST = [64, 128] if check_shared_mem() else [32, 64]
15
+ NUM_WARPS = [2, 4] if is_nvidia_hopper else [2, 4, 8]
16
+
17
+
18
+ @triton.heuristics({
19
+ 'USE_G': lambda args: args['g'] is not None,
20
+ 'USE_G_GAMMA': lambda args: args['g_gamma'] is not None,
21
+ 'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
22
+ 'STORE_FINAL_STATE': lambda args: args['ht'] is not None,
23
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
24
+ })
25
+ @triton.autotune(
26
+ configs=[
27
+ triton.Config({'BV': BV}, num_warps=num_warps, num_stages=num_stages)
28
+ for BV in BKV_LIST
29
+ for num_warps in NUM_WARPS
30
+ for num_stages in [2, 3, 4]
31
+ ],
32
+ key=['H', 'K', 'V', 'BT'],
33
+ )
34
+ @triton.jit(do_not_specialize=['T'])
35
+ def fused_chunk_fwd_kernel(
36
+ q,
37
+ k,
38
+ v,
39
+ g,
40
+ g_gamma,
41
+ o,
42
+ h0,
43
+ ht,
44
+ cu_seqlens,
45
+ scale,
46
+ T,
47
+ B: tl.constexpr,
48
+ H: tl.constexpr,
49
+ K: tl.constexpr,
50
+ V: tl.constexpr,
51
+ BT: tl.constexpr,
52
+ BK: tl.constexpr,
53
+ BV: tl.constexpr,
54
+ USE_G: tl.constexpr,
55
+ USE_G_GAMMA: tl.constexpr,
56
+ USE_INITIAL_STATE: tl.constexpr,
57
+ STORE_FINAL_STATE: tl.constexpr,
58
+ IS_VARLEN: tl.constexpr,
59
+ ):
60
+ i_v, i_k, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
61
+ i_n, i_h = i_nh // H, i_nh % H
62
+
63
+ all = B * T
64
+ if IS_VARLEN:
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
+ else:
68
+ bos, eos = i_n * T, i_n * T + T
69
+ NT = tl.cdiv(T, BT)
70
+
71
+ o_i = tl.arange(0, BT)
72
+
73
+ if USE_G_GAMMA:
74
+ # decay rate given the head index
75
+ b_gamma = tl.load(g_gamma + i_h)
76
+ b_g = b_gamma * (o_i + 1)
77
+ b_g_last = b_gamma * BT
78
+ b_gq = exp(b_g)
79
+ b_gk = exp(b_g_last - b_g)
80
+ b_gn = exp(b_g_last)
81
+
82
+ # [BT, BT]
83
+ m_s = o_i[:, None] >= o_i[None, :]
84
+
85
+ q = q + (bos*H + i_h) * K
86
+ k = k + (bos*H + i_h) * K
87
+ v = v + (bos*H + i_h) * V
88
+ o = o + (i_k * all + bos).to(tl.int64) * H*V + i_h * V
89
+
90
+ # [BK, BV]
91
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
92
+ if USE_INITIAL_STATE:
93
+ p_h = tl.make_block_ptr(h0 + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
94
+ b_h = tl.load(p_h, boundary_check=(0, 1)).to(tl.float32)
95
+
96
+ for i_t in range(0, NT):
97
+ p_q = tl.make_block_ptr(q, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
98
+ p_k = tl.make_block_ptr(k, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
99
+ p_v = tl.make_block_ptr(v, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
100
+ p_o = tl.make_block_ptr(o, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
101
+
102
+ o_t = i_t * BT + tl.arange(0, BT)
103
+ m_t = o_t < T
104
+ # [BT, BK]
105
+ b_q = tl.load(p_q, boundary_check=(0, 1))
106
+ b_q = (b_q * scale).to(b_q.dtype)
107
+ # [BK, BT]
108
+ b_k = tl.load(p_k, boundary_check=(0, 1))
109
+ # [BT, BV]
110
+ b_v = tl.load(p_v, boundary_check=(0, 1))
111
+ last_idx = min(i_t * BT + BT, T) - 1
112
+
113
+ # [BT, BT]
114
+ b_s = tl.dot(b_q, b_k)
115
+
116
+ # scalar decay
117
+ if USE_G:
118
+ p_g = g + (bos + o_t) * H + i_h
119
+ b_g = tl.load(p_g, mask=(o_t < T), other=0.)
120
+ b_g_last = tl.load(g + (bos + last_idx) * H + i_h)
121
+
122
+ b_gq = exp(b_g)
123
+ b_gk = exp(b_g_last - b_g)
124
+ b_gn = exp(b_g_last)
125
+ if USE_G_GAMMA:
126
+ b_g_last = b_gamma * min(BT, T - i_t * BT)
127
+ b_gk = exp(b_g_last - b_g)
128
+ b_gn = exp(b_g_last)
129
+ if USE_G or USE_G_GAMMA:
130
+ b_gs = tl.where(m_s & m_t, exp(b_g[:, None] - b_g[None, :]), 0)
131
+ # [BT, BT]
132
+ b_s *= b_gs
133
+ # [BT, BV]
134
+ b_o = tl.dot(b_s.to(b_q.dtype), b_v) + tl.dot(b_q, b_h.to(b_q.dtype)) * b_gq[:, None]
135
+ b_v = (b_v * b_gk[:, None]).to(b_v.dtype)
136
+ b_h *= b_gn
137
+ else:
138
+ # [BT, BT]
139
+ b_s *= m_s & m_t
140
+ # [BT, BV]
141
+ b_o = tl.dot(b_s.to(b_q.dtype), b_v) + tl.dot(b_q, b_h.to(b_q.dtype))
142
+
143
+ b_h += tl.dot(b_k, b_v)
144
+
145
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1))
146
+
147
+ if STORE_FINAL_STATE:
148
+ p_ht = tl.make_block_ptr(ht + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
149
+ tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
150
+
151
+
152
+ @triton.heuristics({
153
+ 'USE_G': lambda args: args['g'] is not None,
154
+ 'USE_G_GAMMA': lambda args: args['g_gamma'] is not None,
155
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
156
+ 'USE_INITIAL_STATE': lambda args: args['dh0'] is not None,
157
+ 'USE_FINAL_STATE': lambda args: args['dht'] is not None,
158
+ })
159
+ @triton.autotune(
160
+ configs=[
161
+ triton.Config({}, num_warps=num_warps, num_stages=num_stages)
162
+ for num_warps in NUM_WARPS
163
+ for num_stages in [2, 3, 4]
164
+ ],
165
+ key=['H', 'K', 'V', 'BT'],
166
+ )
167
+ @triton.jit(do_not_specialize=['T'])
168
+ def fused_chunk_bwd_kernel(
169
+ q,
170
+ k,
171
+ v,
172
+ g,
173
+ g_gamma,
174
+ do,
175
+ dq,
176
+ dk,
177
+ dv,
178
+ dg,
179
+ h0,
180
+ dht,
181
+ dh0,
182
+ cu_seqlens,
183
+ scale,
184
+ T,
185
+ B: tl.constexpr,
186
+ H: tl.constexpr,
187
+ K: tl.constexpr,
188
+ V: tl.constexpr,
189
+ BT: tl.constexpr,
190
+ BK: tl.constexpr,
191
+ BV: tl.constexpr,
192
+ USE_G: tl.constexpr,
193
+ USE_G_GAMMA: tl.constexpr,
194
+ IS_VARLEN: tl.constexpr,
195
+ USE_INITIAL_STATE: tl.constexpr,
196
+ USE_FINAL_STATE: tl.constexpr,
197
+ ):
198
+ i_v, i_k, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
199
+ i_n, i_h = i_nh // H, i_nh % H
200
+
201
+ all = B * T
202
+ if IS_VARLEN:
203
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
204
+ T = eos - bos
205
+ else:
206
+ bos, eos = i_n * T, i_n * T + T
207
+ NT = tl.cdiv(T, BT)
208
+ NV = tl.cdiv(V, BV)
209
+
210
+ o_i = tl.arange(0, BT)
211
+ if USE_G_GAMMA:
212
+ b_gamma = tl.load(g_gamma + i_h)
213
+ b_g = b_gamma * (o_i + 1)
214
+ b_g_last = b_gamma * BT
215
+ b_gq = exp(b_g)
216
+ b_gk = exp(b_g_last - b_g)
217
+ b_gn = exp(b_g_last)
218
+
219
+ m_s = o_i[:, None] >= o_i[None, :]
220
+
221
+ q = q + (bos*H + i_h) * K
222
+ k = k + (bos*H + i_h) * K
223
+ v = v + (bos*H + i_h) * V
224
+ do = do + (bos*H + i_h) * V
225
+ dq = dq + (i_v * all + bos).to(tl.int64) * H*K + i_h * K
226
+ dk = dk + (i_v * all + bos).to(tl.int64) * H*K + i_h * K
227
+ dv = dv + (i_k * all + bos).to(tl.int64) * H*V + i_h * V
228
+
229
+ # [BV, BK]
230
+ b_h = tl.zeros([BV, BK], dtype=tl.float32)
231
+ if USE_INITIAL_STATE:
232
+ p_h = tl.make_block_ptr(h0 + i_nh * K*V, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
233
+ b_h = tl.load(p_h, boundary_check=(0, 1)).to(tl.float32)
234
+
235
+ for i_t in range(0, NT):
236
+ p_q = tl.make_block_ptr(q, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
237
+ p_k = tl.make_block_ptr(k, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
238
+ p_v = tl.make_block_ptr(v, (V, T), (1, H*V), (i_v * BV, i_t * BT), (BV, BT), (0, 1))
239
+ p_do = tl.make_block_ptr(do, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
240
+ p_dq = tl.make_block_ptr(dq, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
241
+
242
+ o_t = i_t * BT + tl.arange(0, BT)
243
+ m_t = o_t < T
244
+ # [BT, BK]
245
+ b_k = tl.load(p_k, boundary_check=(0, 1))
246
+ # [BV, BT]
247
+ b_v = tl.load(p_v, boundary_check=(0, 1))
248
+ # [BT, BV]
249
+ b_do = tl.load(p_do, boundary_check=(0, 1))
250
+ last_idx = min(i_t * BT + BT, T) - 1
251
+
252
+ # [BT, BT]
253
+ b_ds = tl.dot(b_do, b_v) * scale
254
+
255
+ # scalar decay
256
+ if USE_G:
257
+ p_g = g + (bos + o_t) * H + i_h
258
+ b_g = tl.load(p_g, mask=(o_t < T), other=0.)
259
+ b_g_last = tl.load(g + (bos + last_idx) * H + i_h)
260
+
261
+ b_gq = exp(b_g)
262
+ b_gk = exp(b_g_last - b_g)
263
+ b_gn = exp(b_g_last)
264
+
265
+ p_dg = dg + ((i_k * NV + i_v) * all + (bos + o_t)).to(tl.int64) * H + i_h
266
+ # [BT, BT]
267
+ b_gs = tl.where(m_s & m_t, exp(b_g[:, None] - b_g[None, :]), 0)
268
+ b_ds = b_ds * b_gs
269
+ # [BT, BK]
270
+ b_q = tl.load(p_q, boundary_check=(0, 1))
271
+ b_dq = tl.dot(b_ds.to(b_k.dtype), b_k) + tl.dot((b_do * b_gq[:, None] * scale).to(b_k.dtype), b_h.to(b_k.dtype))
272
+ # [BT]
273
+ b_dg_t = tl.sum(b_q * b_dq, 1)
274
+ tl.store(p_dg, b_dg_t.to(p_dg.dtype.element_ty), mask=m_t)
275
+ # [BV, BK]
276
+ b_h = b_h * b_gn + tl.dot(b_v, (b_k * b_gk[:, None]).to(b_k.dtype))
277
+
278
+ elif USE_G_GAMMA:
279
+ b_g_last = b_gamma * min(BT, T - i_t * BT)
280
+ b_gk = exp(b_g_last - b_g)
281
+ b_gn = exp(b_g_last)
282
+
283
+ # [BT, BT]
284
+ b_gs = tl.where(m_s & m_t, exp(b_g[:, None] - b_g[None, :]), 0)
285
+ b_ds = b_ds * b_gs
286
+ # [BT, BK]
287
+ b_q = tl.load(p_q, boundary_check=(0, 1))
288
+ b_dq = tl.dot(b_ds.to(b_k.dtype), b_k) + tl.dot((b_do * b_gq[:, None] * scale).to(b_k.dtype), b_h.to(b_k.dtype))
289
+ # [BV, BK]
290
+ b_h = b_h * b_gn + tl.dot(b_v, (b_k * b_gk[:, None]).to(b_k.dtype))
291
+
292
+ else:
293
+ # [BT, BT]
294
+ b_ds *= m_s & m_t
295
+ # [BT, BK]
296
+ b_dq = tl.dot(b_ds.to(b_k.dtype), b_k) + tl.dot((b_do * scale).to(b_k.dtype), b_h.to(b_k.dtype))
297
+ # [BV, BK]
298
+ b_h += tl.dot(b_v, b_k)
299
+
300
+ tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
301
+
302
+ # [BK, BV]
303
+ b_dh = tl.zeros([BK, BV], dtype=tl.float32)
304
+ if USE_FINAL_STATE:
305
+ p_dh = tl.make_block_ptr(dht + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
306
+ b_dh += tl.load(p_dh, boundary_check=(0, 1)).to(tl.float32)
307
+
308
+ if USE_G:
309
+ b_dg = tl.zeros([BT,], dtype=tl.float32)
310
+ b_dg_last = tl.sum(tl.trans(b_h) * b_dh)
311
+
312
+ # sync threads
313
+ b_h = None
314
+ tl.debug_barrier()
315
+
316
+ for i_t in range(NT - 1, -1, -1):
317
+ p_q = tl.make_block_ptr(q, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
318
+ p_k = tl.make_block_ptr(k, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
319
+ p_v = tl.make_block_ptr(v, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
320
+ p_do = tl.make_block_ptr(do, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
321
+ p_dk = tl.make_block_ptr(dk, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
322
+ p_dv = tl.make_block_ptr(dv, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
323
+ # [BK, BT]
324
+ b_q = tl.load(p_q, boundary_check=(0, 1))
325
+ # [BT, BK]
326
+ b_k = tl.load(p_k, boundary_check=(0, 1))
327
+ # [BT, BV]
328
+ b_v = tl.load(p_v, boundary_check=(0, 1))
329
+ b_do = tl.load(p_do, boundary_check=(0, 1))
330
+ last_idx = min(i_t * BT + BT, T) - 1
331
+
332
+ o_t = i_t * BT + tl.arange(0, BT)
333
+ m_t = o_t < T
334
+ # [BT, BT]
335
+ b_s = tl.dot(b_k, b_q)
336
+ b_ds = tl.dot(b_v, tl.trans(b_do))
337
+
338
+ if USE_G:
339
+ p_g = g + (bos + o_t) * H + i_h
340
+ p_dg = dg + ((i_k * NV + i_v) * all + (bos + o_t)).to(tl.int64) * H + i_h
341
+ b_g = tl.load(p_g, mask=m_t, other=0.)
342
+ b_g_last = tl.load(g + (bos + last_idx) * H + i_h)
343
+
344
+ b_gq = exp(b_g)
345
+ b_gk = exp(b_g_last - b_g)
346
+ b_gn = exp(b_g_last)
347
+ b_gs = tl.trans(tl.where(m_s & (m_t[:, None] & m_t), exp(b_g[:, None] - b_g[None, :]), 0)) * scale
348
+
349
+ b_s = b_s * b_gs
350
+ b_ds = b_ds * b_gs
351
+
352
+ # [BT, BK]
353
+ b_dk = tl.dot(b_ds.to(b_k.dtype), tl.trans(b_q)) + tl.dot(b_v, tl.trans(b_dh).to(b_v.dtype)) * b_gk[:, None]
354
+
355
+ # [BT]
356
+ b_dg_t = tl.where(m_t, tl.load(p_dg, mask=m_t, other=0.) - tl.sum(b_k * b_dk, 1), 0)
357
+ b_dg_last += tl.sum(b_dg_t, 0)
358
+ b_dg = b_dg_last + b_dg_t - tl.cumsum(b_dg_t, 0)
359
+
360
+ # [BT, BV]
361
+ b_dv = tl.dot(b_s.to(b_do.dtype), b_do) + tl.dot(b_k, b_dh.to(b_k.dtype)) * b_gk[:, None]
362
+ # [BK, BV]
363
+ b_dh = b_dh * b_gn + tl.dot(b_q, (b_do * b_gq[:, None] * scale).to(b_do.dtype))
364
+
365
+ tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), mask=m_t)
366
+
367
+ elif USE_G_GAMMA:
368
+ b_g_last = b_gamma * min(BT, T - i_t * BT)
369
+ b_gk = exp(b_g_last - b_g)
370
+ b_gn = exp(b_g_last)
371
+ b_gs = tl.trans(tl.where(m_s & (m_t[:, None] & m_t), exp(b_g[:, None] - b_g[None, :]), 0)) * scale
372
+
373
+ b_s = b_s * b_gs
374
+ b_ds = b_ds * b_gs
375
+
376
+ b_dk = tl.dot(b_ds.to(b_k.dtype), tl.trans(b_q)) + tl.dot(b_v, tl.trans(b_dh).to(b_v.dtype)) * b_gk[:, None]
377
+ # [BT, BV]
378
+ b_dv = tl.dot(b_s.to(b_do.dtype), b_do) + tl.dot(b_k, b_dh.to(b_k.dtype)) * b_gk[:, None]
379
+ # [BK, BV]
380
+ b_dh = b_dh * b_gn + tl.dot(b_q, (b_do * b_gq[:, None] * scale).to(b_do.dtype))
381
+
382
+ else:
383
+ mask = tl.trans(m_s & (m_t[:, None] & m_t))
384
+ b_s = tl.where(mask, b_s * scale, 0).to(b_do.dtype)
385
+ b_ds = tl.where(mask, b_ds * scale, 0).to(b_q.dtype)
386
+
387
+ b_dk = tl.dot(b_ds, tl.trans(b_q)) + tl.dot(b_v, tl.trans(b_dh).to(b_v.dtype))
388
+ # [BT, BV]
389
+ b_dv = tl.dot(b_s.to(b_do.dtype), b_do) + tl.dot(b_k, b_dh.to(b_k.dtype))
390
+ # [BK, BV]
391
+ b_dh += tl.dot(b_q, (b_do * scale).to(b_do.dtype))
392
+
393
+ tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
394
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
395
+
396
+ if USE_INITIAL_STATE:
397
+ p_dh0 = tl.make_block_ptr(dh0 + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
398
+ tl.store(p_dh0, b_dh.to(p_dh0.dtype.element_ty), boundary_check=(0, 1))
399
+
400
+
401
+ def fused_chunk_fwd(
402
+ q: torch.Tensor,
403
+ k: torch.Tensor,
404
+ v: torch.Tensor,
405
+ g: Optional[torch.Tensor] = None,
406
+ g_gamma: Optional[torch.Tensor] = None,
407
+ scale: Optional[float] = None,
408
+ initial_state: Optional[torch.Tensor] = None,
409
+ output_final_state: bool = False,
410
+ cu_seqlens: Optional[torch.LongTensor] = None,
411
+ chunk_size: int = 64
412
+ ):
413
+ B, T, H, K, V = *q.shape, v.shape[-1]
414
+ BT = chunk_size
415
+ BK = min(max(triton.next_power_of_2(K), 16), 64)
416
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
417
+ NK = triton.cdiv(K, BK)
418
+
419
+ o = v.new_empty(NK, *v.shape, dtype=torch.float) if NK > 1 else torch.empty_like(v)
420
+ ht = k.new_empty(N, H, K, V, dtype=torch.float) if output_final_state else None
421
+ def grid(meta): return (triton.cdiv(V, meta['BV']), NK, N * H)
422
+ fused_chunk_fwd_kernel[grid](
423
+ q=q,
424
+ k=k,
425
+ v=v,
426
+ g=g,
427
+ g_gamma=g_gamma,
428
+ o=o,
429
+ h0=initial_state,
430
+ ht=ht,
431
+ cu_seqlens=cu_seqlens,
432
+ scale=scale,
433
+ B=B,
434
+ T=T,
435
+ H=H,
436
+ K=K,
437
+ V=V,
438
+ BT=BT,
439
+ BK=BK,
440
+ )
441
+ if NK > 1:
442
+ o = o.sum(0).to(v)
443
+ return o, ht
444
+
445
+
446
+ def fused_chunk_bwd(
447
+ q,
448
+ k,
449
+ v,
450
+ g,
451
+ g_gamma,
452
+ do,
453
+ scale,
454
+ initial_state: torch.Tensor,
455
+ dht: torch.Tensor,
456
+ cu_seqlens: Optional[torch.LongTensor] = None,
457
+ chunk_size: int = 64
458
+ ):
459
+ B, T, H, K, V = *q.shape, v.shape[-1]
460
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
461
+ BT = chunk_size
462
+ BK = min(max(triton.next_power_of_2(K), 16), 64)
463
+ BV = min(max(triton.next_power_of_2(V), 16), 64)
464
+ NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
465
+
466
+ dq = q.new_empty(NV, *q.shape, dtype=torch.float) if NV > 1 else torch.empty_like(q)
467
+ dk = k.new_empty(NV, *k.shape, dtype=torch.float) if NV > 1 else torch.empty_like(k)
468
+ dv = v.new_empty(NK, *v.shape, dtype=torch.float) if NK > 1 else torch.empty_like(v)
469
+ dg = g.new_empty(NK*NV, *g.shape, dtype=torch.float) if g is not None else None
470
+ dh0 = torch.empty_like(initial_state) if initial_state is not None else None
471
+
472
+ grid = (NV, NK, N * H)
473
+ fused_chunk_bwd_kernel[grid](
474
+ q=q,
475
+ k=k,
476
+ v=v,
477
+ g=g,
478
+ g_gamma=g_gamma,
479
+ do=do,
480
+ dq=dq,
481
+ dk=dk,
482
+ dv=dv,
483
+ dg=dg,
484
+ h0=initial_state,
485
+ dht=dht,
486
+ dh0=dh0,
487
+ cu_seqlens=cu_seqlens,
488
+ scale=scale,
489
+ T=T,
490
+ B=B,
491
+ H=H,
492
+ K=K,
493
+ V=V,
494
+ BT=BT,
495
+ BK=BK,
496
+ BV=BV,
497
+ )
498
+ dq = dq.sum(0) if NV > 1 else dq
499
+ dk = dk.sum(0) if NV > 1 else dk
500
+ dv = dv.sum(0) if NK > 1 else dv
501
+ if dg is not None:
502
+ dg = dg.sum(0).to(g)
503
+
504
+ return dq, dk, dv, dg, dh0
505
+
506
+
507
+ class FusedChunkFunction(torch.autograd.Function):
508
+
509
+ @staticmethod
510
+ @input_guard
511
+ @autocast_custom_fwd
512
+ def forward(
513
+ ctx,
514
+ q,
515
+ k,
516
+ v,
517
+ g,
518
+ g_gamma,
519
+ scale,
520
+ initial_state,
521
+ output_final_state,
522
+ cu_seqlens
523
+ ):
524
+ chunk_size = min(64, max(16, triton.next_power_of_2(q.shape[1])))
525
+ g = chunk_local_cumsum(g, chunk_size=chunk_size, cu_seqlens=cu_seqlens) if g is not None else None
526
+ o, ht = fused_chunk_fwd(
527
+ q=q,
528
+ k=k,
529
+ v=v,
530
+ g=g,
531
+ g_gamma=g_gamma,
532
+ scale=scale,
533
+ initial_state=initial_state,
534
+ output_final_state=output_final_state,
535
+ cu_seqlens=cu_seqlens,
536
+ chunk_size=chunk_size
537
+ )
538
+
539
+ ctx.save_for_backward(q, k, v, g, g_gamma, initial_state)
540
+ ctx.chunk_size = chunk_size
541
+ ctx.scale = scale
542
+ ctx.cu_seqlens = cu_seqlens
543
+ return o.to(q.dtype), ht
544
+
545
+ @staticmethod
546
+ @input_guard
547
+ @autocast_custom_bwd
548
+ def backward(ctx, do, dht=None):
549
+ q, k, v, g, g_gamma, initial_state = ctx.saved_tensors
550
+
551
+ dq, dk, dv, dg, dh0 = fused_chunk_bwd(
552
+ q=q,
553
+ k=k,
554
+ v=v,
555
+ g=g,
556
+ g_gamma=g_gamma,
557
+ do=do,
558
+ scale=ctx.scale,
559
+ initial_state=initial_state,
560
+ dht=dht,
561
+ cu_seqlens=ctx.cu_seqlens,
562
+ chunk_size=ctx.chunk_size
563
+ )
564
+ if g is not None:
565
+ dg = dg.to(g)
566
+ return dq.to(q), dk.to(k), dv.to(v), dg, None, None, dh0, None, None
567
+
568
+
569
+ def fused_chunk(
570
+ q: torch.Tensor,
571
+ k: torch.Tensor,
572
+ v: torch.Tensor,
573
+ g: Optional[torch.Tensor] = None,
574
+ g_gamma: Optional[torch.Tensor] = None,
575
+ scale: Optional[float] = None,
576
+ initial_state: Optional[torch.Tensor] = None,
577
+ output_final_state: bool = False,
578
+ cu_seqlens: Optional[torch.LongTensor] = None,
579
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
580
+ r"""
581
+ Args:
582
+ q (torch.Tensor):
583
+ queries of shape `[B, T, H, K]`.
584
+ k (torch.Tensor):
585
+ keys of shape `[B, T, H, K]`.
586
+ v (torch.Tensor):
587
+ values of shape `[B, T, H, V]`.
588
+ g (torch.Tensor):
589
+ Forget gates of shape `[B, T, H]`.
590
+ Compared to GLA, the gating is head-wise instead of elementwise.
591
+ g_gamma (torch.Tensor):
592
+ Log decay of shape `[H]`.
593
+ Head-wise data-independent decay is used if `g_gamma` is provided.
594
+ Only one of `g` or `g_gamma` should be provided.
595
+ scale (Optional[int]):
596
+ Scale factor for the attention scores.
597
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
598
+ initial_state (Optional[torch.Tensor]):
599
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
600
+ For equal-length input sequences, `N` equals the batch size `B`.
601
+ Default: `None`.
602
+ output_final_state (Optional[bool]):
603
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
604
+ cu_seqlens (torch.LongTensor):
605
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
606
+ consistent with the FlashAttention API.
607
+
608
+ Returns:
609
+ o (torch.Tensor):
610
+ Outputs of shape `[B, T, H, V]`.
611
+ final_state (torch.Tensor):
612
+ Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
613
+ """
614
+ if g is not None and g_gamma is not None:
615
+ raise ValueError("Only one of `g` or `g_gamma` should be provided.")
616
+ if scale is None:
617
+ scale = k.shape[-1] ** -0.5
618
+ o, final_state = FusedChunkFunction.apply(
619
+ q,
620
+ k,
621
+ v,
622
+ g,
623
+ g_gamma,
624
+ scale,
625
+ initial_state,
626
+ output_final_state,
627
+ cu_seqlens
628
+ )
629
+ return o, final_state