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,103 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from typing import Optional
4
+
5
+ import torch
6
+
7
+
8
+ def naive_recurrent_rwkv6(
9
+ q: torch.Tensor,
10
+ k: torch.Tensor,
11
+ v: torch.Tensor,
12
+ w: torch.Tensor,
13
+ u: torch.Tensor,
14
+ scale: Optional[float] = None,
15
+ initial_state: Optional[torch.Tensor] = None,
16
+ output_final_state: Optional[bool] = False
17
+ ):
18
+ orig_dtype = q.dtype
19
+ B, H, T, K, V = *q.shape, v.shape[-1]
20
+ q, k, v, w, u = map(lambda x: x.float(), (q, k, v, w, u))
21
+ h = torch.zeros(B, H, K, V, dtype=torch.float32, device=q.device)
22
+ o = torch.zeros_like(v)
23
+
24
+ if scale is None:
25
+ scale = K ** -0.5
26
+
27
+ if initial_state is not None:
28
+ h += initial_state
29
+
30
+ for i in range(T):
31
+ q_i = q[:, :, i, :] * scale
32
+ k_i = k[:, :, i]
33
+ v_i = v[:, :, i, :]
34
+ w_i = w[:, :, i].exp()
35
+ kv_i = k_i[..., None] * v_i[..., None, :]
36
+ o_i = (h + u[None, ..., None] * kv_i) * q_i[..., None]
37
+ o[:, :, i] = o_i.sum(-2)
38
+ h = h * w_i[..., None] + kv_i
39
+ ht = h if output_final_state else None
40
+ return o.to(orig_dtype), ht
41
+
42
+
43
+ @torch.no_grad
44
+ @torch.jit.script
45
+ def naive_recurrent_rwkv6_bwd(
46
+ q: torch.Tensor,
47
+ k: torch.Tensor,
48
+ v: torch.Tensor,
49
+ w: torch.Tensor,
50
+ u: torch.Tensor,
51
+ o: torch.Tensor,
52
+ do: torch.Tensor,
53
+ initial_state: Optional[torch.Tensor] = None
54
+ ):
55
+ q, k, v, w, u, o, do = (x.to(dtype=torch.float32) for x in (q, k, v, w, u, o, do))
56
+ B, H, T, K, V = q.shape[0], q.shape[1], q.shape[2], q.shape[3], v.shape[-1]
57
+ h = torch.zeros(B, H, K, V, dtype=torch.float32, device=q.device)
58
+ dq = torch.zeros_like(q)
59
+ dq_aux = torch.zeros_like(q)
60
+
61
+ if initial_state is not None:
62
+ h += initial_state
63
+
64
+ for i in range(T):
65
+ k_i = k[:, :, i]
66
+ v_i = v[:, :, i]
67
+ w_i = w[:, :, i].exp()
68
+ kv_i = k_i[..., None] * v_i[..., None, :]
69
+ h_i = (h + u[None, ..., None] * kv_i)
70
+ dq_i = (do[:, :, i, None, :] * h_i).sum(-1)
71
+ dq_aux_i = (do[:, :, i, None, :] * h).sum(-1)
72
+ dq[:, :, i] = dq_i
73
+ dq_aux[:, :, i] = dq_aux_i
74
+ h = h * w_i[..., None] + kv_i
75
+
76
+ du = torch.zeros_like(u)
77
+ dh = torch.zeros_like(h)
78
+ dk = torch.zeros_like(k)
79
+ dk_aux = torch.zeros_like(k)
80
+ dv = torch.zeros_like(v)
81
+
82
+ for i in range(T - 1, -1, -1):
83
+ d_kv_i = do[:, :, i, None, :] * q[:, :, i, :, None]
84
+ k_i = k[:, :, i]
85
+ v_i = v[:, :, i]
86
+ du_i = (d_kv_i * k_i[..., None] * v_i[..., None, :]).sum(-1)
87
+ du += du_i.sum(0)
88
+ dk_i = (dh * v_i[..., None, :]).sum(-1)
89
+ dk_aux[:, :, i] = dk_i
90
+ dk_i += (d_kv_i * u[None, ..., None] * v_i[..., None, :]).sum(-1)
91
+ dv_i = (d_kv_i * u[None, ..., None] * k_i[..., None]).sum(-2)
92
+ dv_i += (dh * k_i[..., None]).sum(-2)
93
+
94
+ dk[:, :, i] = dk_i
95
+ dv[:, :, i] = dv_i
96
+ dh = dh * w[:, :, i, :, None].exp() + d_kv_i
97
+
98
+ # dw = q * dq_aux - k * dk_aux
99
+ dw = torch.zeros_like(w)
100
+ for i in range(T - 2, -1, -1):
101
+ dw[:, :, i] = dw[:, :, i+1] + dq_aux[:, :, i+1] * q[:, :, i+1] - dk_aux[:, :, i] * k[:, :, i]
102
+
103
+ return dq, dk, dv, dw, du, dh
@@ -0,0 +1,10 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from .chunk import chunk_rwkv7
4
+ from .fused_recurrent import fused_mul_recurrent_rwkv7, fused_recurrent_rwkv7
5
+
6
+ __all__ = [
7
+ 'chunk_rwkv7',
8
+ 'fused_recurrent_rwkv7',
9
+ 'fused_mul_recurrent_rwkv7'
10
+ ]
@@ -0,0 +1,323 @@
1
+ import logging
2
+
3
+ import torch
4
+ import triton
5
+ import triton.language as tl
6
+
7
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, check_pytorch_version, input_guard, use_cuda_graph
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ if not check_pytorch_version('2.4'):
12
+ logger.warning('PyTorch < 2.4 detected - computations may be slower due to lack of optimizations')
13
+
14
+
15
+ @triton.autotune(
16
+ configs=[
17
+ triton.Config({'BLOCK_SIZE': block_size})
18
+ for block_size in [128, 256, 512, 1024, 2048, 4096, 8192]
19
+ ],
20
+ key=['hidden_dim'],
21
+ use_cuda_graph=use_cuda_graph,
22
+ )
23
+ @triton.jit
24
+ def rwkv_seq_mix_kernel(
25
+ x_ptr,
26
+ x_prev_ptr,
27
+ mix_k_ptr,
28
+ output_ptr,
29
+ batch_size: tl.constexpr,
30
+ token_length,
31
+ hidden_dim: tl.constexpr,
32
+ BLOCK_SIZE: tl.constexpr
33
+ ):
34
+ block_start = tl.program_id(0) * BLOCK_SIZE
35
+ block_idx = block_start + tl.arange(0, BLOCK_SIZE)[:]
36
+
37
+ total_seq_dim = token_length * hidden_dim
38
+ batch_idx = block_idx // total_seq_dim
39
+ seq_and_feat = block_idx % total_seq_dim
40
+ seq_idx = seq_and_feat // hidden_dim
41
+ feat_idx = seq_and_feat % hidden_dim
42
+
43
+ is_valid = (batch_idx < batch_size) & (seq_idx < token_length)
44
+
45
+ x_idx = batch_idx * total_seq_dim + seq_idx * hidden_dim + feat_idx
46
+
47
+ curr_x = tl.load(x_ptr + x_idx, mask=is_valid, other=0.0).to(tl.float32)
48
+ k_value = tl.load(mix_k_ptr + feat_idx).to(tl.float32)
49
+
50
+ is_first = seq_idx < 1
51
+ prev_state_idx = batch_idx * hidden_dim + feat_idx
52
+ prev_state = tl.load(x_prev_ptr + prev_state_idx,
53
+ mask=(is_first & is_valid),
54
+ other=0.0).to(tl.float32)
55
+
56
+ prev_x_idx = x_idx - hidden_dim
57
+ prev_x = tl.load(x_ptr + prev_x_idx,
58
+ mask=(~is_first & is_valid),
59
+ other=0.0).to(tl.float32)
60
+
61
+ prev_value = tl.where(is_first, prev_state, prev_x)
62
+ state_diff = prev_value - curr_x
63
+ mixed = state_diff * k_value
64
+ result = tl.cast(curr_x + mixed, dtype=output_ptr.dtype.element_ty, fp_downcast_rounding='rtne')
65
+ tl.store(output_ptr + x_idx, result, mask=is_valid)
66
+
67
+
68
+ @triton.jit
69
+ def rwkv_channel_mixing_pow_and_relu(
70
+ in_ptr,
71
+ out_ptr,
72
+ BLOCK_SIZE: tl.constexpr
73
+ ):
74
+ """Fused ReLU and Power operation: x = ReLU(x)^2"""
75
+ xoffset = tl.program_id(0) * BLOCK_SIZE
76
+ xindex = xoffset + tl.arange(0, BLOCK_SIZE)
77
+ x0 = xindex
78
+ x = tl.load(in_ptr + (x0), None)
79
+ x = tl.maximum(x, 0.0).to(tl.float32)
80
+ x = tl.cast(x * x, dtype=out_ptr.dtype.element_ty, fp_downcast_rounding='rtne')
81
+ tl.store(out_ptr + (x0), x, None)
82
+
83
+
84
+ def rwkv_mix_torch(x: torch.Tensor, x_prev: torch.Tensor, x_k: torch.Tensor):
85
+ if x_prev.dim() == 2:
86
+ x_prev = x_prev.unsqueeze(1) # (batch_size, 1, hidden_dim)
87
+ xx = torch.cat((x_prev, x[:, :-1, :]), dim=1) - x
88
+ k = x.addcmul(xx, x_k)
89
+ return k
90
+
91
+
92
+ def rwkv_relu_and_square_torch(x: torch.Tensor):
93
+ return torch.relu(x) ** 2
94
+
95
+
96
+ def rwkv_mix_fwd(x, x_prev, x_k):
97
+ has_batch = x.dim() == 3
98
+
99
+ if has_batch:
100
+ batch_size, token_length, hidden_dim = x.shape
101
+ else:
102
+ token_length, hidden_dim = x.shape
103
+ batch_size = 1
104
+ x = x.unsqueeze(0)
105
+ x_prev = x_prev.unsqueeze(0)
106
+
107
+ token_length = x.shape[1]
108
+ hidden_dim = x.shape[2]
109
+ total_elements = batch_size * token_length * hidden_dim
110
+
111
+ output = torch.empty_like(x)
112
+
113
+ def grid(meta): return (
114
+ (total_elements + meta['BLOCK_SIZE'] - 1) // meta['BLOCK_SIZE'], # grid_0
115
+ 1, # grid_1
116
+ 1 # grid_2
117
+ )
118
+
119
+ rwkv_seq_mix_kernel[grid](
120
+ x.contiguous(),
121
+ x_prev.contiguous(),
122
+ x_k.squeeze(),
123
+ output,
124
+ batch_size=batch_size,
125
+ token_length=token_length,
126
+ hidden_dim=hidden_dim,
127
+ )
128
+ if not has_batch:
129
+ output = output.squeeze(0)
130
+ return output
131
+
132
+
133
+ def rwkv_relu_and_square_fwd(x: torch.Tensor, inplace: bool = True):
134
+ """
135
+ Triton implementation of RWKV's ReLU and square operation
136
+ Args:
137
+ x: Input tensor
138
+ Returns:
139
+ Tensor after ReLU and square operations
140
+ """
141
+ x = x.contiguous()
142
+ output = x if inplace else torch.empty_like(x)
143
+
144
+ def grid(meta): return (
145
+ (output.numel() + meta['BLOCK_SIZE'] - 1) // meta['BLOCK_SIZE'], # grid_0
146
+ 1, # grid_1
147
+ 1 # grid_2
148
+ )
149
+ rwkv_channel_mixing_pow_and_relu[grid](
150
+ x,
151
+ output,
152
+ BLOCK_SIZE=4096,
153
+ )
154
+
155
+ return output
156
+
157
+
158
+ @triton.jit
159
+ def relu_square_bwd_kernel(
160
+ out_ptr,
161
+ forward_input_ptr,
162
+ BLOCK_SIZE: tl.constexpr
163
+ ):
164
+ """ReLU(x)^2 backward kernel
165
+ grad_input = grad_output * 2 * x if x > 0 else 0
166
+ """
167
+ pid = tl.program_id(0)
168
+ block_start = pid * BLOCK_SIZE
169
+ offsets = block_start + tl.arange(0, BLOCK_SIZE)
170
+
171
+ x = tl.load(forward_input_ptr + offsets).to(tl.float32)
172
+ grad = tl.load(out_ptr + offsets).to(tl.float32)
173
+
174
+ x = tl.maximum(x, 0.0)
175
+
176
+ grad_input = grad * 2 * x
177
+
178
+ tl.store(out_ptr + offsets, grad_input.to(out_ptr.dtype.element_ty))
179
+
180
+
181
+ @triton.autotune(
182
+ configs=[
183
+ triton.Config({'BLOCK_SIZE': block_size})
184
+ for block_size in [128, 256, 512, 1024, 2048, 4096, 8192]
185
+ ],
186
+ key=['hidden_dim'],
187
+ use_cuda_graph=use_cuda_graph,
188
+ )
189
+ @triton.jit
190
+ def rwkv_mix_bwd_kenel(
191
+ dk1_ptr0,
192
+ xk_ptr,
193
+ dx_ptr,
194
+ dx_prev_ptr,
195
+ batch_size,
196
+ token_length,
197
+ hidden_dim: tl.constexpr,
198
+ BLOCK_SIZE: tl.constexpr
199
+ ):
200
+ pid = tl.program_id(0)
201
+ offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
202
+
203
+ batch_idx = offsets // (token_length * hidden_dim)
204
+ seq_feat = offsets % (token_length * hidden_dim)
205
+ seq_idx = seq_feat // hidden_dim
206
+ feat_idx = seq_feat % hidden_dim
207
+
208
+ is_valid = offsets < (batch_size * token_length * hidden_dim)
209
+
210
+ dk1 = tl.load(dk1_ptr0 + offsets, mask=is_valid)
211
+ xk = tl.load(xk_ptr + feat_idx, mask=is_valid)
212
+ prod = dk1 * xk
213
+
214
+ mask_next = seq_idx < (token_length - 1)
215
+ next_offset = offsets + hidden_dim
216
+ dk1_next = tl.load(dk1_ptr0 + next_offset, mask=mask_next & is_valid, other=0.0)
217
+ prod_next = dk1_next * xk
218
+ dx_val = dk1 - prod + tl.where(mask_next, prod_next, 0.0)
219
+ dx_val = tl.cast(dx_val, dtype=dx_ptr.dtype.element_ty, fp_downcast_rounding='rtne')
220
+ tl.store(dx_ptr + offsets, dx_val, mask=is_valid)
221
+
222
+ dx_prev_offset = batch_idx * hidden_dim + feat_idx
223
+ is_first_step = seq_idx == 0
224
+
225
+ tl.store(
226
+ dx_prev_ptr + dx_prev_offset,
227
+ tl.cast(prod, dtype=dx_prev_ptr.dtype.element_ty),
228
+ mask=is_first_step
229
+ )
230
+
231
+
232
+ @torch.compile(fullgraph=True)
233
+ def compute_x_k_grad(dk1, x, x_prev):
234
+ """
235
+ Args:
236
+ dk1: (batch*seq_len, hidden_dim)
237
+ x: (batch, seq_len, hidden_dim)
238
+ x_prev: (batch, hidden_dim) or (batch, 1, hidden_dim)
239
+ """
240
+
241
+ if x_prev.dim() == 2:
242
+ x_prev = x_prev.unsqueeze(1) # (batch, 1, hidden_dim)
243
+ xx = torch.cat((x_prev, x[:, :-1, :]), dim=1) - x # (batch, seq_len, hidden_dim)
244
+
245
+ # (hidden_dim,) --> (1, 1, hidden_dim)
246
+ grad_x_k = (dk1 * xx.reshape(-1, x.shape[2])).sum(dim=0).view(1, 1, -1)
247
+ return grad_x_k
248
+
249
+
250
+ def rwkv_channel_mixing_bwd(grad_output, x, x_prev, x_k, key_weight, value_weight, k1, k1_K, k, inplace=True):
251
+ batch_size = x.shape[0] if x.dim() == 3 else 1
252
+ seq_len, n_embd = x.shape[-2], x.shape[-1]
253
+
254
+ dV = k.transpose(-2, -1) @ grad_output
255
+ dk = grad_output @ value_weight.transpose(-2, -1)
256
+
257
+ BLOCK_SIZE = 4096
258
+ grid = ((dk.numel() + BLOCK_SIZE - 1) // BLOCK_SIZE,)
259
+ relu_square_bwd_kernel[grid](
260
+ dk,
261
+ k1_K,
262
+ BLOCK_SIZE=BLOCK_SIZE
263
+ )
264
+
265
+ dK = k1.transpose(-2, -1) @ dk
266
+ dk1 = dk @ key_weight.transpose(-2, -1)
267
+ dk1 = dk1.view(-1, n_embd).contiguous()
268
+
269
+ dk_reduced = compute_x_k_grad(dk1, x, x_prev)
270
+ dx_prev = torch.empty_like(x_prev) if not inplace else x_prev
271
+ dx = torch.empty_like(x) if not inplace else x
272
+
273
+ def grid(meta): return ((batch_size * seq_len * n_embd + meta['BLOCK_SIZE'] - 1) // meta['BLOCK_SIZE'], 1, 1)
274
+ rwkv_mix_bwd_kenel[grid](
275
+ dk1,
276
+ x_k.squeeze(),
277
+ dx,
278
+ dx_prev,
279
+ batch_size,
280
+ seq_len,
281
+ n_embd,
282
+ )
283
+ # dx_prev.shape batch_size, seq_len, n_embd
284
+ return dx, dx_prev, dk_reduced, dK, dV
285
+
286
+
287
+ class Rwkv7ChannelMixing(torch.autograd.Function):
288
+ @staticmethod
289
+ @input_guard
290
+ @autocast_custom_fwd
291
+ def forward(ctx, x, x_prev, x_k, key_weight, value_weight, inplace: bool = True):
292
+ k1 = rwkv_mix_fwd(x, x_prev, x_k)
293
+ k1_K = k1 @ key_weight
294
+ k = rwkv_relu_and_square_fwd(k1_K, inplace=True)
295
+ ctx.save_for_backward(x, x_prev, x_k, key_weight, value_weight)
296
+ ctx.inplace = inplace
297
+ return k @ value_weight
298
+
299
+ @staticmethod
300
+ @input_guard
301
+ @autocast_custom_bwd
302
+ def backward(ctx, dkv):
303
+ x, x_prev, x_k, key_weight, value_weight = ctx.saved_tensors
304
+ k1 = rwkv_mix_fwd(x, x_prev, x_k)
305
+ k1_K = k1 @ key_weight
306
+ k = rwkv_relu_and_square_fwd(k1_K, inplace=False)
307
+ dx, dx_prev, dk_reduced, dK, dV = rwkv_channel_mixing_bwd(
308
+ dkv, x, x_prev, x_k, key_weight, value_weight, k1, k1_K, k, ctx.inplace)
309
+ return dx, dx_prev, dk_reduced, dK, dV, None
310
+
311
+
312
+ def channel_mixing_rwkv7(x: torch.Tensor, x_prev: torch.Tensor, x_k: torch.Tensor,
313
+ key_weight: torch.Tensor, value_weight: torch.Tensor, inplace: bool = True):
314
+ assert x.dim() == 3
315
+
316
+ return Rwkv7ChannelMixing.apply(x, x_prev, x_k, key_weight, value_weight, inplace), x[-1, :]
317
+
318
+
319
+ def channel_mixing_rwkv7_torch(x, x_prev, x_k, key_weight, value_weight):
320
+ k1 = rwkv_mix_torch(x, x_prev, x_k)
321
+ k1_K = k1 @ key_weight
322
+ k = rwkv_relu_and_square_torch(k1_K)
323
+ return k @ value_weight, x[-1, :]
fla/ops/rwkv7/chunk.py ADDED
@@ -0,0 +1,78 @@
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.generalized_delta_rule import chunk_dplr_delta_rule
10
+
11
+
12
+ def chunk_rwkv7(
13
+ r: torch.Tensor,
14
+ w: torch.Tensor,
15
+ k: torch.Tensor,
16
+ v: torch.Tensor,
17
+ a: torch.Tensor,
18
+ b: torch.Tensor,
19
+ scale: float = 1.0,
20
+ initial_state: torch.Tensor = None,
21
+ output_final_state: bool = True,
22
+ cu_seqlens: Optional[torch.LongTensor] = None,
23
+ head_first: bool = False,
24
+ ):
25
+ """
26
+ Args:
27
+ r (torch.Tensor):
28
+ r of shape `[B, T, H, K]`.
29
+ w (torch.Tensor):
30
+ log decay of shape `[B, T, H, K]`.
31
+ k (torch.Tensor):
32
+ k of shape `[B, T, H, K]`.
33
+ v (torch.Tensor):
34
+ v of shape `[B, T, H, V]`.
35
+ a (torch.Tensor):
36
+ a of shape `[B, T, H, K]`.
37
+ b (torch.Tensor):
38
+ b of shape `[B, T, H, K]`.
39
+ scale (float):
40
+ scale of the attention.
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
+ cu_seqlens (torch.LongTensor):
48
+ Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
49
+ consistent with the FlashAttention API.
50
+ head_first (Optional[bool]):
51
+ Whether the inputs are in the head-first format. Default: `False`.
52
+ This argument has been deprecated.
53
+ """
54
+ if head_first:
55
+ raise DeprecationWarning(
56
+ "head_first is deprecated and will be removed in a future version. "
57
+ "Please use head_first=False for now instead."
58
+ )
59
+ if not head_first and r.shape[1] < r.shape[2]:
60
+ warnings.warn(
61
+ f"Input tensor shape suggests potential format mismatch: seq_len ({r.shape[1]}) < num_heads ({r.shape[2]}). "
62
+ "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
63
+ "when head_first=False was specified. "
64
+ "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
65
+ )
66
+ return chunk_dplr_delta_rule(
67
+ q=r,
68
+ k=k,
69
+ v=v,
70
+ a=a,
71
+ b=b,
72
+ gk=w,
73
+ scale=scale,
74
+ initial_state=initial_state,
75
+ output_final_state=output_final_state,
76
+ cu_seqlens=cu_seqlens,
77
+ head_first=head_first,
78
+ )