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
fla/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ __path__ = __import__('pkgutil').extend_path(__path__, __name__)
4
+ __version__ = '0.3.2'
@@ -0,0 +1,33 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from fla.modules.convolution import ImplicitLongConvolution, LongConvolution, ShortConvolution
4
+ from fla.modules.fused_bitlinear import BitLinear, FusedBitLinear
5
+ from fla.modules.fused_cross_entropy import FusedCrossEntropyLoss
6
+ from fla.modules.fused_kl_div import FusedKLDivLoss
7
+ from fla.modules.fused_linear_cross_entropy import FusedLinearCrossEntropyLoss
8
+ from fla.modules.fused_norm_gate import (
9
+ FusedLayerNormGated,
10
+ FusedLayerNormSwishGate,
11
+ FusedLayerNormSwishGateLinear,
12
+ FusedRMSNormGated,
13
+ FusedRMSNormSwishGate,
14
+ FusedRMSNormSwishGateLinear
15
+ )
16
+ from fla.modules.l2norm import L2Norm
17
+ from fla.modules.layernorm import GroupNorm, GroupNormLinear, LayerNorm, LayerNormLinear, RMSNorm, RMSNormLinear
18
+ from fla.modules.mlp import GatedMLP
19
+ from fla.modules.rotary import RotaryEmbedding
20
+ from fla.modules.token_shift import TokenShift
21
+
22
+ __all__ = [
23
+ 'ImplicitLongConvolution', 'LongConvolution', 'ShortConvolution',
24
+ 'BitLinear', 'FusedBitLinear',
25
+ 'FusedCrossEntropyLoss', 'FusedLinearCrossEntropyLoss', 'FusedKLDivLoss',
26
+ 'L2Norm',
27
+ 'GroupNorm', 'GroupNormLinear', 'LayerNorm', 'LayerNormLinear', 'RMSNorm', 'RMSNormLinear',
28
+ 'FusedLayerNormGated', 'FusedLayerNormSwishGate', 'FusedLayerNormSwishGateLinear',
29
+ 'FusedRMSNormGated', 'FusedRMSNormSwishGate', 'FusedRMSNormSwishGateLinear',
30
+ 'GatedMLP',
31
+ 'RotaryEmbedding',
32
+ 'TokenShift'
33
+ ]
@@ -0,0 +1,548 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Tri Dao, Yu Zhang, Songlin Yang.
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+ import triton
7
+ import triton.language as tl
8
+
9
+ from fla.ops.utils.op import exp, log
10
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard, is_amd
11
+
12
+ try:
13
+ from torch.distributed.tensor import DTensor
14
+ except (ImportError, AttributeError):
15
+ DTensor = None
16
+
17
+ NUM_WARPS_AUTOTUNE = [1, 2, 4, 8, 16] if is_amd else [1, 2, 4, 8, 16, 32]
18
+
19
+
20
+ @triton.autotune(
21
+ configs=[
22
+ triton.Config({'B': bs}, num_warps=num_warps)
23
+ for bs in [512, 1024, 2048, 4096, 8192]
24
+ for num_warps in NUM_WARPS_AUTOTUNE
25
+ ],
26
+ key=['D']
27
+ )
28
+ @triton.jit(do_not_specialize=['T'])
29
+ def sigmoid_fwd_kernel(
30
+ x, y,
31
+ T,
32
+ B: tl.constexpr,
33
+ D: tl.constexpr
34
+ ):
35
+ pid = tl.program_id(0)
36
+ offs = pid * B + tl.arange(0, B)
37
+ mask = offs < T
38
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
39
+ y_val = 1.0 / (1.0 + exp(-x_val))
40
+ tl.store(y + offs, y_val.to(y.dtype.element_ty), mask=mask)
41
+
42
+
43
+ @triton.autotune(
44
+ configs=[
45
+ triton.Config({'B': bs}, num_warps=num_warps)
46
+ for bs in [512, 1024, 2048, 4096, 8192]
47
+ for num_warps in NUM_WARPS_AUTOTUNE
48
+ ],
49
+ key=['D']
50
+ )
51
+ @triton.jit(do_not_specialize=['T'])
52
+ def sigmoid_bwd_kernel(
53
+ x, dy, dx,
54
+ T,
55
+ B: tl.constexpr,
56
+ D: tl.constexpr
57
+ ):
58
+ pid = tl.program_id(0)
59
+ offs = pid * B + tl.arange(0, B)
60
+ mask = offs < T
61
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
62
+ g_val = tl.load(dy + offs, mask=mask, other=0.).to(tl.float32)
63
+ s = 1.0 / (1.0 + exp(-x_val))
64
+ dx_val = g_val * s * (1.0 - s)
65
+ tl.store(dx + offs, dx_val.to(dx.dtype.element_ty), mask=mask)
66
+
67
+
68
+ def sigmoid_fwd(x: torch.Tensor) -> torch.Tensor:
69
+ T, D = x.numel(), x.shape[-1]
70
+ y = torch.empty_like(x)
71
+ sigmoid_fwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, y, T=T, D=D)
72
+ return y
73
+
74
+
75
+ def sigmoid_bwd(x: torch.Tensor, dy: torch.Tensor) -> torch.Tensor:
76
+ T, D = x.numel(), x.shape[-1]
77
+ dx = torch.empty_like(x)
78
+ sigmoid_bwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, dy, dx, T=T, D=D)
79
+ return dx
80
+
81
+
82
+ class SigmoidFunction(torch.autograd.Function):
83
+
84
+ @staticmethod
85
+ def forward(ctx, x):
86
+ ctx.save_for_backward(x)
87
+ return sigmoid_fwd(x)
88
+
89
+ @staticmethod
90
+ def backward(ctx, dout):
91
+ x, = ctx.saved_tensors
92
+ return sigmoid_bwd(x, dout)
93
+
94
+
95
+ sigmoid = SigmoidFunction.apply
96
+
97
+
98
+ @triton.autotune(
99
+ configs=[
100
+ triton.Config({'B': bs}, num_warps=num_warps)
101
+ for bs in [512, 1024, 2048, 4096, 8192]
102
+ for num_warps in NUM_WARPS_AUTOTUNE
103
+ ],
104
+ key=['D']
105
+ )
106
+ @triton.jit(do_not_specialize=['T'])
107
+ def logsigmoid_fwd_kernel(
108
+ x,
109
+ y,
110
+ temperature,
111
+ T,
112
+ B: tl.constexpr,
113
+ D: tl.constexpr
114
+ ):
115
+ i = tl.program_id(0)
116
+ o_i = i * B + tl.arange(0, B)
117
+ m_i = o_i < T
118
+
119
+ b_x = tl.load(x + o_i, mask=m_i, other=0.).to(tl.float32)
120
+ b_m = tl.minimum(0., b_x)
121
+ b_z = 1. + exp(-tl.abs(b_x))
122
+ b_y = (b_m - log(b_z)) / temperature
123
+ tl.store(y + o_i, b_y.to(y.dtype.element_ty), mask=m_i)
124
+
125
+
126
+ @triton.autotune(
127
+ configs=[
128
+ triton.Config({'B': bs}, num_warps=num_warps)
129
+ for bs in [512, 1024, 2048, 4096, 8192]
130
+ for num_warps in NUM_WARPS_AUTOTUNE
131
+ ],
132
+ key=['D']
133
+ )
134
+ @triton.jit(do_not_specialize=['T'])
135
+ def logsigmoid_bwd_kernel(
136
+ x,
137
+ dx,
138
+ dy,
139
+ temperature,
140
+ T,
141
+ B: tl.constexpr,
142
+ D: tl.constexpr
143
+ ):
144
+ i = tl.program_id(0)
145
+ o_i = i * B + tl.arange(0, B)
146
+ m_i = o_i < T
147
+
148
+ b_x = tl.load(x + o_i, mask=m_i, other=0.).to(tl.float32)
149
+ b_dy = tl.load(dy + o_i, mask=m_i, other=0.).to(tl.float32)
150
+ b_dx = b_dy * ((1. - tl.sigmoid(b_x)) / temperature)
151
+ tl.store(dx + o_i, b_dx.to(dx.dtype.element_ty), mask=m_i)
152
+
153
+
154
+ def logsigmoid_fwd(x: torch.Tensor, temperature: float = 1.) -> torch.Tensor:
155
+ T, D = x.numel(), x.shape[-1]
156
+ y = torch.empty_like(x)
157
+ logsigmoid_fwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](
158
+ x=x,
159
+ y=y,
160
+ temperature=temperature,
161
+ T=T,
162
+ D=D,
163
+ )
164
+ return y
165
+
166
+
167
+ def logsigmoid_bwd(x: torch.Tensor, dy: torch.Tensor, temperature: float = 1.) -> torch.Tensor:
168
+ T, D = x.numel(), x.shape[-1]
169
+ dx = torch.empty_like(x)
170
+ logsigmoid_bwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](
171
+ x=x,
172
+ dx=dx,
173
+ dy=dy,
174
+ temperature=temperature,
175
+ T=T,
176
+ D=D,
177
+ )
178
+ return dx
179
+
180
+
181
+ class LogSigmoidFunction(torch.autograd.Function):
182
+
183
+ @staticmethod
184
+ @input_guard
185
+ def forward(ctx, x, temperature):
186
+ ctx.save_for_backward(x,)
187
+ ctx.temperature = temperature
188
+ return logsigmoid_fwd(x, temperature)
189
+
190
+ @staticmethod
191
+ @input_guard
192
+ def backward(ctx, dy):
193
+ x, = ctx.saved_tensors
194
+ return logsigmoid_bwd(x, dy, ctx.temperature), None
195
+
196
+
197
+ def logsigmoid(x: torch.Tensor, temperature: float = 1.) -> torch.Tensor:
198
+ return LogSigmoidFunction.apply(x, temperature)
199
+
200
+
201
+ @triton.autotune(
202
+ configs=[
203
+ triton.Config({'B': bs}, num_warps=num_warps)
204
+ for bs in [512, 1024, 2048, 4096, 8192]
205
+ for num_warps in NUM_WARPS_AUTOTUNE
206
+ ],
207
+ key=['D']
208
+ )
209
+ @triton.jit(do_not_specialize=['T'])
210
+ def swish_fwd_kernel(
211
+ x, y,
212
+ T,
213
+ B: tl.constexpr,
214
+ D: tl.constexpr
215
+ ):
216
+ pid = tl.program_id(0)
217
+ offs = pid * B + tl.arange(0, B)
218
+ mask = offs < T
219
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
220
+ s = 1.0 / (1.0 + exp(-x_val))
221
+ y_val = x_val * s
222
+ tl.store(y + offs, y_val.to(y.dtype.element_ty), mask=mask)
223
+
224
+
225
+ @triton.autotune(
226
+ configs=[
227
+ triton.Config({'B': bs}, num_warps=num_warps)
228
+ for bs in [512, 1024, 2048, 4096, 8192]
229
+ for num_warps in NUM_WARPS_AUTOTUNE
230
+ ],
231
+ key=['D']
232
+ )
233
+ @triton.jit(do_not_specialize=['T'])
234
+ def swish_bwd_kernel(
235
+ x, dy, dx,
236
+ T,
237
+ B: tl.constexpr,
238
+ D: tl.constexpr
239
+ ):
240
+ pid = tl.program_id(0)
241
+ offs = pid * B + tl.arange(0, B)
242
+ mask = offs < T
243
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
244
+ g_val = tl.load(dy + offs, mask=mask, other=0.).to(tl.float32)
245
+ s = 1.0 / (1.0 + exp(-x_val))
246
+ dx_val = g_val * s * (1.0 + x_val * (1.0 - s))
247
+ tl.store(dx + offs, dx_val.to(dx.dtype.element_ty), mask=mask)
248
+
249
+
250
+ def swish_fwd(x: torch.Tensor) -> torch.Tensor:
251
+ T, D = x.numel(), x.shape[-1]
252
+ y = torch.empty_like(x)
253
+ swish_fwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, y, T=T, D=D)
254
+ return y
255
+
256
+
257
+ def swish_bwd(x: torch.Tensor, dy: torch.Tensor) -> torch.Tensor:
258
+ T, D = x.numel(), x.shape[-1]
259
+ dx = torch.empty_like(x)
260
+ swish_bwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, dy, dx, T=T, D=D)
261
+ return dx
262
+
263
+
264
+ class SwishFunction(torch.autograd.Function):
265
+
266
+ @staticmethod
267
+ def forward(ctx, x):
268
+ ctx.save_for_backward(x)
269
+ return swish_fwd(x)
270
+
271
+ @staticmethod
272
+ def backward(ctx, dout):
273
+ x, = ctx.saved_tensors
274
+ return swish_bwd(x, dout)
275
+
276
+
277
+ swish = SwishFunction.apply
278
+
279
+ # 1/sqrt(2*pi)-> 0.3989423
280
+ # 1/sqrt(2) -> 0.70710678
281
+ # sqrt(2/pi) -> 0.79788456
282
+
283
+
284
+ # this function is tanh approximation of gelu
285
+ # actual gelu is:
286
+ # x * 0.5 * (1.0 + torch.erf(x * 0.70710678))
287
+ @torch.compile
288
+ def bias_gelu(y, bias):
289
+ x = bias + y
290
+ return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=y.dtype)
291
+
292
+
293
+ # gradient of tanh approximation of gelu
294
+ # gradient of actual gelu is:
295
+ # 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x)
296
+ @torch.compile
297
+ def bias_gelu_bwd(g, y, bias):
298
+ """Assume that y has shape (B, D=D) and bias has shape (D)"""
299
+ x = bias + y
300
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
301
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
302
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (
303
+ 1 + tanh_out
304
+ )
305
+ grad_y = ff * g
306
+ return grad_y.to(dtype=y.dtype), grad_y.sum(dim=(0), dtype=bias.dtype)
307
+
308
+
309
+ class GeLUFunction(torch.autograd.Function):
310
+
311
+ @staticmethod
312
+ # bias is an optional argument
313
+ def forward(ctx, input, bias):
314
+ ctx.save_for_backward(input, bias)
315
+ return bias_gelu(input, bias)
316
+
317
+ @staticmethod
318
+ def backward(ctx, grad_output):
319
+ input, bias = ctx.saved_tensors
320
+ tmp = bias_gelu_bwd(grad_output, input, bias)
321
+ return tmp, tmp
322
+
323
+
324
+ bias_gelu_impl = GeLUFunction.apply
325
+
326
+
327
+ # this function is tanh approximation of gelu
328
+ # actual gelu is:
329
+ # x * 0.5 * (1.0 + torch.erf(x * 0.70710678))
330
+ @torch.compile
331
+ def gelu_fwd(x):
332
+ return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=x.dtype)
333
+
334
+
335
+ # gradient of tanh approximation of gelu
336
+ # gradient of actual gelu is:
337
+ # 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x)
338
+ @torch.compile
339
+ def gelu_bwd(g, x):
340
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
341
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
342
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (
343
+ 1 + tanh_out
344
+ )
345
+ return (ff * g).to(dtype=x.dtype)
346
+
347
+
348
+ class FastGeLUFunction(torch.autograd.Function):
349
+ @staticmethod
350
+ # bias is an optional argument
351
+ def forward(ctx, input):
352
+ ctx.save_for_backward(input)
353
+ return gelu_fwd(input)
354
+
355
+ @staticmethod
356
+ def backward(ctx, grad_output):
357
+ (input,) = ctx.saved_tensors
358
+ tmp = gelu_bwd(grad_output, input)
359
+ return tmp
360
+
361
+
362
+ fast_gelu_impl = FastGeLUFunction.apply
363
+
364
+
365
+ @torch.compile
366
+ def relu_bwd(g, x):
367
+ return torch.where(x >= 0, g, 0.0).to(dtype=x.dtype)
368
+
369
+
370
+ @torch.compile
371
+ def sqrelu_fwd(x):
372
+ r = F.relu(x.float())
373
+ return (r * r).to(dtype=x.dtype)
374
+
375
+
376
+ @torch.compile
377
+ def sqrelu_bwd(g, x):
378
+ return (2.0 * g * F.relu(x.float())).to(dtype=x.dtype)
379
+
380
+
381
+ class SquaredReLUFunction(torch.autograd.Function):
382
+
383
+ @staticmethod
384
+ def forward(ctx, input):
385
+ ctx.save_for_backward(input)
386
+ return sqrelu_fwd(input)
387
+
388
+ @staticmethod
389
+ def backward(ctx, grad_output):
390
+ input, = ctx.saved_tensors
391
+ return sqrelu_bwd(grad_output, input)
392
+
393
+
394
+ sqrelu = SquaredReLUFunction.apply
395
+
396
+
397
+ @triton.autotune(
398
+ configs=[
399
+ triton.Config({'B': bs}, num_warps=num_warps)
400
+ for bs in [512, 1024, 2048, 4096, 8192]
401
+ for num_warps in NUM_WARPS_AUTOTUNE
402
+ ],
403
+ key=['D']
404
+ )
405
+ @triton.jit(do_not_specialize=['T'])
406
+ def swiglu_fwd_kernel(
407
+ x, y, z,
408
+ T,
409
+ B: tl.constexpr,
410
+ D: tl.constexpr
411
+ ):
412
+ pid = tl.program_id(0)
413
+ offs = pid * B + tl.arange(0, B)
414
+ mask = offs < T
415
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
416
+ y_val = tl.load(y + offs, mask=mask, other=0.).to(tl.float32)
417
+ s = 1.0 / (1.0 + exp(-x_val))
418
+ z_val = x_val * s * y_val
419
+ tl.store(z + offs, z_val.to(z.dtype.element_ty), mask=mask)
420
+
421
+
422
+ @triton.heuristics({
423
+ 'HAS_WEIGHT': lambda args: args['z'] is not None,
424
+ })
425
+ @triton.autotune(
426
+ configs=[
427
+ triton.Config({'B': bs}, num_warps=num_warps)
428
+ for bs in [512, 1024, 2048, 4096, 8192]
429
+ for num_warps in NUM_WARPS_AUTOTUNE
430
+ ],
431
+ key=['D']
432
+ )
433
+ @triton.jit(do_not_specialize=['T'])
434
+ def swiglu_fwdbwd_kernel(
435
+ x, y, g, dx, dy, z,
436
+ T,
437
+ B: tl.constexpr,
438
+ D: tl.constexpr,
439
+ HAS_WEIGHT: tl.constexpr
440
+ ):
441
+ pid = tl.program_id(0)
442
+ offs = pid * B + tl.arange(0, B)
443
+ mask = offs < T
444
+ x_val = tl.load(x + offs, mask=mask, other=0.).to(tl.float32)
445
+ y_val = tl.load(y + offs, mask=mask, other=0.).to(tl.float32)
446
+ g_val = tl.load(g + offs, mask=mask, other=0.).to(tl.float32)
447
+
448
+ s = 1.0 / (1.0 + exp(-x_val))
449
+ x_s = x_val * s
450
+ dx_val = g_val * s * (1.0 + x_val * (1.0 - s)) * y_val
451
+ dy_val = g_val * x_s
452
+
453
+ tl.store(dx + offs, dx_val.to(dx.dtype.element_ty), mask=mask)
454
+ tl.store(dy + offs, dy_val.to(dy.dtype.element_ty), mask=mask)
455
+ if HAS_WEIGHT:
456
+ z_val = x_s * y_val
457
+ tl.store(z + offs, z_val.to(z.dtype.element_ty), mask=mask)
458
+
459
+
460
+ def swiglu_fwd(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
461
+ T, D = x.numel(), x.shape[-1]
462
+ z = torch.empty_like(x)
463
+ swiglu_fwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, y, z, T=T, D=D)
464
+ return z
465
+
466
+
467
+ def swiglu_fwdbwd(x: torch.Tensor, y: torch.Tensor, g: torch.Tensor, use_weight: bool = False):
468
+ T, D = x.numel(), x.shape[-1]
469
+ dx = torch.empty_like(x)
470
+ dy = torch.empty_like(x)
471
+ if use_weight:
472
+ # recomputed for weight grad
473
+ z = torch.empty_like(x)
474
+ else:
475
+ z = None
476
+ swiglu_fwdbwd_kernel[lambda meta: (triton.cdiv(T, meta['B']),)](x, y, g, dx, dy, z, T=T, D=D)
477
+ if use_weight:
478
+ return dx, dy, z
479
+ return dx, dy
480
+
481
+
482
+ class SwiGLUFunction(torch.autograd.Function):
483
+ r"""
484
+ Swish-Gated Linear Unit (SwiGLU) function.
485
+
486
+ .. math::
487
+ \text{SwiGLU}(x, y) = swish(x) * y = \frac{x}{1 + \exp(-x)} * y
488
+ """
489
+
490
+ @staticmethod
491
+ def forward(ctx, x, y):
492
+ ctx.save_for_backward(x, y)
493
+ return swiglu_fwd(x, y)
494
+
495
+ @staticmethod
496
+ def backward(ctx, dout):
497
+ x, y = ctx.saved_tensors
498
+ return swiglu_fwdbwd(x, y, dout)
499
+
500
+
501
+ class SwiGLULinearFunction(torch.autograd.Function):
502
+ r"""
503
+ Swish-Gated Linear Unit (SwiGLU) function followed by a linear transformation.
504
+
505
+ .. math::
506
+ \text{SwiGLULinear}(x, y, W, b) = (swish(x) * y) W + b
507
+
508
+ This simple wrap discards the intermediate results of SwiGLU(x, y) to save memory.
509
+ """
510
+
511
+ @staticmethod
512
+ @autocast_custom_fwd
513
+ def forward(ctx, x, y, weight, bias):
514
+ z = swiglu_fwd(x, y)
515
+ out = F.linear(z, weight, bias)
516
+ # We don't store z, will be recomputed in the backward pass to save memory
517
+ ctx.save_for_backward(x, y, weight)
518
+ ctx.linear_bias_is_none = bias is None
519
+ return out
520
+
521
+ @staticmethod
522
+ @autocast_custom_bwd
523
+ def backward(ctx, dout, *args):
524
+ x, y, weight = ctx.saved_tensors
525
+ dout = dout.reshape(-1, dout.shape[-1])
526
+ dz = F.linear(dout, weight.t()).view_as(x)
527
+ dx, dy, z = swiglu_fwdbwd(x, y, dz, use_weight=True)
528
+ dlinear_weight = torch.einsum("bo,bi->oi", dout, z.reshape(-1, z.shape[-1]))
529
+ dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0)
530
+ return dx, dy, dlinear_weight, dlinear_bias
531
+
532
+
533
+ swiglu = SwiGLUFunction.apply
534
+
535
+
536
+ swiglu_linear = SwiGLULinearFunction.apply
537
+
538
+
539
+ ACT2FN = {
540
+ 'relu': F.relu,
541
+ 'sigmoid': sigmoid,
542
+ 'logsigmoid': logsigmoid,
543
+ 'silu': swish,
544
+ 'swish': swish,
545
+ 'sqrelu': sqrelu,
546
+ 'gelu': fast_gelu_impl,
547
+ 'bias_gelu': bias_gelu_impl,
548
+ }