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,71 @@
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
+
9
+ from fla.ops.simple_gla.parallel import parallel_simple_gla
10
+
11
+
12
+ def parallel_retention(
13
+ q: torch.Tensor,
14
+ k: torch.Tensor,
15
+ v: torch.Tensor,
16
+ scale: Optional[float] = None,
17
+ output_attentions: bool = False,
18
+ cu_seqlens: Optional[torch.LongTensor] = None,
19
+ head_first: bool = False
20
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
21
+ r"""
22
+ Args:
23
+ q (torch.Tensor):
24
+ queries of shape `[B, T, H, K]`.
25
+ k (torch.Tensor):
26
+ keys of shape `[B, T, H, K]`.
27
+ v (torch.Tensor):
28
+ values of shape `[B, T, H, V]`.
29
+ scale (Optional[float]):
30
+ Scale factor for attention scores.
31
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
32
+ output_attentions (bool):
33
+ Whether to output the materialized attention scores of shape [B, H, T, T]. Default: `False`.
34
+ cu_seqlens (torch.LongTensor):
35
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
36
+ consistent with the FlashAttention API.
37
+ head_first (Optional[bool]):
38
+ Whether the inputs are in the head-first format. Default: `False`.
39
+ This argument has been deprecated.
40
+
41
+ Returns:
42
+ o (torch.Tensor):
43
+ Outputs of shape `[B, T, H, V]`.
44
+ attn (torch.Tensor):
45
+ Attention scores of shape `[B, H, T, T]` if `output_attentions=True` else `None`
46
+ """
47
+ if head_first:
48
+ raise DeprecationWarning(
49
+ "head_first is deprecated and will be removed in a future version. "
50
+ "Please use head_first=False for now instead."
51
+ )
52
+ if not head_first and q.shape[1] < q.shape[2]:
53
+ warnings.warn(
54
+ f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
55
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
56
+ "when head_first=False was specified. "
57
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
58
+ )
59
+ s = (1 - q.new_tensor(2., dtype=torch.float).pow(-5. - q.new_tensor(range(q.shape[2]), dtype=torch.float))).log()
60
+ g = s[None, None, :].expand(q.shape[0], q.shape[1], q.shape[2])
61
+
62
+ o, attn = parallel_simple_gla(
63
+ q=q,
64
+ k=k,
65
+ v=v,
66
+ scale=scale,
67
+ g=g,
68
+ output_attentions=output_attentions,
69
+ cu_seqlens=cu_seqlens
70
+ )
71
+ return o, attn
@@ -0,0 +1,7 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from .fused_recurrent import fused_recurrent_rwkv4
4
+
5
+ __all__ = [
6
+ 'fused_recurrent_rwkv4'
7
+ ]
@@ -0,0 +1,472 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2024, Songlin Yang, Yu Zhang
3
+
4
+ from typing import Any, cast
5
+
6
+ import torch
7
+ import triton
8
+ import triton.language as tl
9
+ from torch import Tensor
10
+ from torch.autograd.function import Function, FunctionCtx, once_differentiable
11
+
12
+ from fla.ops.utils.op import exp
13
+ from fla.utils import input_guard
14
+
15
+
16
+ def get_block_size_c(chans: int) -> int:
17
+ if chans < 32:
18
+ return 32
19
+ if chans < 64:
20
+ return 64
21
+ return 128
22
+
23
+
24
+ @triton.jit
25
+ def fused_recurrent_rwkv4_forward_kernel(
26
+ # W
27
+ w_ptr,
28
+ w_s_c,
29
+ # U
30
+ u_ptr,
31
+ u_s_c,
32
+ # K
33
+ k_ptr,
34
+ k_s_b,
35
+ k_s_t,
36
+ k_s_c,
37
+ # V
38
+ v_ptr,
39
+ v_s_b,
40
+ v_s_t,
41
+ v_s_c,
42
+ # State
43
+ state_ptr,
44
+ state_s_b,
45
+ state_s_abe,
46
+ state_s_c,
47
+ # WKV
48
+ wkv_ptr,
49
+ wkv_s_b,
50
+ wkv_s_t,
51
+ wkv_s_c,
52
+ # Output state
53
+ state_out_ptr,
54
+ state_out_s_b,
55
+ state_out_s_abe,
56
+ state_out_s_t,
57
+ state_out_s_c,
58
+ # Params
59
+ chans,
60
+ tsz,
61
+ BLOCK_SIZE_C: tl.constexpr,
62
+ ):
63
+ # Parallelize over the batch dimension.
64
+ b_idx = tl.program_id(0)
65
+ c_idx = tl.program_id(1)
66
+
67
+ cs = (c_idx * BLOCK_SIZE_C) + tl.arange(0, BLOCK_SIZE_C)
68
+ cmask = cs < chans
69
+
70
+ # Pointers to the batch (and possibly channel) for the input tensors.
71
+ k_ptr = k_ptr + b_idx * k_s_b
72
+ v_ptr = v_ptr + b_idx * v_s_b
73
+ alpha_ptr = state_ptr + b_idx * state_s_b
74
+ beta_ptr = state_ptr + b_idx * state_s_b + state_s_abe
75
+ eps_ptr = state_ptr + b_idx * state_s_b + 2 * state_s_abe
76
+
77
+ # Pointers to the batch (and possibly channel) for the output tensors.
78
+ wkv_ptr = wkv_ptr + b_idx * wkv_s_b
79
+ alpha_out_ptr = state_out_ptr + b_idx * state_out_s_b
80
+ beta_out_ptr = state_out_ptr + b_idx * state_out_s_b + state_out_s_abe
81
+ eps_out_ptr = state_out_ptr + b_idx * state_out_s_b + 2 * state_out_s_abe
82
+
83
+ # Loads parameters.
84
+ alpha = tl.load(alpha_ptr + cs * state_s_c, mask=cmask).to(tl.float32)
85
+ beta = tl.load(beta_ptr + cs * state_s_c, mask=cmask).to(tl.float32)
86
+ eps = tl.load(eps_ptr + cs * state_s_c, mask=cmask).to(tl.float32)
87
+ w = tl.load(w_ptr + cs * w_s_c, mask=cmask).to(tl.float32)
88
+ u = tl.load(u_ptr + cs * u_s_c, mask=cmask).to(tl.float32)
89
+
90
+ for t in range(tsz):
91
+ kt = tl.load(k_ptr + t * k_s_t + cs * k_s_c, mask=cmask).to(tl.float32)
92
+ vt = tl.load(v_ptr + t * v_s_t + cs * v_s_c, mask=cmask).to(tl.float32)
93
+
94
+ ukt = u + kt
95
+ tau = tl.maximum(ukt, eps)
96
+ e1a = exp(eps - tau)
97
+ e2a = exp(ukt - tau)
98
+ wkv = (e1a * alpha + e2a * vt) / (e1a * beta + e2a)
99
+ tl.store(wkv_ptr + t * wkv_s_t + cs * wkv_s_c, wkv, mask=cmask)
100
+
101
+ w_eps = w + eps
102
+ eps = tl.maximum(w_eps, kt)
103
+ e1b = exp(w_eps - eps)
104
+ e2b = exp(kt - eps)
105
+ alpha = e1b * alpha + e2b * vt
106
+ beta = e1b * beta + e2b
107
+ tl.store(alpha_out_ptr + t * state_out_s_t + cs * state_out_s_c, alpha, mask=cmask)
108
+ tl.store(beta_out_ptr + t * state_out_s_t + cs * state_out_s_c, beta, mask=cmask)
109
+ tl.store(eps_out_ptr + t * state_out_s_t + cs * state_out_s_c, eps, mask=cmask)
110
+
111
+
112
+ def fused_recurrent_rwkv4_forward(
113
+ w: Tensor,
114
+ u: Tensor,
115
+ k: Tensor,
116
+ v: Tensor,
117
+ state: Tensor,
118
+ ) -> tuple[Tensor, Tensor]:
119
+ (bsz, tsz, chans) = k.shape
120
+
121
+ # New tensors to output.
122
+ wkvs = k.new_empty(bsz, tsz, chans)
123
+ state_out = k.new_empty(bsz, 3, tsz, chans)
124
+
125
+ # Constants.
126
+ block_size_c = get_block_size_c(chans)
127
+
128
+ def grid(meta: dict[str, Any]) -> tuple[int, ...]:
129
+ return (bsz, triton.cdiv(chans, meta["BLOCK_SIZE_C"]))
130
+
131
+ fused_recurrent_rwkv4_forward_kernel[grid](
132
+ # W
133
+ w,
134
+ w.stride(0),
135
+ # U
136
+ u,
137
+ u.stride(0),
138
+ # K
139
+ k,
140
+ k.stride(0),
141
+ k.stride(1),
142
+ k.stride(2),
143
+ # V
144
+ v,
145
+ v.stride(0),
146
+ v.stride(1),
147
+ v.stride(2),
148
+ # State
149
+ state,
150
+ state.stride(0),
151
+ state.stride(1),
152
+ state.stride(3),
153
+ # WKV
154
+ wkvs,
155
+ wkvs.stride(0),
156
+ wkvs.stride(1),
157
+ wkvs.stride(2),
158
+ # Output state
159
+ state_out,
160
+ state_out.stride(0),
161
+ state_out.stride(1),
162
+ state_out.stride(2),
163
+ state_out.stride(3),
164
+ # Params
165
+ chans,
166
+ tsz,
167
+ BLOCK_SIZE_C=block_size_c,
168
+ )
169
+
170
+ state_out = torch.cat((state, state_out), dim=2)
171
+
172
+ return wkvs, state_out
173
+
174
+
175
+ @triton.jit
176
+ def fused_recurrent_rwkv4_backward_kernel(
177
+ # W
178
+ w_ptr,
179
+ w_s_c,
180
+ # U
181
+ u_ptr,
182
+ u_s_c,
183
+ # K
184
+ k_ptr,
185
+ k_s_b,
186
+ k_s_t,
187
+ k_s_c,
188
+ # V
189
+ v_ptr,
190
+ v_s_b,
191
+ v_s_t,
192
+ v_s_c,
193
+ # State
194
+ state_ptr,
195
+ state_s_b,
196
+ state_s_abe,
197
+ state_s_t,
198
+ state_s_c,
199
+ # WKV grad
200
+ gwkv_ptr,
201
+ gwkv_s_b,
202
+ gwkv_s_t,
203
+ gwkv_s_c,
204
+ # Output state grad
205
+ gstate_out_ptr,
206
+ gstate_out_s_b,
207
+ gstate_out_s_abe,
208
+ gstate_out_s_c,
209
+ # W grad
210
+ gw_ptr,
211
+ gw_s_b,
212
+ gw_s_c,
213
+ # U grad
214
+ gu_ptr,
215
+ gu_s_b,
216
+ gu_s_c,
217
+ # K grad
218
+ gk_ptr,
219
+ gk_s_b,
220
+ gk_s_t,
221
+ gk_s_c,
222
+ # V grad
223
+ gv_ptr,
224
+ gv_s_b,
225
+ gv_s_t,
226
+ gv_s_c,
227
+ # State grad
228
+ gstate_ptr,
229
+ gstate_s_b,
230
+ gstate_s_abe,
231
+ gstate_s_c,
232
+ # Params
233
+ tsz,
234
+ chans,
235
+ BLOCK_SIZE_C: tl.constexpr,
236
+ ):
237
+ # Parallelize over the batch dimension.
238
+ b_idx = tl.program_id(0)
239
+ c_idx = tl.program_id(1)
240
+
241
+ cs = (c_idx * BLOCK_SIZE_C) + tl.arange(0, BLOCK_SIZE_C)
242
+ cmask = cs < chans
243
+
244
+ # Pointers to the batch (and possibly channel) for the input tensors.
245
+ k_ptr = k_ptr + b_idx * k_s_b
246
+ v_ptr = v_ptr + b_idx * v_s_b
247
+ alpha_ptr = state_ptr + b_idx * state_s_b
248
+ beta_ptr = state_ptr + b_idx * state_s_b + state_s_abe
249
+ eps_ptr = state_ptr + b_idx * state_s_b + 2 * state_s_abe
250
+
251
+ # Pointers to the batch (and possibly channel) for the output tensors.
252
+ gk_ptr = gk_ptr + b_idx * gk_s_b
253
+ gv_ptr = gv_ptr + b_idx * gv_s_b
254
+
255
+ # Pointers to gradients which were recieved by the function.
256
+ gwkv_ptr = gwkv_ptr + b_idx * gwkv_s_b
257
+ galpha_out_ptr = gstate_out_ptr + b_idx * gstate_out_s_b
258
+ gbeta_out_ptr = gstate_out_ptr + b_idx * gstate_out_s_b + gstate_out_s_abe
259
+ geps_out_ptr = gstate_out_ptr + b_idx * gstate_out_s_b + 2 * gstate_out_s_abe
260
+
261
+ # Loads parameters.
262
+ galpha = tl.load(galpha_out_ptr + gstate_out_s_c * cs, mask=cmask).to(tl.float32)
263
+ gbeta = tl.load(gbeta_out_ptr + gstate_out_s_c * cs, mask=cmask).to(tl.float32)
264
+ geps = tl.load(geps_out_ptr + gstate_out_s_c * cs, mask=cmask).to(tl.float32)
265
+ w = tl.load(w_ptr + w_s_c * cs, mask=cmask).to(tl.float32)
266
+ u = tl.load(u_ptr + u_s_c * cs, mask=cmask).to(tl.float32)
267
+
268
+ # Gradient accumulators.
269
+ gw = tl.zeros_like(w)
270
+ gu = tl.zeros_like(u)
271
+
272
+ alpha_prev = tl.load(alpha_ptr + tsz * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
273
+ beta_prev = tl.load(beta_ptr + tsz * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
274
+ eps_prev = tl.load(eps_ptr + tsz * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
275
+
276
+ for t in range(tsz):
277
+ tc = tsz - t - 1
278
+
279
+ kt = tl.load(k_ptr + tc * k_s_t + k_s_c * cs, mask=cmask).to(tl.float32)
280
+ vt = tl.load(v_ptr + tc * v_s_t + v_s_c * cs, mask=cmask).to(tl.float32)
281
+
282
+ alpha_curr = alpha_prev
283
+ beta_curr = beta_prev
284
+ eps_curr = eps_prev
285
+
286
+ alpha_prev = tl.load(alpha_ptr + tc * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
287
+ beta_prev = tl.load(beta_ptr + tc * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
288
+ eps_prev = tl.load(eps_ptr + tc * state_s_t + state_s_c * cs, mask=cmask).to(tl.float32)
289
+
290
+ ukt = u + kt
291
+ tau = tl.maximum(ukt, eps_prev)
292
+ e1 = exp(eps_prev - tau)
293
+ e2 = exp(ukt - tau)
294
+
295
+ euke = exp(ukt + eps_prev - 2 * tau)
296
+
297
+ denom = e1 * beta_prev + e2
298
+ denom_sq = denom * denom
299
+
300
+ gwkvt = tl.load(gwkv_ptr + tc * gwkv_s_t + gwkv_s_c * cs, mask=cmask).to(tl.float32)
301
+
302
+ # Backpropagates wkv gradients.
303
+ guk = gwkvt * e2 * (e1 * beta_prev * vt - e1 * alpha_prev) / denom_sq
304
+ gu += guk
305
+ gk = guk
306
+ gv = gwkvt * e2 / denom
307
+
308
+ galpha_wkv = gwkvt * e1 / denom
309
+ gbeta_wkv = -gwkvt * e1 * (e2 * vt + e1 * alpha_prev) / denom_sq
310
+ geps_wkv_denom = e1 * beta_prev + e2
311
+ geps_wkv = gwkvt * euke * (alpha_prev - vt * beta_prev) / (geps_wkv_denom * geps_wkv_denom)
312
+
313
+ e1 = exp(w + eps_prev - eps_curr)
314
+ e2 = exp(kt - eps_curr)
315
+
316
+ # Backpropagates alpha gradients.
317
+ galpha_we = galpha * e1 * alpha_prev
318
+ gw += galpha_we
319
+ gk += galpha * e2 * vt
320
+ gv += galpha * e2
321
+ geps += galpha * -alpha_curr
322
+
323
+ # Backpropagates beta gradients.
324
+ gbeta_we = gbeta * e1 * beta_prev
325
+ gw += gbeta_we
326
+ gk += gbeta * e2
327
+ geps += gbeta * -beta_curr
328
+
329
+ # Backpropagates epsilon gradients.
330
+ geps_mask = w + eps_prev > kt
331
+ geps_we = tl.where(geps_mask, geps, tl.zeros_like(geps))
332
+ gw += geps_we
333
+ gk += tl.where(geps_mask, tl.zeros_like(geps), geps)
334
+
335
+ # Stores the gradients for k and v.
336
+ tl.store(gk_ptr + tc * gk_s_t + gk_s_c * cs, gk, mask=cmask)
337
+ tl.store(gv_ptr + tc * gv_s_t + gv_s_c * cs, gv, mask=cmask)
338
+
339
+ # Computes new gradients for alpha and beta.
340
+ galpha = galpha * e1 + galpha_wkv
341
+ gbeta = gbeta * e1 + gbeta_wkv
342
+ geps = galpha_we + gbeta_we + geps_we + geps_wkv
343
+
344
+ # Stores final gradients for alpha and beta.
345
+ galpha_ptr = gstate_ptr + b_idx * gstate_s_b
346
+ gbeta_ptr = gstate_ptr + b_idx * gstate_s_b + gstate_s_abe
347
+ geps_ptr = gstate_ptr + b_idx * gstate_s_b + 2 * gstate_s_abe
348
+ tl.store(galpha_ptr + gstate_s_c * cs, galpha, mask=cmask)
349
+ tl.store(gbeta_ptr + gstate_s_c * cs, gbeta, mask=cmask)
350
+ tl.store(geps_ptr + gstate_s_c * cs, geps, mask=cmask)
351
+
352
+ # Stores final gradients for w and u.
353
+ tl.store(gw_ptr + gw_s_b * b_idx + gw_s_c * cs, gw*w, mask=cmask)
354
+ tl.store(gu_ptr + gu_s_b * b_idx + gu_s_c * cs, gu, mask=cmask)
355
+
356
+
357
+ def fused_recurrent_rwkv4_backward(
358
+ w: Tensor,
359
+ u: Tensor,
360
+ k: Tensor,
361
+ v: Tensor,
362
+ state: Tensor,
363
+ grad_wkv: Tensor,
364
+ grad_state: Tensor,
365
+ ) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
366
+ bsz, tsz, chans = k.shape
367
+
368
+ gw = w.new_empty(bsz, chans, dtype=torch.float) # New tensors to output.
369
+ gu = u.new_empty(bsz, chans, dtype=torch.float)
370
+ gk = torch.empty_like(k)
371
+ gv = torch.empty_like(v)
372
+ gstate = k.new_empty(bsz, 3, 1, chans)
373
+
374
+ block_size_c = get_block_size_c(chans) # Constants.
375
+
376
+ def grid(meta: dict[str, Any]) -> tuple[int, ...]:
377
+ return (bsz, triton.cdiv(chans, meta["BLOCK_SIZE_C"]))
378
+
379
+ fused_recurrent_rwkv4_backward_kernel[grid](
380
+ # W
381
+ w,
382
+ w.stride(0),
383
+ # U
384
+ u,
385
+ u.stride(0),
386
+ # K
387
+ k,
388
+ k.stride(0),
389
+ k.stride(1),
390
+ k.stride(2),
391
+ # V
392
+ v,
393
+ v.stride(0),
394
+ v.stride(1),
395
+ v.stride(2),
396
+ # State
397
+ state,
398
+ state.stride(0),
399
+ state.stride(1),
400
+ state.stride(2),
401
+ state.stride(3),
402
+ # WKV grad
403
+ grad_wkv,
404
+ grad_wkv.stride(0),
405
+ grad_wkv.stride(1),
406
+ grad_wkv.stride(2),
407
+ # Output state grad
408
+ grad_state,
409
+ grad_state.stride(0),
410
+ grad_state.stride(1),
411
+ grad_state.stride(3),
412
+ # W grad
413
+ gw,
414
+ gw.stride(0),
415
+ gw.stride(1),
416
+ # U grad
417
+ gu,
418
+ gu.stride(0),
419
+ gu.stride(1),
420
+ # K grad
421
+ gk,
422
+ gk.stride(0),
423
+ gk.stride(1),
424
+ gk.stride(2),
425
+ # V grad
426
+ gv,
427
+ gv.stride(0),
428
+ gv.stride(1),
429
+ gv.stride(2),
430
+ # State grad
431
+ gstate,
432
+ gstate.stride(0),
433
+ gstate.stride(1),
434
+ gstate.stride(3),
435
+ # Params
436
+ tsz,
437
+ chans,
438
+ BLOCK_SIZE_C=block_size_c,
439
+ )
440
+
441
+ return gw.sum(0), gu.sum(0), gk, gv, gstate
442
+
443
+
444
+ class FusedRecurrentRWKV4Function(Function):
445
+
446
+ @staticmethod
447
+ @input_guard
448
+ def forward(
449
+ ctx: FunctionCtx,
450
+ w: Tensor,
451
+ u: Tensor,
452
+ k: Tensor,
453
+ v: Tensor,
454
+ state: Tensor,
455
+ ) -> tuple[Tensor, Tensor]:
456
+ ctx.w_dtype = w.dtype
457
+ w = -torch.exp(w.float())
458
+ wkv, state_out = fused_recurrent_rwkv4_forward(w, u, k, v, state)
459
+ ctx.save_for_backward(w, u, k, v, state_out[:, :, :-1])
460
+ return wkv, state_out[:, :, -1:]
461
+
462
+ @staticmethod
463
+ @once_differentiable
464
+ @input_guard
465
+ def backward(ctx: FunctionCtx, gwkv: Tensor, gstate: Tensor) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
466
+ w, u, k, v, state = cast(tuple[Tensor, ...], ctx.saved_tensors)
467
+ gw, gu, gk, gv, gstate = fused_recurrent_rwkv4_backward(w, u, k, v, state, gwkv, gstate)
468
+ return gw.to(ctx.w_dtype), gu.to(u), gk.to(k), gv.to(v), gstate.to(state)
469
+
470
+
471
+ def fused_recurrent_rwkv4(w: Tensor, u: Tensor, k: Tensor, v: Tensor, state: Tensor) -> tuple[Tensor, Tensor]:
472
+ return FusedRecurrentRWKV4Function.apply(w, u, k, v, state)
@@ -0,0 +1,9 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from .chunk import chunk_rwkv6
4
+ from .fused_recurrent import fused_recurrent_rwkv6
5
+
6
+ __all__ = [
7
+ 'chunk_rwkv6',
8
+ 'fused_recurrent_rwkv6'
9
+ ]