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
fla/ops/comba/chunk.py ADDED
@@ -0,0 +1,342 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from typing import Optional
5
+
6
+ import torch
7
+
8
+ from fla.modules.l2norm import l2norm_bwd, l2norm_fwd
9
+ from fla.ops.comba.utils import chunk_comba_cumsum_scalar_bwd, chunk_comba_cumsum_scalar_fwd
10
+ from fla.ops.comba.wy_fast import chunk_scaled_dot_comba_pkt_fwd, prepare_wy_repr_bwd, recompute_w_u_fwd
11
+ from fla.ops.common.chunk_delta_h import chunk_gated_delta_rule_bwd_dhu, chunk_gated_delta_rule_fwd_h
12
+ from fla.ops.common.chunk_o import chunk_bwd_dqkwg, chunk_bwd_dv_local, chunk_fwd_o
13
+ from fla.ops.utils import chunk_local_cumsum, solve_tril
14
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
15
+
16
+
17
+ def chunk_comba_fwd(
18
+ q: torch.Tensor,
19
+ k: torch.Tensor,
20
+ v: torch.Tensor,
21
+ p: torch.Tensor,
22
+ g: torch.Tensor,
23
+ beta: torch.Tensor,
24
+ scale: float,
25
+ initial_state: torch.Tensor,
26
+ output_final_state: bool,
27
+ cu_seqlens: Optional[torch.LongTensor] = None
28
+ ):
29
+ g0, g = chunk_comba_cumsum_scalar_fwd(g, chunk_size=64, cu_seqlens=cu_seqlens)
30
+ # obtain WY representation. u is actually the new v.
31
+ A = chunk_scaled_dot_comba_pkt_fwd(
32
+ k=k,
33
+ p=p,
34
+ beta=beta,
35
+ g0=g0,
36
+ g=g,
37
+ cu_seqlens=cu_seqlens,
38
+ output_dtype=torch.float32
39
+ )
40
+ A = solve_tril(
41
+ A=A,
42
+ cu_seqlens=cu_seqlens,
43
+ output_dtype=k.dtype
44
+ )
45
+ w, u = recompute_w_u_fwd(
46
+ k=p,
47
+ v=v,
48
+ beta=beta,
49
+ A=A,
50
+ g_cumsum=g0,
51
+ cu_seqlens=cu_seqlens,
52
+ )
53
+ h, v_new, final_state = chunk_gated_delta_rule_fwd_h(
54
+ k=k,
55
+ w=w,
56
+ u=u,
57
+ g=g,
58
+ initial_state=initial_state,
59
+ output_final_state=output_final_state,
60
+ cu_seqlens=cu_seqlens,
61
+ )
62
+ o = chunk_fwd_o(
63
+ q=q,
64
+ k=k,
65
+ v=v_new,
66
+ h=h,
67
+ g=g,
68
+ scale=scale,
69
+ cu_seqlens=cu_seqlens,
70
+ )
71
+ return g0, g, o, A, final_state
72
+
73
+
74
+ def chunk_comba_bwd(
75
+ q: torch.Tensor,
76
+ k: torch.Tensor,
77
+ v: torch.Tensor,
78
+ p: torch.Tensor,
79
+ g0: torch.Tensor,
80
+ g: torch.Tensor,
81
+ beta: torch.Tensor,
82
+ A: torch.Tensor,
83
+ scale: float,
84
+ initial_state: torch.Tensor,
85
+ do: torch.Tensor,
86
+ dht: torch.Tensor,
87
+ cu_seqlens: Optional[torch.LongTensor] = None,
88
+ ):
89
+ w, u = recompute_w_u_fwd(
90
+ k=p,
91
+ v=v,
92
+ beta=beta,
93
+ A=A,
94
+ g_cumsum=g0,
95
+ cu_seqlens=cu_seqlens,
96
+ )
97
+ h, v_new, _ = chunk_gated_delta_rule_fwd_h(
98
+ k=k,
99
+ w=w,
100
+ u=u,
101
+ g=g,
102
+ initial_state=initial_state,
103
+ output_final_state=False,
104
+ cu_seqlens=cu_seqlens,
105
+ )
106
+ dv = chunk_bwd_dv_local(
107
+ q=q,
108
+ k=k,
109
+ g=g,
110
+ do=do,
111
+ scale=scale,
112
+ cu_seqlens=cu_seqlens,
113
+ )
114
+ dh, dh0, dv = chunk_gated_delta_rule_bwd_dhu(
115
+ q=q,
116
+ k=k,
117
+ w=w,
118
+ g=g,
119
+ h0=initial_state,
120
+ dht=dht,
121
+ do=do,
122
+ dv=dv,
123
+ scale=scale,
124
+ cu_seqlens=cu_seqlens,
125
+ )
126
+ dq, dk, dw, dg = chunk_bwd_dqkwg(
127
+ q=q,
128
+ k=k,
129
+ v=v_new,
130
+ w=w,
131
+ g=g,
132
+ h=h,
133
+ dv=dv,
134
+ do=do,
135
+ dh=dh,
136
+ scale=scale,
137
+ cu_seqlens=cu_seqlens,
138
+ )
139
+ dk2, dv, dp, db, dg0, dg2 = prepare_wy_repr_bwd(
140
+ k=k,
141
+ v=v,
142
+ p=p,
143
+ beta=beta,
144
+ g0=g0,
145
+ g=g,
146
+ A=A,
147
+ dw=dw,
148
+ du=dv,
149
+ cu_seqlens=cu_seqlens,
150
+ )
151
+ dk.add_(dk2)
152
+ dg.add_(dg2)
153
+ assert dg.dtype == torch.float32, "dg should be fp32"
154
+ dg = chunk_local_cumsum(dg, chunk_size=64, reverse=True, cu_seqlens=cu_seqlens)
155
+ # dg0 = d(g_cumsum - g)
156
+ dg += chunk_comba_cumsum_scalar_bwd(dg0, chunk_size=64, cu_seqlens=cu_seqlens)
157
+ return dq, dk, dv, dp, db, dg, dh0
158
+
159
+
160
+ class ChunkCombaFunction(torch.autograd.Function):
161
+
162
+ @staticmethod
163
+ @input_guard
164
+ @autocast_custom_fwd
165
+ def forward(
166
+ ctx,
167
+ q: torch.Tensor,
168
+ k: torch.Tensor,
169
+ v: torch.Tensor,
170
+ p: torch.Tensor,
171
+ g: torch.Tensor,
172
+ beta: torch.Tensor,
173
+ scale: float,
174
+ initial_state: torch.Tensor,
175
+ output_final_state: bool,
176
+ use_qk_l2norm_in_kernel: bool = False,
177
+ cu_seqlens: Optional[torch.LongTensor] = None,
178
+ ):
179
+ if use_qk_l2norm_in_kernel:
180
+ q, q_rstd = l2norm_fwd(q)
181
+ k, k_rstd = l2norm_fwd(k)
182
+ p, p_rstd = l2norm_fwd(p)
183
+ else:
184
+ q_rstd, k_rstd, p_rstd = None, None, None
185
+
186
+ g0, g, o, A, final_state = chunk_comba_fwd(
187
+ q=q,
188
+ k=k,
189
+ v=v,
190
+ p=p,
191
+ g=g,
192
+ beta=beta,
193
+ scale=scale,
194
+ initial_state=initial_state,
195
+ output_final_state=output_final_state,
196
+ cu_seqlens=cu_seqlens,
197
+ )
198
+ ctx.save_for_backward(q, q_rstd, k, k_rstd, p, p_rstd, v, g0, g, beta, A, initial_state, cu_seqlens)
199
+ ctx.scale = scale
200
+ ctx.use_qk_l2norm_in_kernel = use_qk_l2norm_in_kernel
201
+ return o.to(q.dtype), final_state
202
+
203
+ @staticmethod
204
+ @input_guard
205
+ @autocast_custom_bwd
206
+ def backward(
207
+ ctx,
208
+ do: torch.Tensor,
209
+ dht: torch.Tensor
210
+ ):
211
+ q, q_rstd, k, k_rstd, p, p_rstd, v, g0, g, beta, A, initial_state, cu_seqlens = ctx.saved_tensors
212
+ dq, dk, dv, dp, db, dg, dh0 = chunk_comba_bwd(
213
+ q=q,
214
+ k=k,
215
+ v=v,
216
+ p=p,
217
+ g0=g0,
218
+ g=g,
219
+ beta=beta,
220
+ A=A,
221
+ scale=ctx.scale,
222
+ initial_state=initial_state,
223
+ do=do,
224
+ dht=dht,
225
+ cu_seqlens=cu_seqlens,
226
+ )
227
+ if ctx.use_qk_l2norm_in_kernel:
228
+ dq = l2norm_bwd(q, q_rstd, dq)
229
+ dk = l2norm_bwd(k, k_rstd, dk)
230
+ dp = l2norm_bwd(p, p_rstd, dp)
231
+ return dq.to(q), dk.to(k), dv.to(v), dp.to(p), dg.to(g), db.to(beta), None, dh0, None, None, None
232
+
233
+
234
+ @torch.compiler.disable
235
+ def chunk_comba(
236
+ q: torch.Tensor,
237
+ k: torch.Tensor,
238
+ v: torch.Tensor,
239
+ p: torch.Tensor,
240
+ g: torch.Tensor,
241
+ beta: torch.Tensor = None,
242
+ scale: float = None,
243
+ initial_state: torch.Tensor = None,
244
+ output_final_state: bool = False,
245
+ use_qk_l2norm_in_kernel: bool = False,
246
+ cu_seqlens: Optional[torch.LongTensor] = None,
247
+ ):
248
+ r"""
249
+ Args:
250
+ q (torch.Tensor):
251
+ queries of shape `[B, T, H, K]`.
252
+ k (torch.Tensor):
253
+ keys of shape `[B, T, H, K]`.
254
+ v (torch.Tensor):
255
+ values of shape `[B, T, H, V]`.
256
+ p (torch.Tensor):
257
+ auxiliary keys of shape `[B, T, H, K]`.
258
+ g (torch.Tensor):
259
+ (forget) gating tensor (in log space!) of shape `[B, T, H]`.
260
+ beta (torch.Tensor):
261
+ betas of shape `[B, T, H]`.
262
+ scale (Optional[int]):
263
+ Scale factor for the RetNet attention scores.
264
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
265
+ initial_state (Optional[torch.Tensor]):
266
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
267
+ For equal-length input sequences, `N` equals the batch size `B`.
268
+ Default: `None`.
269
+ output_final_state (Optional[bool]):
270
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
271
+ use_qk_l2norm_in_kernel (bool):
272
+ Whether to apply L2norm to the q/k tensor internally. Default: `False`.
273
+ cu_seqlens (torch.LongTensor):
274
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
275
+ consistent with the FlashAttention API.
276
+
277
+ Returns:
278
+ o (torch.Tensor):
279
+ Outputs of shape `[B, T, H, V]`.
280
+ final_state (torch.Tensor):
281
+ Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
282
+
283
+ Examples::
284
+ >>> import torch
285
+ >>> import torch.nn.functional as F
286
+ >>> from einops import rearrange
287
+ >>> from fla.ops.comba import chunk_comba
288
+ # inputs with equal lengths
289
+ >>> B, T, H, K, V = 4, 2048, 4, 512, 512
290
+ >>> q = torch.randn(B, T, H, K, dtype=torch.bfloat16, device='cuda')
291
+ >>> k = F.normalize(torch.randn(B, T, H, K, dtype=torch.bfloat16, device='cuda'), p=2, dim=-1)
292
+ >>> v = torch.randn(B, T, H, V, dtype=torch.bfloat16, device='cuda')
293
+ >>> b = torch.rand(H, dtype=torch.bfloat16, device='cuda').sigmoid()
294
+ >>> p = k * b[:, None]
295
+ >>> beta = torch.rand(B, T, H, dtype=torch.bfloat16, device='cuda').sigmoid()
296
+ >>> g = F.logsigmoid(torch.rand(B, T, H, dtype=torch.bfloat16, device='cuda'))
297
+ >>> h0 = torch.randn(B, H, K, V, dtype=torch.bfloat16, device='cuda')
298
+ >>> o, ht = chunk_comba(
299
+ q, k, v, p, g, beta,
300
+ initial_state=h0,
301
+ output_final_state=True
302
+ )
303
+ # for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
304
+ >>> q, k, v, beta, g = map(lambda x: rearrange(x, 'b t ... -> 1 (b t) ...'), (q, k, v, beta, g))
305
+ # for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
306
+ >>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
307
+ >>> o_var, ht_var = chunk_comba(
308
+ q, k, v, p, g, beta,
309
+ initial_state=h0,
310
+ output_final_state=True,
311
+ cu_seqlens=cu_seqlens
312
+ )
313
+ """
314
+ if p is None:
315
+ p = k
316
+ if cu_seqlens is not None:
317
+ if q.shape[0] != 1:
318
+ raise ValueError(
319
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
320
+ f"Please flatten variable-length inputs before processing."
321
+ )
322
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
323
+ raise ValueError(
324
+ f"The number of initial states is expected to be equal to the number of input sequences, "
325
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
326
+ )
327
+ if scale is None:
328
+ scale = k.shape[-1] ** -0.5
329
+ o, final_state = ChunkCombaFunction.apply(
330
+ q,
331
+ k,
332
+ v,
333
+ p,
334
+ g,
335
+ beta,
336
+ scale,
337
+ initial_state,
338
+ output_final_state,
339
+ use_qk_l2norm_in_kernel,
340
+ cu_seqlens,
341
+ )
342
+ return o, final_state
@@ -0,0 +1,332 @@
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.op import exp
11
+ from fla.utils import input_guard
12
+
13
+
14
+ @triton.heuristics({
15
+ 'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
16
+ 'STORE_FINAL_STATE': lambda args: args['ht'] is not None,
17
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
18
+ })
19
+ @triton.jit(do_not_specialize=['T'])
20
+ def fused_recurrent_comba_fwd_kernel(
21
+ q,
22
+ k,
23
+ p,
24
+ v,
25
+ g,
26
+ beta,
27
+ o,
28
+ h0,
29
+ ht,
30
+ cu_seqlens,
31
+ scale,
32
+ T,
33
+ B: tl.constexpr,
34
+ H: tl.constexpr,
35
+ HV: tl.constexpr,
36
+ K: tl.constexpr,
37
+ V: tl.constexpr,
38
+ BK: tl.constexpr,
39
+ BV: tl.constexpr,
40
+ USE_INITIAL_STATE: tl.constexpr, # whether to use initial state
41
+ STORE_FINAL_STATE: tl.constexpr, # whether to store final state
42
+ IS_BETA_HEADWISE: tl.constexpr, # whether beta is headwise vector or scalar,
43
+ USE_QK_L2NORM_IN_KERNEL: tl.constexpr,
44
+ IS_VARLEN: tl.constexpr
45
+ ):
46
+ i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
47
+ i_n, i_hv = i_nh // HV, i_nh % HV
48
+ i_h = i_hv // (HV // H)
49
+ if IS_VARLEN:
50
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int64), tl.load(cu_seqlens + i_n + 1).to(tl.int64)
51
+ all = T
52
+ T = eos - bos
53
+ else:
54
+ bos, eos = i_n * T, i_n * T + T
55
+ all = B * T
56
+ o_k = i_k * BK + tl.arange(0, BK)
57
+ o_v = i_v * BV + tl.arange(0, BV)
58
+
59
+ p_q = q + (bos * H + i_h) * K + o_k
60
+ p_k = k + (bos * H + i_h) * K + o_k
61
+ p_v = v + (bos * HV + i_hv) * V + o_v
62
+ p_p = p + (bos * H + i_h) * K + o_k
63
+ if IS_BETA_HEADWISE:
64
+ p_beta = beta + (bos * HV + i_hv) * V + o_v
65
+ else:
66
+ p_beta = beta + bos * HV + i_hv
67
+ p_g = g + bos * HV + i_hv
68
+ p_o = o + ((i_k * all + bos) * HV + i_hv) * V + o_v
69
+
70
+ mask_k = o_k < K
71
+ mask_v = o_v < V
72
+ mask_h = mask_k[:, None] & mask_v[None, :]
73
+
74
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
75
+ if USE_INITIAL_STATE:
76
+ p_h0 = h0 + i_nh * K*V + o_k[:, None] * V + o_v[None, :]
77
+ b_h += tl.load(p_h0, mask=mask_h, other=0).to(tl.float32)
78
+
79
+ for _ in range(0, T):
80
+ b_q = tl.load(p_q, mask=mask_k, other=0).to(tl.float32)
81
+ b_k = tl.load(p_k, mask=mask_k, other=0).to(tl.float32)
82
+ b_v = tl.load(p_v, mask=mask_v, other=0).to(tl.float32)
83
+ b_p = tl.load(p_p, mask=mask_k, other=0).to(tl.float32)
84
+ b_g = tl.load(p_g).to(tl.float32)
85
+
86
+ if USE_QK_L2NORM_IN_KERNEL:
87
+ b_q = b_q / tl.sqrt(tl.sum(b_q * b_q) + 1e-6)
88
+ b_k = b_k / tl.sqrt(tl.sum(b_k * b_k) + 1e-6)
89
+ b_p = b_p / tl.sqrt(tl.sum(b_p * b_p) + 1e-6)
90
+ b_q = b_q * scale
91
+ # [BV]
92
+ b_v -= tl.sum(b_h * b_p[:, None], 0)
93
+ # [BK, BV]
94
+ b_h *= exp(b_g)
95
+ if IS_BETA_HEADWISE:
96
+ b_beta = tl.load(p_beta, mask=mask_v, other=0).to(tl.float32)
97
+ else:
98
+ b_beta = tl.load(p_beta).to(tl.float32)
99
+ b_v *= b_beta
100
+ # [BK, BV]
101
+ b_h += b_k[:, None] * b_v[None, :]
102
+ # [BV]
103
+ b_o = tl.sum(b_h * b_q[:, None], 0)
104
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), mask=mask_v)
105
+
106
+ p_q += H*K
107
+ p_k += H*K
108
+ p_o += HV*V
109
+ p_v += HV*V
110
+ p_p += H*K
111
+ p_g += HV
112
+ p_beta += HV * (V if IS_BETA_HEADWISE else 1)
113
+
114
+ if STORE_FINAL_STATE:
115
+ p_ht = ht + i_nh * K*V + o_k[:, None] * V + o_v[None, :]
116
+ tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), mask=mask_h)
117
+
118
+
119
+ def fused_recurrent_comba_fwd(
120
+ q: torch.Tensor,
121
+ k: torch.Tensor,
122
+ v: torch.Tensor,
123
+ p: torch.Tensor,
124
+ g: torch.Tensor,
125
+ beta: torch.Tensor,
126
+ scale: float,
127
+ initial_state: torch.Tensor,
128
+ output_final_state: bool,
129
+ use_qk_l2norm_in_kernel: bool = False,
130
+ cu_seqlens: Optional[torch.LongTensor] = None,
131
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
132
+ B, T, H, K, V = *k.shape, v.shape[-1]
133
+ HV = v.shape[2]
134
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
135
+ BK, BV = triton.next_power_of_2(K), min(triton.next_power_of_2(V), 8)
136
+ NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
137
+ assert NK == 1, "NK > 1 is not supported yet"
138
+ num_stages = 3
139
+ num_warps = 1
140
+
141
+ o = q.new_empty(NK, *v.shape)
142
+ if output_final_state:
143
+ final_state = q.new_empty(N, HV, K, V, dtype=torch.float32)
144
+ else:
145
+ final_state = None
146
+
147
+ grid = (NK, NV, N * HV)
148
+ fused_recurrent_comba_fwd_kernel[grid](
149
+ q=q,
150
+ k=k,
151
+ p=p,
152
+ v=v,
153
+ g=g,
154
+ beta=beta,
155
+ o=o,
156
+ h0=initial_state,
157
+ ht=final_state,
158
+ cu_seqlens=cu_seqlens,
159
+ scale=scale,
160
+ T=T,
161
+ B=B,
162
+ H=H,
163
+ HV=HV,
164
+ K=K,
165
+ V=V,
166
+ BK=BK,
167
+ BV=BV,
168
+ IS_BETA_HEADWISE=beta.ndim == v.ndim,
169
+ USE_QK_L2NORM_IN_KERNEL=use_qk_l2norm_in_kernel,
170
+ num_warps=num_warps,
171
+ num_stages=num_stages,
172
+ )
173
+ o = o.squeeze(0)
174
+ return o, final_state
175
+
176
+
177
+ class FusedRecurrentCombaFunction(torch.autograd.Function):
178
+
179
+ @staticmethod
180
+ @input_guard
181
+ def forward(
182
+ ctx,
183
+ q: torch.Tensor,
184
+ k: torch.Tensor,
185
+ p: torch.Tensor,
186
+ v: torch.Tensor,
187
+ g: torch.Tensor,
188
+ beta: torch.Tensor,
189
+ scale: float,
190
+ initial_state: torch.Tensor,
191
+ output_final_state: bool,
192
+ use_qk_l2norm_in_kernel: bool = False,
193
+ cu_seqlens: Optional[torch.LongTensor] = None,
194
+ ):
195
+ o, final_state = fused_recurrent_comba_fwd(
196
+ q=q,
197
+ k=k,
198
+ p=p,
199
+ v=v,
200
+ g=g,
201
+ beta=beta,
202
+ scale=scale,
203
+ initial_state=initial_state,
204
+ output_final_state=output_final_state,
205
+ use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
206
+ cu_seqlens=cu_seqlens
207
+ )
208
+
209
+ return o, final_state
210
+
211
+ @staticmethod
212
+ @input_guard
213
+ def backward(ctx, do, dht):
214
+ raise NotImplementedError(
215
+ "Backward pass is not implemented yet and we do not have plans to implement it "
216
+ "because we haven't figured out how to compute dg without materializing the full "
217
+ "hidden states for all time steps."
218
+ )
219
+
220
+
221
+ def fused_recurrent_comba(
222
+ q: torch.Tensor,
223
+ k: torch.Tensor,
224
+ p: torch.Tensor,
225
+ v: torch.Tensor,
226
+ g: torch.Tensor,
227
+ beta: torch.Tensor = None,
228
+ scale: float = None,
229
+ initial_state: torch.Tensor = None,
230
+ output_final_state: bool = False,
231
+ use_qk_l2norm_in_kernel: bool = False,
232
+ cu_seqlens: Optional[torch.LongTensor] = None,
233
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
234
+ r"""
235
+ Args:
236
+ q (torch.Tensor):
237
+ queries of shape `[B, T, H, K]`.
238
+ k (torch.Tensor):
239
+ keys of shape `[B, T, H, K]`.
240
+ p (torch.Tensor):
241
+ auxiliary keys of shape `[B, T, H, K]`.
242
+ v (torch.Tensor):
243
+ values of shape `[B, T, HV, V]`.
244
+ GVA is applied if `HV > H`.
245
+ g (torch.Tensor):
246
+ g (decays) of shape `[B, T, HV]`.
247
+ beta (torch.Tensor):
248
+ betas of shape `[B, T, HV]`.
249
+ scale (Optional[int]):
250
+ Scale factor for the RetNet attention scores.
251
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
252
+ initial_state (Optional[torch.Tensor]):
253
+ Initial state of shape `[N, HV, K, V]` for `N` input sequences.
254
+ For equal-length input sequences, `N` equals the batch size `B`.
255
+ Default: `None`.
256
+ output_final_state (Optional[bool]):
257
+ Whether to output the final state of shape `[N, HV, K, V]`. Default: `False`.
258
+ use_qk_l2norm_in_kernel (Optional[bool]):
259
+ Whether to use qk l2norm within the kernel for saving GPU memory.
260
+ Default: `False`.
261
+ cu_seqlens (torch.LongTensor):
262
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
263
+ consistent with the FlashAttention API.
264
+
265
+ Returns:
266
+ o (torch.Tensor):
267
+ Outputs of shape `[B, T, HV, V]`.
268
+ final_state (torch.Tensor):
269
+ Final state of shape `[N, HV, K, V]` if `output_final_state=True` else `None`.
270
+
271
+ Examples::
272
+ >>> import torch
273
+ >>> import torch.nn.functional as F
274
+ >>> from einops import rearrange
275
+ >>> from fla.ops.comba import fused_recurrent_comba
276
+ # inputs with equal lengths
277
+ >>> B, T, H, HV, K, V = 4, 2048, 4, 8, 512, 512
278
+ >>> q = torch.randn(B, T, H, K, device='cuda')
279
+ >>> k = F.normalize(torch.randn(B, T, H, K, device='cuda'), p=2, dim=-1)
280
+ >>> v = torch.randn(B, T, HV, V, device='cuda')
281
+ >>> b = torch.rand(H, dtype=torch.bfloat16, device='cuda').sigmoid()
282
+ >>> p = k * b[:, None]
283
+ >>> g = F.logsigmoid(torch.rand(B, T, HV, device='cuda'))
284
+ >>> beta = torch.rand(B, T, HV, device='cuda').sigmoid()
285
+ >>> h0 = torch.randn(B, HV, K, V, device='cuda')
286
+ >>> o, ht = fused_recurrent_comba(
287
+ q, k, v, p, g, beta,
288
+ initial_state=h0,
289
+ output_final_state=True
290
+ )
291
+ # for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
292
+ >>> q, k, v, p, g, beta = map(lambda x: rearrange(x, 'b t ... -> 1 (b t) ...'), (q, k, v, p, g, beta))
293
+ # for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
294
+ >>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
295
+ >>> o_var, ht_var = fused_recurrent_comba(
296
+ q, k, p, v, g, beta,
297
+ initial_state=h0,
298
+ output_final_state=True,
299
+ cu_seqlens=cu_seqlens
300
+ )
301
+ """
302
+ if cu_seqlens is not None:
303
+ if q.shape[0] != 1:
304
+ raise ValueError(
305
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
306
+ f"Please flatten variable-length inputs before processing."
307
+ )
308
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
309
+ raise ValueError(
310
+ f"The number of initial states is expected to be equal to the number of input sequences, "
311
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
312
+ )
313
+ if scale is None:
314
+ scale = k.shape[-1] ** -0.5
315
+ if beta is None:
316
+ beta = torch.ones_like(q[..., 0])
317
+ if p is None:
318
+ p = k
319
+ o, final_state = FusedRecurrentCombaFunction.apply(
320
+ q,
321
+ k,
322
+ p,
323
+ v,
324
+ g,
325
+ beta,
326
+ scale,
327
+ initial_state,
328
+ output_final_state,
329
+ use_qk_l2norm_in_kernel,
330
+ cu_seqlens,
331
+ )
332
+ return o, final_state