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,1253 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from __future__ import annotations
5
+
6
+ import math
7
+ from typing import Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ import triton
13
+ import triton.language as tl
14
+
15
+ from fla.utils import get_multiprocessor_count, input_guard
16
+
17
+
18
+ @triton.heuristics({
19
+ 'STORE_RESIDUAL_OUT': lambda args: args['residual_out'] is not None,
20
+ 'HAS_RESIDUAL': lambda args: args['residual'] is not None,
21
+ 'HAS_WEIGHT': lambda args: args['w'] is not None,
22
+ 'HAS_BIAS': lambda args: args['b'] is not None,
23
+ })
24
+ @triton.autotune(
25
+ configs=[
26
+ triton.Config({'BT': BT}, num_warps=num_warps)
27
+ for BT in [16, 32, 64]
28
+ for num_warps in [4, 8, 16]
29
+ ],
30
+ key=['D', 'NB', 'IS_RMS_NORM', 'STORE_RESIDUAL_OUT', 'HAS_RESIDUAL', 'HAS_WEIGHT'],
31
+ )
32
+ @triton.jit
33
+ def layer_norm_gated_fwd_kernel(
34
+ x, # pointer to the input
35
+ g, # pointer to the gate
36
+ y, # pointer to the output
37
+ w, # pointer to the weights
38
+ b, # pointer to the biases
39
+ residual, # pointer to the residual
40
+ residual_out, # pointer to the residual
41
+ mean, # pointer to the mean
42
+ rstd, # pointer to the 1/std
43
+ eps, # epsilon to avoid division by zero
44
+ T, # number of rows in x
45
+ D: tl.constexpr, # number of columns in x
46
+ BT: tl.constexpr,
47
+ BD: tl.constexpr,
48
+ NB: tl.constexpr,
49
+ ACTIVATION: tl.constexpr,
50
+ IS_RMS_NORM: tl.constexpr,
51
+ STORE_RESIDUAL_OUT: tl.constexpr,
52
+ HAS_RESIDUAL: tl.constexpr,
53
+ HAS_WEIGHT: tl.constexpr,
54
+ HAS_BIAS: tl.constexpr
55
+ ):
56
+ i_t = tl.program_id(0)
57
+
58
+ o_d = tl.arange(0, BD)
59
+ m_d = o_d < D
60
+
61
+ p_x = tl.make_block_ptr(x, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
62
+ b_x = tl.load(p_x, boundary_check=(0, 1)).to(tl.float32)
63
+ if HAS_RESIDUAL:
64
+ p_res = tl.make_block_ptr(residual, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
65
+ b_x += tl.load(p_res, boundary_check=(0, 1)).to(tl.float32)
66
+ if STORE_RESIDUAL_OUT:
67
+ p_res_out = tl.make_block_ptr(residual_out, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
68
+ tl.store(p_res_out, b_x.to(p_res_out.dtype.element_ty), boundary_check=(0, 1))
69
+ if not IS_RMS_NORM:
70
+ b_mean = tl.sum(b_x, axis=1) / D
71
+ p_mean = tl.make_block_ptr(mean, (T,), (1,), (i_t * BT,), (BT,), (0,))
72
+ tl.store(p_mean, b_mean.to(p_mean.dtype.element_ty), boundary_check=(0,))
73
+ b_xbar = tl.where(m_d[None, :], b_x - b_mean[:, None], 0.0)
74
+ b_var = tl.sum(b_xbar * b_xbar, axis=1) / D
75
+ else:
76
+ b_xbar = tl.where(m_d[None, :], b_x, 0.0)
77
+ b_var = tl.sum(b_xbar * b_xbar, axis=1) / D
78
+ b_rstd = 1 / tl.sqrt(b_var + eps)
79
+
80
+ p_rstd = tl.make_block_ptr(rstd, (T,), (1,), (i_t * BT,), (BT,), (0,))
81
+ tl.store(p_rstd, b_rstd.to(p_rstd.dtype.element_ty), boundary_check=(0,))
82
+
83
+ if HAS_WEIGHT:
84
+ b_w = tl.load(w + o_d, mask=m_d).to(tl.float32)
85
+ if HAS_BIAS:
86
+ b_b = tl.load(b + o_d, mask=m_d).to(tl.float32)
87
+ b_x_hat = (b_x - b_mean[:, None]) * b_rstd[:, None] if not IS_RMS_NORM else b_x * b_rstd[:, None]
88
+ b_y = b_x_hat * b_w[None, :] if HAS_WEIGHT else b_x_hat
89
+ if HAS_BIAS:
90
+ b_y = b_y + b_b[None, :]
91
+
92
+ # swish/sigmoid output gate
93
+ p_g = tl.make_block_ptr(g, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
94
+ b_g = tl.load(p_g, boundary_check=(0, 1)).to(tl.float32)
95
+ if ACTIVATION == 'swish':
96
+ b_y = b_y * b_g * tl.sigmoid(b_g)
97
+ elif ACTIVATION == 'silu':
98
+ b_y = b_y * b_g * tl.sigmoid(b_g)
99
+ elif ACTIVATION == 'sigmoid':
100
+ b_y = b_y * tl.sigmoid(b_g)
101
+
102
+ # Write output
103
+ p_y = tl.make_block_ptr(y, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
104
+ tl.store(p_y, b_y.to(p_y.dtype.element_ty), boundary_check=(0, 1))
105
+
106
+
107
+ @triton.heuristics({
108
+ 'STORE_RESIDUAL_OUT': lambda args: args['residual_out'] is not None,
109
+ 'HAS_RESIDUAL': lambda args: args['residual'] is not None,
110
+ 'HAS_WEIGHT': lambda args: args['w'] is not None,
111
+ 'HAS_BIAS': lambda args: args['b'] is not None,
112
+ })
113
+ @triton.autotune(
114
+ configs=[
115
+ triton.Config({}, num_warps=num_warps)
116
+ for num_warps in [2, 4, 8, 16]
117
+ ],
118
+ key=['D', 'IS_RMS_NORM', 'STORE_RESIDUAL_OUT', 'HAS_RESIDUAL', 'HAS_WEIGHT'],
119
+ )
120
+ @triton.jit
121
+ def layer_norm_gated_fwd_kernel1(
122
+ x, # pointer to the input
123
+ g, # pointer to the gate
124
+ y, # pointer to the output
125
+ w, # pointer to the weights
126
+ b, # pointer to the biases
127
+ residual, # pointer to the residual
128
+ residual_out, # pointer to the residual
129
+ mean, # pointer to the mean
130
+ rstd, # pointer to the 1/std
131
+ eps, # epsilon to avoid division by zero
132
+ D: tl.constexpr, # number of columns in x
133
+ BD: tl.constexpr,
134
+ ACTIVATION: tl.constexpr,
135
+ IS_RMS_NORM: tl.constexpr,
136
+ STORE_RESIDUAL_OUT: tl.constexpr,
137
+ HAS_RESIDUAL: tl.constexpr,
138
+ HAS_WEIGHT: tl.constexpr,
139
+ HAS_BIAS: tl.constexpr
140
+ ):
141
+ i_t = tl.program_id(0)
142
+ x += i_t * D
143
+ y += i_t * D
144
+ g += i_t * D
145
+ if HAS_RESIDUAL:
146
+ residual += i_t * D
147
+ if STORE_RESIDUAL_OUT:
148
+ residual_out += i_t * D
149
+
150
+ o_d = tl.arange(0, BD)
151
+ m_d = o_d < D
152
+ b_x = tl.load(x + o_d, mask=m_d, other=0.0).to(tl.float32)
153
+ if HAS_RESIDUAL:
154
+ b_x += tl.load(residual + o_d, mask=m_d, other=0.0).to(tl.float32)
155
+ if STORE_RESIDUAL_OUT:
156
+ tl.store(residual_out + o_d, b_x, mask=m_d)
157
+ if not IS_RMS_NORM:
158
+ b_mean = tl.sum(b_x, axis=0) / D
159
+ tl.store(mean + i_t, b_mean)
160
+ b_xbar = tl.where(m_d, b_x - b_mean, 0.0)
161
+ b_var = tl.sum(b_xbar * b_xbar, axis=0) / D
162
+ else:
163
+ b_xbar = tl.where(m_d, b_x, 0.0)
164
+ b_var = tl.sum(b_xbar * b_xbar, axis=0) / D
165
+ b_rstd = 1 / tl.sqrt(b_var + eps)
166
+ tl.store(rstd + i_t, b_rstd)
167
+
168
+ if HAS_WEIGHT:
169
+ b_w = tl.load(w + o_d, mask=m_d).to(tl.float32)
170
+ if HAS_BIAS:
171
+ b_b = tl.load(b + o_d, mask=m_d).to(tl.float32)
172
+ b_x_hat = (b_x - b_mean) * b_rstd if not IS_RMS_NORM else b_x * b_rstd
173
+ b_y = b_x_hat * b_w if HAS_WEIGHT else b_x_hat
174
+ if HAS_BIAS:
175
+ b_y = b_y + b_b
176
+
177
+ # swish/sigmoid output gate
178
+ b_g = tl.load(g + o_d, mask=m_d, other=0.0).to(tl.float32)
179
+ if ACTIVATION == 'swish':
180
+ b_y = b_y * b_g * tl.sigmoid(b_g)
181
+ elif ACTIVATION == 'silu':
182
+ b_y = b_y * b_g * tl.sigmoid(b_g)
183
+ elif ACTIVATION == 'sigmoid':
184
+ b_y = b_y * tl.sigmoid(b_g)
185
+
186
+ # Write output
187
+ tl.store(y + o_d, b_y, mask=m_d)
188
+
189
+
190
+ @triton.heuristics({
191
+ 'HAS_DRESIDUAL': lambda args: args['dresidual'] is not None,
192
+ 'HAS_WEIGHT': lambda args: args['w'] is not None,
193
+ 'HAS_BIAS': lambda args: args['b'] is not None,
194
+ 'RECOMPUTE_OUTPUT': lambda args: args['y'] is not None
195
+ })
196
+ @triton.autotune(
197
+ configs=[
198
+ triton.Config({'BT': BT}, num_warps=num_warps)
199
+ for BT in [16, 32, 64]
200
+ for num_warps in [4, 8, 16]
201
+ ],
202
+ key=['D', 'NB', 'IS_RMS_NORM', 'HAS_DRESIDUAL', 'HAS_WEIGHT'],
203
+ )
204
+ @triton.jit
205
+ def layer_norm_gated_bwd_kernel(
206
+ x, # pointer to the input
207
+ g, # pointer to the gate
208
+ w, # pointer to the weights
209
+ b, # pointer to the biases
210
+ y, # pointer to the output to be recomputed
211
+ dy, # pointer to the output gradient
212
+ dx, # pointer to the input gradient
213
+ dg, # pointer to the gate gradient
214
+ dw, # pointer to the partial sum of weights gradient
215
+ db, # pointer to the partial sum of biases gradient
216
+ dresidual,
217
+ dresidual_in,
218
+ mean,
219
+ rstd,
220
+ T,
221
+ BS,
222
+ D: tl.constexpr,
223
+ BT: tl.constexpr,
224
+ BD: tl.constexpr,
225
+ NB: tl.constexpr,
226
+ ACTIVATION: tl.constexpr,
227
+ IS_RMS_NORM: tl.constexpr,
228
+ STORE_DRESIDUAL: tl.constexpr,
229
+ HAS_DRESIDUAL: tl.constexpr,
230
+ HAS_WEIGHT: tl.constexpr,
231
+ HAS_BIAS: tl.constexpr,
232
+ RECOMPUTE_OUTPUT: tl.constexpr,
233
+ ):
234
+ i_s = tl.program_id(0)
235
+ o_d = tl.arange(0, BD)
236
+ m_d = o_d < D
237
+ if HAS_WEIGHT:
238
+ b_w = tl.load(w + o_d, mask=m_d).to(tl.float32)
239
+ b_dw = tl.zeros((BT, BD), dtype=tl.float32)
240
+ if HAS_BIAS:
241
+ b_b = tl.load(b + o_d, mask=m_d, other=0.0).to(tl.float32)
242
+ b_db = tl.zeros((BT, BD), dtype=tl.float32)
243
+
244
+ T = min(i_s * BS + BS, T)
245
+ for i_t in range(i_s * BS, T, BT):
246
+ p_x = tl.make_block_ptr(x, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
247
+ p_g = tl.make_block_ptr(g, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
248
+ p_dy = tl.make_block_ptr(dy, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
249
+ p_dx = tl.make_block_ptr(dx, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
250
+ p_dg = tl.make_block_ptr(dg, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
251
+ # [BT, BD]
252
+ b_x = tl.load(p_x, boundary_check=(0, 1)).to(tl.float32)
253
+ b_g = tl.load(p_g, boundary_check=(0, 1)).to(tl.float32)
254
+ b_dy = tl.load(p_dy, boundary_check=(0, 1)).to(tl.float32)
255
+
256
+ if not IS_RMS_NORM:
257
+ p_mean = tl.make_block_ptr(mean, (T,), (1,), (i_t,), (BT,), (0,))
258
+ b_mean = tl.load(p_mean, boundary_check=(0,))
259
+ p_rstd = tl.make_block_ptr(rstd, (T,), (1,), (i_t,), (BT,), (0,))
260
+ b_rstd = tl.load(p_rstd, boundary_check=(0,))
261
+ # Compute dx
262
+ b_xhat = (b_x - b_mean[:, None]) * b_rstd[:, None] if not IS_RMS_NORM else b_x * b_rstd[:, None]
263
+ b_xhat = tl.where(m_d[None, :], b_xhat, 0.0)
264
+
265
+ b_y = b_xhat * b_w[None, :] if HAS_WEIGHT else b_xhat
266
+ if HAS_BIAS:
267
+ b_y = b_y + b_b[None, :]
268
+ if RECOMPUTE_OUTPUT:
269
+ p_y = tl.make_block_ptr(y, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
270
+ tl.store(p_y, b_y.to(p_y.dtype.element_ty), boundary_check=(0, 1))
271
+
272
+ b_sigmoid_g = tl.sigmoid(b_g)
273
+ if ACTIVATION == 'swish':
274
+ b_dg = b_dy * b_y * (b_sigmoid_g + b_g * b_sigmoid_g * (1 - b_sigmoid_g))
275
+ b_dy = b_dy * b_g * b_sigmoid_g
276
+ elif ACTIVATION == 'silu':
277
+ b_dg = b_dy * b_y * (b_sigmoid_g + b_g * b_sigmoid_g * (1 - b_sigmoid_g))
278
+ b_dy = b_dy * b_g * b_sigmoid_g
279
+ elif ACTIVATION == 'sigmoid':
280
+ b_dg = b_dy * b_y * b_sigmoid_g * (1 - b_sigmoid_g)
281
+ b_dy = b_dy * b_sigmoid_g
282
+ b_wdy = b_dy
283
+
284
+ if HAS_WEIGHT or HAS_BIAS:
285
+ m_t = (i_t + tl.arange(0, BT)) < T
286
+ if HAS_WEIGHT:
287
+ b_wdy = b_dy * b_w
288
+ b_dw += tl.where(m_t[:, None], b_dy * b_xhat, 0.0)
289
+ if HAS_BIAS:
290
+ b_db += tl.where(m_t[:, None], b_dy, 0.0)
291
+ if not IS_RMS_NORM:
292
+ b_c1 = tl.sum(b_xhat * b_wdy, axis=1) / D
293
+ b_c2 = tl.sum(b_wdy, axis=1) / D
294
+ b_dx = (b_wdy - (b_xhat * b_c1[:, None] + b_c2[:, None])) * b_rstd[:, None]
295
+ else:
296
+ b_c1 = tl.sum(b_xhat * b_wdy, axis=1) / D
297
+ b_dx = (b_wdy - b_xhat * b_c1[:, None]) * b_rstd[:, None]
298
+ if HAS_DRESIDUAL:
299
+ p_dres = tl.make_block_ptr(dresidual, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
300
+ b_dres = tl.load(p_dres, boundary_check=(0, 1)).to(tl.float32)
301
+ b_dx += b_dres
302
+ # Write dx
303
+ if STORE_DRESIDUAL:
304
+ p_dres_in = tl.make_block_ptr(dresidual_in, (T, D), (D, 1), (i_t, 0), (BT, BD), (1, 0))
305
+ tl.store(p_dres_in, b_dx.to(p_dres_in.dtype.element_ty), boundary_check=(0, 1))
306
+
307
+ tl.store(p_dx, b_dx.to(p_dx.dtype.element_ty), boundary_check=(0, 1))
308
+ tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0, 1))
309
+
310
+ if HAS_WEIGHT:
311
+ tl.store(dw + i_s * D + o_d, tl.sum(b_dw, axis=0), mask=m_d)
312
+ if HAS_BIAS:
313
+ tl.store(db + i_s * D + o_d, tl.sum(b_db, axis=0), mask=m_d)
314
+
315
+
316
+ @triton.heuristics({
317
+ 'HAS_DRESIDUAL': lambda args: args['dresidual'] is not None,
318
+ 'HAS_WEIGHT': lambda args: args['w'] is not None,
319
+ 'HAS_BIAS': lambda args: args['b'] is not None,
320
+ 'RECOMPUTE_OUTPUT': lambda args: args['y'] is not None
321
+ })
322
+ @triton.autotune(
323
+ configs=[
324
+ triton.Config({}, num_warps=num_warps)
325
+ for num_warps in [2, 4, 8, 16]
326
+ ],
327
+ key=['D', 'IS_RMS_NORM', 'STORE_DRESIDUAL', 'HAS_DRESIDUAL', 'HAS_WEIGHT'],
328
+ )
329
+ @triton.jit
330
+ def layer_norm_gated_bwd_kernel1(
331
+ x, # pointer to the input
332
+ g, # pointer to the gate
333
+ w, # pointer to the weights
334
+ b, # pointer to the biases
335
+ y, # pointer to the output to be recomputed
336
+ dy, # pointer to the output gradient
337
+ dx, # pointer to the input gradient
338
+ dg, # pointer to the gate gradient
339
+ dw, # pointer to the partial sum of weights gradient
340
+ db, # pointer to the partial sum of biases gradient
341
+ dresidual,
342
+ dresidual_in,
343
+ mean,
344
+ rstd,
345
+ T,
346
+ BS,
347
+ D: tl.constexpr,
348
+ BD: tl.constexpr,
349
+ ACTIVATION: tl.constexpr,
350
+ IS_RMS_NORM: tl.constexpr,
351
+ STORE_DRESIDUAL: tl.constexpr,
352
+ HAS_DRESIDUAL: tl.constexpr,
353
+ HAS_WEIGHT: tl.constexpr,
354
+ HAS_BIAS: tl.constexpr,
355
+ RECOMPUTE_OUTPUT: tl.constexpr,
356
+ ):
357
+ i_s = tl.program_id(0)
358
+ o_d = tl.arange(0, BD)
359
+ mask = o_d < D
360
+ x += i_s * BS * D
361
+ g += i_s * BS * D
362
+ if HAS_DRESIDUAL:
363
+ dresidual += i_s * BS * D
364
+ if STORE_DRESIDUAL:
365
+ dresidual_in += i_s * BS * D
366
+ dy += i_s * BS * D
367
+ dx += i_s * BS * D
368
+ dg += i_s * BS * D
369
+ if RECOMPUTE_OUTPUT:
370
+ y += i_s * BS * D
371
+ if HAS_WEIGHT:
372
+ b_w = tl.load(w + o_d, mask=mask).to(tl.float32)
373
+ b_dw = tl.zeros((BD,), dtype=tl.float32)
374
+ if HAS_BIAS:
375
+ b_b = tl.load(b + o_d, mask=mask, other=0.0).to(tl.float32)
376
+ b_db = tl.zeros((BD,), dtype=tl.float32)
377
+
378
+ for i_t in range(i_s * BS, min(i_s * BS + BS, T)):
379
+ # Load data to SRAM
380
+ b_x = tl.load(x + o_d, mask=mask, other=0).to(tl.float32)
381
+ b_g = tl.load(g + o_d, mask=mask, other=0).to(tl.float32)
382
+ b_dy = tl.load(dy + o_d, mask=mask, other=0).to(tl.float32)
383
+
384
+ if not IS_RMS_NORM:
385
+ b_mean = tl.load(mean + i_t)
386
+ b_rstd = tl.load(rstd + i_t)
387
+ # Compute dx
388
+ b_xhat = (b_x - b_mean) * b_rstd if not IS_RMS_NORM else b_x * b_rstd
389
+ b_xhat = tl.where(mask, b_xhat, 0.0)
390
+
391
+ b_y = b_xhat * b_w if HAS_WEIGHT else b_xhat
392
+ if HAS_BIAS:
393
+ b_y = b_y + b_b
394
+ if RECOMPUTE_OUTPUT:
395
+ tl.store(y + o_d, b_y, mask=mask)
396
+
397
+ b_sigmoid_g = tl.sigmoid(b_g)
398
+ if ACTIVATION == 'swish':
399
+ b_dg = b_dy * b_y * (b_sigmoid_g + b_g * b_sigmoid_g * (1 - b_sigmoid_g))
400
+ b_dy = b_dy * b_g * b_sigmoid_g
401
+ elif ACTIVATION == 'silu':
402
+ b_dg = b_dy * b_y * (b_sigmoid_g + b_g * b_sigmoid_g * (1 - b_sigmoid_g))
403
+ b_dy = b_dy * b_g * b_sigmoid_g
404
+ elif ACTIVATION == 'sigmoid':
405
+ b_dg = b_dy * b_y * b_sigmoid_g * (1 - b_sigmoid_g)
406
+ b_dy = b_dy * b_sigmoid_g
407
+ b_wdy = b_dy
408
+ if HAS_WEIGHT:
409
+ b_wdy = b_dy * b_w
410
+ b_dw += b_dy * b_xhat
411
+ if HAS_BIAS:
412
+ b_db += b_dy
413
+ if not IS_RMS_NORM:
414
+ b_c1 = tl.sum(b_xhat * b_wdy, axis=0) / D
415
+ b_c2 = tl.sum(b_wdy, axis=0) / D
416
+ b_dx = (b_wdy - (b_xhat * b_c1 + b_c2)) * b_rstd
417
+ else:
418
+ b_c1 = tl.sum(b_xhat * b_wdy, axis=0) / D
419
+ b_dx = (b_wdy - b_xhat * b_c1) * b_rstd
420
+ if HAS_DRESIDUAL:
421
+ b_dres = tl.load(dresidual + o_d, mask=mask, other=0).to(tl.float32)
422
+ b_dx += b_dres
423
+ # Write dx
424
+ if STORE_DRESIDUAL:
425
+ tl.store(dresidual_in + o_d, b_dx, mask=mask)
426
+ tl.store(dx + o_d, b_dx, mask=mask)
427
+ tl.store(dg + o_d, b_dg, mask=mask)
428
+
429
+ x += D
430
+ g += D
431
+ if HAS_DRESIDUAL:
432
+ dresidual += D
433
+ if STORE_DRESIDUAL:
434
+ dresidual_in += D
435
+ if RECOMPUTE_OUTPUT:
436
+ y += D
437
+ dy += D
438
+ dx += D
439
+ dg += D
440
+ if HAS_WEIGHT:
441
+ tl.store(dw + i_s * D + o_d, b_dw, mask=mask)
442
+ if HAS_BIAS:
443
+ tl.store(db + i_s * D + o_d, b_db, mask=mask)
444
+
445
+
446
+ def layer_norm_gated_fwd(
447
+ x: torch.Tensor,
448
+ g: torch.Tensor,
449
+ weight: torch.Tensor,
450
+ bias: torch.Tensor,
451
+ activation: str = 'swish',
452
+ eps: float = 1e-5,
453
+ residual: torch.Tensor = None,
454
+ out_dtype: torch.dtype = None,
455
+ residual_dtype: torch.dtype = None,
456
+ is_rms_norm: bool = False
457
+ ):
458
+ if residual is not None:
459
+ residual_dtype = residual.dtype
460
+ T, D = x.shape
461
+ if residual is not None:
462
+ assert residual.shape == (T, D)
463
+ if weight is not None:
464
+ assert weight.shape == (D,)
465
+ if bias is not None:
466
+ assert bias.shape == (D,)
467
+ # allocate output
468
+ y = torch.empty_like(x, dtype=x.dtype if out_dtype is None else out_dtype)
469
+ if residual is not None or (residual_dtype is not None and residual_dtype != x.dtype):
470
+ residual_out = torch.empty(T, D, device=x.device, dtype=residual_dtype)
471
+ else:
472
+ residual_out = None
473
+ mean = torch.empty((T,), dtype=torch.float, device=x.device) if not is_rms_norm else None
474
+ rstd = torch.empty((T,), dtype=torch.float, device=x.device)
475
+ # Less than 64KB per feature: enqueue fused kernel
476
+ MAX_FUSED_SIZE = 65536 // x.element_size()
477
+ BD = min(MAX_FUSED_SIZE, triton.next_power_of_2(D))
478
+ if D > BD:
479
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
480
+ # heuristics for number of warps
481
+
482
+ if D <= 512:
483
+ NB = triton.cdiv(T, 2048)
484
+ def grid(meta): return (triton.cdiv(T, meta['BT']),)
485
+ layer_norm_gated_fwd_kernel[grid](
486
+ x=x,
487
+ g=g,
488
+ y=y,
489
+ w=weight,
490
+ b=bias,
491
+ residual=residual,
492
+ residual_out=residual_out,
493
+ mean=mean,
494
+ rstd=rstd,
495
+ eps=eps,
496
+ T=T,
497
+ D=D,
498
+ BD=BD,
499
+ NB=NB,
500
+ ACTIVATION=activation,
501
+ IS_RMS_NORM=is_rms_norm,
502
+ )
503
+ else:
504
+ layer_norm_gated_fwd_kernel1[(T,)](
505
+ x=x,
506
+ g=g,
507
+ y=y,
508
+ w=weight,
509
+ b=bias,
510
+ residual=residual,
511
+ residual_out=residual_out,
512
+ mean=mean,
513
+ rstd=rstd,
514
+ eps=eps,
515
+ D=D,
516
+ BD=BD,
517
+ ACTIVATION=activation,
518
+ IS_RMS_NORM=is_rms_norm,
519
+ )
520
+ # residual_out is None if residual is None and residual_dtype == input_dtype
521
+ return y, mean, rstd, residual_out if residual_out is not None else x
522
+
523
+
524
+ def layer_norm_gated_bwd(
525
+ dy: torch.Tensor,
526
+ x: torch.Tensor,
527
+ g: torch.Tensor,
528
+ weight: torch.Tensor,
529
+ bias: torch.Tensor,
530
+ activation: str = 'swish',
531
+ eps: float = 1e-5,
532
+ mean: torch.Tensor = None,
533
+ rstd: torch.Tensor = None,
534
+ dresidual: torch.Tensor = None,
535
+ has_residual: bool = False,
536
+ is_rms_norm: bool = False,
537
+ x_dtype: torch.dtype = None,
538
+ recompute_output: bool = False,
539
+ ):
540
+ T, D = x.shape
541
+ assert dy.shape == (T, D)
542
+ if dresidual is not None:
543
+ assert dresidual.shape == (T, D)
544
+ if weight is not None:
545
+ assert weight.shape == (D,)
546
+ if bias is not None:
547
+ assert bias.shape == (D,)
548
+ # allocate output
549
+ dx = torch.empty_like(x) if x_dtype is None else torch.empty(T, D, dtype=x_dtype, device=x.device)
550
+ dg = torch.empty_like(g) if x_dtype is None else torch.empty(T, D, dtype=x_dtype, device=x.device)
551
+ dresidual_in = torch.empty_like(x) if has_residual and dx.dtype != x.dtype else None
552
+ y = torch.empty(T, D, dtype=dy.dtype, device=dy.device) if recompute_output else None
553
+
554
+ # Less than 64KB per feature: enqueue fused kernel
555
+ MAX_FUSED_SIZE = 65536 // x.element_size()
556
+ BD = min(MAX_FUSED_SIZE, triton.next_power_of_2(D))
557
+ if D > BD:
558
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
559
+ NS = get_multiprocessor_count(x.device.index)
560
+ BS = math.ceil(T / NS)
561
+
562
+ dw = torch.empty((NS, D), dtype=torch.float, device=weight.device) if weight is not None else None
563
+ db = torch.empty((NS, D), dtype=torch.float, device=bias.device) if bias is not None else None
564
+ grid = (NS,)
565
+
566
+ if D <= 512:
567
+ NB = triton.cdiv(T, 2048)
568
+ layer_norm_gated_bwd_kernel[grid](
569
+ x=x,
570
+ g=g,
571
+ w=weight,
572
+ b=bias,
573
+ y=y,
574
+ dy=dy,
575
+ dx=dx,
576
+ dg=dg,
577
+ dw=dw,
578
+ db=db,
579
+ dresidual=dresidual,
580
+ dresidual_in=dresidual_in,
581
+ mean=mean,
582
+ rstd=rstd,
583
+ T=T,
584
+ D=D,
585
+ BS=BS,
586
+ BD=BD,
587
+ NB=NB,
588
+ ACTIVATION=activation,
589
+ IS_RMS_NORM=is_rms_norm,
590
+ STORE_DRESIDUAL=dresidual_in is not None,
591
+ )
592
+ else:
593
+ layer_norm_gated_bwd_kernel1[grid](
594
+ x=x,
595
+ g=g,
596
+ w=weight,
597
+ b=bias,
598
+ y=y,
599
+ dy=dy,
600
+ dx=dx,
601
+ dg=dg,
602
+ dw=dw,
603
+ db=db,
604
+ dresidual=dresidual,
605
+ dresidual_in=dresidual_in,
606
+ mean=mean,
607
+ rstd=rstd,
608
+ T=T,
609
+ D=D,
610
+ BS=BS,
611
+ BD=BD,
612
+ ACTIVATION=activation,
613
+ IS_RMS_NORM=is_rms_norm,
614
+ STORE_DRESIDUAL=dresidual_in is not None,
615
+ )
616
+ dw = dw.sum(0).to(weight.dtype) if weight is not None else None
617
+ db = db.sum(0).to(bias.dtype) if bias is not None else None
618
+ # Don't need to compute dresidual_in separately in this case
619
+ if has_residual and dx.dtype == x.dtype:
620
+ dresidual_in = dx
621
+ return (dx, dg, dw, db, dresidual_in) if not recompute_output else (dx, dg, dw, db, dresidual_in, y)
622
+
623
+
624
+ class LayerNormGatedFunction(torch.autograd.Function):
625
+
626
+ @staticmethod
627
+ @input_guard
628
+ def forward(
629
+ ctx,
630
+ x: torch.Tensor,
631
+ g: torch.Tensor,
632
+ weight: torch.Tensor,
633
+ bias: torch.Tensor,
634
+ activation: str,
635
+ residual: Optional[torch.Tensor] = None,
636
+ eps: float = 1e-6,
637
+ prenorm: bool = False,
638
+ residual_in_fp32: bool = False,
639
+ is_rms_norm: bool = False,
640
+ ):
641
+ x_shape_og = x.shape
642
+ g_shape_og = g.shape
643
+ # reshape input data into 2D tensor
644
+ x = x.reshape(-1, x.shape[-1])
645
+ g = g.reshape(-1, g.shape[-1])
646
+ if residual is not None:
647
+ assert residual.shape == x_shape_og
648
+ residual = residual.reshape(-1, residual.shape[-1])
649
+ residual_dtype = (
650
+ residual.dtype
651
+ if residual is not None
652
+ else (torch.float if residual_in_fp32 else None)
653
+ )
654
+ y, mean, rstd, residual_out = layer_norm_gated_fwd(
655
+ x=x,
656
+ g=g,
657
+ weight=weight,
658
+ bias=bias,
659
+ activation=activation,
660
+ eps=eps,
661
+ residual=residual,
662
+ residual_dtype=residual_dtype,
663
+ is_rms_norm=is_rms_norm
664
+ )
665
+ ctx.save_for_backward(residual_out, g, weight, bias, mean, rstd)
666
+ ctx.x_shape_og = x_shape_og
667
+ ctx.g_shape_og = g_shape_og
668
+ ctx.activation = activation
669
+ ctx.eps = eps
670
+ ctx.is_rms_norm = is_rms_norm
671
+ ctx.has_residual = residual is not None
672
+ ctx.prenorm = prenorm
673
+ ctx.x_dtype = x.dtype
674
+ y = y.reshape(x_shape_og)
675
+ return y if not prenorm else (y, residual_out.reshape(x_shape_og))
676
+
677
+ @staticmethod
678
+ @input_guard
679
+ def backward(ctx, dy, *args):
680
+ x, g, weight, bias, mean, rstd = ctx.saved_tensors
681
+ dy = dy.reshape(-1, dy.shape[-1])
682
+ assert dy.shape == x.shape
683
+ if ctx.prenorm:
684
+ dresidual = args[0]
685
+ dresidual = dresidual.reshape(-1, dresidual.shape[-1])
686
+ assert dresidual.shape == x.shape
687
+ else:
688
+ dresidual = None
689
+ dx, dg, dw, db, dres_in = layer_norm_gated_bwd(
690
+ dy=dy,
691
+ x=x,
692
+ g=g,
693
+ weight=weight,
694
+ bias=bias,
695
+ activation=ctx.activation,
696
+ eps=ctx.eps,
697
+ mean=mean,
698
+ rstd=rstd,
699
+ dresidual=dresidual,
700
+ has_residual=ctx.has_residual,
701
+ is_rms_norm=ctx.is_rms_norm,
702
+ x_dtype=ctx.x_dtype,
703
+ )
704
+ return (
705
+ dx.reshape(ctx.x_shape_og),
706
+ dg.reshape(ctx.g_shape_og),
707
+ dw,
708
+ db,
709
+ None,
710
+ dres_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
711
+ None,
712
+ None,
713
+ None,
714
+ None,
715
+ )
716
+
717
+
718
+ class LayerNormGatedLinearFunction(torch.autograd.Function):
719
+
720
+ @staticmethod
721
+ @input_guard
722
+ def forward(
723
+ ctx,
724
+ x: torch.Tensor,
725
+ g: torch.Tensor,
726
+ norm_weight: torch.Tensor,
727
+ norm_bias: torch.Tensor,
728
+ linear_weight: torch.Tensor,
729
+ linear_bias: torch.Tensor,
730
+ residual: Optional[torch.Tensor] = None,
731
+ eps: float = 1e-6,
732
+ prenorm: bool = False,
733
+ residual_in_fp32: bool = False,
734
+ is_rms_norm: bool = False,
735
+ ):
736
+ x_shape_og = x.shape
737
+ g_shape_og = g.shape
738
+ # reshape input data into 2D tensor
739
+ x = x.reshape(-1, x.shape[-1])
740
+ g = g.reshape(-1, g.shape[-1])
741
+ if residual is not None:
742
+ assert residual.shape == x_shape_og
743
+ residual = residual.reshape(-1, residual.shape[-1])
744
+ residual_dtype = (
745
+ residual.dtype
746
+ if residual is not None
747
+ else (torch.float if residual_in_fp32 else None)
748
+ )
749
+ y, mean, rstd, residual_out = layer_norm_gated_fwd(
750
+ x=x,
751
+ g=g,
752
+ weight=norm_weight,
753
+ bias=norm_bias,
754
+ eps=eps,
755
+ residual=residual,
756
+ residual_dtype=residual_dtype,
757
+ is_rms_norm=is_rms_norm
758
+ )
759
+ y = y.reshape(x_shape_og)
760
+ dtype = torch.get_autocast_gpu_dtype() if torch.is_autocast_enabled() else y.dtype
761
+ linear_weight = linear_weight.to(dtype)
762
+ linear_bias = linear_bias.to(dtype) if linear_bias is not None else None
763
+ out = F.linear(y.to(linear_weight.dtype), linear_weight, linear_bias)
764
+ # We don't store y, will be recomputed in the backward pass to save memory
765
+ ctx.save_for_backward(residual_out, g, norm_weight, norm_bias, linear_weight, mean, rstd)
766
+ ctx.x_shape_og = x_shape_og
767
+ ctx.g_shape_og = g_shape_og
768
+ ctx.eps = eps
769
+ ctx.is_rms_norm = is_rms_norm
770
+ ctx.has_residual = residual is not None
771
+ ctx.prenorm = prenorm
772
+ ctx.x_dtype = x.dtype
773
+ ctx.linear_bias_is_none = linear_bias is None
774
+ return out if not prenorm else (out, residual_out.reshape(x_shape_og))
775
+
776
+ @staticmethod
777
+ @input_guard
778
+ def backward(ctx, dout, *args):
779
+ x, g, norm_weight, norm_bias, linear_weight, mean, rstd = ctx.saved_tensors
780
+ dout = dout.reshape(-1, dout.shape[-1])
781
+ dy = F.linear(dout, linear_weight.t())
782
+ dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0)
783
+ assert dy.shape == x.shape
784
+ if ctx.prenorm:
785
+ dresidual = args[0]
786
+ dresidual = dresidual.reshape(-1, dresidual.shape[-1])
787
+ assert dresidual.shape == x.shape
788
+ else:
789
+ dresidual = None
790
+ dx, dg, dnorm_weight, dnorm_bias, dres_in, y = layer_norm_gated_bwd(
791
+ dy=dy,
792
+ x=x,
793
+ g=g,
794
+ weight=norm_weight,
795
+ bias=norm_bias,
796
+ eps=ctx.eps,
797
+ mean=mean,
798
+ rstd=rstd,
799
+ dresidual=dresidual,
800
+ has_residual=ctx.has_residual,
801
+ is_rms_norm=ctx.is_rms_norm,
802
+ x_dtype=ctx.x_dtype,
803
+ recompute_output=True,
804
+ )
805
+ dlinear_weight = torch.einsum("bo,bi->oi", dout, y)
806
+ return (
807
+ dx.reshape(ctx.x_shape_og),
808
+ dg.reshape(ctx.g_shape_og),
809
+ dnorm_weight,
810
+ dnorm_bias,
811
+ dlinear_weight,
812
+ dlinear_bias,
813
+ dres_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
814
+ None,
815
+ None,
816
+ None,
817
+ None,
818
+ )
819
+
820
+
821
+ def layer_norm_gated(
822
+ x: torch.Tensor,
823
+ g: torch.Tensor,
824
+ weight: torch.Tensor,
825
+ bias: torch.Tensor,
826
+ activation: str = 'swish',
827
+ residual: Optional[torch.Tensor] = None,
828
+ prenorm: bool = False,
829
+ residual_in_fp32: bool = False,
830
+ eps: float = 1e-6
831
+ ):
832
+ return LayerNormGatedFunction.apply(
833
+ x,
834
+ g,
835
+ weight,
836
+ bias,
837
+ activation,
838
+ residual,
839
+ eps,
840
+ prenorm,
841
+ residual_in_fp32,
842
+ False
843
+ )
844
+
845
+
846
+ def rms_norm_gated(
847
+ x: torch.Tensor,
848
+ g: torch.Tensor,
849
+ weight: torch.Tensor,
850
+ bias: torch.Tensor,
851
+ activation: str = 'swish',
852
+ residual: Optional[torch.Tensor] = None,
853
+ prenorm: bool = False,
854
+ residual_in_fp32: bool = False,
855
+ eps: float = 1e-6
856
+ ):
857
+ return LayerNormGatedFunction.apply(
858
+ x,
859
+ g,
860
+ weight,
861
+ bias,
862
+ activation,
863
+ residual,
864
+ eps,
865
+ prenorm,
866
+ residual_in_fp32,
867
+ True
868
+ )
869
+
870
+
871
+ def layer_norm_swish_gate_linear(
872
+ x: torch.Tensor,
873
+ g: torch.Tensor,
874
+ norm_weight: torch.Tensor,
875
+ norm_bias: torch.Tensor,
876
+ linear_weight: torch.Tensor,
877
+ linear_bias: torch.Tensor,
878
+ residual: Optional[torch.Tensor] = None,
879
+ prenorm: bool = False,
880
+ residual_in_fp32: bool = False,
881
+ eps: float = 1e-6
882
+ ):
883
+ return LayerNormGatedLinearFunction.apply(
884
+ x,
885
+ g,
886
+ norm_weight,
887
+ norm_bias,
888
+ linear_weight,
889
+ linear_bias,
890
+ residual,
891
+ eps,
892
+ prenorm,
893
+ residual_in_fp32,
894
+ False
895
+ )
896
+
897
+
898
+ def rms_norm_swish_gate_linear(
899
+ x,
900
+ g: torch.Tensor,
901
+ norm_weight: torch.Tensor,
902
+ norm_bias: torch.Tensor,
903
+ linear_weight: torch.Tensor,
904
+ linear_bias: torch.Tensor,
905
+ residual: Optional[torch.Tensor] = None,
906
+ prenorm: bool = False,
907
+ residual_in_fp32: bool = False,
908
+ eps: float = 1e-6
909
+ ):
910
+ return LayerNormGatedLinearFunction.apply(
911
+ x,
912
+ g,
913
+ norm_weight,
914
+ norm_bias,
915
+ linear_weight,
916
+ linear_bias,
917
+ residual,
918
+ eps,
919
+ prenorm,
920
+ residual_in_fp32,
921
+ True
922
+ )
923
+
924
+
925
+ class FusedLayerNormGated(nn.Module):
926
+
927
+ def __init__(
928
+ self,
929
+ hidden_size: int,
930
+ elementwise_affine: bool = True,
931
+ bias: bool = False,
932
+ activation: str = 'swish',
933
+ eps: float = 1e-5,
934
+ device: Optional[torch.device] = None,
935
+ dtype: Optional[torch.dtype] = None,
936
+ ) -> FusedLayerNormGated:
937
+ factory_kwargs = {"device": device, "dtype": dtype}
938
+ super().__init__()
939
+
940
+ self.hidden_size = hidden_size
941
+ self.elementwise_affine = elementwise_affine
942
+ self.eps = eps
943
+ self.activation = activation
944
+
945
+ if self.activation not in ['swish', 'silu', 'sigmoid']:
946
+ raise ValueError(f"Unsupported activation: {self.activation}")
947
+
948
+ self.register_parameter("weight", None)
949
+ self.register_parameter("bias", None)
950
+ if elementwise_affine:
951
+ self.weight = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
952
+ if bias:
953
+ self.bias = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
954
+
955
+ self.reset_parameters()
956
+
957
+ def reset_parameters(self):
958
+ if self.elementwise_affine:
959
+ nn.init.ones_(self.weight)
960
+ if self.bias is not None:
961
+ nn.init.zeros_(self.bias)
962
+
963
+ def __repr__(self) -> str:
964
+ s = f"{self.__class__.__name__}({self.hidden_size}"
965
+ if not self.elementwise_affine:
966
+ s += f", elementwise_affine={self.elementwise_affine}"
967
+ s += f", eps={self.eps}"
968
+ s += f", activation={self.activation}"
969
+ s += ")"
970
+ return s
971
+
972
+ def forward(
973
+ self,
974
+ x: torch.Tensor,
975
+ g: torch.Tensor,
976
+ residual: Optional[torch.Tensor] = None,
977
+ prenorm: bool = False,
978
+ residual_in_fp32: bool = False
979
+ ) -> torch.Tensor:
980
+ return layer_norm_gated(
981
+ x,
982
+ g,
983
+ self.weight,
984
+ self.bias,
985
+ self.activation,
986
+ residual=residual,
987
+ eps=self.eps,
988
+ prenorm=prenorm,
989
+ residual_in_fp32=residual_in_fp32
990
+ )
991
+
992
+
993
+ class FusedRMSNormGated(nn.Module):
994
+
995
+ def __init__(
996
+ self,
997
+ hidden_size: int,
998
+ elementwise_affine: bool = True,
999
+ eps: float = 1e-5,
1000
+ activation: str = 'swish',
1001
+ device: Optional[torch.device] = None,
1002
+ dtype: Optional[torch.dtype] = None,
1003
+ ) -> FusedRMSNormGated:
1004
+ factory_kwargs = {"device": device, "dtype": dtype}
1005
+ super().__init__()
1006
+
1007
+ self.hidden_size = hidden_size
1008
+ self.elementwise_affine = elementwise_affine
1009
+ self.eps = eps
1010
+ self.activation = activation
1011
+
1012
+ if self.activation not in ['swish', 'silu', 'sigmoid']:
1013
+ raise ValueError(f"Unsupported activation: {self.activation}")
1014
+
1015
+ if elementwise_affine:
1016
+ self.weight = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
1017
+ else:
1018
+ self.register_parameter("weight", None)
1019
+ self.register_parameter("bias", None)
1020
+
1021
+ self.reset_parameters()
1022
+
1023
+ def reset_parameters(self):
1024
+ if self.elementwise_affine:
1025
+ nn.init.ones_(self.weight)
1026
+
1027
+ def __repr__(self) -> str:
1028
+ s = f"{self.__class__.__name__}({self.hidden_size}"
1029
+ if not self.elementwise_affine:
1030
+ s += f", elementwise_affine={self.elementwise_affine}"
1031
+ s += f", eps={self.eps}"
1032
+ s += f", activation={self.activation}"
1033
+ s += ")"
1034
+ return s
1035
+
1036
+ def forward(
1037
+ self,
1038
+ x: torch.Tensor,
1039
+ g: torch.Tensor,
1040
+ residual: Optional[torch.Tensor] = None,
1041
+ prenorm: bool = False,
1042
+ residual_in_fp32: bool = False
1043
+ ) -> torch.Tensor:
1044
+ return rms_norm_gated(
1045
+ x,
1046
+ g,
1047
+ self.weight,
1048
+ self.bias,
1049
+ self.activation,
1050
+ residual=residual,
1051
+ eps=self.eps,
1052
+ prenorm=prenorm,
1053
+ residual_in_fp32=residual_in_fp32
1054
+ )
1055
+
1056
+
1057
+ class FusedLayerNormSwishGate(FusedLayerNormGated):
1058
+
1059
+ def __init__(
1060
+ self,
1061
+ hidden_size: int,
1062
+ elementwise_affine: bool = True,
1063
+ bias: bool = False,
1064
+ eps: float = 1e-5,
1065
+ device: Optional[torch.device] = None,
1066
+ dtype: Optional[torch.dtype] = None,
1067
+ ) -> FusedLayerNormSwishGate:
1068
+ super().__init__(
1069
+ hidden_size=hidden_size,
1070
+ elementwise_affine=elementwise_affine,
1071
+ bias=bias,
1072
+ eps=eps,
1073
+ device=device,
1074
+ dtype=dtype
1075
+ )
1076
+
1077
+
1078
+ class FusedRMSNormSwishGate(FusedRMSNormGated):
1079
+
1080
+ def __init__(
1081
+ self,
1082
+ hidden_size: int,
1083
+ elementwise_affine: bool = True,
1084
+ eps: float = 1e-5,
1085
+ device: Optional[torch.device] = None,
1086
+ dtype: Optional[torch.dtype] = None,
1087
+ ) -> FusedRMSNormSwishGate:
1088
+ super().__init__(
1089
+ hidden_size=hidden_size,
1090
+ elementwise_affine=elementwise_affine,
1091
+ eps=eps,
1092
+ device=device,
1093
+ dtype=dtype
1094
+ )
1095
+
1096
+
1097
+ class FusedLayerNormGatedLinear(nn.Module):
1098
+
1099
+ def __init__(
1100
+ self,
1101
+ hidden_size: int,
1102
+ elementwise_affine: bool = True,
1103
+ eps: float = 1e-5,
1104
+ device: Optional[torch.device] = None,
1105
+ dtype: Optional[torch.dtype] = None,
1106
+ ) -> FusedLayerNormGatedLinear:
1107
+ factory_kwargs = {"device": device, "dtype": dtype}
1108
+ super().__init__()
1109
+
1110
+ self.hidden_size = hidden_size
1111
+ self.elementwise_affine = elementwise_affine
1112
+ self.eps = eps
1113
+
1114
+ if elementwise_affine:
1115
+ self.weight = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
1116
+ else:
1117
+ self.register_parameter("weight", None)
1118
+ self.register_parameter("bias", None)
1119
+
1120
+ self.reset_parameters()
1121
+
1122
+ def reset_parameters(self):
1123
+ if self.elementwise_affine:
1124
+ nn.init.ones_(self.weight)
1125
+
1126
+ def __repr__(self) -> str:
1127
+ s = f"{self.__class__.__name__}({self.hidden_size}"
1128
+ if not self.elementwise_affine:
1129
+ s += f", elementwise_affine={self.elementwise_affine}"
1130
+ s += f", eps={self.eps}"
1131
+ s += ")"
1132
+ return s
1133
+
1134
+ def forward(
1135
+ self,
1136
+ x: torch.Tensor,
1137
+ g: torch.Tensor,
1138
+ weight: Optional[torch.Tensor] = None,
1139
+ bias: Optional[torch.Tensor] = None,
1140
+ residual: Optional[torch.Tensor] = None,
1141
+ prenorm: bool = False,
1142
+ residual_in_fp32: bool = False
1143
+ ) -> torch.Tensor:
1144
+ return layer_norm_swish_gate_linear(
1145
+ x,
1146
+ g,
1147
+ self.weight,
1148
+ self.bias,
1149
+ weight,
1150
+ bias,
1151
+ residual=residual,
1152
+ eps=self.eps,
1153
+ prenorm=prenorm,
1154
+ residual_in_fp32=residual_in_fp32
1155
+ )
1156
+
1157
+
1158
+ class FusedLayerNormSwishGateLinear(FusedLayerNormGatedLinear):
1159
+
1160
+ def __init__(
1161
+ self,
1162
+ hidden_size: int,
1163
+ elementwise_affine: bool = True,
1164
+ eps: float = 1e-5,
1165
+ device: Optional[torch.device] = None,
1166
+ dtype: Optional[torch.dtype] = None,
1167
+ ) -> FusedLayerNormSwishGateLinear:
1168
+ super().__init__(
1169
+ hidden_size=hidden_size,
1170
+ elementwise_affine=elementwise_affine,
1171
+ eps=eps,
1172
+ device=device,
1173
+ dtype=dtype
1174
+ )
1175
+
1176
+
1177
+ class FusedRMSNormGatedLinear(nn.Module):
1178
+
1179
+ def __init__(
1180
+ self,
1181
+ hidden_size,
1182
+ elementwise_affine: bool = True,
1183
+ eps: float = 1e-5,
1184
+ device: Optional[torch.device] = None,
1185
+ dtype: Optional[torch.dtype] = None,
1186
+ ) -> FusedRMSNormGatedLinear:
1187
+ factory_kwargs = {"device": device, "dtype": dtype}
1188
+ super().__init__()
1189
+
1190
+ self.hidden_size = hidden_size
1191
+ self.elementwise_affine = elementwise_affine
1192
+ self.eps = eps
1193
+
1194
+ self.register_parameter("weight", None)
1195
+ self.register_parameter("bias", None)
1196
+ if elementwise_affine:
1197
+ self.weight = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
1198
+
1199
+ self.reset_parameters()
1200
+
1201
+ def reset_parameters(self):
1202
+ if self.elementwise_affine:
1203
+ nn.init.ones_(self.weight)
1204
+
1205
+ def __repr__(self) -> str:
1206
+ s = f"{self.__class__.__name__}({self.hidden_size}"
1207
+ if not self.elementwise_affine:
1208
+ s += f", elementwise_affine={self.elementwise_affine}"
1209
+ s += f", eps={self.eps}"
1210
+ s += ")"
1211
+ return s
1212
+
1213
+ def forward(
1214
+ self,
1215
+ x: torch.Tensor,
1216
+ g: torch.Tensor,
1217
+ weight: Optional[torch.Tensor] = None,
1218
+ bias: Optional[torch.Tensor] = None,
1219
+ residual: Optional[torch.Tensor] = None,
1220
+ prenorm: bool = False,
1221
+ residual_in_fp32: bool = False
1222
+ ) -> torch.Tensor:
1223
+ return rms_norm_swish_gate_linear(
1224
+ x,
1225
+ g,
1226
+ self.weight,
1227
+ self.bias,
1228
+ weight,
1229
+ bias,
1230
+ residual=residual,
1231
+ eps=self.eps,
1232
+ prenorm=prenorm,
1233
+ residual_in_fp32=residual_in_fp32
1234
+ )
1235
+
1236
+
1237
+ class FusedRMSNormSwishGateLinear(FusedRMSNormGatedLinear):
1238
+
1239
+ def __init__(
1240
+ self,
1241
+ hidden_size: int,
1242
+ elementwise_affine: bool = True,
1243
+ eps: float = 1e-5,
1244
+ device: Optional[torch.device] = None,
1245
+ dtype: Optional[torch.dtype] = None,
1246
+ ) -> FusedRMSNormSwishGateLinear:
1247
+ super().__init__(
1248
+ hidden_size=hidden_size,
1249
+ elementwise_affine=elementwise_affine,
1250
+ eps=eps,
1251
+ device=device,
1252
+ dtype=dtype
1253
+ )