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,68 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from typing import Optional
5
+
6
+ import torch
7
+ from einops import rearrange
8
+
9
+ from fla.ops.delta_rule import chunk_delta_rule
10
+ from fla.ops.gated_delta_rule import chunk_gated_delta_rule
11
+
12
+
13
+ @torch.compiler.disable
14
+ def chunk_gated_delta_product_ref(
15
+ q: torch.Tensor,
16
+ k: torch.Tensor,
17
+ v: torch.Tensor,
18
+ g: torch.Tensor,
19
+ beta: torch.Tensor,
20
+ num_householder: int,
21
+ scale: float = None,
22
+ initial_state: torch.Tensor = None,
23
+ output_final_state: bool = False,
24
+ cu_seqlens: Optional[torch.LongTensor] = None,
25
+ use_qk_l2norm_in_kernel: bool = False,
26
+ ):
27
+ assert q.dtype != torch.float32, "ChunkGatedDeltaProductFunction does not support float32. Please use bfloat16."
28
+ B, T, H, K = q.shape
29
+ V = v.shape[-1]
30
+ assert k.shape == (B, T*num_householder, H, K)
31
+ assert v.shape == (B, T*num_householder, H, V)
32
+ assert beta.shape == (B, T*num_householder, H)
33
+ if g is not None:
34
+ assert g.shape == (B, T, H)
35
+ q_new = q.new_zeros(B, T, num_householder, H, K)
36
+ q_new[:, :, -1] = q
37
+ q = rearrange(q_new, 'b t n h d -> b (t n) h d')
38
+
39
+ if g is not None:
40
+ g_new = g.new_zeros(B, T, num_householder, H, dtype=torch.float32)
41
+ g_new[:, :, 0] = g
42
+ g = rearrange(g_new, 'b t n h -> b (t n) h')
43
+ o, final_state = chunk_gated_delta_rule(
44
+ q=q,
45
+ k=k,
46
+ v=v,
47
+ g=g,
48
+ beta=beta,
49
+ initial_state=initial_state,
50
+ output_final_state=output_final_state,
51
+ cu_seqlens=cu_seqlens * num_householder if cu_seqlens is not None else None,
52
+ use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
53
+ scale=scale,
54
+ )
55
+ else:
56
+ o, final_state = chunk_delta_rule(
57
+ q=q,
58
+ k=k,
59
+ v=v,
60
+ beta=beta,
61
+ initial_state=initial_state,
62
+ output_final_state=output_final_state,
63
+ cu_seqlens=cu_seqlens * num_householder if cu_seqlens is not None else None,
64
+ use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
65
+ scale=scale,
66
+ )
67
+ o = rearrange(o, 'b (t n) h d -> b t n h d', n=num_householder)
68
+ return o[:, :, -1].contiguous(), final_state
@@ -0,0 +1,36 @@
1
+ import torch
2
+
3
+
4
+ def naive_recurrent_gated_delta_product(q, k, v, g, beta, scale, cu_seqlens,
5
+ initial_state=None, output_final_state=False,
6
+ num_householder=1):
7
+ q_original_dtype = q.dtype
8
+ B, T, H, K = q.shape
9
+ V = v.shape[-1]
10
+ assert k.shape == (B, T*num_householder, H, K)
11
+ assert v.shape == (B, T*num_householder, H, V)
12
+ assert beta.shape == (B, T*num_householder, H)
13
+ if g is not None:
14
+ assert g.shape == (B, T, H)
15
+ q, k, v, beta = map(lambda x: x.float(), (q, k, v, beta))
16
+
17
+ h = torch.zeros(B, H, K, V, dtype=torch.float32, device=q.device)
18
+ if initial_state is not None:
19
+ h = initial_state
20
+
21
+ o = torch.zeros(B, T, H, V, dtype=torch.float32, device=q.device)
22
+
23
+ for i in range(T):
24
+ if g is not None:
25
+ h = h * g[:, i, :].exp()[..., None, None]
26
+ # multiple state transition
27
+ for j in range(num_householder):
28
+ k_ij = k[:, i*num_householder+j, :, :]
29
+ v_ij = v[:, i*num_householder+j, :, :]
30
+ beta_ij = beta[:, i*num_householder+j, :]
31
+ h = h + (v_ij - (h * k_ij[..., None]).sum(-2)).unsqueeze(-2) * k_ij[..., None] * beta_ij[..., None, None]
32
+ # memory readout
33
+ q_i = q[:, i, :, :]
34
+ o_i = (h * q_i[..., None]).sum(-2)
35
+ o[:, i] = o_i
36
+ return o.to(q_original_dtype), h
@@ -0,0 +1,7 @@
1
+ from .chunk import chunk_gated_delta_rule
2
+ from .fused_recurrent import fused_recurrent_gated_delta_rule
3
+
4
+ __all__ = [
5
+ "chunk_gated_delta_rule",
6
+ "fused_recurrent_gated_delta_rule"
7
+ ]
@@ -0,0 +1,340 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ import warnings
5
+ from typing import Optional
6
+
7
+ import torch
8
+
9
+ from fla.modules.l2norm import l2norm_bwd, l2norm_fwd
10
+ from fla.ops.common.chunk_delta_h import chunk_gated_delta_rule_bwd_dhu, chunk_gated_delta_rule_fwd_h
11
+ from fla.ops.common.chunk_o import chunk_bwd_dqkwg, chunk_bwd_dv_local, chunk_fwd_o
12
+ from fla.ops.common.chunk_scaled_dot_kkt import chunk_scaled_dot_kkt_fwd
13
+ from fla.ops.gated_delta_rule.wy_fast import prepare_wy_repr_bwd, recompute_w_u_fwd
14
+ from fla.ops.utils import chunk_local_cumsum, solve_tril
15
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
16
+
17
+
18
+ def chunk_gated_delta_rule_fwd(
19
+ q: torch.Tensor,
20
+ k: torch.Tensor,
21
+ v: 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
+ g = chunk_local_cumsum(g, chunk_size=64, cu_seqlens=cu_seqlens)
30
+ # obtain WY representation. u is actually the new v.
31
+ A = chunk_scaled_dot_kkt_fwd(
32
+ k=k,
33
+ g=g,
34
+ beta=beta,
35
+ cu_seqlens=cu_seqlens,
36
+ output_dtype=torch.float32
37
+ )
38
+ A = solve_tril(
39
+ A=A,
40
+ cu_seqlens=cu_seqlens,
41
+ output_dtype=k.dtype
42
+ )
43
+ w, u = recompute_w_u_fwd(
44
+ k=k,
45
+ v=v,
46
+ beta=beta,
47
+ A=A,
48
+ g=g,
49
+ cu_seqlens=cu_seqlens,
50
+ )
51
+ h, v_new, final_state = chunk_gated_delta_rule_fwd_h(
52
+ k=k,
53
+ w=w,
54
+ u=u,
55
+ g=g,
56
+ initial_state=initial_state,
57
+ output_final_state=output_final_state,
58
+ cu_seqlens=cu_seqlens,
59
+ )
60
+ o = chunk_fwd_o(
61
+ q=q,
62
+ k=k,
63
+ v=v_new,
64
+ h=h,
65
+ g=g,
66
+ scale=scale,
67
+ cu_seqlens=cu_seqlens,
68
+ )
69
+ return g, o, A, final_state
70
+
71
+
72
+ def chunk_gated_delta_rule_bwd(
73
+ q: torch.Tensor,
74
+ k: torch.Tensor,
75
+ v: torch.Tensor,
76
+ g: torch.Tensor,
77
+ beta: torch.Tensor,
78
+ A: torch.Tensor,
79
+ scale: float,
80
+ initial_state: torch.Tensor,
81
+ do: torch.Tensor,
82
+ dht: torch.Tensor,
83
+ cu_seqlens: Optional[torch.LongTensor] = None,
84
+ ):
85
+ w, u = recompute_w_u_fwd(
86
+ k=k,
87
+ v=v,
88
+ beta=beta,
89
+ A=A,
90
+ g=g,
91
+ cu_seqlens=cu_seqlens,
92
+ )
93
+ h, v_new, _ = chunk_gated_delta_rule_fwd_h(
94
+ k=k,
95
+ w=w,
96
+ u=u,
97
+ g=g,
98
+ initial_state=initial_state,
99
+ output_final_state=False,
100
+ cu_seqlens=cu_seqlens,
101
+ )
102
+ dv = chunk_bwd_dv_local(
103
+ q=q,
104
+ k=k,
105
+ g=g,
106
+ do=do,
107
+ scale=scale,
108
+ cu_seqlens=cu_seqlens,
109
+ )
110
+ dh, dh0, dv = chunk_gated_delta_rule_bwd_dhu(
111
+ q=q,
112
+ k=k,
113
+ w=w,
114
+ g=g,
115
+ h0=initial_state,
116
+ dht=dht,
117
+ do=do,
118
+ dv=dv,
119
+ scale=scale,
120
+ cu_seqlens=cu_seqlens,
121
+ )
122
+ dq, dk, dw, dg = chunk_bwd_dqkwg(
123
+ q=q,
124
+ k=k,
125
+ v=v_new,
126
+ w=w,
127
+ g=g,
128
+ h=h,
129
+ dv=dv,
130
+ do=do,
131
+ dh=dh,
132
+ scale=scale,
133
+ cu_seqlens=cu_seqlens,
134
+ )
135
+ dk2, dv, db, dg2 = prepare_wy_repr_bwd(
136
+ k=k,
137
+ v=v,
138
+ beta=beta,
139
+ g=g,
140
+ A=A,
141
+ dw=dw,
142
+ du=dv,
143
+ cu_seqlens=cu_seqlens,
144
+ )
145
+ dk.add_(dk2)
146
+ dg.add_(dg2)
147
+ assert dg.dtype == torch.float32, "dg should be fp32"
148
+ dg = chunk_local_cumsum(dg, chunk_size=64, reverse=True, cu_seqlens=cu_seqlens)
149
+ return dq, dk, dv, db, dg, dh0
150
+
151
+
152
+ class ChunkGatedDeltaRuleFunction(torch.autograd.Function):
153
+
154
+ @staticmethod
155
+ @input_guard
156
+ @autocast_custom_fwd
157
+ def forward(
158
+ ctx,
159
+ q: torch.Tensor,
160
+ k: torch.Tensor,
161
+ v: torch.Tensor,
162
+ g: torch.Tensor,
163
+ beta: torch.Tensor,
164
+ scale: float,
165
+ initial_state: torch.Tensor,
166
+ output_final_state: bool,
167
+ cu_seqlens: Optional[torch.LongTensor] = None,
168
+ use_qk_l2norm_in_kernel: bool = False
169
+ ):
170
+ if use_qk_l2norm_in_kernel:
171
+ q, q_rstd = l2norm_fwd(q)
172
+ k, k_rstd = l2norm_fwd(k)
173
+ else:
174
+ q_rstd, k_rstd = None, None
175
+
176
+ g, o, A, final_state = chunk_gated_delta_rule_fwd(
177
+ q=q,
178
+ k=k,
179
+ v=v,
180
+ g=g,
181
+ beta=beta,
182
+ scale=scale,
183
+ initial_state=initial_state,
184
+ output_final_state=output_final_state,
185
+ cu_seqlens=cu_seqlens,
186
+ )
187
+ ctx.save_for_backward(q, q_rstd, k, k_rstd, v, g, beta, A, initial_state, cu_seqlens)
188
+ ctx.scale = scale
189
+ ctx.use_qk_l2norm_in_kernel = use_qk_l2norm_in_kernel
190
+ return o.to(q.dtype), final_state
191
+
192
+ @staticmethod
193
+ @input_guard
194
+ @autocast_custom_bwd
195
+ def backward(
196
+ ctx,
197
+ do: torch.Tensor,
198
+ dht: torch.Tensor
199
+ ):
200
+ q, q_rstd, k, k_rstd, v, g, beta, A, initial_state, cu_seqlens = ctx.saved_tensors
201
+ dq, dk, dv, db, dg, dh0 = chunk_gated_delta_rule_bwd(
202
+ q=q,
203
+ k=k,
204
+ v=v,
205
+ g=g,
206
+ beta=beta,
207
+ A=A,
208
+ scale=ctx.scale,
209
+ initial_state=initial_state,
210
+ do=do,
211
+ dht=dht,
212
+ cu_seqlens=cu_seqlens,
213
+ )
214
+ if ctx.use_qk_l2norm_in_kernel:
215
+ dq = l2norm_bwd(q, q_rstd, dq)
216
+ dk = l2norm_bwd(k, k_rstd, dk)
217
+ return dq.to(q), dk.to(k), dv.to(v), dg.to(g), db.to(beta), None, dh0, None, None, None
218
+
219
+
220
+ @torch.compiler.disable
221
+ def chunk_gated_delta_rule(
222
+ q: torch.Tensor,
223
+ k: torch.Tensor,
224
+ v: torch.Tensor,
225
+ g: torch.Tensor,
226
+ beta: torch.Tensor,
227
+ scale: float = None,
228
+ initial_state: torch.Tensor = None,
229
+ output_final_state: bool = False,
230
+ use_qk_l2norm_in_kernel: bool = False,
231
+ cu_seqlens: Optional[torch.LongTensor] = None,
232
+ head_first: bool = False,
233
+ ):
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
+ v (torch.Tensor):
241
+ values of shape `[B, T, H, V]`.
242
+ g (torch.Tensor):
243
+ (forget) gating tensor (in log space!) of shape `[B, T, H]`.
244
+ beta (torch.Tensor):
245
+ betas of shape `[B, T, H]`.
246
+ scale (Optional[float]):
247
+ Scale factor for the RetNet attention scores.
248
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
249
+ initial_state (Optional[torch.Tensor]):
250
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
251
+ For equal-length input sequences, `N` equals the batch size `B`.
252
+ Default: `None`.
253
+ output_final_state (Optional[bool]):
254
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
255
+ use_qk_l2norm_in_kernel (bool):
256
+ Whether to apply L2norm to the q/k tensor internally. Default: `False`.
257
+ cu_seqlens (torch.LongTensor):
258
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
259
+ consistent with the FlashAttention API.
260
+ head_first (Optional[bool]):
261
+ Whether the inputs are in the head-first format. Default: `False`.
262
+ This argument has been deprecated.
263
+
264
+ Returns:
265
+ o (torch.Tensor):
266
+ Outputs of shape `[B, T, H, V]`.
267
+ final_state (torch.Tensor):
268
+ Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
269
+
270
+ Examples::
271
+ >>> import torch
272
+ >>> import torch.nn.functional as F
273
+ >>> from einops import rearrange
274
+ >>> from fla.ops.gated_delta_rule import chunk_gated_delta_rule
275
+ # inputs with equal lengths
276
+ >>> B, T, H, K, V = 4, 2048, 4, 512, 512
277
+ >>> q = torch.randn(B, T, H, K, dtype=torch.bfloat16, device='cuda')
278
+ >>> k = F.normalize(torch.randn(B, T, H, K, dtype=torch.bfloat16, device='cuda'), p=2, dim=-1)
279
+ >>> v = torch.randn(B, T, H, V, dtype=torch.bfloat16, device='cuda')
280
+ >>> beta = torch.rand(B, T, H, dtype=torch.bfloat16, device='cuda').sigmoid()
281
+ >>> g = F.logsigmoid(torch.rand(B, T, H, dtype=torch.bfloat16, device='cuda'))
282
+ >>> h0 = torch.randn(B, H, K, V, dtype=torch.bfloat16, device='cuda')
283
+ >>> o, ht = chunk_gated_delta_rule(
284
+ q, k, v, g, beta,
285
+ initial_state=h0,
286
+ output_final_state=True
287
+ )
288
+ # for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
289
+ >>> q, k, v, beta, g = map(lambda x: rearrange(x, 'b t ... -> 1 (b t) ...'), (q, k, v, beta, g))
290
+ # for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
291
+ >>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
292
+ >>> o, ht = chunk_gated_delta_rule(
293
+ q, k, v, g, beta,
294
+ initial_state=h0,
295
+ output_final_state=True,
296
+ cu_seqlens=cu_seqlens
297
+ )
298
+ """
299
+ assert q.dtype == k.dtype == v.dtype
300
+ assert q.dtype != torch.float32, "ChunkGatedDeltaRuleFunction does not support float32. Please use bfloat16."
301
+ assert len(beta.shape) == 3, "beta must be of shape [B, T, H] if head_first=False, or [B, H, T] otherwise."
302
+
303
+ if head_first:
304
+ warnings.warn(
305
+ "head_first is deprecated and will be removed in a future version. "
306
+ "Please use head_first=False for now instead."
307
+ )
308
+ if not head_first and q.shape[1] < q.shape[2]:
309
+ warnings.warn(
310
+ f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
311
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
312
+ "when head_first=False was specified. "
313
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
314
+ )
315
+ if cu_seqlens is not None:
316
+ if q.shape[0] != 1:
317
+ raise ValueError(
318
+ f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
319
+ f"Please flatten variable-length inputs before processing."
320
+ )
321
+ if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
322
+ raise ValueError(
323
+ f"The number of initial states is expected to be equal to the number of input sequences, "
324
+ f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
325
+ )
326
+ if scale is None:
327
+ scale = k.shape[-1] ** -0.5
328
+ o, final_state = ChunkGatedDeltaRuleFunction.apply(
329
+ q,
330
+ k,
331
+ v,
332
+ g,
333
+ beta,
334
+ scale,
335
+ initial_state,
336
+ output_final_state,
337
+ cu_seqlens,
338
+ use_qk_l2norm_in_kernel
339
+ )
340
+ return o, final_state