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,334 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ import warnings
5
+ from typing import Optional, Tuple
6
+
7
+ import torch
8
+ import triton
9
+ import triton.language as tl
10
+
11
+ from fla.ops.generalized_delta_rule import fused_recurrent_dplr_delta_rule
12
+ from fla.ops.utils.op import exp
13
+ from fla.utils import input_guard, use_cuda_graph
14
+
15
+
16
+ @triton.heuristics({
17
+ 'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
18
+ 'STORE_FINAL_STATE': lambda args: args['ht'] is not None,
19
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
20
+ })
21
+ @triton.autotune(
22
+ configs=[
23
+ triton.Config({'BV': BV}, num_warps=num_warps, num_stages=num_stages)
24
+ for BV in [16, 32, 64]
25
+ for num_warps in [2, 4, 8, 16]
26
+ for num_stages in [2, 3, 4]
27
+ ],
28
+ key=['BK'],
29
+ use_cuda_graph=use_cuda_graph,
30
+ )
31
+ @triton.jit(do_not_specialize=['T'])
32
+ def fused_recurrent_rwkv7_fwd_kernel(
33
+ r,
34
+ w,
35
+ k,
36
+ v,
37
+ kk,
38
+ a,
39
+ o,
40
+ h0,
41
+ ht,
42
+ cu_seqlens,
43
+ scale,
44
+ T,
45
+ B: tl.constexpr,
46
+ H: tl.constexpr,
47
+ K: tl.constexpr,
48
+ V: tl.constexpr,
49
+ BK: tl.constexpr,
50
+ BV: tl.constexpr,
51
+ REVERSE: tl.constexpr,
52
+ USE_INITIAL_STATE: tl.constexpr,
53
+ STORE_FINAL_STATE: tl.constexpr,
54
+ IS_VARLEN: tl.constexpr,
55
+ IS_DECODE: tl.constexpr,
56
+ ):
57
+ i_v, i_nh = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64)
58
+ i_n, i_h = i_nh // H, i_nh % H
59
+
60
+ if IS_VARLEN:
61
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int64), tl.load(cu_seqlens + i_n + 1).to(tl.int64)
62
+ T = eos - bos
63
+ else:
64
+ bos, eos = i_n * T, i_n * T + T
65
+
66
+ o_k = tl.arange(0, BK)
67
+ o_v = i_v * BV + tl.arange(0, BV)
68
+ p_r = r + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
69
+ p_w = w + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
70
+ p_k = k + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
71
+ p_v = v + (bos + ((T - 1) if REVERSE else 0)) * H*V + i_h * V + o_v
72
+ p_a = a + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
73
+ p_kk = kk + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
74
+
75
+ p_o = o + (bos + ((T - 1) if REVERSE else 0)) * H*V + i_h * V + o_v
76
+
77
+ mask_k = o_k < K
78
+ mask_v = o_v < V
79
+ mask_h = mask_k[:, None] & mask_v[None, :]
80
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
81
+
82
+ if USE_INITIAL_STATE:
83
+ p_h0 = h0 + i_nh * K*V + o_k[:, None] * V + o_v
84
+ b_h += tl.load(p_h0, mask=mask_h, other=0).to(tl.float32)
85
+
86
+ if IS_DECODE:
87
+ b_r = tl.load(p_r, mask=mask_k, other=0).to(tl.float32) * scale
88
+ b_w = tl.load(p_w, mask=mask_k, other=0).to(tl.float32)
89
+ b_k = tl.load(p_k, mask=mask_k, other=0).to(tl.float32)
90
+ b_v = tl.load(p_v, mask=mask_v, other=0).to(tl.float32)
91
+ b_a = tl.load(p_a, mask=mask_k, other=0).to(tl.float32)
92
+ b_kk = tl.load(p_kk, mask=mask_k, other=0).to(tl.float32)
93
+ b_act_a = -b_kk
94
+ b_b = b_kk * b_a
95
+
96
+ b_h = exp(b_w)[:, None] * b_h + b_b[:, None] * tl.sum(b_act_a[:, None] * b_h, 0)[None, :]
97
+ b_h += b_k[:, None] * b_v[None, :]
98
+ b_o = tl.sum(b_h * b_r[:, None], 0)
99
+
100
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), mask=mask_v)
101
+ else:
102
+ for _ in range(0, T):
103
+ b_r = tl.load(p_r, mask=mask_k, other=0).to(tl.float32) * scale
104
+ b_w = tl.load(p_w, mask=mask_k, other=0).to(tl.float32)
105
+ b_k = tl.load(p_k, mask=mask_k, other=0).to(tl.float32)
106
+ b_v = tl.load(p_v, mask=mask_v, other=0).to(tl.float32)
107
+ b_a = tl.load(p_a, mask=mask_k, other=0).to(tl.float32)
108
+ b_kk = tl.load(p_kk, mask=mask_k, other=0).to(tl.float32)
109
+ b_act_a = -b_kk
110
+ b_b = b_kk * b_a
111
+
112
+ b_h = exp(b_w)[:, None] * b_h + b_b[:, None] * tl.sum(b_act_a[:, None] * b_h, 0)[None, :]
113
+ b_h += b_k[:, None] * b_v[None, :]
114
+ b_o = tl.sum(b_h * b_r[:, None], 0)
115
+
116
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), mask=mask_v)
117
+ p_r += (-1 if REVERSE else 1) * H*K
118
+ p_w += (-1 if REVERSE else 1) * H*K
119
+ p_k += (-1 if REVERSE else 1) * H*K
120
+ p_v += (-1 if REVERSE else 1) * H*V
121
+ p_a += (-1 if REVERSE else 1) * H*K
122
+ p_kk += (-1 if REVERSE else 1) * H*K
123
+ p_o += (-1 if REVERSE else 1) * H*V
124
+
125
+ if STORE_FINAL_STATE:
126
+ p_ht = ht + i_nh * K*V + o_k[:, None] * V + o_v
127
+ tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), mask=mask_h)
128
+
129
+
130
+ @input_guard
131
+ def fused_recurrent_rwkv7_fwd(
132
+ r: torch.Tensor,
133
+ w: torch.Tensor,
134
+ k: torch.Tensor,
135
+ v: torch.Tensor,
136
+ kk: torch.Tensor,
137
+ a: torch.Tensor,
138
+ scale: Optional[float] = 1.0,
139
+ initial_state: Optional[torch.Tensor] = None,
140
+ output_final_state: bool = False,
141
+ reverse: bool = False,
142
+ cu_seqlens: Optional[torch.LongTensor] = None,
143
+ ):
144
+ B, T, H, K, V = *k.shape, v.shape[-1]
145
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
146
+ BK = triton.next_power_of_2(K)
147
+ IS_DECODE = (T == 1)
148
+
149
+ h0 = initial_state
150
+ if not output_final_state:
151
+ ht = None
152
+ else:
153
+ ht = r.new_empty(N, H, K, V, dtype=torch.float32)
154
+ o = torch.empty_like(v)
155
+
156
+ def grid(meta): return (triton.cdiv(V, meta['BV']), N * H)
157
+ fused_recurrent_rwkv7_fwd_kernel[grid](
158
+ r,
159
+ w,
160
+ k,
161
+ v,
162
+ kk,
163
+ a,
164
+ o,
165
+ h0,
166
+ ht,
167
+ cu_seqlens,
168
+ scale,
169
+ T=T,
170
+ B=B,
171
+ H=H,
172
+ K=K,
173
+ V=V,
174
+ BK=BK,
175
+ REVERSE=reverse,
176
+ IS_DECODE=IS_DECODE
177
+ )
178
+ return o, ht
179
+
180
+
181
+ def fused_recurrent_rwkv7(
182
+ r: torch.Tensor,
183
+ w: torch.Tensor,
184
+ k: torch.Tensor,
185
+ v: torch.Tensor,
186
+ a: torch.Tensor,
187
+ b: torch.Tensor,
188
+ scale: Optional[float] = None,
189
+ initial_state: torch.Tensor = None,
190
+ output_final_state: bool = True,
191
+ cu_seqlens: Optional[torch.LongTensor] = None,
192
+ head_first: bool = False,
193
+ ):
194
+ """
195
+ Args:
196
+ r (torch.Tensor):
197
+ r of shape `[B, T, H, K]`.
198
+ w (torch.Tensor):
199
+ log decay of shape `[B, T, H, K]`.
200
+ k (torch.Tensor):
201
+ k of shape `[B, T, H, K]`.
202
+ v (torch.Tensor):
203
+ v of shape `[B, T, H, V]`.
204
+ a (torch.Tensor):
205
+ a of shape `[B, T, H, K]`.
206
+ b (torch.Tensor):
207
+ b of shape `[B, T, H, K]`.
208
+ scale (float):
209
+ scale of the attention.
210
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
211
+ initial_state (torch.Tensor):
212
+ initial state of shape `[B, H, K, V]` if cu_seqlens is None else `[N, H, K, V]` where N = len(cu_seqlens) - 1.
213
+ output_final_state (bool):
214
+ whether to output the final state.
215
+ cu_seqlens (torch.LongTensor):
216
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
217
+ consistent with the FlashAttention API.
218
+ head_first (Optional[bool]):
219
+ Whether the inputs are in the head-first format. Default: `False`.
220
+ This argument has been deprecated.
221
+ """
222
+ if head_first:
223
+ raise DeprecationWarning(
224
+ "head_first is deprecated and will be removed in a future version. "
225
+ "Please use head_first=False for now instead."
226
+ )
227
+ elif r.shape[1] < r.shape[2]:
228
+ warnings.warn(
229
+ f"Input tensor shape suggests potential format mismatch: seq_len ({r.shape[1]}) < num_heads ({r.shape[2]}). "
230
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
231
+ "when head_first=False was specified. "
232
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
233
+ )
234
+ return fused_recurrent_dplr_delta_rule(
235
+ q=r,
236
+ k=k,
237
+ v=v,
238
+ a=a,
239
+ b=b,
240
+ gk=w,
241
+ scale=scale,
242
+ initial_state=initial_state,
243
+ output_final_state=output_final_state,
244
+ cu_seqlens=cu_seqlens,
245
+ )
246
+
247
+
248
+ def fused_mul_recurrent_rwkv7(
249
+ r: torch.Tensor,
250
+ w: torch.Tensor,
251
+ k: torch.Tensor,
252
+ v: torch.Tensor,
253
+ kk: torch.Tensor,
254
+ a: torch.Tensor,
255
+ scale: Optional[float] = 1.0,
256
+ initial_state: Optional[torch.Tensor] = None,
257
+ output_final_state: bool = False,
258
+ reverse: bool = False,
259
+ cu_seqlens: Optional[torch.Tensor] = None,
260
+ head_first: bool = False,
261
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
262
+ r"""
263
+ This function computes the recurrence S_t = S_t @ (I + a_t b_t^T) + v_t k_t^T in a recurrent manner.
264
+
265
+ Args:
266
+ r (torch.Tensor):
267
+ queries of shape `[B, T, H, K]`.
268
+ w (torch.Tensor):
269
+ keys of shape `[B, T, H, K]`.
270
+ k (torch.Tensor):
271
+ values of shape `[B, T, H, V]`.
272
+ v (torch.Tensor):
273
+ a of shape `[B, T, H, K]`.
274
+ kk (torch.Tensor):
275
+ b of shape `[B, T, H, K]`.
276
+ a (torch.Tensor):
277
+ gk of shape `[B, T, H, K]`. decay term in log space!
278
+ scale (Optional[float]):
279
+ Scale factor for the RetNet attention scores.
280
+ If not provided, it will default to `1 / sqrt(K)`. Default: 1.
281
+ initial_state (Optional[torch.Tensor]):
282
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
283
+ For equal-length input sequences, `N` equals the batch size `B`.
284
+ Default: `None`.
285
+ output_final_state (Optional[bool]):
286
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
287
+ reverse (Optional[bool]):
288
+ If `True`, process the state passing in reverse order. Default: `False`.
289
+ cu_seqlens (Optional[torch.Tensor]):
290
+ Cumulative sequence lengths of shape `[N + 1]` used for variable-length training,
291
+ consistent with the FlashAttention API.
292
+ head_first (Optional[bool]):
293
+ Whether the inputs are in the head-first format. Default: `False`.
294
+ This argument has been deprecated.
295
+ """
296
+ if head_first:
297
+ raise DeprecationWarning(
298
+ "head_first is deprecated and will be removed in a future version. "
299
+ "Please use head_first=False for now instead."
300
+ )
301
+ elif r.shape[1] < r.shape[2]:
302
+ warnings.warn(
303
+ f"Input tensor shape suggests potential format mismatch: seq_len ({r.shape[1]}) < num_heads ({r.shape[2]}). "
304
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
305
+ "when head_first=False was specified. "
306
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
307
+ )
308
+ if cu_seqlens is not None:
309
+ if r.shape[0] != 1:
310
+ raise ValueError(
311
+ f"The batch size is expected to be 1 rather than {r.shape[0]} when using `cu_seqlens`."
312
+ f"Please flatten variable-length inputs before processing."
313
+ )
314
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
315
+ raise ValueError(
316
+ f"The number of initial states is expected to be equal to the number of input sequences, "
317
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
318
+ )
319
+ if scale is None:
320
+ scale = r.shape[-1] ** -0.5
321
+ o, final_state = fused_recurrent_rwkv7_fwd(
322
+ r,
323
+ w,
324
+ k,
325
+ v,
326
+ kk,
327
+ a,
328
+ scale,
329
+ initial_state,
330
+ output_final_state,
331
+ reverse,
332
+ cu_seqlens,
333
+ )
334
+ return o, final_state
@@ -0,0 +1,244 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import torch
4
+ import triton
5
+ import triton.language as tl
6
+
7
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
8
+
9
+
10
+ def gate_output_correction_ref(
11
+ o: torch.Tensor,
12
+ r: torch.Tensor,
13
+ k: torch.Tensor,
14
+ r_k: torch.Tensor,
15
+ v: torch.Tensor,
16
+ g: torch.Tensor,
17
+ ):
18
+ """
19
+ o: [B, T, H*D]
20
+ r: [B, T, H, D]
21
+ k: [B, T, H, D]
22
+ r_k: [H, D]
23
+ v: [B, T, H, D]
24
+ g: [B, T, H*D]
25
+ """
26
+ # Unsqueeze r_k for broadcasting across batch and time
27
+ correction_term = ((r * k * r_k.unsqueeze(0).unsqueeze(0)).sum(-1, keepdim=True) * v).view(o.shape)
28
+ output = (o + correction_term) * g
29
+ return output
30
+
31
+
32
+ def gate_output_correction_backward_ref(grad_output, o, r, k, r_k, v, g):
33
+ """
34
+ Reference backward pass implementation in pure PyTorch.
35
+ """
36
+ B, T, HD = o.shape
37
+ H, D = r.shape[-2], r.shape[-1]
38
+
39
+ # Unsqueeze r_k for broadcasting
40
+ r_k_b = r_k.unsqueeze(0).unsqueeze(0)
41
+ correction_scalar = (r * k * r_k_b).sum(-1, keepdim=True)
42
+ gated_input = o + (correction_scalar * v).view(B, T, HD)
43
+
44
+ grad_g = grad_output * gated_input
45
+ grad_gated_input = grad_output * g
46
+ grad_o = grad_gated_input
47
+ grad_correction = grad_gated_input
48
+ grad_correction_reshaped = grad_correction.view(B, T, H, D)
49
+ grad_v = grad_correction_reshaped * correction_scalar
50
+ grad_correction_scalar = (grad_correction_reshaped * v).sum(-1, keepdim=True)
51
+ grad_r_mul_k_mul_rk = grad_correction_scalar.expand_as(r)
52
+ grad_r = grad_r_mul_k_mul_rk * k * r_k_b
53
+ grad_k = grad_r_mul_k_mul_rk * r * r_k_b
54
+ # Sum over batch and time, keep the head dimension
55
+ grad_r_k = (grad_r_mul_k_mul_rk * r * k).sum(dim=(0, 1))
56
+ return grad_o, grad_r, grad_k, grad_r_k, grad_v, grad_g
57
+
58
+
59
+ @triton.autotune(
60
+ configs=[
61
+ triton.Config({'BT': BT}, num_warps=num_warps)
62
+ for num_warps in [2, 4, 8]
63
+ for BT in [2, 4, 8]
64
+ ],
65
+ key=['num_heads', 'head_dim', 'BLOCK_SIZE_D'],
66
+ )
67
+ @triton.jit
68
+ def gate_output_correction_fwd_kernel(
69
+ o_ptr, r_ptr, k_ptr, r_k_ptr, v_ptr, g_ptr, output_ptr,
70
+ o_b_stride, o_t_stride,
71
+ r_b_stride, r_t_stride, r_h_stride,
72
+ v_b_stride, v_t_stride, v_h_stride,
73
+ r_k_h_stride,
74
+ T,
75
+ T_OFFSET,
76
+ num_heads: tl.constexpr,
77
+ head_dim: tl.constexpr,
78
+ BLOCK_SIZE_D: tl.constexpr,
79
+ BT: tl.constexpr,
80
+ ):
81
+ pid_b, pid_t_block = tl.program_id(0), tl.program_id(1)
82
+ pid_h = tl.program_id(2)
83
+ t_start = pid_t_block * BT + T_OFFSET
84
+ t_idx = t_start + tl.arange(0, BT)[:, None]
85
+ mask_t = t_idx < T
86
+
87
+ d_idx = tl.arange(0, BLOCK_SIZE_D)[None, :]
88
+ mask_d = d_idx < head_dim
89
+ mask = mask_t & mask_d
90
+
91
+ offset_rk_h = pid_h * r_k_h_stride
92
+ vec_r_k = tl.load(r_k_ptr + offset_rk_h + d_idx, mask=mask_d, other=0.0).to(tl.float32)
93
+
94
+ offset_rh = pid_b * r_b_stride + t_idx * r_t_stride + pid_h * r_h_stride
95
+ offset_vh = pid_b * v_b_stride + t_idx * v_t_stride + pid_h * v_h_stride
96
+ vec_r = tl.load(r_ptr + offset_rh + d_idx, mask=mask, other=0.0).to(tl.float32)
97
+ vec_k = tl.load(k_ptr + offset_rh + d_idx, mask=mask, other=0.0).to(tl.float32)
98
+ vec_v = tl.load(v_ptr + offset_vh + d_idx, mask=mask, other=0.0).to(tl.float32)
99
+ correction = tl.sum(vec_r * vec_k * vec_r_k, axis=1)[:, None] * vec_v
100
+
101
+ offset_o = pid_b * o_b_stride + t_idx * o_t_stride + pid_h * head_dim
102
+ vec_o = tl.load(o_ptr + offset_o + d_idx, mask=mask, other=0.0).to(tl.float32)
103
+ vec_g = tl.load(g_ptr + offset_o + d_idx, mask=mask, other=0.0).to(tl.float32)
104
+ final_output = (vec_o + correction) * vec_g
105
+
106
+ tl.store(output_ptr + offset_o + d_idx, final_output.to(output_ptr.dtype.element_ty), mask=mask)
107
+
108
+
109
+ @triton.autotune(
110
+ configs=[
111
+ triton.Config({'BT': BT}, num_warps=num_warps, num_stages=num_stages)
112
+ for num_warps in [2, 4, 8]
113
+ for num_stages in [1, 2, 4]
114
+ for BT in [2, 4, 8]
115
+ ],
116
+ key=['num_heads', 'head_dim', 'BLOCK_SIZE_D'],
117
+ )
118
+ @triton.jit
119
+ def gate_output_correction_bwd_kernel(
120
+ grad_output_ptr, o_ptr, r_ptr, k_ptr, r_k_ptr, v_ptr, g_ptr,
121
+ grad_o_ptr, grad_r_ptr, grad_k_ptr, grad_r_k_intermediate_ptr, grad_v_ptr, grad_g_ptr,
122
+ r_b_stride, r_t_stride, r_h_stride, o_b_stride, o_t_stride, r_k_h_stride,
123
+ T,
124
+ T_OFFSET,
125
+ num_heads: tl.constexpr,
126
+ head_dim: tl.constexpr,
127
+ BLOCK_SIZE_D: tl.constexpr,
128
+ BT: tl.constexpr,
129
+ ):
130
+ pid_b, pid_t_block = tl.program_id(0), tl.program_id(1)
131
+ pid_h = tl.program_id(2)
132
+
133
+ t_idx = pid_t_block * BT + T_OFFSET + tl.arange(0, BT)[:, None]
134
+ mask_t = t_idx < T
135
+
136
+ d_idx = tl.arange(0, BLOCK_SIZE_D)[None, :]
137
+ mask_d = d_idx < head_dim
138
+ mask = mask_t & mask_d
139
+
140
+ rkv_offset = pid_b * r_b_stride + t_idx * r_t_stride + pid_h * r_h_stride
141
+ vec_r = tl.load(r_ptr + rkv_offset + d_idx, mask=mask, other=0.0).to(tl.float32)
142
+ vec_k = tl.load(k_ptr + rkv_offset + d_idx, mask=mask, other=0.0).to(tl.float32)
143
+ vec_v = tl.load(v_ptr + rkv_offset + d_idx, mask=mask, other=0.0).to(tl.float32)
144
+
145
+ og_offset = pid_b * o_b_stride + t_idx * o_t_stride + pid_h * head_dim
146
+ vec_o = tl.load(o_ptr + og_offset + d_idx, mask=mask, other=0.0).to(tl.float32)
147
+ vec_g = tl.load(g_ptr + og_offset + d_idx, mask=mask, other=0.0).to(tl.float32)
148
+ vec_grad_output = tl.load(grad_output_ptr + og_offset + d_idx, mask=mask, other=0.0).to(tl.float32)
149
+
150
+ offset_rk_h = pid_h * r_k_h_stride
151
+ vec_r_k = tl.load(r_k_ptr + offset_rk_h + d_idx, mask=mask_d, other=0.0).to(tl.float32)
152
+
153
+ prod_r_k_rk = vec_r * vec_k * vec_r_k
154
+ corr_scalar = tl.sum(prod_r_k_rk, axis=1)
155
+ corr_vec = corr_scalar[:, None] * vec_v
156
+ gated_input = vec_o + corr_vec
157
+
158
+ vec_grad_g = vec_grad_output * gated_input
159
+ vec_grad_gate = vec_grad_output * vec_g
160
+ vec_grad_o = vec_grad_gate
161
+ vec_grad_corr = vec_grad_gate
162
+ vec_grad_v = vec_grad_corr * corr_scalar[:, None]
163
+ grad_corr_s = tl.sum(vec_grad_corr * vec_v, axis=1)[:, None]
164
+ vec_grad_r = grad_corr_s * vec_k * vec_r_k
165
+ vec_grad_k = grad_corr_s * vec_r * vec_r_k
166
+ local_grad_rk = grad_corr_s * vec_r * vec_k
167
+
168
+ tl.store(grad_o_ptr + og_offset + d_idx, vec_grad_o.to(grad_o_ptr.dtype.element_ty), mask=mask)
169
+ tl.store(grad_g_ptr + og_offset + d_idx, vec_grad_g.to(grad_g_ptr.dtype.element_ty), mask=mask)
170
+ tl.store(grad_r_ptr + rkv_offset + d_idx, vec_grad_r.to(grad_r_ptr.dtype.element_ty), mask=mask)
171
+ tl.store(grad_k_ptr + rkv_offset + d_idx, vec_grad_k.to(grad_k_ptr.dtype.element_ty), mask=mask)
172
+ tl.store(grad_v_ptr + rkv_offset + d_idx, vec_grad_v.to(grad_v_ptr.dtype.element_ty), mask=mask)
173
+ tl.store(grad_r_k_intermediate_ptr + rkv_offset + d_idx,
174
+ local_grad_rk.to(grad_r_k_intermediate_ptr.dtype.element_ty), mask=mask)
175
+
176
+
177
+ def gate_output_correction_backward_triton(grad_output, o, r, k, r_k, v, g):
178
+ batch_size, seq_len, _ = o.shape
179
+ num_heads, head_dim = r.shape[-2], r.shape[-1]
180
+
181
+ grad_o = torch.empty_like(o)
182
+ grad_r = torch.empty_like(r)
183
+ grad_k = torch.empty_like(k)
184
+ grad_v = torch.empty_like(v)
185
+ grad_g = torch.empty_like(g)
186
+ # Keep intermediate in float32 for precision
187
+ grad_r_k = torch.empty_like(r, dtype=torch.float32)
188
+
189
+ BLOCK_SIZE_D = triton.next_power_of_2(head_dim)
190
+
191
+ for t_offset in range(0, seq_len, 65536):
192
+ T_SIZE = min(65536, seq_len - t_offset)
193
+ def grid(meta): return (batch_size, triton.cdiv(T_SIZE, meta['BT']), num_heads)
194
+
195
+ gate_output_correction_bwd_kernel[grid](
196
+ grad_output, o, r, k, r_k, v, g,
197
+ grad_o, grad_r, grad_k, grad_r_k, grad_v, grad_g,
198
+ r.stride(0), r.stride(1), r.stride(2),
199
+ o.stride(0), o.stride(1),
200
+ r_k.stride(0),
201
+ T_SIZE, t_offset,
202
+ num_heads=num_heads, head_dim=head_dim, BLOCK_SIZE_D=BLOCK_SIZE_D,
203
+ )
204
+ # Sum over batch and time to get the final gradient for r_k
205
+ grad_r_k = grad_r_k.sum(dim=(0, 1)).type_as(r_k)
206
+ return grad_o, grad_r, grad_k, grad_r_k, grad_v, grad_g
207
+
208
+
209
+ class GateOutputCorrection(torch.autograd.Function):
210
+ @staticmethod
211
+ @autocast_custom_fwd
212
+ @input_guard
213
+ def forward(ctx, o, r, k, r_k, v, g):
214
+ assert r_k.dim() == 2 and r_k.shape[0] == r.shape[-2] and r_k.shape[1] == r.shape[-1]
215
+
216
+ batch_size, seq_len, _ = o.shape
217
+ num_heads, head_dim = r.shape[-2], r.shape[-1]
218
+ output = torch.empty_like(o)
219
+ ctx.save_for_backward(o, r, k, r_k, v, g)
220
+ for t in range(0, seq_len, 65536):
221
+ T_OFFSET = t
222
+ T_SIZE = min(65536, seq_len - t)
223
+ def grid(meta): return (batch_size, triton.cdiv(T_SIZE, meta['BT']), num_heads)
224
+
225
+ gate_output_correction_fwd_kernel[grid](
226
+ o, r, k, r_k, v, g, output,
227
+ o.stride(0), o.stride(1),
228
+ r.stride(0), r.stride(1), r.stride(2),
229
+ v.stride(0), v.stride(1), v.stride(2),
230
+ r_k.stride(0),
231
+ T_SIZE, T_OFFSET,
232
+ num_heads, head_dim, BLOCK_SIZE_D=triton.next_power_of_2(head_dim)
233
+ )
234
+ return output
235
+
236
+ @staticmethod
237
+ @autocast_custom_bwd
238
+ @input_guard
239
+ def backward(ctx, grad_output):
240
+ o, r, k, r_k, v, g = ctx.saved_tensors
241
+ return gate_output_correction_backward_triton(grad_output, o, r, k, r_k, v, g)
242
+
243
+
244
+ gate_output_correction = GateOutputCorrection.apply
@@ -0,0 +1,13 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from .chunk import chunk_simple_gla
4
+ from .fused_chunk import fused_chunk_simple_gla
5
+ from .fused_recurrent import fused_recurrent_simple_gla
6
+ from .parallel import parallel_simple_gla
7
+
8
+ __all__ = [
9
+ 'chunk_simple_gla',
10
+ 'fused_chunk_simple_gla',
11
+ 'fused_recurrent_simple_gla',
12
+ 'parallel_simple_gla'
13
+ ]