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,268 @@
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 autocast_custom_bwd, autocast_custom_fwd, input_guard, use_cuda_graph
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.autotune(
20
+ configs=[
21
+ triton.Config({'BV': BV}, num_warps=num_warps, num_stages=num_stages)
22
+ for BV in [16, 32, 64]
23
+ for num_warps in [2, 4, 8, 16]
24
+ for num_stages in [2, 3, 4]
25
+ ],
26
+ key=['BK'],
27
+ use_cuda_graph=use_cuda_graph,
28
+ )
29
+ @triton.jit(do_not_specialize=['T'])
30
+ def fused_recurrent_dplr_delta_rule_fwd_kernel(
31
+ q,
32
+ k,
33
+ v,
34
+ a,
35
+ b,
36
+ gk,
37
+ o,
38
+ h0,
39
+ ht,
40
+ cu_seqlens,
41
+ scale,
42
+ T,
43
+ B: tl.constexpr,
44
+ H: tl.constexpr,
45
+ K: tl.constexpr,
46
+ V: tl.constexpr,
47
+ BK: tl.constexpr,
48
+ BV: tl.constexpr,
49
+ REVERSE: tl.constexpr,
50
+ USE_INITIAL_STATE: tl.constexpr,
51
+ STORE_FINAL_STATE: tl.constexpr,
52
+ IS_VARLEN: tl.constexpr,
53
+ ):
54
+ i_v, i_nh = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64)
55
+ i_n, i_h = i_nh // H, i_nh % H
56
+
57
+ if IS_VARLEN:
58
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int64), tl.load(cu_seqlens + i_n + 1).to(tl.int64)
59
+ T = eos - bos
60
+ else:
61
+ bos, eos = i_n * T, i_n * T + T
62
+
63
+ o_k = tl.arange(0, BK)
64
+ o_v = i_v * BV + tl.arange(0, BV)
65
+ p_q = q + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
66
+ p_k = k + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
67
+ p_a = a + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
68
+ p_b = b + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
69
+ p_gk = gk + (bos + ((T - 1) if REVERSE else 0)) * H*K + i_h * K + o_k
70
+ p_v = v + (bos + ((T - 1) if REVERSE else 0)) * H*V + i_h * V + o_v
71
+ p_o = o + (bos + ((T - 1) if REVERSE else 0)) * H*V + i_h * V + o_v
72
+
73
+ mask_k = o_k < K
74
+ mask_v = o_v < V
75
+ mask_h = mask_k[:, None] & mask_v[None, :]
76
+ b_h = tl.zeros([BK, BV], dtype=tl.float32)
77
+
78
+ if USE_INITIAL_STATE:
79
+ p_h0 = h0 + i_nh * K*V + o_k[:, None] * V + o_v
80
+ b_h += tl.load(p_h0, mask=mask_h, other=0).to(tl.float32)
81
+
82
+ for _ in range(0, T):
83
+ b_q = tl.load(p_q, mask=mask_k, other=0).to(tl.float32) * scale
84
+ b_k = tl.load(p_k, mask=mask_k, other=0).to(tl.float32)
85
+ b_a = tl.load(p_a, mask=mask_k, other=0).to(tl.float32)
86
+ b_b = tl.load(p_b, mask=mask_k, other=0).to(tl.float32)
87
+ b_gk = tl.load(p_gk, mask=mask_k, other=0).to(tl.float32)
88
+ b_v = tl.load(p_v, mask=mask_v, other=0).to(tl.float32)
89
+
90
+ b_h = exp(b_gk)[:, None] * b_h + b_b[:, None] * tl.sum(b_a[:, None] * b_h, 0)[None, :]
91
+ b_h += b_k[:, None] * b_v[None, :]
92
+ b_o = tl.sum(b_h * b_q[:, None], 0)
93
+
94
+ tl.store(p_o, b_o.to(p_o.dtype.element_ty), mask=mask_v)
95
+ p_q += (-1 if REVERSE else 1) * H*K
96
+ p_k += (-1 if REVERSE else 1) * H*K
97
+ p_a += (-1 if REVERSE else 1) * H*K
98
+ p_b += (-1 if REVERSE else 1) * H*K
99
+ p_gk += (-1 if REVERSE else 1) * H*K
100
+ p_v += (-1 if REVERSE else 1) * H*V
101
+ p_o += (-1 if REVERSE else 1) * H*V
102
+
103
+ if STORE_FINAL_STATE:
104
+ p_ht = ht + i_nh * K*V + o_k[:, None] * V + o_v
105
+ tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), mask=mask_h)
106
+
107
+
108
+ def fused_recurrent_dplr_delta_rule_fwd(
109
+ q: torch.Tensor,
110
+ k: torch.Tensor,
111
+ v: torch.Tensor,
112
+ a: torch.Tensor,
113
+ b: torch.Tensor,
114
+ gk: torch.Tensor,
115
+ scale: Optional[float] = 1.0,
116
+ initial_state: Optional[torch.Tensor] = None,
117
+ output_final_state: bool = False,
118
+ reverse: bool = False,
119
+ cu_seqlens: Optional[torch.LongTensor] = None,
120
+ ):
121
+ B, T, H, K, V = *k.shape, v.shape[-1]
122
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
123
+ BK = triton.next_power_of_2(K)
124
+
125
+ h0 = initial_state
126
+ ht = q.new_empty(N, H, K, V, dtype=torch.float32) if output_final_state else None
127
+ o = torch.empty_like(v)
128
+
129
+ def grid(meta): return (triton.cdiv(V, meta['BV']), N * H)
130
+ fused_recurrent_dplr_delta_rule_fwd_kernel[grid](
131
+ q=q,
132
+ k=k,
133
+ v=v,
134
+ a=a,
135
+ b=b,
136
+ gk=gk,
137
+ o=o,
138
+ h0=h0,
139
+ ht=ht,
140
+ cu_seqlens=cu_seqlens,
141
+ scale=scale,
142
+ T=T,
143
+ B=B,
144
+ H=H,
145
+ K=K,
146
+ V=V,
147
+ BK=BK,
148
+ REVERSE=reverse,
149
+ )
150
+ return o, ht
151
+
152
+
153
+ class FusedRecurrentDPLRDeltaRuleFunction(torch.autograd.Function):
154
+
155
+ @staticmethod
156
+ @input_guard
157
+ @autocast_custom_fwd
158
+ def forward(
159
+ ctx,
160
+ q: torch.Tensor,
161
+ k: torch.Tensor,
162
+ v: torch.Tensor,
163
+ a: torch.Tensor,
164
+ b: torch.Tensor,
165
+ gk: torch.Tensor,
166
+ scale: Optional[float] = None,
167
+ initial_state: Optional[torch.Tensor] = None,
168
+ output_final_state: bool = False,
169
+ reverse: bool = False,
170
+ cu_seqlens: Optional[torch.LongTensor] = None,
171
+ ):
172
+ o, ht = fused_recurrent_dplr_delta_rule_fwd(
173
+ q=q,
174
+ k=k,
175
+ v=v,
176
+ a=a,
177
+ b=b,
178
+ gk=gk,
179
+ scale=scale,
180
+ initial_state=initial_state,
181
+ output_final_state=output_final_state,
182
+ reverse=reverse,
183
+ cu_seqlens=cu_seqlens,
184
+ )
185
+ return o, ht
186
+
187
+ @staticmethod
188
+ @input_guard
189
+ @autocast_custom_bwd
190
+ def backward(ctx, do, dht):
191
+ raise NotImplementedError(
192
+ "Backward pass for fused_recurrent_dplr_delta_rule is not implemented and will not be supported. "
193
+ "This kernel is only for inference. "
194
+ "For training, please use `chunk_dplr_delta_rule`."
195
+ )
196
+
197
+
198
+ def fused_recurrent_dplr_delta_rule(
199
+ q: torch.Tensor,
200
+ k: torch.Tensor,
201
+ v: torch.Tensor,
202
+ a: torch.Tensor,
203
+ b: torch.Tensor,
204
+ gk: torch.Tensor,
205
+ scale: Optional[float] = None,
206
+ initial_state: Optional[torch.Tensor] = None,
207
+ output_final_state: bool = False,
208
+ reverse: bool = False,
209
+ cu_seqlens: Optional[torch.Tensor] = None,
210
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
211
+ r"""
212
+ This function computes the recurrence S_t = S_t @ (Diag(g_t) + a_t b_t^T) + v_t k_t^T in a recurrent manner.
213
+
214
+ Args:
215
+ q (torch.Tensor):
216
+ queries of shape `[B, T, H, K]`.
217
+ k (torch.Tensor):
218
+ keys of shape `[B, T, H, K]`.
219
+ v (torch.Tensor):
220
+ values of shape `[B, T, H, V]`.
221
+ a (torch.Tensor):
222
+ a of shape `[B, T, H, K]`.
223
+ b (torch.Tensor):
224
+ b of shape `[B, T, H, K]`.
225
+ gk (torch.Tensor):
226
+ gk of shape `[B, T, H, K]`. decay term in log space!
227
+ scale (Optional[float]):
228
+ Scale factor for the RetNet attention scores.
229
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
230
+ initial_state (Optional[torch.Tensor]):
231
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
232
+ For equal-length input sequences, `N` equals the batch size `B`.
233
+ Default: `None`.
234
+ output_final_state (Optional[bool]):
235
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
236
+ reverse (Optional[bool]):
237
+ If `True`, process the state passing in reverse order. Default: `False`.
238
+ cu_seqlens (Optional[torch.Tensor]):
239
+ Cumulative sequence lengths of shape `[N + 1]` used for variable-length training,
240
+ consistent with the FlashAttention API.
241
+ """
242
+ if cu_seqlens is not None:
243
+ if q.shape[0] != 1:
244
+ raise ValueError(
245
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
246
+ f"Please flatten variable-length inputs before processing."
247
+ )
248
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
249
+ raise ValueError(
250
+ f"The number of initial states is expected to be equal to the number of input sequences, "
251
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
252
+ )
253
+ if scale is None:
254
+ scale = q.shape[-1] ** -0.5
255
+ o, final_state = FusedRecurrentDPLRDeltaRuleFunction.apply(
256
+ q,
257
+ k,
258
+ v,
259
+ a,
260
+ b,
261
+ gk,
262
+ scale,
263
+ initial_state,
264
+ output_final_state,
265
+ reverse,
266
+ cu_seqlens,
267
+ )
268
+ return o, final_state
@@ -0,0 +1,96 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import torch
4
+ from einops import rearrange
5
+
6
+ # S_t = S_t @ (I + alpha_t beta_t^T) + v_t k_t^T
7
+ # q, k, alpha, beta [B, H, L, D_K]
8
+ # v [B, H, L, D_V]
9
+
10
+
11
+ def dplr_recurrence(q, k, v, alpha, beta, gk, initial_state=None, output_final_state=True):
12
+ orig_dtype = q.dtype
13
+ b, h, l, d_k = q.shape
14
+ q, k, v, beta, gk = map(lambda x: x.float(), [q, k, v, beta, gk])
15
+ d_v = v.shape[-1]
16
+ o = torch.zeros_like(v)
17
+ S = torch.zeros(b, h, d_k, d_v).to(v)
18
+ q = q * (d_k ** -0.5)
19
+
20
+ if initial_state is not None:
21
+ S += initial_state
22
+
23
+ for i in range(l):
24
+ _k = k[:, :, i]
25
+ _q = q[:, :, i]
26
+ _v = v[:, :, i]
27
+ _alpha = alpha[:, :, i].clone()
28
+ _beta = beta[:, :, i].clone()
29
+ _kv = _k[..., None] * _v[..., None, :] + (S.clone() * _alpha[..., None]).sum(-2, keepdim=True) * _beta[..., None]
30
+ S = S.clone() * gk[:, :, i].exp()[..., None] + _kv
31
+ o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S)
32
+ S = None if output_final_state is False else S
33
+ return o.to(orig_dtype), S
34
+
35
+
36
+ def dplr_chunkwise(q, k, v, alpha, beta, gk, initial_state=None, output_final_state=True, chunk_size=32):
37
+ b, h, l, d_k = q.shape
38
+ d_v = v.shape[-1]
39
+ q = q * (d_k ** -0.5)
40
+ v = v
41
+ assert l % chunk_size == 0
42
+
43
+ S = k.new_zeros(b, h, d_k, d_v).to(q)
44
+ if initial_state is not None:
45
+ S += initial_state
46
+
47
+ # note that diagonal is masked.
48
+ mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=q.device), diagonal=0)
49
+ q, k, v, alpha, beta, gk = map(lambda x: rearrange(x, 'b h (n c) d -> b h n c d',
50
+ c=chunk_size).float(), [q, k, v, alpha, beta, gk])
51
+
52
+ gk_cumsum = gk.cumsum(-2)
53
+
54
+ # v2 = (alpha @ k.transpose(-1, -2)).masked_fill_(mask, 0) @ v
55
+ A_ab = torch.zeros(b, h, l // chunk_size, chunk_size, chunk_size).to(q.device)
56
+ A_qk = torch.zeros(b, h, l // chunk_size, chunk_size, chunk_size).to(q.device)
57
+ A_ak = torch.zeros(b, h, l // chunk_size, chunk_size, chunk_size).to(q.device)
58
+ A_qb = torch.zeros(b, h, l // chunk_size, chunk_size, chunk_size).to(q.device)
59
+
60
+ for i in range(chunk_size):
61
+ alpha_i = alpha[:, :, :, i, None]
62
+ q_i = q[:, :, :, i, None]
63
+ gk_i = gk_cumsum[:, :, :, i, None]
64
+ mask = (torch.arange(chunk_size) <= i).to(q.device)
65
+ attn_i = (gk_i - gk_cumsum).masked_fill(~mask.unsqueeze(-1), float('-inf')).exp()
66
+ A_qk[:, :, :, i, :] = (q_i * k * attn_i).sum(-1).clone()
67
+ A_qb[:, :, :, i, :] = (q_i * beta * attn_i).sum(-1).clone()
68
+ mask = (torch.arange(chunk_size) < i).to(q.device)
69
+ # shift by one.
70
+ attn_i = (gk_i - gk[:, :, :, i, None] - gk_cumsum).masked_fill(~mask.unsqueeze(-1), float('-inf')).exp()
71
+ A_ab[:, :, :, i, :] = (alpha_i * beta * attn_i).sum(-1).clone()
72
+ A_ak[:, :, :, i, :] = (alpha_i * k * attn_i).sum(-1).clone()
73
+
74
+ A_ab = A_ab
75
+ for i in range(1, chunk_size):
76
+ A_ab[..., i, :i] = A_ab[..., i, :i].clone() + (A_ab[..., i, :, None].clone() * A_ab[..., :, :i].clone()).sum(-2)
77
+
78
+ A_ab = A_ab + torch.eye(chunk_size, dtype=torch.float, device=q.device)
79
+ u = A_ab @ (A_ak @ v)
80
+ w = A_ab @ ((gk_cumsum-gk).exp() * alpha)
81
+
82
+ o = torch.zeros_like(v)
83
+ mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=q.device), diagonal=1)
84
+ for i in range(0, l // chunk_size):
85
+ q_i, k_i, v_i, u_i, w_i, beta_i = q[:, :, i], k[:, :, i], v[:, :, i], u[:, :, i], w[:, :, i], beta[:, :, i]
86
+ v2_i = u_i + w_i @ S
87
+
88
+ o_1 = A_qk[:, :, i] @ v_i
89
+ o_2 = A_qb[:, :, i] @ v2_i
90
+ o_3 = (q_i * gk_cumsum[:, :, i].exp()) @ S
91
+ o[:, :, i] = o_1 + o_2 + o_3
92
+ decay = (gk_cumsum[:, :, i, -1, None] - gk_cumsum[:, :, i]).exp()
93
+ S = S*gk_cumsum[:, :, i, -1, :, None].exp() + (k_i * decay).transpose(-1, -2) @ v_i + \
94
+ (beta_i * decay).transpose(-1, -2) @ v2_i
95
+ S = None if output_final_state is False else S
96
+ return rearrange(o, 'b h n c d -> b h (n c) d'), S
@@ -0,0 +1,164 @@
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 prepare_chunk_indices
11
+ from fla.utils import check_shared_mem, is_intel_alchemist, use_cuda_graph
12
+
13
+ # https://github.com/intel/intel-xpu-backend-for-triton/issues/3449
14
+ triton_config = {'grf_mode': 'large'} if is_intel_alchemist else {}
15
+
16
+
17
+ @triton.heuristics({
18
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
19
+ })
20
+ @triton.autotune(
21
+ configs=[
22
+ triton.Config(triton_config, num_warps=num_warps, num_stages=num_stages)
23
+ for num_warps in [2, 4, 8, 16]
24
+ for num_stages in [2, 3, 4]
25
+ ],
26
+ key=['BT', 'BK', 'BV'],
27
+ use_cuda_graph=use_cuda_graph,
28
+ )
29
+ @triton.jit(do_not_specialize=['T'])
30
+ def prepare_wy_repr_bwd_kernel(
31
+ A_ab_inv,
32
+ A_ak,
33
+ ag,
34
+ v,
35
+ dw,
36
+ du,
37
+ dv,
38
+ dv0,
39
+ dag,
40
+ dAak,
41
+ dAab,
42
+ cu_seqlens,
43
+ chunk_indices,
44
+ T,
45
+ H: tl.constexpr,
46
+ K: tl.constexpr,
47
+ V: tl.constexpr,
48
+ BT: tl.constexpr,
49
+ BK: tl.constexpr,
50
+ BV: tl.constexpr,
51
+ IS_VARLEN: tl.constexpr,
52
+ ):
53
+ i_t, i_bh = tl.program_id(0), tl.program_id(1)
54
+ i_b, i_h = i_bh // H, i_bh % H
55
+ if IS_VARLEN:
56
+ i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
57
+ bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
58
+ T = eos - bos
59
+ else:
60
+ bos, eos = i_b * T, i_b * T + T
61
+
62
+ p_Aak_t = tl.make_block_ptr(A_ak + (bos*H + i_h) * BT, (BT, T), (1, H*BT), (0, i_t * BT), (BT, BT), (0, 1))
63
+ p_Aab_inv_t = tl.make_block_ptr(A_ab_inv + (bos*H + i_h) * BT, (BT, T), (1, H*BT), (0, i_t * BT), (BT, BT), (0, 1))
64
+ p_dAak = tl.make_block_ptr(dAak + (bos*H + i_h) * BT, (T, BT), (H*BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
65
+ p_dAab = tl.make_block_ptr(dAab + (bos*H + i_h) * BT, (T, BT), (H*BT, 1), (i_t * BT, 0), (BT, BT), (1, 0))
66
+
67
+ b_A_ab_inv_t = tl.load(p_Aab_inv_t, boundary_check=(0, 1))
68
+ b_A_ak_t = tl.load(p_Aak_t, boundary_check=(0, 1))
69
+ b_A_ak_t = tl.where(tl.arange(0, BT)[:, None] < tl.arange(0, BT)[None, :], b_A_ak_t, 0)
70
+ b_A_ab_inv_t = tl.where(tl.arange(0, BT)[:, None] <= tl.arange(0, BT)[None, :], b_A_ab_inv_t, 0)
71
+ b_A_tmp_t = tl.dot(b_A_ak_t, b_A_ab_inv_t).to(v.dtype.element_ty)
72
+ b_dA_tmp = tl.zeros([BT, BT], dtype=tl.float32)
73
+
74
+ for i_v in range(tl.cdiv(V, BV)):
75
+ p_v = tl.make_block_ptr(v + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
76
+ p_dv = tl.make_block_ptr(dv + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
77
+ p_dv0 = tl.make_block_ptr(dv0 + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
78
+ p_du = tl.make_block_ptr(du + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
79
+ b_v = tl.load(p_v, boundary_check=(0, 1))
80
+ b_du = tl.load(p_du, boundary_check=(0, 1))
81
+ b_dA_tmp += tl.dot(b_du.to(b_v.dtype), tl.trans(b_v))
82
+ b_dv0 = tl.load(p_dv0, boundary_check=(0, 1))
83
+ b_dv = b_dv0 + tl.dot(b_A_tmp_t, b_du)
84
+ tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))
85
+
86
+ m_i = tl.arange(0, BT)[:, None] > tl.arange(0, BT)[None, :]
87
+ b_dA_tmp = tl.where(m_i, b_dA_tmp, 0)
88
+ b_dA_ak = tl.dot(b_A_ab_inv_t, b_dA_tmp)
89
+ b_dA_ak = tl.where(m_i, b_dA_ak, 0)
90
+ tl.store(p_dAak, b_dA_ak, boundary_check=(0, 1))
91
+ b_dA_ab_inv = tl.dot(b_dA_tmp, b_A_ak_t)
92
+
93
+ for i_k in range(tl.cdiv(K, BK)):
94
+ p_ag = tl.make_block_ptr(ag + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
95
+ p_dag = tl.make_block_ptr(dag + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
96
+ p_dw = tl.make_block_ptr(dw + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
97
+ b_ag = tl.load(p_ag, boundary_check=(0, 1))
98
+ b_dw = tl.load(p_dw, boundary_check=(0, 1))
99
+ b_dA_ab_inv += tl.dot(b_dw, tl.trans(b_ag))
100
+ b_dag = tl.dot(b_A_ab_inv_t.to(b_dw.dtype), b_dw)
101
+ tl.store(p_dag, b_dag.to(p_dag.dtype.element_ty), boundary_check=(0, 1))
102
+
103
+ # if we know dL/dA^(-1), for dL/dA, we can use the following formula:
104
+ # dL/dA = -(A^(-1))^T @ (dL/dA^(-1)) @ (A^(-1))^T
105
+ # in the fwd pass we use fwd substitution to calculate (I-lower(A_ab))^-1.
106
+ # denote A = I - lower(A_ab), B = A^-1
107
+ # in the backward pass.
108
+ # dL/dA = -(B)^T @ (dL/dB) @ B^T
109
+ # dL/dA_ab = lower(B^T @ dL/dB @ B^T)
110
+ b_dA_ab_inv = tl.where(tl.arange(0, BT)[:, None] >= tl.arange(0, BT)[None, :], b_dA_ab_inv, 0)
111
+ b_dA_ab_inv = tl.dot(b_A_ab_inv_t, b_dA_ab_inv)
112
+ b_dA_ab_inv = tl.dot(b_dA_ab_inv, b_A_ab_inv_t)
113
+ b_dA_ab_inv = tl.where(m_i, b_dA_ab_inv, 0)
114
+ tl.store(p_dAab, b_dA_ab_inv, boundary_check=(0, 1))
115
+
116
+
117
+ def chunk_dplr_bwd_wy(
118
+ A_ab_inv: torch.Tensor,
119
+ A_ak: torch.Tensor,
120
+ v: torch.Tensor,
121
+ ag: torch.Tensor,
122
+ dw: torch.Tensor,
123
+ du: torch.Tensor,
124
+ dv0: torch.Tensor,
125
+ cu_seqlens: Optional[torch.LongTensor],
126
+ chunk_size: int,
127
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
128
+ A_ab_inv, A_ak, v, ag, dw, du = map(lambda x: x.contiguous(), [A_ab_inv, A_ak, v, ag, dw, du])
129
+ B, T, H, K, V = *dw.shape, du.shape[-1]
130
+ BT = min(chunk_size, max(triton.next_power_of_2(T), 16))
131
+
132
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
133
+ NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
134
+ BK = min(max(triton.next_power_of_2(K), 16), 64)
135
+ BV = min(max(triton.next_power_of_2(V), 16), 64) if check_shared_mem() else min(max(triton.next_power_of_2(V), 16), 32)
136
+
137
+ dA_ab = torch.empty_like(A_ab_inv, dtype=torch.float)
138
+ dA_ak = torch.empty_like(A_ak, dtype=torch.float)
139
+ dv = torch.empty_like(v)
140
+ dag = torch.empty_like(ag)
141
+
142
+ prepare_wy_repr_bwd_kernel[(NT, B * H)](
143
+ A_ab_inv=A_ab_inv,
144
+ A_ak=A_ak,
145
+ ag=ag,
146
+ v=v,
147
+ dw=dw,
148
+ du=du,
149
+ dv=dv,
150
+ dv0=dv0,
151
+ dag=dag,
152
+ dAak=dA_ak,
153
+ dAab=dA_ab,
154
+ cu_seqlens=cu_seqlens,
155
+ chunk_indices=chunk_indices,
156
+ T=T,
157
+ H=H,
158
+ K=K,
159
+ V=V,
160
+ BT=BT,
161
+ BK=BK,
162
+ BV=BV,
163
+ )
164
+ return dA_ab, dA_ak, dv, dag