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,1143 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ import math
5
+ import warnings
6
+ from typing import Optional, Tuple
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ import triton
12
+ import triton.language as tl
13
+ from einops import rearrange
14
+
15
+ from fla.ops.utils import prepare_chunk_indices, prepare_sequence_ids
16
+ from fla.utils import get_multiprocessor_count, input_guard, is_amd
17
+
18
+ NUM_WARPS_AUTOTUNE = [2, 4, 8, 16] if is_amd else [4, 8, 16, 32]
19
+ STATIC_WARPS = 32 if not is_amd else 16
20
+
21
+
22
+ try:
23
+ from causal_conv1d import causal_conv1d_fn
24
+ from causal_conv1d import causal_conv1d_update as causal_conv1d_update_cuda
25
+ except ImportError:
26
+ causal_conv1d_fn = None
27
+ causal_conv1d_update_cuda = None
28
+
29
+
30
+ @triton.heuristics({
31
+ 'HAS_WEIGHT': lambda args: args['weight'] is not None,
32
+ 'HAS_BIAS': lambda args: args['bias'] is not None,
33
+ 'HAS_RESIDUAL': lambda args: args['residual'] is not None,
34
+ 'USE_INITIAL_STATE': lambda args: args['initial_state'] is not None,
35
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
36
+ })
37
+ @triton.autotune(
38
+ configs=[
39
+ triton.Config({'BD': BD}, num_warps=num_warps)
40
+ for BD in [16, 32, 64, 128]
41
+ for num_warps in NUM_WARPS_AUTOTUNE
42
+ ],
43
+ key=['D', 'W', 'NB'],
44
+ )
45
+ @triton.jit
46
+ def causal_conv1d_fwd_kernel(
47
+ x,
48
+ y,
49
+ weight,
50
+ bias,
51
+ residual,
52
+ cu_seqlens,
53
+ initial_state,
54
+ chunk_indices,
55
+ B,
56
+ T,
57
+ D: tl.constexpr,
58
+ W: tl.constexpr,
59
+ BT: tl.constexpr,
60
+ BW: tl.constexpr,
61
+ BD: tl.constexpr,
62
+ NB: tl.constexpr,
63
+ ACTIVATION: tl.constexpr,
64
+ HAS_WEIGHT: tl.constexpr,
65
+ HAS_BIAS: tl.constexpr,
66
+ HAS_RESIDUAL: tl.constexpr,
67
+ USE_INITIAL_STATE: tl.constexpr,
68
+ IS_VARLEN: tl.constexpr,
69
+ ):
70
+ i_d, i_t, i_b = tl.program_id(0), tl.program_id(1), tl.program_id(2)
71
+
72
+ if IS_VARLEN:
73
+ i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
74
+ bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
75
+ T = eos - bos
76
+ else:
77
+ i_n = i_b
78
+ bos, eos = i_b * T, i_b * T + T
79
+
80
+ o_d = i_d * BD + tl.arange(0, BD)
81
+ o_w = tl.arange(0, BW) + W - BW
82
+ m_d = o_d < D
83
+ m_w = o_w >= 0
84
+
85
+ if HAS_WEIGHT:
86
+ # [BD, BW]
87
+ b_w = tl.load(weight + o_d[:, None] * W + o_w, mask=m_d[:, None] & m_w, other=0).to(tl.float32)
88
+
89
+ b_y = tl.zeros((BT, BD), dtype=tl.float32)
90
+ if not USE_INITIAL_STATE:
91
+ for i_w in tl.static_range(-W + 1, 1):
92
+ p_yi = tl.make_block_ptr(x + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
93
+ # [BT, BD]
94
+ b_yi = tl.load(p_yi, boundary_check=(0, 1)).to(tl.float32)
95
+ if HAS_WEIGHT:
96
+ b_yi *= tl.sum(b_w * (o_w == (i_w + W - 1)), 1)
97
+ b_y += b_yi
98
+ elif i_t * BT >= W:
99
+ # to make Triton compiler happy, we need to copy codes
100
+ for i_w in tl.static_range(-W + 1, 1):
101
+ p_yi = tl.make_block_ptr(x + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
102
+ # [BT, BD]
103
+ b_yi = tl.load(p_yi, boundary_check=(0, 1)).to(tl.float32)
104
+ if HAS_WEIGHT:
105
+ b_yi *= tl.sum(b_w * (o_w == (i_w + W - 1)), 1)
106
+ b_y += b_yi
107
+ else:
108
+ o_t = i_t * BT + tl.arange(0, BT)
109
+ for i_w in tl.static_range(-W + 1, 1):
110
+ o_x = o_t + i_w
111
+ m_x = ((o_x >= 0) & (o_x < T))[:, None] & m_d
112
+ m_c = ((o_x + W >= 0) & (o_x < 0))[:, None] & m_d
113
+
114
+ b_yi = tl.load(x + bos * D + o_x[:, None] * D + o_d, mask=m_x, other=0).to(tl.float32)
115
+
116
+ b_yi += tl.load(initial_state + i_n * D*W + o_d * W + (o_x + W)[:, None], mask=m_c, other=0).to(tl.float32)
117
+
118
+ if HAS_WEIGHT:
119
+ b_yi *= tl.sum(b_w * (o_w == (i_w + W - 1)), 1)
120
+ b_y += b_yi
121
+
122
+ if HAS_BIAS:
123
+ b_y += tl.load(bias + o_d, mask=m_d).to(tl.float32)
124
+
125
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
126
+ b_y = b_y * tl.sigmoid(b_y)
127
+
128
+ if HAS_RESIDUAL:
129
+ p_residual = tl.make_block_ptr(residual + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
130
+ b_residual = tl.load(p_residual, boundary_check=(0, 1))
131
+ b_y += b_residual
132
+
133
+ p_y = tl.make_block_ptr(y + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
134
+ tl.store(p_y, tl.cast(b_y, dtype=p_y.dtype.element_ty, fp_downcast_rounding='rtne'), boundary_check=(0, 1))
135
+
136
+
137
+ @triton.heuristics({
138
+ 'HAS_WEIGHT': lambda args: args['dw'] is not None,
139
+ 'HAS_BIAS': lambda args: args['db'] is not None,
140
+ 'USE_INITIAL_STATE': lambda args: args['dh0'] is not None,
141
+ 'USE_FINAL_STATE': lambda args: args['dht'] is not None,
142
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
143
+ })
144
+ @triton.autotune(
145
+ configs=[
146
+ triton.Config({'BD': BD}, num_warps=num_warps)
147
+ for BD in [16, 32, 64, 128]
148
+ for num_warps in [4, 8, 16, 32]
149
+ ],
150
+ key=['D', 'W', 'NB'],
151
+ )
152
+ @triton.jit
153
+ def causal_conv1d_bwd_kernel(
154
+ x,
155
+ y,
156
+ weight,
157
+ initial_state,
158
+ dh0,
159
+ dht,
160
+ dy,
161
+ dx,
162
+ dw,
163
+ db,
164
+ cu_seqlens,
165
+ chunk_indices,
166
+ B,
167
+ T,
168
+ D: tl.constexpr,
169
+ W: tl.constexpr,
170
+ BT: tl.constexpr,
171
+ BW: tl.constexpr,
172
+ BD: tl.constexpr,
173
+ NB: tl.constexpr,
174
+ ACTIVATION: tl.constexpr,
175
+ HAS_WEIGHT: tl.constexpr,
176
+ HAS_BIAS: tl.constexpr,
177
+ USE_INITIAL_STATE: tl.constexpr,
178
+ USE_FINAL_STATE: tl.constexpr,
179
+ IS_VARLEN: tl.constexpr,
180
+ ):
181
+ i_d, i_t, i_b = tl.program_id(0), tl.program_id(1), tl.program_id(2)
182
+ if IS_VARLEN:
183
+ i_tg = i_t
184
+ i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
185
+ bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
186
+ T = eos - bos
187
+ else:
188
+ i_tg = i_b * tl.num_programs(1) + i_t
189
+ i_n = i_b
190
+ bos, eos = i_b * T, i_b * T + T
191
+
192
+ o_d = i_d * BD + tl.arange(0, BD)
193
+ o_w = tl.arange(0, BW) + W - BW
194
+ m_d = o_d < D
195
+ m_w = o_w >= 0
196
+
197
+ if HAS_WEIGHT:
198
+ p_x = tl.make_block_ptr(x + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
199
+ b_x = tl.load(p_x, boundary_check=(0, 1))
200
+ # [BD, BW]
201
+ b_w = tl.load(weight + o_d[:, None] * W + o_w, mask=m_d[:, None] & m_w, other=0)
202
+
203
+ b_dx = tl.zeros((BT, BD), dtype=tl.float32)
204
+ if HAS_BIAS:
205
+ b_db = tl.zeros((BD,), dtype=tl.float32)
206
+
207
+ if not USE_FINAL_STATE:
208
+ for i_w in tl.static_range(0, W):
209
+ p_dy = tl.make_block_ptr(dy + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
210
+ # [BT, BD]
211
+ b_dy = tl.load(p_dy, boundary_check=(0, 1)).to(tl.float32)
212
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
213
+ p_y = tl.make_block_ptr(y + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
214
+ b_y = tl.load(p_y, boundary_check=(0, 1)).to(tl.float32)
215
+ b_ys = tl.sigmoid(b_y)
216
+ b_dy = b_dy * b_ys * (1 + b_y * (1 - b_ys))
217
+ b_wdy = b_dy
218
+ if HAS_WEIGHT:
219
+ # [BT, BD]
220
+ b_wdy = b_wdy * tl.sum(b_w * (o_w == (W - i_w - 1)), 1)
221
+ # [BD]
222
+ b_dw = tl.sum(b_dy * b_x, 0)
223
+ tl.store(dw + i_tg * D*W + o_d * W + W - i_w - 1, b_dw.to(dw.dtype.element_ty), mask=m_d)
224
+ if HAS_BIAS and i_w == 0:
225
+ b_db += tl.sum(b_dy, 0)
226
+ b_dx += b_wdy
227
+ elif i_t * BT >= W:
228
+ # to make Triton compiler happy, we need to copy codes
229
+ for i_w in tl.static_range(0, W):
230
+ p_dy = tl.make_block_ptr(dy + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
231
+ # [BT, BD]
232
+ b_dy = tl.load(p_dy, boundary_check=(0, 1)).to(tl.float32)
233
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
234
+ p_y = tl.make_block_ptr(y + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
235
+ b_y = tl.load(p_y, boundary_check=(0, 1)).to(tl.float32)
236
+ b_ys = tl.sigmoid(b_y)
237
+ b_dy = b_dy * b_ys * (1 + b_y * (1 - b_ys))
238
+ b_wdy = b_dy
239
+ if HAS_WEIGHT:
240
+ # [BT, BD]
241
+ b_wdy = b_wdy * tl.sum(b_w * (o_w == (W - i_w - 1)), 1)
242
+ # [BD]
243
+ b_dw = tl.sum(b_dy * b_x, 0)
244
+ tl.store(dw + i_tg * D*W + o_d * W + W - i_w - 1, b_dw.to(dw.dtype.element_ty), mask=m_d)
245
+ if HAS_BIAS and i_w == 0:
246
+ b_db += tl.sum(b_dy, 0)
247
+ b_dx += b_wdy
248
+ else:
249
+ # which may use initial state
250
+ o_t = i_t * BT + tl.arange(0, BT)
251
+ for i_w in tl.static_range(0, W):
252
+ p_dy = tl.make_block_ptr(dy + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
253
+ b_dy_shift = tl.load(p_dy, boundary_check=(0, 1)).to(tl.float32)
254
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
255
+ p_y = tl.make_block_ptr(y + bos * D, (T, D), (D, 1), (i_t * BT + i_w, i_d * BD), (BT, BD), (1, 0))
256
+ b_y_shift = tl.load(p_y, boundary_check=(0, 1)).to(tl.float32)
257
+ b_ys = tl.sigmoid(b_y_shift)
258
+ b_dy_shift = b_dy_shift * b_ys * (1 + b_y_shift * (1 - b_ys))
259
+ if HAS_WEIGHT:
260
+ # gradient comes from x:sum_t dy[t+i_w] * x[t]
261
+ b_dw = tl.sum(b_dy_shift * b_x, 0)
262
+ # index of cache:c = W - i_w + t
263
+ if USE_INITIAL_STATE:
264
+ mask_head_rows = (o_t < i_w)
265
+ # dy_head = dy[t]
266
+ b_dy_head = tl.load(dy + bos * D + o_t[:, None] * D + o_d, mask=(mask_head_rows[:, None] & m_d[None, :]),
267
+ other=0.0).to(tl.float32)
268
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
269
+ # use y[t] (not y[t+i_w])
270
+ b_y_head = tl.load(y + bos * D + o_t[:, None] * D + o_d,
271
+ mask=(mask_head_rows[:, None] & m_d[None, :]), other=0.0).to(tl.float32)
272
+ b_ys_head = tl.sigmoid(b_y_head)
273
+ b_dy_head = b_dy_head * b_ys_head * (1 + b_y_head * (1 - b_ys_head))
274
+ o_c = W - i_w + o_t
275
+ # index 0 is padding 0
276
+ mask_c = (mask_head_rows & (o_c >= 1) & (o_c < W))
277
+ b_xc = tl.load(initial_state + i_n * D * W + o_d[None, :] * W + o_c[:, None],
278
+ mask=(mask_c[:, None] & m_d[None, :]), other=0.0).to(tl.float32)
279
+ # add the gradient comes from initial_state
280
+ b_dw += tl.sum(b_dy_head * b_xc, 0)
281
+ tl.store(dw + i_tg * D * W + o_d * W + W - i_w - 1, b_dw.to(dw.dtype.element_ty), mask=m_d)
282
+
283
+ if HAS_BIAS and i_w == 0:
284
+ b_db += tl.sum(b_dy_shift, 0)
285
+ b_wdy = b_dy_shift if not HAS_WEIGHT else (b_dy_shift * tl.sum(b_w * (o_w == (W - i_w - 1)), 1))
286
+ b_dx += b_wdy
287
+
288
+ if USE_INITIAL_STATE:
289
+ p_dy0 = tl.make_block_ptr(dy + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
290
+ b_dy0 = tl.load(p_dy0, boundary_check=(0, 1)).to(tl.float32)
291
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
292
+ p_y0 = tl.make_block_ptr(y + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
293
+ b_y0 = tl.load(p_y0, boundary_check=(0, 1)).to(tl.float32)
294
+ b_ys0 = tl.sigmoid(b_y0)
295
+ b_dy0 = b_dy0 * b_ys0 * (1 + b_y0 * (1 - b_ys0))
296
+ # index 0 is padding 0, skip calculation
297
+ for i_w in tl.static_range(1, W):
298
+ m_rows = (o_t < i_w)
299
+ if HAS_WEIGHT:
300
+ # [BT]
301
+ w_idx_rows = i_w - 1 - o_t
302
+ # [BT, BW]
303
+ w_mask = (o_w[None, :] == w_idx_rows[:, None])
304
+ w_pick = tl.sum(b_w[None, :, :] * w_mask[:, None, :], 2)
305
+ else:
306
+ w_pick = 1.0
307
+ contrib = (b_dy0 * w_pick).to(tl.float32)
308
+ contrib = tl.where(m_rows[:, None] & m_d[None, :], contrib, 0.0)
309
+ # [BD]
310
+ b_dh0_s = tl.sum(contrib, 0)
311
+ # dh0: [NT, B, D, W]
312
+ tl.store(dh0 + i_t * B * D * W + i_n * D * W + o_d * W + i_w,
313
+ b_dh0_s.to(dh0.dtype.element_ty, fp_downcast_rounding='rtne'), mask=m_d)
314
+
315
+ if HAS_BIAS:
316
+ b_db = tl.cast(b_db, dtype=db.dtype.element_ty, fp_downcast_rounding='rtne')
317
+ tl.store(db + i_tg * D + o_d, b_db, mask=m_d)
318
+
319
+ if USE_FINAL_STATE:
320
+ if i_t * BT + BT >= T-W:
321
+ start_tok = max(0, T - (W - 1))
322
+ offset = i_t * BT + tl.arange(0, BT)
323
+ tok_idx = offset - start_tok
324
+ mask = (offset >= start_tok) & (offset < T)
325
+ w_idx = 1 + tok_idx
326
+ dht_off = i_n * D * W + o_d[None, :] * W + w_idx[:, None]
327
+ b_dht = tl.load(dht + dht_off, mask=mask[:, None] & m_d[None, :], other=0.).to(tl.float32)
328
+ b_dx += b_dht
329
+
330
+ p_dx = tl.make_block_ptr(dx + bos * D, (T, D), (D, 1), (i_t * BT, i_d * BD), (BT, BD), (1, 0))
331
+ tl.store(p_dx, tl.cast(b_dx, dtype=p_dx.dtype.element_ty, fp_downcast_rounding='rtne'), boundary_check=(0, 1))
332
+
333
+
334
+ @triton.heuristics({
335
+ 'USE_INITIAL_STATE': lambda args: args['cache'] is not None,
336
+ 'HAS_WEIGHT': lambda args: args['weight'] is not None,
337
+ 'HAS_BIAS': lambda args: args['bias'] is not None,
338
+ 'HAS_RESIDUAL': lambda args: args['residual'] is not None,
339
+ })
340
+ @triton.jit
341
+ def causal_conv1d_update_kernel(
342
+ x,
343
+ cache,
344
+ residual,
345
+ y,
346
+ weight,
347
+ bias,
348
+ D: tl.constexpr,
349
+ W: tl.constexpr,
350
+ BD: tl.constexpr,
351
+ BW: tl.constexpr,
352
+ ACTIVATION: tl.constexpr,
353
+ USE_INITIAL_STATE: tl.constexpr,
354
+ HAS_WEIGHT: tl.constexpr,
355
+ HAS_BIAS: tl.constexpr,
356
+ HAS_RESIDUAL: tl.constexpr,
357
+ ):
358
+ i_d, i_n = tl.program_id(0), tl.program_id(1)
359
+
360
+ o_d = i_d * BD + tl.arange(0, BD)
361
+ o_w = tl.arange(0, BW) + W - BW
362
+ m_d = o_d < D
363
+ m_w = o_w >= 0
364
+ m_c = o_w < W - 1
365
+
366
+ # [BD]
367
+ b_x = tl.load(x + i_n * D + o_d, mask=m_d, other=0).to(tl.float32)
368
+
369
+ if USE_INITIAL_STATE:
370
+ # shift the cache by 1 with the last one being discarded
371
+ p_cache = tl.make_block_ptr(cache + i_n * D*W, (D, W), (W, 1), (i_d * BD, W - BW + 1), (BD, BW), (1, 0))
372
+ # [BD, BW]
373
+ b_cache = tl.load(p_cache, boundary_check=(0, 1)).to(tl.float32)
374
+ b_cache = tl.where(m_c[None, :], b_cache, b_x[:, None])
375
+ else:
376
+ b_cache = tl.zeros((BD, BW), dtype=tl.float32)
377
+
378
+ if HAS_WEIGHT:
379
+ b_w = tl.load(weight + o_d[:, None] * W + o_w, mask=m_d[:, None] & m_w, other=0)
380
+ b_y = tl.sum(b_cache * b_w, 1)
381
+ else:
382
+ b_y = tl.sum(b_cache, 1)
383
+ if HAS_BIAS:
384
+ b_y += tl.load(bias + o_d, mask=m_d)
385
+
386
+ if ACTIVATION == 'swish' or ACTIVATION == 'silu':
387
+ b_y = b_y * tl.sigmoid(b_y)
388
+
389
+ if HAS_RESIDUAL:
390
+ b_y += tl.load(residual + i_n * D + o_d, mask=m_d, other=0)
391
+
392
+ tl.store(y + i_n * D + o_d, tl.cast(b_y, dtype=y.dtype.element_ty, fp_downcast_rounding='rtne'), mask=m_d)
393
+
394
+ if USE_INITIAL_STATE:
395
+ b_cache = tl.cast(b_cache, dtype=cache.dtype.element_ty, fp_downcast_rounding='rtne')
396
+ # update the cache in-place
397
+ p_cache = tl.make_block_ptr(cache + i_n * D*W, (D, W), (W, 1), (i_d * BD, W - BW), (BD, BW), (1, 0))
398
+ tl.store(p_cache, b_cache, boundary_check=(0, 1))
399
+
400
+
401
+ def causal_conv1d_fwd(
402
+ x: torch.Tensor,
403
+ weight: torch.Tensor,
404
+ bias: torch.Tensor,
405
+ residual: torch.Tensor,
406
+ initial_state: Optional[torch.Tensor] = None,
407
+ output_final_state: bool = False,
408
+ activation: Optional[str] = None,
409
+ cu_seqlens: Optional[torch.Tensor] = None,
410
+ ) -> torch.Tensor:
411
+ shape = x.shape
412
+ if x.shape[-1] != weight.shape[0]:
413
+ x = rearrange(x, 'b t ... -> b t (...)')
414
+ B, T, D, W = *x.shape, weight.shape[1]
415
+ BT = min(64, triton.next_power_of_2(triton.cdiv(max(16, B*T), get_multiprocessor_count(x.device.index))))
416
+ BW = triton.next_power_of_2(W)
417
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
418
+ NT = len(chunk_indices) if cu_seqlens is not None else triton.cdiv(T, BT)
419
+ NB = triton.cdiv(B*T, 1024)
420
+
421
+ y = torch.empty_like(x)
422
+ def grid(meta): return (triton.cdiv(D, meta['BD']), NT, B)
423
+ causal_conv1d_fwd_kernel[grid](
424
+ x=x,
425
+ y=y,
426
+ weight=weight,
427
+ bias=bias,
428
+ residual=residual,
429
+ cu_seqlens=cu_seqlens,
430
+ initial_state=initial_state,
431
+ chunk_indices=chunk_indices,
432
+ B=B,
433
+ T=T,
434
+ D=D,
435
+ W=W,
436
+ BT=BT,
437
+ BW=BW,
438
+ NB=NB,
439
+ ACTIVATION=activation,
440
+ )
441
+ final_state = None
442
+ if output_final_state:
443
+ final_state = causal_conv1d_update_states(
444
+ x=x,
445
+ state_len=W,
446
+ initial_state=initial_state,
447
+ cu_seqlens=cu_seqlens,
448
+ )
449
+ return y.view(shape), final_state
450
+
451
+
452
+ def causal_conv1d_bwd(
453
+ x: torch.Tensor,
454
+ dy: torch.Tensor,
455
+ dht: torch.Tensor,
456
+ weight: Optional[torch.Tensor] = None,
457
+ bias: Optional[torch.Tensor] = None,
458
+ residual: Optional[torch.Tensor] = None,
459
+ initial_state: Optional[torch.Tensor] = None,
460
+ activation: Optional[str] = None,
461
+ cu_seqlens: Optional[torch.Tensor] = None,
462
+ ):
463
+ shape = x.shape
464
+ if x.shape[-1] != weight.shape[0]:
465
+ x = rearrange(x, 'b t ... -> b t (...)')
466
+ B, T, D = x.shape
467
+ W = weight.shape[1] if weight is not None else None
468
+ BT = min(64, triton.next_power_of_2(triton.cdiv(max(16, B*T), get_multiprocessor_count(x.device.index))))
469
+ BW = triton.next_power_of_2(W)
470
+ chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if cu_seqlens is not None else None
471
+ NT = len(chunk_indices) if cu_seqlens is not None else triton.cdiv(T, BT)
472
+ NB = triton.cdiv(B*T, 1024)
473
+
474
+ y = None
475
+ if activation is not None:
476
+ y, _ = causal_conv1d_fwd(
477
+ x=x,
478
+ weight=weight,
479
+ bias=bias,
480
+ residual=None,
481
+ initial_state=initial_state,
482
+ activation=None,
483
+ cu_seqlens=cu_seqlens,
484
+ output_final_state=False
485
+ )
486
+ dx = torch.empty_like(x)
487
+ dw = weight.new_empty(B*NT, *weight.shape, dtype=torch.float) if weight is not None else None
488
+ db = bias.new_empty(B*NT, *bias.shape, dtype=torch.float) if bias is not None else None
489
+ dr = dy if residual is not None else None
490
+ dh0 = initial_state.new_zeros(min(NT, triton.cdiv(W, BT)), *initial_state.shape) if initial_state is not None else None
491
+
492
+ def grid(meta): return (triton.cdiv(D, meta['BD']), NT, B)
493
+ causal_conv1d_bwd_kernel[grid](
494
+ x=x,
495
+ y=y,
496
+ weight=weight,
497
+ initial_state=initial_state,
498
+ dh0=dh0,
499
+ dht=dht,
500
+ dy=dy,
501
+ dx=dx,
502
+ dw=dw,
503
+ db=db,
504
+ cu_seqlens=cu_seqlens,
505
+ chunk_indices=chunk_indices,
506
+ B=B,
507
+ T=T,
508
+ D=D,
509
+ W=W,
510
+ BT=BT,
511
+ BW=BW,
512
+ NB=NB,
513
+ ACTIVATION=activation,
514
+ )
515
+ if weight is not None:
516
+ dw = dw.sum(0).to(weight)
517
+ if bias is not None:
518
+ db = db.sum(0).to(bias)
519
+ if initial_state is not None:
520
+ dh0 = dh0.sum(0, dtype=torch.float32).to(initial_state)
521
+
522
+ return dx.view(shape), dw, db, dr, dh0
523
+
524
+
525
+ @triton.heuristics({
526
+ 'USE_INITIAL_STATE': lambda args: args['initial_state'] is not None,
527
+ 'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
528
+ })
529
+ @triton.jit
530
+ def causal_conv1d_states_fwd_kernel(
531
+ x,
532
+ initial_state,
533
+ final_state,
534
+ cu_seqlens,
535
+ T,
536
+ D,
537
+ W,
538
+ BD: tl.constexpr,
539
+ BW: tl.constexpr,
540
+ USE_INITIAL_STATE: tl.constexpr,
541
+ IS_VARLEN: tl.constexpr,
542
+ ):
543
+ i_d, i_n = tl.program_id(0), tl.program_id(1)
544
+ if IS_VARLEN:
545
+ bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
546
+ T = eos - bos
547
+ else:
548
+ bos, eos = i_n * T, i_n * T + T
549
+
550
+ o_t = eos - BW + tl.arange(0, BW)
551
+ o_d = i_d * BD + tl.arange(0, BD)
552
+ o_w = W - BW + tl.arange(0, BW)
553
+ m_t = (o_t >= tl.maximum(bos, eos - W))
554
+ m_d = o_d < D
555
+ m_w = (o_w >= 0) & (o_w < W)
556
+
557
+ b_x = tl.load(x + o_t * D + o_d[:, None], mask=(m_t & m_d[:, None]), other=0)
558
+ if USE_INITIAL_STATE:
559
+ if T < BW:
560
+ o_c = W - (BW - T) + tl.arange(0, BW)
561
+ m_c = (o_c >= 0) & (o_c < W)
562
+ b_cache = tl.load(initial_state + i_n * D*W + o_d[:, None] * W + o_c, mask=m_d[:, None] & m_c, other=0)
563
+ b_x += b_cache
564
+
565
+ tl.store(final_state + i_n * D*W + o_d[:, None] * W + o_w, b_x, mask=m_d[:, None] & m_w)
566
+
567
+
568
+ @input_guard
569
+ def causal_conv1d_update_states(
570
+ x: torch.Tensor,
571
+ state_len: int,
572
+ initial_state: Optional[torch.Tensor] = None,
573
+ cu_seqlens: Optional[torch.Tensor] = None,
574
+ ) -> torch.Tensor:
575
+ B, T, D, W = *x.shape, state_len
576
+ N = len(cu_seqlens) - 1 if cu_seqlens is not None else B
577
+
578
+ final_state = torch.empty(N, D, W, dtype=x.dtype, device=x.device)
579
+ BD = min(triton.next_power_of_2(D), 256)
580
+ BW = triton.next_power_of_2(W)
581
+ grid = (triton.cdiv(D, BD), N)
582
+ causal_conv1d_states_fwd_kernel[grid](
583
+ x=x,
584
+ initial_state=initial_state,
585
+ final_state=final_state,
586
+ cu_seqlens=cu_seqlens,
587
+ T=T,
588
+ D=D,
589
+ W=W,
590
+ BW=BW,
591
+ BD=BD
592
+ )
593
+ return final_state
594
+
595
+
596
+ @input_guard
597
+ def causal_conv1d_update(
598
+ x: torch.Tensor,
599
+ cache: torch.Tensor,
600
+ residual: Optional[torch.Tensor] = None,
601
+ weight: Optional[torch.Tensor] = None,
602
+ bias: Optional[torch.Tensor] = None,
603
+ activation: Optional[str] = None
604
+ ) -> torch.Tensor:
605
+ shape = x.shape
606
+ if weight is not None and x.shape[-1] != weight.shape[0]:
607
+ x = rearrange(x, 'b t ... -> b t (...)')
608
+ *_, D = x.shape
609
+ N = x.numel() // D
610
+ W = weight.shape[1] if weight is not None else None
611
+ BD = 8
612
+ BW = triton.next_power_of_2(W)
613
+
614
+ y = torch.empty_like(x)
615
+ # NOTE: autotuning is disabled as cache is updated in-place
616
+ def grid(meta): return (triton.cdiv(D, meta['BD']), N)
617
+ causal_conv1d_update_kernel[grid](
618
+ x=x,
619
+ cache=cache,
620
+ residual=residual,
621
+ y=y,
622
+ weight=weight,
623
+ bias=bias,
624
+ D=D,
625
+ W=W,
626
+ BD=BD,
627
+ BW=BW,
628
+ ACTIVATION=activation,
629
+ num_warps=STATIC_WARPS,
630
+ )
631
+ return y.view(shape), cache
632
+
633
+
634
+ class CausalConv1dFunction(torch.autograd.Function):
635
+
636
+ @staticmethod
637
+ @input_guard
638
+ def forward(
639
+ ctx,
640
+ x: torch.Tensor,
641
+ weight: Optional[torch.Tensor] = None,
642
+ bias: Optional[torch.Tensor] = None,
643
+ residual: Optional[torch.Tensor] = None,
644
+ initial_state: Optional[torch.Tensor] = None,
645
+ output_final_state: Optional[bool] = False,
646
+ activation: Optional[str] = None,
647
+ cu_seqlens: Optional[torch.Tensor] = None,
648
+ ):
649
+ ctx.activation = activation
650
+ ctx.cu_seqlens = cu_seqlens
651
+ ctx.save_for_backward(x, weight, bias, residual, initial_state)
652
+ y, final_state = causal_conv1d_fwd(
653
+ x=x,
654
+ weight=weight,
655
+ bias=bias,
656
+ residual=residual,
657
+ initial_state=initial_state,
658
+ output_final_state=output_final_state,
659
+ activation=activation,
660
+ cu_seqlens=cu_seqlens,
661
+ )
662
+ return y, final_state
663
+
664
+ @staticmethod
665
+ @input_guard
666
+ def backward(ctx, dy: torch.Tensor, dht: Optional[torch.Tensor] = None):
667
+ x, weight, bias, residual, initial_state = ctx.saved_tensors
668
+ dx, dw, db, dr, dh0 = causal_conv1d_bwd(
669
+ x=x,
670
+ dy=dy,
671
+ dht=dht,
672
+ weight=weight,
673
+ bias=bias,
674
+ residual=residual,
675
+ initial_state=initial_state,
676
+ activation=ctx.activation,
677
+ cu_seqlens=ctx.cu_seqlens,
678
+ )
679
+ return dx, dw, db, dr, dh0, None, None, None
680
+
681
+
682
+ @input_guard
683
+ def causal_conv1d(
684
+ x: torch.Tensor,
685
+ weight: Optional[torch.Tensor] = None,
686
+ bias: Optional[torch.Tensor] = None,
687
+ residual: Optional[torch.Tensor] = None,
688
+ initial_state: Optional[torch.Tensor] = None,
689
+ output_final_state: Optional[bool] = False,
690
+ activation: Optional[str] = None,
691
+ backend: Optional[str] = 'triton',
692
+ cu_seqlens: Optional[torch.Tensor] = None,
693
+ **kwargs,
694
+ ):
695
+ """
696
+ A causal 1D convolution implementation that powers Mamba/Mamba2 and DeltaNet architectures.
697
+
698
+ When a residual connection is provided, this implements the Canon operation
699
+ described in the paper at https://papers.ssrn.com/sol3/papers.cfm?abstract_id=5240330.
700
+
701
+ Args:
702
+ x (torch.Tensor):
703
+ Input tensor of shape [B, T, D].
704
+ weight (Optional[torch.Tensor]):
705
+ Weight tensor of shape [D, W]. Default: `None`.
706
+ bias (Optional[torch.Tensor]):
707
+ Bias tensor of shape [D]. Default: `None`.
708
+ residual (Optional[torch.Tensor]):
709
+ Residual tensor of shape [B, T, D]. Default: `None`.
710
+ initial_state (Optional[torch.Tensor]):
711
+ Initial state tensor of shape [N, D, W],
712
+ where `N` is the number of sequences in the batch and `W` is the kernel size.
713
+ If provided, the initial state is used to initialize the cache. Default: `None`.
714
+ output_final_state (Optional[bool]):
715
+ Whether to output the final state of shape [N, D, W]. Default: `False`.
716
+ activation (Optional[str]):
717
+ Activations applied to output, only `swish`/`silu` or `None` (i.e., no activation) are supported.
718
+ Default: `None`.
719
+ backend (Optional[str]):
720
+ Specifies the backend to use for the convolution operation. Supported values are `'cuda'` and `'triton'`.
721
+ Default: `'triton'`.
722
+ cu_seqlens (Optional[torch.Tensor]):
723
+ Cumulative sequence lengths (optional)
724
+
725
+ Returns:
726
+ Tuple of (output, final_state).
727
+ If `output_final_state` is `False`, the final state is `None`.
728
+ """
729
+
730
+ if backend == 'triton':
731
+ y, final_state = CausalConv1dFunction.apply(
732
+ x,
733
+ weight,
734
+ bias,
735
+ residual,
736
+ initial_state,
737
+ output_final_state,
738
+ activation,
739
+ cu_seqlens,
740
+ )
741
+ return y, final_state
742
+
743
+ B, _, D, W = *x.shape, weight.shape[-1]
744
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
745
+ x = rearrange(x, 'b t d -> b d t')
746
+
747
+ # check if cu_seqlens and cache are both provided
748
+ # Sequence index for each token. Used for varlen.
749
+ # Suppose a batch consists of two sequences with lengths 3 and 4,
750
+ # seq_idx=[0, 0, 0, 1, 1, 1, 1] for this batch.
751
+ # NOTE: No need to provide this arg if `cu_seqlens` is passed.
752
+ # This arg is just for BC, and will be removed in the future.
753
+ # [B, T]
754
+ seq_idx = kwargs.get('seq_idx', None)
755
+ if cu_seqlens is not None and seq_idx is None:
756
+ seq_idx = prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0)
757
+
758
+ # equivalent to:
759
+ # y = _conv_forward(x, weight, bias)[..., :x.shape[-1]]
760
+ # if activation is not None:
761
+ # y = ACT2FN[activation](x)
762
+
763
+ cache, initial_state = initial_state, None
764
+ if cache is not None:
765
+ # To make causal-conv1d happy
766
+ initial_state = (
767
+ cache[:, :, -(W-1):] # [N, D, W-1]
768
+ .transpose(1, 2).contiguous() # [N, W-1, D] and stride(2)==1
769
+ .transpose(1, 2) # [N, D, W-1] and stride(1)==1
770
+ )
771
+
772
+ result = causal_conv1d_fn(
773
+ x=x,
774
+ weight=weight,
775
+ bias=bias,
776
+ activation=activation,
777
+ seq_idx=seq_idx,
778
+ initial_states=initial_state,
779
+ return_final_states=output_final_state,
780
+ )
781
+ y, final_state = result if output_final_state else (result, None)
782
+ y = rearrange(y, 'b d t -> b t d')
783
+ if output_final_state:
784
+ cache = x.new_zeros(N, D, W)
785
+ cache[:, :, -W+1:].copy_(final_state[:, :, -W+1:])
786
+ if residual is not None:
787
+ y.add_(residual)
788
+
789
+ return y, cache
790
+
791
+
792
+ class ShortConvolution(nn.Conv1d):
793
+ """
794
+ Simple wrapper around `nn.Conv1d` that accepts dimension last.
795
+ """
796
+
797
+ def __init__(
798
+ self,
799
+ hidden_size: int,
800
+ kernel_size: int,
801
+ bias: bool = False,
802
+ activation: Optional[str] = 'silu',
803
+ backend: Optional[str] = 'cuda',
804
+ device: Optional[torch.device] = None,
805
+ dtype: Optional[torch.dtype] = None,
806
+ **kwargs,
807
+ ):
808
+ super().__init__(
809
+ in_channels=hidden_size,
810
+ out_channels=hidden_size,
811
+ kernel_size=kernel_size,
812
+ groups=hidden_size,
813
+ bias=bias,
814
+ padding=kernel_size - 1,
815
+ device=device,
816
+ dtype=dtype,
817
+ )
818
+
819
+ self.hidden_size = hidden_size
820
+ self.activation = None
821
+
822
+ if activation is not None:
823
+ assert activation in ['silu', 'swish'], f"Activation `{activation}` not supported yet."
824
+ self.activation = activation
825
+
826
+ if 'use_fast_conv1d' in kwargs:
827
+ warnings.warn(
828
+ "The `use_fast_conv1d` parameter is deprecated and will be ignored. "
829
+ "Please use the `backend` parameter instead."
830
+ )
831
+ import os
832
+ self.backend = os.environ.get('FLA_CONV_BACKEND', backend)
833
+ if backend not in ['cuda', 'triton']:
834
+ raise ValueError(f"Invalid backend: {backend}, must be one of ['cuda', 'triton']")
835
+ if backend == 'cuda':
836
+ if causal_conv1d_fn is None:
837
+ warnings.warn(
838
+ "The `backend` parameter is set to `cuda`, but `causal_conv1d_fn` is not available. "
839
+ "Switching to the Triton implementation instead. "
840
+ "Consider installing `causal_conv1d` to enable the CUDA backend."
841
+ )
842
+ self.backend = 'triton'
843
+
844
+ def extra_repr(self):
845
+ s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}'
846
+ ', stride={stride}')
847
+ if self.padding != (0,) * len(self.padding):
848
+ s += ', padding={padding}'
849
+ if self.dilation != (1,) * len(self.dilation):
850
+ s += ', dilation={dilation}'
851
+ if self.output_padding != (0,) * len(self.output_padding):
852
+ s += ', output_padding={output_padding}'
853
+ if self.groups != 1:
854
+ s += ', groups={groups}'
855
+ if self.bias is None:
856
+ s += ', bias=False'
857
+ if self.padding_mode != 'zeros':
858
+ s += ', padding_mode={padding_mode}'
859
+ if self.activation is not None:
860
+ s += ', activation={activation}'
861
+ s += f', backend={self.backend}'
862
+ return s.format(**self.__dict__)
863
+
864
+ def forward(
865
+ self,
866
+ x: torch.Tensor,
867
+ residual: Optional[torch.Tensor] = None,
868
+ mask: Optional[torch.Tensor] = None,
869
+ cache: Optional[torch.Tensor] = None,
870
+ output_final_state: bool = False,
871
+ cu_seqlens: Optional[torch.LongTensor] = None,
872
+ **kwargs,
873
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
874
+ """
875
+ Args:
876
+ x (`torch.Tensor`):
877
+ Tensor of shape `[B, T, D]`. `B` must be 1 if `seq_idx` is provided.
878
+ residual (`Optional[torch.Tensor]`):
879
+ Residual tensor of shape `[B, T, D]`. Default: `None`.
880
+ mask (`Optional[torch.Tensor]`):
881
+ Attention mask dealing with padded positions.
882
+ cache (`Optional[torch.Tensor]`):
883
+ Previous cache tensor of shape `[N, D, W]`, where `W` is the kernel size.
884
+ If provided, the cache is updated **inplace**.
885
+ output_final_state (Optional[bool]):
886
+ Whether to output the final state of shape `[N, D, W]`. Default: `False`.
887
+ cu_seqlens (Optional[torch.LongTensor]):
888
+ Cumulative sequence lengths for each batch. Used for varlen. Default: `None`.
889
+ Shape: [B+1]
890
+
891
+ Returns:
892
+ Tensor of shape `[B, T, D]`.
893
+ """
894
+
895
+ B, T, *_ = x.shape
896
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
897
+ if mask is not None:
898
+ if cu_seqlens is not None:
899
+ raise ValueError("`mask` and `cu_seqlens` cannot be provided at the same time")
900
+ x = x.mul_(mask.unsqueeze(-1))
901
+
902
+ # in decoding phase, the cache (if provided) is updated inplace
903
+ if B * T == N:
904
+ y, cache = self.step(
905
+ x=x,
906
+ residual=residual,
907
+ cache=cache,
908
+ output_final_state=output_final_state,
909
+ cu_seqlens=cu_seqlens
910
+ )
911
+ return y, cache
912
+
913
+ # cuda backend do not support:
914
+ # 1. both `cu_seqlens` and `cache` being provided
915
+ # 2. both `cu_seqlens` and `output_final_state` being provided
916
+ if self.backend == 'cuda' and (
917
+ (cu_seqlens is not None and cache is not None) or
918
+ (cu_seqlens is not None and output_final_state)
919
+ ):
920
+ warnings.warn(
921
+ "The CUDA backend does not support both `cu_seqlens` and `cache` being provided, "
922
+ "or both `cu_seqlens` and `output_final_state` being provided. "
923
+ "Switching to the Triton backend instead. ",
924
+ stacklevel=2
925
+ )
926
+ self.backend = 'triton'
927
+
928
+ return causal_conv1d(
929
+ x=x,
930
+ weight=rearrange(self.weight, "d 1 w -> d w"),
931
+ bias=self.bias,
932
+ residual=residual,
933
+ initial_state=cache,
934
+ output_final_state=output_final_state,
935
+ activation=self.activation,
936
+ backend=self.backend,
937
+ cu_seqlens=cu_seqlens,
938
+ **kwargs
939
+ )
940
+
941
+ def step(
942
+ self,
943
+ x: torch.Tensor,
944
+ residual: torch.Tensor,
945
+ cache: torch.Tensor,
946
+ output_final_state: bool = False,
947
+ cu_seqlens: Optional[torch.LongTensor] = None
948
+ ):
949
+ B, _, D, W = *x.shape, self.kernel_size[0]
950
+ N = B if cu_seqlens is None else len(cu_seqlens) - 1
951
+ if output_final_state and cache is None:
952
+ cache = x.new_zeros(N, D, W)
953
+ # NOTE: we follow the fast mode that updates the cache in-place
954
+ if self.backend == 'triton':
955
+ return causal_conv1d_update(
956
+ x=x,
957
+ cache=cache,
958
+ residual=residual,
959
+ weight=rearrange(self.weight, "d 1 w -> d w"),
960
+ bias=self.bias,
961
+ activation=self.activation,
962
+ )
963
+
964
+ shape = x.shape
965
+ x = x.squeeze(0) if cu_seqlens is not None else x.squeeze(1)
966
+ # equivalent to:
967
+ # cache.copy_(cache.roll(shifts=-1, dims=-1))
968
+ # cache[:, :, -1] = x
969
+ # y = torch.sum(cache * rearrange(self.weight, "d 1 w -> d w"), dim=-1)
970
+ y = causal_conv1d_update_cuda(
971
+ x=x,
972
+ conv_state=cache,
973
+ weight=rearrange(self.weight, "d 1 w -> d w"),
974
+ bias=self.bias,
975
+ activation=self.activation,
976
+ )
977
+ y = y.view(shape)
978
+ if residual is not None:
979
+ y.add_(residual)
980
+ return y, cache
981
+
982
+ @property
983
+ def state_size(self) -> int:
984
+ return self.hidden_size * self.kernel_size
985
+
986
+
987
+ def fft_conv(u, k, dropout_mask, gelu=True, k_rev=None):
988
+ seqlen = u.shape[-1]
989
+ fft_size = 2 * seqlen
990
+ k_f = torch.fft.rfft(k, n=fft_size) / fft_size
991
+ if k_rev is not None:
992
+ k_rev_f = torch.fft.rfft(k_rev, n=fft_size) / fft_size
993
+ k_f = k_f + k_rev_f.conj()
994
+ u_f = torch.fft.rfft(u.to(dtype=k.dtype), n=fft_size)
995
+
996
+ if len(u.shape) > 3:
997
+ k_f = k_f.unsqueeze(1)
998
+ y = torch.fft.irfft(u_f * k_f, n=fft_size, norm="forward")[..., :seqlen]
999
+
1000
+ out = y + u
1001
+ if gelu:
1002
+ out = F.gelu(out)
1003
+ if dropout_mask is not None:
1004
+ return (out * rearrange(dropout_mask, "b H -> b H 1")).to(dtype=u.dtype)
1005
+ else:
1006
+ return out.to(dtype=u.dtype)
1007
+
1008
+
1009
+ class LongConvolution(nn.Module):
1010
+ """
1011
+ LongConvolution applies a convolution operation on the input tensor using a fixed
1012
+ filter of length max_len.
1013
+ The filter is learned during training and is applied using FFT convolution.
1014
+
1015
+ Args:
1016
+ hidden_size (int): The number of expected features in the input and output.
1017
+ max_len (int): The maximum sequence length.
1018
+
1019
+ Returns:
1020
+ y: [batch_size, seq_len, hidden_size] tensor
1021
+ """
1022
+
1023
+ def __init__(
1024
+ self,
1025
+ hidden_size: int,
1026
+ max_len: int,
1027
+ **kwargs,
1028
+ ):
1029
+ """
1030
+ Initializes the LongConvolution module.
1031
+ Args:
1032
+ hidden_size (int): The number of expected features in the input and output.
1033
+ max_len (int): The maximum sequence length.
1034
+ """
1035
+ super().__init__()
1036
+ self.hidden_size = hidden_size
1037
+ self.filter = nn.Parameter(torch.randn(self.hidden_size, max_len), requires_grad=True)
1038
+
1039
+ def forward(self, x: torch.Tensor, *args, **kwargs):
1040
+ """
1041
+ Applies the LongConvolution operation on the input tensor.
1042
+ Args:
1043
+ x: [batch_size, seq_len, hidden_size] tensor
1044
+ Returns:
1045
+ y: [batch_size, seq_len, hidden_size] tensor
1046
+ """
1047
+ x = x.transpose(1, 2)
1048
+ y = fft_conv(x, self.filter, dropout_mask=None, gelu=False)
1049
+ y = y.transpose(1, 2)
1050
+ return y.to(dtype=x.dtype)
1051
+
1052
+
1053
+ class PositionalEmbedding(nn.Module):
1054
+ def __init__(self, emb_dim: int, seq_len: int, **kwargs):
1055
+ """Complex exponential positional embeddings for implicit long convolution filters."""
1056
+ super().__init__()
1057
+
1058
+ self.seq_len = seq_len
1059
+ # The time embedding fed to the filteres is normalized so that t_f = 1
1060
+ t = torch.linspace(0, 1, self.seq_len)[None, :, None] # 1, L, 1
1061
+
1062
+ if emb_dim > 1:
1063
+ bands = (emb_dim - 1) // 2
1064
+ # To compute the right embeddings we use the "proper" linspace
1065
+ t_rescaled = torch.linspace(0, seq_len - 1, seq_len)[None, :, None]
1066
+ w = 2 * math.pi * t_rescaled / seq_len # 1, L, 1
1067
+
1068
+ f = torch.linspace(1e-4, bands - 1, bands)[None, None]
1069
+ z = torch.exp(-1j * f * w)
1070
+ z = torch.cat([t, z.real, z.imag], dim=-1)
1071
+ self.z = nn.Parameter(z, requires_grad=False)
1072
+
1073
+ def forward(self, L):
1074
+ return self.z[:, :L]
1075
+
1076
+
1077
+ class ImplicitLongConvolution(nn.Module):
1078
+ """
1079
+ Long convolution with implicit filter parameterized by an MLP.
1080
+
1081
+ Args:
1082
+ hidden_size (int):
1083
+ The number of expected features in the input and output.
1084
+ max_len (int):
1085
+ The maximum sequence length.
1086
+ d_emb (Optional[int]):
1087
+ The dimension of the positional embeddings. Must be odd and greater or equal to 3 (time, sine and cosine).
1088
+ Defaults to 3.
1089
+ d_hidden (Optional[int]):
1090
+ The number of features in the hidden layer of the MLP. Defaults to 16.
1091
+
1092
+ Attributes:
1093
+ pos_emb (`PositionalEmbedding`): The positional embedding layer.
1094
+ mlp (`nn.Sequential`): The MLP that parameterizes the implicit filter.
1095
+
1096
+ """
1097
+
1098
+ def __init__(
1099
+ self,
1100
+ hidden_size: int,
1101
+ max_len: int,
1102
+ d_emb: int = 3,
1103
+ d_hidden: int = 16,
1104
+ **kwargs,
1105
+ ):
1106
+ """
1107
+ Long convolution with implicit filter parameterized by an MLP.
1108
+
1109
+
1110
+ """
1111
+ super().__init__()
1112
+ self.hidden_size = hidden_size
1113
+ self.d_emb = d_emb
1114
+
1115
+ assert (
1116
+ d_emb % 2 != 0 and d_emb >= 3
1117
+ ), "d_emb must be odd and greater or equal to 3 (time, sine and cosine)"
1118
+ self.pos_emb = PositionalEmbedding(d_emb, max_len)
1119
+
1120
+ # final linear layer
1121
+ self.mlp = nn.Sequential(
1122
+ nn.Linear(d_emb, d_hidden),
1123
+ torch.nn.ReLU(),
1124
+ nn.Linear(d_hidden, hidden_size),
1125
+ )
1126
+
1127
+ def filter(self, seq_len: int, *args, **kwargs):
1128
+ return self.mlp(self.pos_emb(seq_len)).transpose(1, 2)
1129
+
1130
+ def forward(self, x: torch.Tensor, *args, **kwargs):
1131
+ """
1132
+ Args:
1133
+ x: [batch_size, seq_len, hidden_size] tensor
1134
+
1135
+ Returns:
1136
+ y: [batch_size, seq_len, hidden_size] tensor
1137
+ """
1138
+ x = x.transpose(1, 2)
1139
+ k = self.filter(x.shape[-1])
1140
+ y = fft_conv(x, k, dropout_mask=None, gelu=False)
1141
+
1142
+ y = y.transpose(1, 2)
1143
+ return y.to(dtype=x.dtype)