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,64 @@
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.ops.attn.parallel import parallel_attn
10
+
11
+
12
+ def parallel_forgetting_attn(
13
+ q: torch.Tensor,
14
+ k: torch.Tensor,
15
+ v: torch.Tensor,
16
+ g: torch.Tensor,
17
+ scale: Optional[float] = None,
18
+ cu_seqlens: Optional[torch.LongTensor] = None,
19
+ head_first: bool = False
20
+ ) -> torch.Tensor:
21
+ r"""
22
+ Args:
23
+ q (torch.Tensor):
24
+ queries of shape `[B, T, HQ, K]`.
25
+ k (torch.Tensor):
26
+ keys of shape `[B, T, H, K]`.
27
+ GQA will be applied if HQ is divisible by H.
28
+ v (torch.Tensor):
29
+ values of shape `[B, T, H, V]`.
30
+ g (torch.Tensor):
31
+ Log decay at rach time step (in **log space**) of shape `[B, T, HQ]` if `head_first=False` else `[B, HQ, T]`.
32
+ scale (Optional[float]):
33
+ Scale factor for attention scores.
34
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
35
+ cu_seqlens (torch.LongTensor):
36
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
37
+ consistent with the FlashAttention API.
38
+ head_first (Optional[bool]):
39
+ Whether the inputs are in the head-first format. Default: `False`.
40
+ This argument has been deprecated.
41
+
42
+ Returns:
43
+ o (torch.Tensor):
44
+ Outputs of shape `[B, T, HQ, V]`.
45
+ """
46
+
47
+ if scale is None:
48
+ scale = k.shape[-1] ** -0.5
49
+ if cu_seqlens is not None:
50
+ assert q.shape[0] == 1, "batch size must be 1 when cu_seqlens are provided"
51
+ if head_first:
52
+ raise DeprecationWarning(
53
+ "head_first is deprecated and will be removed in a future version. "
54
+ "Please use head_first=False for now instead."
55
+ )
56
+ if not head_first and q.shape[1] < q.shape[2]:
57
+ warnings.warn(
58
+ f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
59
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
60
+ "when head_first=False was specified. "
61
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
62
+ )
63
+ o = parallel_attn(q, k, v, g, scale, cu_seqlens)
64
+ return o
@@ -0,0 +1,5 @@
1
+ from .chunk import chunk_gated_delta_product
2
+
3
+ __all__ = [
4
+ "chunk_gated_delta_product"
5
+ ]
@@ -0,0 +1,305 @@
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.modules.l2norm import l2norm_bwd, l2norm_fwd
10
+ from fla.ops.common.chunk_scaled_dot_kkt import chunk_scaled_dot_kkt_fwd
11
+ from fla.ops.delta_rule.chunk import chunk_delta_rule_bwd
12
+ from fla.ops.delta_rule.wy_fast import recompute_w_u_fwd as dn_recompute_w_u_fwd
13
+ from fla.ops.gated_delta_product.chunk_deltaproduct_h import chunk_gated_delta_product_fwd_h
14
+ from fla.ops.gated_delta_product.chunk_deltaproduct_o import chunk_gated_delta_product_fwd_o
15
+ from fla.ops.gated_delta_rule.chunk import chunk_gated_delta_rule_bwd
16
+ from fla.ops.gated_delta_rule.wy_fast import recompute_w_u_fwd as gdn_recompute_w_u_fwd
17
+ from fla.ops.utils import chunk_local_cumsum, solve_tril
18
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
19
+
20
+
21
+ def chunk_gated_delta_product_fwd(
22
+ q: torch.Tensor,
23
+ k: torch.Tensor,
24
+ v: torch.Tensor,
25
+ g: torch.Tensor,
26
+ beta: torch.Tensor,
27
+ scale: float,
28
+ cu_seqlens: Optional[torch.LongTensor] = None,
29
+ initial_state: Optional[torch.Tensor] = None,
30
+ output_final_state: bool = False,
31
+ num_householder: int = 1,
32
+ ):
33
+ cu_seqlens_dp = cu_seqlens * num_householder if cu_seqlens is not None else None
34
+ if g is not None:
35
+ g_interleaved = g.new_zeros(g.shape[0], g.shape[1], num_householder, g.shape[2], dtype=torch.float32)
36
+ g_interleaved[:, :, 0] = g
37
+ g_interleaved = rearrange(g_interleaved, 'b l n h -> b (l n) h').contiguous()
38
+ g = chunk_local_cumsum(g, chunk_size=64, cu_seqlens=cu_seqlens, output_dtype=torch.float32)
39
+ g_interleaved = chunk_local_cumsum(g_interleaved, chunk_size=64, cu_seqlens=cu_seqlens_dp, output_dtype=torch.float32)
40
+ else:
41
+ g_interleaved = None
42
+ g = None
43
+ # obtain WY representation. u is actually the new v.
44
+ A = chunk_scaled_dot_kkt_fwd(
45
+ k=k,
46
+ g=g_interleaved,
47
+ beta=beta,
48
+ cu_seqlens=cu_seqlens_dp,
49
+ output_dtype=torch.float32
50
+ )
51
+ A = solve_tril(
52
+ A=A,
53
+ cu_seqlens=cu_seqlens_dp,
54
+ output_dtype=k.dtype
55
+ )
56
+ if g is not None:
57
+ w, u = gdn_recompute_w_u_fwd(
58
+ k=k,
59
+ v=v,
60
+ beta=beta,
61
+ A=A,
62
+ g=g_interleaved,
63
+ cu_seqlens=cu_seqlens_dp,
64
+ )
65
+ else:
66
+ w, u = dn_recompute_w_u_fwd(
67
+ k=k,
68
+ v=v,
69
+ beta=beta,
70
+ A=A,
71
+ cu_seqlens=cu_seqlens_dp,
72
+ )
73
+ h, v_new, final_state = chunk_gated_delta_product_fwd_h(
74
+ k=k,
75
+ w=w,
76
+ u=u,
77
+ g=g_interleaved,
78
+ initial_state=initial_state,
79
+ output_final_state=output_final_state,
80
+ cu_seqlens=cu_seqlens_dp,
81
+ num_householder=num_householder,
82
+ )
83
+ o = chunk_gated_delta_product_fwd_o(
84
+ q=q,
85
+ k=k,
86
+ v=v_new,
87
+ h=h,
88
+ g=g,
89
+ scale=scale,
90
+ cu_seqlens=cu_seqlens,
91
+ num_householder=num_householder,
92
+ )
93
+ return g, g_interleaved, o, A, final_state
94
+
95
+
96
+ class ChunkGatedDeltaProductFunction(torch.autograd.Function):
97
+
98
+ @staticmethod
99
+ @input_guard
100
+ @autocast_custom_fwd
101
+ def forward(
102
+ ctx,
103
+ q: torch.Tensor,
104
+ k: torch.Tensor,
105
+ v: torch.Tensor,
106
+ g: torch.Tensor,
107
+ beta: torch.Tensor,
108
+ scale: float,
109
+ num_householder: int,
110
+ initial_state: torch.Tensor,
111
+ output_final_state: bool,
112
+ use_qk_l2norm_in_kernel: bool = False,
113
+ cu_seqlens: Optional[torch.LongTensor] = None,
114
+ ):
115
+ if use_qk_l2norm_in_kernel:
116
+ q, q_rstd = l2norm_fwd(q)
117
+ k, k_rstd = l2norm_fwd(k)
118
+ else:
119
+ q_rstd, k_rstd = None, None
120
+
121
+ g, g_interleaved, o, A, final_state = chunk_gated_delta_product_fwd(
122
+ q=q,
123
+ k=k,
124
+ v=v,
125
+ g=g,
126
+ beta=beta,
127
+ scale=scale,
128
+ initial_state=initial_state,
129
+ output_final_state=output_final_state,
130
+ cu_seqlens=cu_seqlens,
131
+ num_householder=num_householder,
132
+ )
133
+ ctx.save_for_backward(q, q_rstd, k, k_rstd, v, g_interleaved, beta, A, initial_state, cu_seqlens)
134
+ ctx.scale = scale
135
+ ctx.use_qk_l2norm_in_kernel = use_qk_l2norm_in_kernel
136
+ ctx.num_householder = num_householder
137
+ return o.to(q.dtype), final_state
138
+
139
+ @staticmethod
140
+ @input_guard
141
+ @autocast_custom_bwd
142
+ def backward(
143
+ ctx,
144
+ do: torch.Tensor,
145
+ dht: torch.Tensor
146
+ ):
147
+ q, q_rstd, k, k_rstd, v, g, beta, A, initial_state, cu_seqlens = ctx.saved_tensors
148
+ q_new = q.new_zeros(q.shape[0], q.shape[1], ctx.num_householder, q.shape[2], q.shape[3])
149
+ q_new[:, :, -1] = q
150
+ do_new = do.new_zeros(do.shape[0], do.shape[1], ctx.num_householder, do.shape[2], do.shape[3])
151
+ do_new[:, :, -1] = do
152
+ q_org, q = q, rearrange(q_new, 'b t n h d -> b (t n) h d')
153
+ do = rearrange(do_new, 'b t n h d -> b (t n) h d')
154
+ # call the gated deltanet kernel for now.
155
+ # TODO: optimize the backward pass like the forward pass.
156
+ if g is not None:
157
+ dq, dk, dv, db, dg, dh0 = chunk_gated_delta_rule_bwd(
158
+ q=q,
159
+ k=k,
160
+ v=v,
161
+ g=g,
162
+ beta=beta,
163
+ A=A,
164
+ scale=ctx.scale,
165
+ initial_state=initial_state,
166
+ do=do,
167
+ dht=dht,
168
+ cu_seqlens=cu_seqlens * ctx.num_householder if cu_seqlens is not None else None,
169
+ )
170
+ dg = rearrange(dg, 'b (l n) h -> b l n h ', n=ctx.num_householder)[:, :, 0].contiguous().to(g)
171
+ else:
172
+ dq, dk, dv, db, dh0 = chunk_delta_rule_bwd(
173
+ q=q,
174
+ k=k,
175
+ v=v,
176
+ beta=beta,
177
+ A=A,
178
+ scale=ctx.scale,
179
+ initial_state=initial_state,
180
+ do=do,
181
+ dht=dht,
182
+ cu_seqlens=cu_seqlens * ctx.num_householder if cu_seqlens is not None else None,
183
+ )
184
+ dg = None
185
+ dq = rearrange(dq, 'b (l n) h d -> b l n h d', n=ctx.num_householder)[:, :, -1].contiguous()
186
+ if ctx.use_qk_l2norm_in_kernel:
187
+ dq = l2norm_bwd(q_org, q_rstd, dq)
188
+ dk = l2norm_bwd(k, k_rstd, dk)
189
+ return dq.to(q), dk.to(k), dv.to(v), dg, db.to(beta), None, None, dh0, None, None, None
190
+
191
+
192
+ @torch.compiler.disable
193
+ def chunk_gated_delta_product(
194
+ q: torch.Tensor,
195
+ k: torch.Tensor,
196
+ v: torch.Tensor,
197
+ g: torch.Tensor,
198
+ beta: torch.Tensor,
199
+ num_householder: int,
200
+ scale: float = None,
201
+ initial_state: torch.Tensor = None,
202
+ output_final_state: bool = False,
203
+ use_qk_l2norm_in_kernel: bool = False,
204
+ cu_seqlens: Optional[torch.LongTensor] = None,
205
+ ):
206
+ r"""
207
+ Args:
208
+ q (torch.Tensor):
209
+ queries of shape `[B, T, H, K]`.
210
+ k (torch.Tensor):
211
+ keys of shape `[B, T, H, K]`.
212
+ v (torch.Tensor):
213
+ values of shape `[B, T, H, V]`.
214
+ g (torch.Tensor):
215
+ (forget) gating tensor (in log space!) of shape `[B, T, H]`.
216
+ beta (torch.Tensor):
217
+ betas of shape `[B, T, H]`.
218
+ num_householder (int):
219
+ Number of householder transformations to apply. Default: `1`.
220
+ scale (Optional[float]):
221
+ Scale factor for the RetNet attention scores.
222
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
223
+ initial_state (Optional[torch.Tensor]):
224
+ Initial state of shape `[N, H, K, V]` for `N` input sequences.
225
+ For equal-length input sequences, `N` equals the batch size `B`.
226
+ Default: `None`.
227
+ output_final_state (Optional[bool]):
228
+ Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
229
+ use_qk_l2norm_in_kernel (Optional[bool]):
230
+ Whether to use qk l2norm within the kernel for saving GPU memory.
231
+ Default: `False`.
232
+ cu_seqlens (torch.LongTensor):
233
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
234
+ consistent with the FlashAttention API.
235
+
236
+ Returns:
237
+ o (torch.Tensor):
238
+ Outputs of shape `[B, T, H, V]`.
239
+ final_state (torch.Tensor):
240
+ Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
241
+
242
+ Examples::
243
+ >>> import torch
244
+ >>> import torch.nn.functional as F
245
+ >>> from einops import rearrange
246
+ >>> from fla.ops.gated_delta_rule import chunk_gated_delta_product
247
+ # inputs with equal lengths
248
+ >>> B, T, H, K, V = 4, 2048, 4, 512, 512
249
+ >>> q = torch.randn(B, T, H, K, dtype=torch.bfloat16, device='cuda')
250
+ >>> k = F.normalize(torch.randn(B, T, H, K, dtype=torch.bfloat16, device='cuda'), p=2, dim=-1)
251
+ >>> v = torch.randn(B, T, H, V, dtype=torch.bfloat16, device='cuda')
252
+ >>> beta = torch.rand(B, T, H, dtype=torch.bfloat16, device='cuda').sigmoid()
253
+ >>> g = F.logsigmoid(torch.rand(B, T, H, dtype=torch.bfloat16, device='cuda'))
254
+ >>> h0 = torch.randn(B, H, K, V, dtype=torch.bfloat16, device='cuda')
255
+ >>> o, ht = chunk_gated_delta_product(
256
+ q, k, v, g, beta,
257
+ initial_state=h0,
258
+ output_final_state=True
259
+ )
260
+ # for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
261
+ >>> q, k, v, beta, g = map(lambda x: rearrange(x, 'b t ... -> 1 (b t) ...'), (q, k, v, beta, g))
262
+ # for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
263
+ >>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
264
+ >>> o, ht = chunk_gated_delta_product(
265
+ q, k, v, g, beta,
266
+ initial_state=h0,
267
+ output_final_state=True,
268
+ cu_seqlens=cu_seqlens
269
+ )
270
+ """
271
+ assert q.dtype != torch.float32, "ChunkGatedDeltaProductFunction does not support float32. Please use bfloat16."
272
+ B, T, H, K, V = *q.shape, v.shape[-1]
273
+ assert k.shape == (B, T*num_householder, H, K)
274
+ assert v.shape == (B, T*num_householder, H, V)
275
+ assert beta.shape == (B, T*num_householder, H)
276
+ if g is not None:
277
+ assert g.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 = ChunkGatedDeltaProductFunction.apply(
293
+ q,
294
+ k,
295
+ v,
296
+ g,
297
+ beta,
298
+ scale,
299
+ num_householder,
300
+ initial_state,
301
+ output_final_state,
302
+ use_qk_l2norm_in_kernel,
303
+ cu_seqlens,
304
+ )
305
+ return o, final_state