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,303 @@
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
+
10
+ from fla.ops.common.chunk_h import chunk_bwd_dh, chunk_fwd_h
11
+ from fla.ops.common.chunk_o import chunk_bwd_dqkwg, chunk_bwd_dv, chunk_fwd_o
12
+ from fla.ops.utils import chunk_local_cumsum
13
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
14
+
15
+
16
+ def chunk_simple_gla_fwd(
17
+ q: torch.Tensor,
18
+ k: torch.Tensor,
19
+ v: torch.Tensor,
20
+ g: Optional[torch.Tensor] = None,
21
+ g_gamma: Optional[torch.Tensor] = None,
22
+ scale: Optional[float] = None,
23
+ initial_state: Optional[torch.Tensor] = None,
24
+ output_final_state: bool = False,
25
+ cu_seqlens: Optional[torch.LongTensor] = None,
26
+ chunk_size: int = 64
27
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
28
+ h, ht = chunk_fwd_h(
29
+ k=k,
30
+ v=v,
31
+ g=g,
32
+ g_gamma=g_gamma,
33
+ gk=None,
34
+ gv=None,
35
+ h0=initial_state,
36
+ output_final_state=output_final_state,
37
+ states_in_fp32=False,
38
+ cu_seqlens=cu_seqlens,
39
+ chunk_size=chunk_size
40
+ )
41
+ o = chunk_fwd_o(
42
+ q=q,
43
+ k=k,
44
+ v=v,
45
+ g=g,
46
+ g_gamma=g_gamma,
47
+ h=h,
48
+ scale=scale,
49
+ cu_seqlens=cu_seqlens,
50
+ chunk_size=chunk_size
51
+ )
52
+ return o, ht
53
+
54
+
55
+ def chunk_simple_gla_bwd(
56
+ q: torch.Tensor,
57
+ k: torch.Tensor,
58
+ v: torch.Tensor,
59
+ g: torch.Tensor,
60
+ g_gamma: torch.Tensor,
61
+ initial_state: torch.Tensor,
62
+ do: torch.Tensor,
63
+ dht: torch.Tensor,
64
+ scale: float,
65
+ cu_seqlens: Optional[torch.LongTensor] = None,
66
+ chunk_size: int = 64
67
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
68
+ # (SY 09/22) states_in_fp32 seems not affecting the error of dg but for safety, set to True
69
+ h, _ = chunk_fwd_h(
70
+ k=k,
71
+ v=v,
72
+ g=g,
73
+ g_gamma=g_gamma,
74
+ gk=None,
75
+ gv=None,
76
+ h0=initial_state,
77
+ output_final_state=False,
78
+ states_in_fp32=True,
79
+ cu_seqlens=cu_seqlens,
80
+ chunk_size=chunk_size
81
+ )
82
+ dh, dh0 = chunk_bwd_dh(
83
+ q=q,
84
+ k=k,
85
+ v=v,
86
+ g=g,
87
+ g_gamma=g_gamma,
88
+ gk=None,
89
+ gv=None,
90
+ do=do,
91
+ h0=initial_state,
92
+ dht=dht,
93
+ scale=scale,
94
+ states_in_fp32=True,
95
+ cu_seqlens=cu_seqlens,
96
+ chunk_size=chunk_size
97
+ )
98
+ dq, dk, _, dg = chunk_bwd_dqkwg(
99
+ q=q,
100
+ k=k,
101
+ v=v,
102
+ g=g,
103
+ g_gamma=g_gamma,
104
+ h=h,
105
+ do=do,
106
+ dh=dh,
107
+ scale=scale,
108
+ cu_seqlens=cu_seqlens,
109
+ chunk_size=chunk_size
110
+ )
111
+ dv = chunk_bwd_dv(
112
+ q=q,
113
+ k=k,
114
+ g=g,
115
+ g_gamma=g_gamma,
116
+ do=do,
117
+ dh=dh,
118
+ scale=scale,
119
+ cu_seqlens=cu_seqlens,
120
+ chunk_size=chunk_size
121
+ )
122
+ return dq, dk, dv, dg, dh0
123
+
124
+
125
+ class ChunkSimpleGLAFunction(torch.autograd.Function):
126
+
127
+ @staticmethod
128
+ @input_guard
129
+ @autocast_custom_fwd
130
+ def forward(
131
+ ctx,
132
+ q,
133
+ k,
134
+ v,
135
+ g,
136
+ g_gamma,
137
+ scale,
138
+ initial_state,
139
+ output_final_state,
140
+ cu_seqlens
141
+ ):
142
+ T = q.shape[1]
143
+ chunk_size = min(64, max(16, triton.next_power_of_2(T)))
144
+
145
+ g = chunk_local_cumsum(g, chunk_size=chunk_size, cu_seqlens=cu_seqlens) if g is not None else None
146
+ o, ht = chunk_simple_gla_fwd(
147
+ q=q,
148
+ k=k,
149
+ v=v,
150
+ g=g,
151
+ g_gamma=g_gamma,
152
+ scale=scale,
153
+ initial_state=initial_state,
154
+ output_final_state=output_final_state,
155
+ cu_seqlens=cu_seqlens,
156
+ chunk_size=chunk_size
157
+ )
158
+ ctx.save_for_backward(q, k, v, g, g_gamma, initial_state)
159
+ ctx.chunk_size = chunk_size
160
+ ctx.scale = scale
161
+ ctx.cu_seqlens = cu_seqlens
162
+ return o.to(q.dtype), ht
163
+
164
+ @staticmethod
165
+ @input_guard
166
+ @autocast_custom_bwd
167
+ def backward(ctx, do, dht):
168
+ chunk_size, scale, cu_seqlens = ctx.chunk_size, ctx.scale, ctx.cu_seqlens
169
+ q, k, v, g, g_gamma, initial_state = ctx.saved_tensors
170
+ dq, dk, dv, dg, dh0 = chunk_simple_gla_bwd(
171
+ q=q,
172
+ k=k,
173
+ v=v,
174
+ g=g,
175
+ g_gamma=g_gamma,
176
+ initial_state=initial_state,
177
+ do=do,
178
+ dht=dht,
179
+ scale=scale,
180
+ cu_seqlens=cu_seqlens,
181
+ chunk_size=chunk_size
182
+ )
183
+ if g is not None:
184
+ dg = chunk_local_cumsum(dg, chunk_size=chunk_size, reverse=True, cu_seqlens=cu_seqlens).to(g)
185
+ else:
186
+ dg = None
187
+ return dq.to(q), dk.to(k), dv.to(v), dg, None, None, dh0, None, None
188
+
189
+
190
+ @torch.compiler.disable
191
+ def chunk_simple_gla(
192
+ q: torch.Tensor,
193
+ k: torch.Tensor,
194
+ v: torch.Tensor,
195
+ g: Optional[torch.Tensor] = None,
196
+ g_gamma: Optional[torch.Tensor] = None,
197
+ scale: Optional[float] = None,
198
+ initial_state: Optional[torch.Tensor] = None,
199
+ output_final_state: bool = False,
200
+ cu_seqlens: Optional[torch.LongTensor] = None,
201
+ head_first: bool = False
202
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
203
+ r"""
204
+ Args:
205
+ q (torch.Tensor):
206
+ queries of shape `[B, T, H, K]`.
207
+ k (torch.Tensor):
208
+ keys of shape `[B, T, H, K]`.
209
+ v (torch.Tensor):
210
+ values of shape `[B, T, H, V]`.
211
+ g (torch.Tensor):
212
+ Forget gates of shape `[B, T, H]`.
213
+ Compared to GLA, the gating is head-wise instead of elementwise.
214
+ g_gamma (torch.Tensor):
215
+ Log decay of shape `[H]`.
216
+ Head-wise data-independent decay is used if `g_gamma` is provided.
217
+ Only one of `g` or `g_gamma` should be provided.
218
+ scale (Optional[float]):
219
+ Scale factor for the attention scores.
220
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
221
+ initial_state (Optional[torch.Tensor]):
222
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
223
+ For equal-length input sequences, `N` equals the batch size `B`.
224
+ Default: `None`.
225
+ output_final_state (Optional[bool]):
226
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
227
+ cu_seqlens (torch.LongTensor):
228
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
229
+ consistent with the FlashAttention API.
230
+ head_first (Optional[bool]):
231
+ Whether the inputs are in the head-first format. Default: `False`.
232
+ This argument has been deprecated.
233
+
234
+ Returns:
235
+ o (torch.Tensor):
236
+ Outputs of shape `[B, T, H, V]`.
237
+ final_state (torch.Tensor):
238
+ Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
239
+
240
+ Examples::
241
+ >>> import torch
242
+ >>> import torch.nn.functional as F
243
+ >>> from einops import rearrange
244
+ >>> from fla.ops.simple_gla import chunk_simple_gla
245
+ # inputs with equal lengths
246
+ >>> B, T, H, K, V = 4, 2048, 4, 512, 512
247
+ >>> q = torch.randn(B, T, H, K, device='cuda')
248
+ >>> k = torch.randn(B, T, H, K, device='cuda')
249
+ >>> v = torch.randn(B, T, H, V, device='cuda')
250
+ >>> g = F.logsigmoid(torch.randn(B, T, H, device='cuda'))
251
+ >>> o, ht = chunk_simple_gla(
252
+ q, k, v, g,
253
+ initial_state=None,
254
+ output_final_state=True
255
+ )
256
+ # for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
257
+ >>> q, k, v, g = map(lambda x: rearrange(x, 'b t ... -> 1 (b t) ...'), (q, k, v, g))
258
+ # for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
259
+ >>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
260
+ >>> o_var, ht_var = chunk_simple_gla(
261
+ q, k, v, g,
262
+ initial_state=None,
263
+ output_final_state=True,
264
+ cu_seqlens=cu_seqlens
265
+ )
266
+ """
267
+ if head_first:
268
+ raise DeprecationWarning(
269
+ "head_first is deprecated and will be removed in a future version. "
270
+ "Please use head_first=False for now instead."
271
+ )
272
+ if not head_first and q.shape[1] < q.shape[2]:
273
+ warnings.warn(
274
+ f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
275
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
276
+ "when head_first=False was specified. "
277
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
278
+ )
279
+ if cu_seqlens is not None:
280
+ if q.shape[0] != 1:
281
+ raise ValueError(
282
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
283
+ f"Please flatten variable-length inputs before processing."
284
+ )
285
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
286
+ raise ValueError(
287
+ f"The number of initial states is expected to be equal to the number of input sequences, "
288
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
289
+ )
290
+ if scale is None:
291
+ scale = k.shape[-1] ** -0.5
292
+ o, final_state = ChunkSimpleGLAFunction.apply(
293
+ q,
294
+ k,
295
+ v,
296
+ g,
297
+ g_gamma,
298
+ scale,
299
+ initial_state,
300
+ output_final_state,
301
+ cu_seqlens
302
+ )
303
+ return o, final_state
@@ -0,0 +1,108 @@
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
+
8
+ from fla.ops.common.fused_chunk import fused_chunk
9
+
10
+
11
+ def fused_chunk_simple_gla(
12
+ q: torch.Tensor,
13
+ k: torch.Tensor,
14
+ v: torch.Tensor,
15
+ g: torch.Tensor = None,
16
+ g_gamma: torch.Tensor = None,
17
+ scale: Optional[float] = None,
18
+ initial_state: Optional[torch.Tensor] = None,
19
+ output_final_state: bool = False,
20
+ cu_seqlens: Optional[torch.LongTensor] = None,
21
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
22
+ r"""
23
+ Args:
24
+ q (torch.Tensor):
25
+ queries of shape `[B, T, H, K]`.
26
+ k (torch.Tensor):
27
+ keys of shape `[B, T, H, K]`.
28
+ v (torch.Tensor):
29
+ values of shape `[B, T, H, V]`.
30
+ g (torch.Tensor):
31
+ Forget gates of shape `[B, T, H]`.
32
+ Compared to GLA, the gating is head-wise instead of elementwise.
33
+ g_gamma (torch.Tensor):
34
+ Log decay of shape `[H]`.
35
+ Head-wise data-independent decay is used if `g_gamma` is provided.
36
+ Only one of `g` or `g_gamma` should be provided.
37
+ scale (Optional[int]):
38
+ Scale factor for the attention scores.
39
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
40
+ initial_state (Optional[torch.Tensor]):
41
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
42
+ For equal-length input sequences, `N` equals the batch size `B`.
43
+ Default: `None`.
44
+ output_final_state (Optional[bool]):
45
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
46
+ cu_seqlens (torch.LongTensor):
47
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
48
+ consistent with the FlashAttention API.
49
+
50
+ Returns:
51
+ o (torch.Tensor):
52
+ Outputs of shape `[B, T, H, V]`.
53
+ final_state (torch.Tensor):
54
+ Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
55
+
56
+ Examples::
57
+ >>> import torch
58
+ >>> import torch.nn.functional as F
59
+ >>> from einops import rearrange
60
+ >>> from fla.ops.simple_gla import fused_chunk_simple_gla
61
+ # inputs with equal lengths
62
+ >>> B, T, H, K, V = 4, 2048, 4, 512, 512
63
+ >>> q = torch.randn(B, T, H, K, device='cuda')
64
+ >>> k = torch.randn(B, T, H, K, device='cuda')
65
+ >>> v = torch.randn(B, T, H, V, device='cuda')
66
+ >>> g = F.logsigmoid(torch.randn(B, T, H, device='cuda'))
67
+ >>> h0 = torch.randn(B, H, K, V, device='cuda')
68
+ >>> o, ht = fused_chunk_simple_gla(
69
+ q, k, v, g,
70
+ initial_state=h0,
71
+ output_final_state=True
72
+ )
73
+ # for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
74
+ >>> q, k, v, g = map(lambda x: rearrange(x, 'b t h d -> 1 (b t) h d'), (q, k, v, g))
75
+ # for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
76
+ >>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
77
+ >>> o, ht = fused_chunk_simple_gla(
78
+ q, k, v, g,
79
+ initial_state=h0,
80
+ output_final_state=True,
81
+ cu_seqlens=cu_seqlens
82
+ )
83
+ """
84
+ if cu_seqlens is not None:
85
+ if q.shape[0] != 1:
86
+ raise ValueError(
87
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
88
+ f"Please flatten variable-length inputs before processing."
89
+ )
90
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
91
+ raise ValueError(
92
+ f"The number of initial states is expected to be equal to the number of input sequences, "
93
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
94
+ )
95
+ if scale is None:
96
+ scale = k.shape[-1] ** -0.5
97
+ o, final_state = fused_chunk(
98
+ q=q,
99
+ k=k,
100
+ v=v,
101
+ g=g,
102
+ g_gamma=g_gamma,
103
+ scale=scale,
104
+ initial_state=initial_state,
105
+ output_final_state=output_final_state,
106
+ cu_seqlens=cu_seqlens
107
+ )
108
+ return o, final_state
@@ -0,0 +1,112 @@
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
+
8
+ from fla.ops.common.fused_recurrent import fused_recurrent
9
+
10
+
11
+ def fused_recurrent_simple_gla(
12
+ q: torch.Tensor,
13
+ k: torch.Tensor,
14
+ v: torch.Tensor,
15
+ g: torch.Tensor = None,
16
+ g_gamma: torch.Tensor = None,
17
+ scale: Optional[float] = None,
18
+ initial_state: Optional[torch.Tensor] = None,
19
+ output_final_state: bool = False,
20
+ reverse: bool = False,
21
+ cu_seqlens: Optional[torch.LongTensor] = None,
22
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
23
+ r"""
24
+ Args:
25
+ q (torch.Tensor):
26
+ queries of shape `[B, T, H, K]`.
27
+ k (torch.Tensor):
28
+ keys of shape `[B, T, H, K]`.
29
+ v (torch.Tensor):
30
+ values of shape `[B, T, H, V]`.
31
+ g (torch.Tensor):
32
+ Forget gates of shape `[B, T, H]`.
33
+ Compared to GLA, the gating is head-wise instead of elementwise.
34
+ g_gamma (torch.Tensor):
35
+ Log decay of shape `[H]`.
36
+ Head-wise data-independent decay is used if `g_gamma` is provided.
37
+ Only one of `g` or `g_gamma` should be provided.
38
+ scale (Optional[float]):
39
+ Scale factor for the attention scores.
40
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
41
+ initial_state (Optional[torch.Tensor]):
42
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
43
+ For equal-length input sequences, `N` equals the batch size `B`.
44
+ Default: `None`.
45
+ output_final_state (Optional[bool]):
46
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
47
+ reverse (Optional[bool]):
48
+ If `True`, process the state passing in reverse order. Default: `False`.
49
+ cu_seqlens (torch.LongTensor):
50
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
51
+ consistent with the FlashAttention API.
52
+
53
+ Returns:
54
+ o (torch.Tensor):
55
+ Outputs of shape `[B, T, H, V]`.
56
+ final_state (torch.Tensor):
57
+ Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
58
+
59
+ Examples::
60
+ >>> import torch
61
+ >>> import torch.nn.functional as F
62
+ >>> from einops import rearrange
63
+ >>> from fla.ops.simple_gla import fused_recurrent_simple_gla
64
+ # inputs with equal lengths
65
+ >>> B, T, H, K, V = 4, 2048, 4, 512, 512
66
+ >>> q = torch.randn(B, T, H, K, device='cuda')
67
+ >>> k = torch.randn(B, T, H, K, device='cuda')
68
+ >>> v = torch.randn(B, T, H, V, device='cuda')
69
+ >>> g = F.logsigmoid(torch.randn(B, T, H, K, device='cuda'))
70
+ >>> h0 = torch.randn(B, H, K, V, device='cuda')
71
+ >>> o, ht = fused_recurrent_simple_gla(
72
+ q, k, v, g,
73
+ initial_state=h0,
74
+ output_final_state=True
75
+ )
76
+ # for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
77
+ >>> q, k, v, g = map(lambda x: rearrange(x, 'b t h d -> 1 (b t) h d'), (q, k, v, g))
78
+ # for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
79
+ >>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
80
+ >>> o_var, ht_var = fused_recurrent_simple_gla(
81
+ q, k, v, g,
82
+ initial_state=h0,
83
+ output_final_state=True,
84
+ cu_seqlens=cu_seqlens
85
+ )
86
+ """
87
+ if cu_seqlens is not None:
88
+ if q.shape[0] != 1:
89
+ raise ValueError(
90
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
91
+ f"Please flatten variable-length inputs before processing."
92
+ )
93
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
94
+ raise ValueError(
95
+ f"The number of initial states is expected to be equal to the number of input sequences, "
96
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
97
+ )
98
+ if scale is None:
99
+ scale = k.shape[-1] ** -0.5
100
+ o, final_state = fused_recurrent(
101
+ q=q,
102
+ k=k,
103
+ v=v,
104
+ g=g,
105
+ g_gamma=g_gamma,
106
+ scale=scale,
107
+ initial_state=initial_state,
108
+ output_final_state=output_final_state,
109
+ reverse=reverse,
110
+ cu_seqlens=cu_seqlens
111
+ )
112
+ return o, final_state
@@ -0,0 +1,114 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from typing import Optional
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from einops import rearrange
8
+
9
+
10
+ def naive_chunk_simple_gla(
11
+ q: torch.Tensor,
12
+ k: torch.Tensor,
13
+ v: torch.Tensor,
14
+ g: torch.Tensor,
15
+ initial_state: Optional[torch.Tensor] = None,
16
+ output_final_state: bool = False,
17
+ chunk_size: int = 64,
18
+ scale: Optional[float] = None,
19
+ ):
20
+ q, k, v, g = map(lambda x: rearrange(x, 'b t h ... -> b h t ...').to(torch.float32), [q, k, v, g])
21
+ if scale is None:
22
+ scale = 1.0 / q.shape[-1] ** 0.5
23
+
24
+ T = q.shape[-2]
25
+ BT = chunk_size
26
+ pad_len = (BT - (T % BT)) % BT
27
+ if pad_len > 0:
28
+ # Pad all tensors
29
+ q = F.pad(q, (0, 0, 0, pad_len))
30
+ k = F.pad(k, (0, 0, 0, pad_len))
31
+ v = F.pad(v, (0, 0, 0, pad_len))
32
+ g = F.pad(g, (0, pad_len))
33
+ decay = g
34
+ B, H, T1, K = q.shape
35
+ V = v.shape[-1]
36
+ q = q * scale
37
+ q, k, v, decay = map(lambda x: rearrange(x, 'b h (n c) d -> b h n c d', c=chunk_size), [q, k, v, decay.unsqueeze(-1)])
38
+ decay = decay.squeeze(-1).cumsum(-1)
39
+ L_mask = ((decay.unsqueeze(-1) - decay.unsqueeze(-2)).tril().exp().float()).tril()
40
+ S = k.new_zeros(B, H, K, V)
41
+ if initial_state is not None:
42
+ S = initial_state
43
+ o = torch.zeros_like(v)
44
+ for i in range(0, T1 // chunk_size):
45
+ q_i, k_i, v_i = q[:, :, i], k[:, :, i], v[:, :, i]
46
+ attn = (q_i @ k_i.transpose(-1, -2) * L_mask[:, :, i])
47
+ o_inter = (q_i * decay[:, :, i, :, None].exp()) @ S
48
+ o[:, :, i] = o_inter + attn @ v_i
49
+ S = S * decay[:, :, i, -1, None, None].exp() + \
50
+ (k_i * (decay[:, :, i, -1, None] - decay[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_i
51
+ if not output_final_state:
52
+ S = None
53
+ # unpad
54
+ o = rearrange(o, 'b h n c d -> b (n c) h d')[:, :T]
55
+ return o, S
56
+
57
+
58
+ def naive_recurrent_simple_gla(
59
+ q: torch.Tensor,
60
+ k: torch.Tensor,
61
+ v: torch.Tensor,
62
+ g: torch.Tensor,
63
+ scale: Optional[float] = None,
64
+ initial_state: Optional[torch.Tensor] = None,
65
+ output_final_state: bool = True
66
+ ):
67
+ dtype = q.dtype
68
+ q, k, v, g = map(lambda x: x.transpose(1, 2).float(), (q, k, v, g))
69
+ B, H, T, K = q.shape
70
+ V = v.shape[-1]
71
+ if scale is None:
72
+ scale = K ** -0.5
73
+ q = q * scale
74
+ o = v.new_zeros(B, H, T, V)
75
+
76
+ S = q.new_zeros(B, H, K, V)
77
+ if initial_state is not None:
78
+ S += initial_state
79
+
80
+ for i in range(T):
81
+ gate = g[:, :, i].exp()
82
+ key = k[:, :, i]
83
+ value = v[:, :, i]
84
+ kv = key.unsqueeze(-1) * value.unsqueeze(-2)
85
+ S = S * gate.unsqueeze(-1).unsqueeze(-1) + kv
86
+ q_i = q[:, :, i, :]
87
+ o_i = (q_i.unsqueeze(-1) * S).sum(-2)
88
+ o[:, :, i] = o_i
89
+ if not output_final_state:
90
+ S = None
91
+ return o.transpose(1, 2).to(dtype), S
92
+
93
+
94
+ def naive_parallel_simple_gla(
95
+ q: torch.Tensor,
96
+ k: torch.Tensor,
97
+ v: torch.Tensor,
98
+ g: torch.Tensor,
99
+ scale: Optional[float] = None
100
+ ):
101
+ q, k, v, g = map(lambda x: rearrange(x, 'b t h ... -> b h t ...').to(torch.float32), [q, k, v, g])
102
+ if scale is None:
103
+ scale = 1.0 / q.shape[-1] ** 0.5
104
+ dtype = q.dtype
105
+ A = (q @ k.transpose(-1, -2) * scale)
106
+ if g is not None:
107
+ g = g.cumsum(-1)
108
+ D = (g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().tril()
109
+ A = A * D
110
+ else:
111
+ A = A.tril()
112
+ o = A @ v
113
+ o = o.transpose(1, 2)
114
+ return o.to(dtype), A