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,632 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ # Implementations of BitLinear layer with fused LayerNorm and quantized Linear layer.
5
+ # [The Era of 1-bit LLMs: All Large Language Models are in 1.58 Bits](https://arxiv.org/abs/2402.17764)
6
+ # [Scalable MatMul-free Language Modeling](https://arxiv.org/abs/2406.02528)
7
+
8
+ # Code adapted from https://github.com/ridgerchu/matmulfreellm/
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ import triton
18
+ import triton.language as tl
19
+
20
+ from fla.modules.layernorm import RMSNorm
21
+ from fla.utils import get_multiprocessor_count, input_guard, is_amd, require_version
22
+
23
+ NUM_WARPS_AUTOTUNE = [1, 2, 4, 8, 16] if is_amd else [1, 2, 4, 8, 16, 32]
24
+
25
+
26
+ def activation_quant(x):
27
+ """
28
+ Per-token quantization to 8 bits. No grouping is needed for quantization.
29
+
30
+ Args:
31
+ x: An activation tensor with shape [n, d].
32
+
33
+ Returns:
34
+ A quantized activation tensor with shape [n, d].
35
+ """
36
+ # Compute the scale factor
37
+ scale = 127.0 / x.abs().max(dim=-1, keepdim=True).values.clamp_(min=1e-5)
38
+ # Quantize and then de-quantize the tensor
39
+ y = (x * scale).round().clamp_(-128, 127) / scale
40
+ return y
41
+
42
+
43
+ def weight_quant(w):
44
+ """
45
+ Per-tensor quantization to 1.58 bits. No grouping is needed for quantization.
46
+
47
+ Args:
48
+ w: A weight tensor with shape [d, k].
49
+
50
+ Returns:
51
+ A quantized weight tensor with shape [d, k].
52
+ """
53
+ # Compute the scale factor
54
+ scale = 1.0 / w.abs().mean().clamp_(min=1e-5)
55
+ # Quantize and then de-quantize the tensor
56
+ u = (w * scale).round().clamp_(-1, 1) / scale
57
+ return u
58
+
59
+
60
+ @triton.autotune(
61
+ configs=[
62
+ triton.Config({}, num_warps=num_warps)
63
+ for num_warps in NUM_WARPS_AUTOTUNE
64
+ ],
65
+ key=["N", "HAS_RESIDUAL", "STORE_RESIDUAL_OUT", "IS_RMS_NORM", "HAS_BIAS"],
66
+ )
67
+ @triton.jit
68
+ def layer_norm_fwd_kernel_quant(
69
+ X, # pointer to the input
70
+ Y, # pointer to the output
71
+ W, # pointer to the weights
72
+ B, # pointer to the biases
73
+ RESIDUAL, # pointer to the residual
74
+ RESIDUAL_OUT, # pointer to the residual
75
+ Mean, # pointer to the mean
76
+ Rstd, # pointer to the 1/std
77
+ stride_x_row, # how much to increase the pointer when moving by 1 row
78
+ stride_y_row,
79
+ stride_res_row,
80
+ stride_res_out_row,
81
+ N, # number of columns in X
82
+ eps, # epsilon to avoid division by zero
83
+ IS_RMS_NORM: tl.constexpr,
84
+ BLOCK_N: tl.constexpr,
85
+ HAS_RESIDUAL: tl.constexpr,
86
+ STORE_RESIDUAL_OUT: tl.constexpr,
87
+ HAS_WEIGHT: tl.constexpr,
88
+ HAS_BIAS: tl.constexpr
89
+ ):
90
+ # Map the program id to the row of X and Y it should compute.
91
+ row = tl.program_id(0)
92
+ X += row * stride_x_row
93
+ Y += row * stride_y_row
94
+ if HAS_RESIDUAL:
95
+ RESIDUAL += row * stride_res_row
96
+ if STORE_RESIDUAL_OUT:
97
+ RESIDUAL_OUT += row * stride_res_out_row
98
+ # Compute mean and variance
99
+ cols = tl.arange(0, BLOCK_N)
100
+ x = tl.load(X + cols, mask=cols < N, other=0.0).to(tl.float32)
101
+ if HAS_RESIDUAL:
102
+ residual = tl.load(RESIDUAL + cols, mask=cols < N, other=0.0).to(tl.float32)
103
+ x += residual
104
+ if STORE_RESIDUAL_OUT:
105
+ tl.store(RESIDUAL_OUT + cols, x, mask=cols < N)
106
+ if not IS_RMS_NORM:
107
+ mean = tl.sum(x, axis=0) / N
108
+ tl.store(Mean + row, mean)
109
+ xbar = tl.where(cols < N, x - mean, 0.0)
110
+ var = tl.sum(xbar * xbar, axis=0) / N
111
+ else:
112
+ xbar = tl.where(cols < N, x, 0.0)
113
+ var = tl.sum(xbar * xbar, axis=0) / N
114
+ rstd = 1 / tl.sqrt(var + eps)
115
+ tl.store(Rstd + row, rstd)
116
+ # Normalize and apply linear transformation
117
+ mask = cols < N
118
+ if HAS_WEIGHT:
119
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
120
+ if HAS_BIAS:
121
+ b = tl.load(B + cols, mask=mask).to(tl.float32)
122
+ x_hat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
123
+
124
+ y = x_hat * w if HAS_WEIGHT else x_hat
125
+ if HAS_BIAS:
126
+ y = y + b
127
+
128
+ # Aply quantization to the output
129
+ scale = 127.0 / tl.maximum(tl.max(tl.abs(y), 0), 1e-5)
130
+ # Quantize and then de-quantize the tensor
131
+ y = tl.extra.cuda.libdevice.round(y * scale)
132
+ y = tl.maximum(tl.minimum(y, 127), -128) / scale
133
+
134
+ # Write output
135
+ tl.store(Y + cols, y, mask=mask)
136
+
137
+
138
+ def layer_norm_fwd_quant(
139
+ x: torch.Tensor,
140
+ weight: torch.Tensor,
141
+ bias: torch.Tensor,
142
+ eps: float,
143
+ residual: torch.Tensor = None,
144
+ out_dtype: torch.dtype = None,
145
+ residual_dtype: torch.dtype = None,
146
+ is_rms_norm: bool = False
147
+ ):
148
+ if residual is not None:
149
+ residual_dtype = residual.dtype
150
+ M, N = x.shape
151
+ # allocate output
152
+ y = torch.empty_like(x, dtype=x.dtype if out_dtype is None else out_dtype)
153
+ if residual is not None or (residual_dtype is not None and residual_dtype != x.dtype):
154
+ residual_out = torch.empty(M, N, device=x.device, dtype=residual_dtype)
155
+ else:
156
+ residual_out = None
157
+ mean = torch.empty((M,), dtype=torch.float32, device=x.device) if not is_rms_norm else None
158
+ rstd = torch.empty((M,), dtype=torch.float32, device=x.device)
159
+ # Less than 64KB per feature: enqueue fused kernel
160
+ MAX_FUSED_SIZE = 65536 // x.element_size()
161
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
162
+ if N > BLOCK_N:
163
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
164
+ # heuristics for number of warps
165
+ layer_norm_fwd_kernel_quant[(M,)](
166
+ x,
167
+ y,
168
+ weight,
169
+ bias,
170
+ residual,
171
+ residual_out,
172
+ mean,
173
+ rstd,
174
+ x.stride(0),
175
+ y.stride(0),
176
+ residual.stride(0) if residual is not None else 0,
177
+ residual_out.stride(0) if residual_out is not None else 0,
178
+ N,
179
+ eps,
180
+ is_rms_norm,
181
+ BLOCK_N,
182
+ residual is not None,
183
+ residual_out is not None,
184
+ weight is not None,
185
+ bias is not None,
186
+ )
187
+ # residual_out is None if residual is None and residual_dtype == input_dtype
188
+ return y, mean, rstd, residual_out if residual_out is not None else x
189
+
190
+
191
+ @triton.heuristics({
192
+ "RECOMPUTE_OUTPUT": lambda args: args["Y"] is not None
193
+ })
194
+ @triton.autotune(
195
+ configs=[
196
+ triton.Config({}, num_warps=num_warps)
197
+ for num_warps in NUM_WARPS_AUTOTUNE
198
+ ],
199
+ key=["N", "HAS_DRESIDUAL", "STORE_DRESIDUAL", "IS_RMS_NORM", "HAS_BIAS"],
200
+ )
201
+ @triton.jit
202
+ def layer_norm_bwd_kernel(
203
+ X, # pointer to the input
204
+ W, # pointer to the weights
205
+ B, # pointer to the biases
206
+ Y, # pointer to the output to be recomputed
207
+ DY, # pointer to the output gradient
208
+ DX, # pointer to the input gradient
209
+ DW, # pointer to the partial sum of weights gradient
210
+ DB, # pointer to the partial sum of biases gradient
211
+ DRESIDUAL,
212
+ DRESIDUAL_IN,
213
+ Mean, # pointer to the mean
214
+ Rstd, # pointer to the 1/std
215
+ stride_x_row, # how much to increase the pointer when moving by 1 row
216
+ stride_y_row,
217
+ stride_dy_row,
218
+ stride_dx_row,
219
+ stride_dres_row,
220
+ stride_dres_in_row,
221
+ M, # number of rows in X
222
+ N, # number of columns in X
223
+ eps, # epsilon to avoid division by zero
224
+ rows_per_program,
225
+ IS_RMS_NORM: tl.constexpr,
226
+ BLOCK_N: tl.constexpr,
227
+ HAS_DRESIDUAL: tl.constexpr,
228
+ STORE_DRESIDUAL: tl.constexpr,
229
+ HAS_WEIGHT: tl.constexpr,
230
+ HAS_BIAS: tl.constexpr,
231
+ RECOMPUTE_OUTPUT: tl.constexpr,
232
+ ):
233
+ # Map the program id to the elements of X, DX, and DY it should compute.
234
+ row_block_id = tl.program_id(0)
235
+ row_start = row_block_id * rows_per_program
236
+ cols = tl.arange(0, BLOCK_N)
237
+ mask = cols < N
238
+ X += row_start * stride_x_row
239
+ if HAS_DRESIDUAL:
240
+ DRESIDUAL += row_start * stride_dres_row
241
+ if STORE_DRESIDUAL:
242
+ DRESIDUAL_IN += row_start * stride_dres_in_row
243
+ DY += row_start * stride_dy_row
244
+ DX += row_start * stride_dx_row
245
+ if RECOMPUTE_OUTPUT:
246
+ Y += row_start * stride_y_row
247
+ if HAS_WEIGHT:
248
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
249
+ dw = tl.zeros((BLOCK_N,), dtype=tl.float32)
250
+ if RECOMPUTE_OUTPUT and HAS_BIAS:
251
+ b = tl.load(B + cols, mask=mask, other=0.0).to(tl.float32)
252
+ if HAS_BIAS:
253
+ db = tl.zeros((BLOCK_N,), dtype=tl.float32)
254
+ row_end = min((row_block_id + 1) * rows_per_program, M)
255
+ for row in range(row_start, row_end):
256
+ # Load data to SRAM
257
+ x = tl.load(X + cols, mask=mask, other=0).to(tl.float32)
258
+ dy = tl.load(DY + cols, mask=mask, other=0).to(tl.float32)
259
+ if not IS_RMS_NORM:
260
+ mean = tl.load(Mean + row)
261
+ rstd = tl.load(Rstd + row)
262
+ # Compute dx
263
+ xhat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
264
+ xhat = tl.where(mask, xhat, 0.0)
265
+ if RECOMPUTE_OUTPUT:
266
+ y = xhat * w if HAS_WEIGHT else xhat
267
+ if HAS_BIAS:
268
+ y = y + b
269
+
270
+ # Aply quantization to the output
271
+ scale = 127.0 / tl.maximum(tl.max(tl.abs(y), 0), 1e-5)
272
+ # Quantize and then de-quantize the tensor
273
+ y = tl.extra.cuda.libdevice.round(y * scale)
274
+ y = tl.maximum(tl.minimum(y, 127), -128) / scale
275
+
276
+ tl.store(Y + cols, y, mask=mask)
277
+ wdy = dy
278
+ if HAS_WEIGHT:
279
+ wdy = dy * w
280
+ dw += dy * xhat
281
+ if HAS_BIAS:
282
+ db += dy
283
+ if not IS_RMS_NORM:
284
+ c1 = tl.sum(xhat * wdy, axis=0) / N
285
+ c2 = tl.sum(wdy, axis=0) / N
286
+ dx = (wdy - (xhat * c1 + c2)) * rstd
287
+ else:
288
+ c1 = tl.sum(xhat * wdy, axis=0) / N
289
+ dx = (wdy - xhat * c1) * rstd
290
+ if HAS_DRESIDUAL:
291
+ dres = tl.load(DRESIDUAL + cols, mask=mask, other=0).to(tl.float32)
292
+ dx += dres
293
+ # Write dx
294
+ if STORE_DRESIDUAL:
295
+ tl.store(DRESIDUAL_IN + cols, dx, mask=mask)
296
+ tl.store(DX + cols, dx, mask=mask)
297
+
298
+ X += stride_x_row
299
+ if HAS_DRESIDUAL:
300
+ DRESIDUAL += stride_dres_row
301
+ if STORE_DRESIDUAL:
302
+ DRESIDUAL_IN += stride_dres_in_row
303
+ if RECOMPUTE_OUTPUT:
304
+ Y += stride_y_row
305
+ DY += stride_dy_row
306
+ DX += stride_dx_row
307
+ if HAS_WEIGHT:
308
+ tl.store(DW + row_block_id * N + cols, dw, mask=mask)
309
+ if HAS_BIAS:
310
+ tl.store(DB + row_block_id * N + cols, db, mask=mask)
311
+
312
+
313
+ def layer_norm_bwd(
314
+ dy: torch.Tensor,
315
+ x: torch.Tensor,
316
+ weight: torch.Tensor,
317
+ bias: torch.Tensor,
318
+ eps: float,
319
+ mean: torch.Tensor,
320
+ rstd: torch.Tensor,
321
+ dresidual: torch.Tensor = None,
322
+ has_residual: bool = False,
323
+ is_rms_norm: bool = False,
324
+ x_dtype: torch.dtype = None,
325
+ recompute_output: bool = False,
326
+ ):
327
+ M, N = x.shape
328
+ # allocate output
329
+ dx = torch.empty_like(x) if x_dtype is None else torch.empty(M, N, dtype=x_dtype, device=x.device)
330
+ dresidual_in = torch.empty_like(x) if has_residual and dx.dtype != x.dtype else None
331
+ y = torch.empty(M, N, dtype=dy.dtype, device=dy.device) if recompute_output else None
332
+
333
+ # Less than 64KB per feature: enqueue fused kernel
334
+ MAX_FUSED_SIZE = 65536 // x.element_size()
335
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
336
+ if N > BLOCK_N:
337
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
338
+ sm_count = get_multiprocessor_count(x.device.index)
339
+ _dw = torch.empty((sm_count, N), dtype=torch.float32, device=weight.device) if weight is not None else None
340
+ _db = torch.empty((sm_count, N), dtype=torch.float32, device=bias.device) if bias is not None else None
341
+ rows_per_program = math.ceil(M / sm_count)
342
+ grid = (sm_count,)
343
+ layer_norm_bwd_kernel[grid](
344
+ x,
345
+ weight,
346
+ bias,
347
+ y,
348
+ dy,
349
+ dx,
350
+ _dw,
351
+ _db,
352
+ dresidual,
353
+ dresidual_in,
354
+ mean,
355
+ rstd,
356
+ x.stride(0),
357
+ 0 if not recompute_output else y.stride(0),
358
+ dy.stride(0),
359
+ dx.stride(0),
360
+ dresidual.stride(0) if dresidual is not None else 0,
361
+ dresidual_in.stride(0) if dresidual_in is not None else 0,
362
+ M,
363
+ N,
364
+ eps,
365
+ rows_per_program,
366
+ is_rms_norm,
367
+ BLOCK_N,
368
+ dresidual is not None,
369
+ dresidual_in is not None,
370
+ weight is not None,
371
+ bias is not None,
372
+ )
373
+ dw = _dw.sum(0).to(weight.dtype) if weight is not None else None
374
+ db = _db.sum(0).to(bias.dtype) if bias is not None else None
375
+ # Don't need to compute dresidual_in separately in this case
376
+ if has_residual and dx.dtype == x.dtype:
377
+ dresidual_in = dx
378
+ return (dx, dw, db, dresidual_in) if not recompute_output else (dx, dw, db, dresidual_in, y)
379
+
380
+
381
+ class LayerNormLinearQuantFn(torch.autograd.Function):
382
+
383
+ @staticmethod
384
+ @input_guard
385
+ def forward(
386
+ ctx,
387
+ x,
388
+ norm_weight,
389
+ norm_bias,
390
+ linear_weight,
391
+ linear_bias,
392
+ residual=None,
393
+ eps=1e-6,
394
+ prenorm=False,
395
+ residual_in_fp32=False,
396
+ is_rms_norm=False,
397
+ ):
398
+ x_shape_og = x.shape
399
+ # reshape input data into 2D tensor
400
+ x = x.reshape(-1, x.shape[-1])
401
+ if residual is not None:
402
+ assert residual.shape == x_shape_og
403
+ residual = residual.reshape(-1, residual.shape[-1])
404
+ residual_dtype = residual.dtype if residual is not None else (torch.float32 if residual_in_fp32 else None)
405
+ y, mean, rstd, residual_out = layer_norm_fwd_quant(
406
+ x,
407
+ norm_weight,
408
+ norm_bias,
409
+ eps,
410
+ residual,
411
+ out_dtype=None if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype(),
412
+ residual_dtype=residual_dtype,
413
+ is_rms_norm=is_rms_norm,
414
+ )
415
+ y = y.reshape(x_shape_og)
416
+ dtype = torch.get_autocast_gpu_dtype() if torch.is_autocast_enabled() else y.dtype
417
+ linear_weight = weight_quant(linear_weight).to(dtype)
418
+ linear_bias = linear_bias.to(dtype) if linear_bias is not None else None
419
+ out = F.linear(y.to(linear_weight.dtype), linear_weight, linear_bias)
420
+ # We don't store y, will be recomputed in the backward pass to save memory
421
+ ctx.save_for_backward(residual_out, norm_weight, norm_bias, linear_weight, mean, rstd)
422
+ ctx.x_shape_og = x_shape_og
423
+ ctx.eps = eps
424
+ ctx.is_rms_norm = is_rms_norm
425
+ ctx.has_residual = residual is not None
426
+ ctx.prenorm = prenorm
427
+ ctx.x_dtype = x.dtype
428
+ ctx.linear_bias_is_none = linear_bias is None
429
+ return out if not prenorm else (out, residual_out.reshape(x_shape_og))
430
+
431
+ @staticmethod
432
+ @input_guard
433
+ def backward(ctx, dout, *args):
434
+ x, norm_weight, norm_bias, linear_weight, mean, rstd = ctx.saved_tensors
435
+ dout = dout.reshape(-1, dout.shape[-1])
436
+ dy = F.linear(dout, linear_weight.t())
437
+ dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0)
438
+ assert dy.shape == x.shape
439
+ if ctx.prenorm:
440
+ dresidual = args[0]
441
+ dresidual = dresidual.reshape(-1, dresidual.shape[-1])
442
+ assert dresidual.shape == x.shape
443
+ else:
444
+ dresidual = None
445
+ dx, dnorm_weight, dnorm_bias, dresidual_in, y = layer_norm_bwd(
446
+ dy,
447
+ x,
448
+ norm_weight,
449
+ norm_bias,
450
+ ctx.eps,
451
+ mean,
452
+ rstd,
453
+ dresidual,
454
+ ctx.has_residual,
455
+ ctx.is_rms_norm,
456
+ x_dtype=ctx.x_dtype,
457
+ recompute_output=True
458
+ )
459
+ dlinear_weight = torch.einsum("bo,bi->oi", dout, y)
460
+ return (
461
+ dx.reshape(ctx.x_shape_og),
462
+ dnorm_weight,
463
+ dnorm_bias,
464
+ dlinear_weight,
465
+ dlinear_bias,
466
+ dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
467
+ None,
468
+ None,
469
+ None,
470
+ None,
471
+ )
472
+
473
+
474
+ def layer_norm_linear_quant_fn(
475
+ x,
476
+ norm_weight,
477
+ norm_bias,
478
+ linear_weight,
479
+ linear_bias,
480
+ residual=None,
481
+ eps=1e-6,
482
+ prenorm=False,
483
+ residual_in_fp32=False,
484
+ is_rms_norm=False,
485
+ ):
486
+ return LayerNormLinearQuantFn.apply(
487
+ x,
488
+ norm_weight,
489
+ norm_bias,
490
+ linear_weight,
491
+ linear_bias,
492
+ residual,
493
+ eps,
494
+ prenorm,
495
+ residual_in_fp32,
496
+ is_rms_norm,
497
+ )
498
+
499
+
500
+ def rms_norm_linear_quant(
501
+ x: torch.Tensor,
502
+ norm_weight: torch.Tensor,
503
+ norm_bias: torch.Tensor,
504
+ linear_weight: torch.Tensor,
505
+ linear_bias: torch.Tensor,
506
+ residual: torch.Tensor = None,
507
+ eps: float = 1e-5,
508
+ prenorm: bool = False,
509
+ residual_in_fp32: bool = False
510
+ ):
511
+ return layer_norm_linear_quant_fn(
512
+ x=x,
513
+ norm_weight=norm_weight,
514
+ norm_bias=norm_bias,
515
+ linear_weight=linear_weight,
516
+ linear_bias=linear_bias,
517
+ residual=residual,
518
+ eps=eps,
519
+ prenorm=prenorm,
520
+ residual_in_fp32=residual_in_fp32,
521
+ is_rms_norm=True
522
+ )
523
+
524
+
525
+ @require_version("triton>=3.0", "Triton >= 3.0 is required to do online quantization.")
526
+ def bit_linear(x, weight, bias=None, norm_weight=None, norm_bias=None, eps=1e-8):
527
+ """
528
+ A functional version of BitLinear that applies quantization to activations and weights.
529
+
530
+ Args:
531
+ x: Input tensor with shape [n, d].
532
+ weight: Weight tensor with shape [out_features, in_features].
533
+ bias: Bias tensor with shape [out_features] (optional).
534
+ norm_weight: Weight tensor for RMS normalization with shape [in_features].
535
+ norm_bias: Bias tensor for RMS normalization with shape [in_features].
536
+ eps: A small constant for numerical stability in normalization.
537
+
538
+ Returns:
539
+ Output tensor with shape [n, out_features].
540
+ """
541
+ return layer_norm_linear_quant_fn(
542
+ x,
543
+ norm_weight,
544
+ norm_bias,
545
+ weight,
546
+ bias,
547
+ is_rms_norm=True
548
+ )
549
+
550
+
551
+ class BitLinear(nn.Linear):
552
+ """
553
+ A custom linear layer that applies quantization on both activations and weights.
554
+ This is primarily for training; kernel optimization is needed for efficiency in deployment.
555
+ """
556
+
557
+ def __init__(
558
+ self,
559
+ in_features: int,
560
+ out_features: int,
561
+ bias: bool = False,
562
+ norm_eps: float = 1e-8
563
+ ):
564
+ """
565
+ Initializes the BitLinear layer.
566
+
567
+ Args:
568
+ in_features: Size of each input sample.
569
+ out_features: Size of each output sample.
570
+ bias: If set to False, the layer will not learn an additive bias. Default: True.
571
+ """
572
+ # Initialize the superclass nn.Linear with the given parameters
573
+ super(BitLinear, self).__init__(in_features, out_features, bias=bias)
574
+
575
+ self.norm = RMSNorm(in_features, eps=norm_eps)
576
+
577
+ def __repr__(self) -> str:
578
+ return f"{self.__class__.__name__}({super().extra_repr()}, norm_eps={self.norm.eps})"
579
+
580
+ def forward(self, x):
581
+ """
582
+ Overrides the forward pass to include quantization.
583
+
584
+ Args:
585
+ x: An input tensor with shape [n, d].
586
+
587
+ Returns:
588
+ An output tensor with shape [n, d].
589
+ """
590
+ # Weight tensor
591
+ w = self.weight
592
+
593
+ # Apply RMS normalization to the input
594
+ x_norm = self.norm(x)
595
+
596
+ # Apply quantization to both activations and weights
597
+ # Uses Straight-Through Estimator (STE) trick with .detach() for gradient flow
598
+ x_quant = x_norm + (activation_quant(x_norm) - x_norm).detach()
599
+ w_quant = w + (weight_quant(w) - w).detach()
600
+ # Perform linear operation with quantized values
601
+ y = F.linear(x_quant, w_quant)
602
+
603
+ return y
604
+
605
+
606
+ class FusedBitLinear(BitLinear):
607
+ """
608
+ A custom linear layer that applies quantization on both activations and weights.
609
+ This is primarily for training; kernel optimization is needed for efficiency in deployment.
610
+ """
611
+
612
+ def __init__(self, in_features, out_features, bias=False):
613
+ """
614
+ Initializes the BitLinear layer.
615
+
616
+ Args:
617
+ in_features: Size of each input sample.
618
+ out_features: Size of each output sample.
619
+ bias: If set to False, the layer will not learn an additive bias. Default: True.
620
+ """
621
+ # Initialize the superclass nn.Linear with the given parameters
622
+ super(FusedBitLinear, self).__init__(in_features, out_features, bias=bias)
623
+
624
+ def forward(self, x):
625
+ return layer_norm_linear_quant_fn(
626
+ x,
627
+ self.norm.weight,
628
+ self.norm.bias,
629
+ self.weight,
630
+ self.bias,
631
+ is_rms_norm=True
632
+ )