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,620 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Code adapted from
4
+ # https://github.com/linkedin/Liger-Kernel/blob/main/src/liger_kernel/ops/fused_linear_cross_entropy.py
5
+
6
+ from functools import partial
7
+ from typing import Optional, Tuple
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
+ from torch.distributed import DeviceMesh
15
+ from torch.distributed.tensor import Replicate, Shard, distribute_module
16
+ from torch.distributed.tensor.parallel import ParallelStyle
17
+
18
+ from fla.ops.utils import logsumexp_fwd
19
+ from fla.ops.utils.op import exp
20
+ from fla.utils import input_guard, is_amd
21
+
22
+ try:
23
+ from torch.distributed.tensor import DTensor
24
+ except (ImportError, AttributeError):
25
+ DTensor = None
26
+
27
+ # The hard limit of TRITON_MAX_TENSOR_NUMEL is 1048576
28
+ # https://github.com/triton-lang/triton/blob/ba42a5c68fd0505f8c42f4202d53be0f8d9a5fe0/python/triton/language/core.py#L19
29
+ # However, setting limit as 65536 as in LayerNorm tutorial is faster because of less register spilling
30
+ # The optimal maximum block size depends on your hardware, your kernel, and your dtype
31
+ MAX_FUSED_SIZE = 65536 // 2
32
+ STATIC_WARPS = 32 if not is_amd else 16
33
+
34
+
35
+ @triton.jit
36
+ def cross_entropy_kernel(
37
+ logits,
38
+ lse,
39
+ target,
40
+ loss,
41
+ total,
42
+ ignore_index,
43
+ label_smoothing: tl.constexpr,
44
+ logit_scale: tl.constexpr,
45
+ reduction: tl.constexpr,
46
+ V: tl.constexpr,
47
+ BV: tl.constexpr
48
+ ):
49
+ """
50
+ This kernel computes both cross entropy loss and the gradient of the input.
51
+ We only consider hard label + mean reduction for now.
52
+ Please refer to https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html for the math.
53
+
54
+ Args:
55
+ logits:
56
+ Pointer to logits tensor.
57
+ lse:
58
+ Pointer to logsumexp tensor.
59
+ target: Pointer to target tensor.
60
+ loss:
61
+ Pointer to tensor to store the loss.
62
+ V (int):
63
+ The number of columns in the input tensor.
64
+ total (int):
65
+ The number of non-ignored classes.
66
+ ignore_index (int):
67
+ The index to ignore in the target.
68
+ label_smoothing (float):
69
+ The amount of smoothing when computing the loss, where 0.0 means no smoothing.
70
+ reduction (str):
71
+ The string for the reduction to apply
72
+ BV (int):
73
+ The block size for vocab.
74
+ """
75
+
76
+ # https://github.com/triton-lang/triton/issues/1058
77
+ # If B*T*V is too large, i_n * stride will overflow out of int32, so we convert to int64
78
+ i_n = tl.program_id(0).to(tl.int64)
79
+ NV = tl.cdiv(V, BV)
80
+
81
+ # 1. Load target first because if the target is ignore_index, we can return right away
82
+ b_y = tl.load(target + i_n)
83
+
84
+ # 2. locate the start index
85
+ logits += i_n * V
86
+
87
+ if b_y == ignore_index:
88
+ # set all x as 0
89
+ for i in range(0, V, BV):
90
+ o_v = i + tl.arange(0, BV)
91
+ tl.store(logits + o_v, 0.0, mask=o_v < V)
92
+ return
93
+
94
+ # Online softmax: 2 loads + 1 store (compared with 3 loads + 1 store for the safe softmax)
95
+ # Refer to Algorithm 3 in the paper: https://arxiv.org/pdf/1805.02867
96
+
97
+ # 3. [Online softmax] first pass: compute logsumexp
98
+ # we did this in anouter kernel
99
+ b_l = tl.load(logits + b_y) * logit_scale
100
+ b_lse = tl.load(lse + i_n)
101
+
102
+ # 4. Calculate the loss
103
+ # loss = lse - logits_l
104
+ b_loss = b_lse - b_l
105
+
106
+ # Label smoothing is a general case of normal cross entropy
107
+ # See the full derivation at https://github.com/linkedin/Liger-Kernel/pull/198#issue-2503665310
108
+ b_z = 0.0
109
+ eps = label_smoothing / V
110
+
111
+ # We need tl.debug_barrier() as mentioned in
112
+ # https://github.com/triton-lang/triton/blob/ba42a5c68fd0505f8c42f4202d53be0f8d9a5fe0/python/triton/ops/cross_entropy.py#L34
113
+ tl.debug_barrier()
114
+
115
+ # 5. [Online Softmax] Second pass: compute gradients
116
+ # For 'mean' reduction, gradients are normalized by number of non-ignored elements
117
+ # dx_y = (softmax(x_y) - 1) / N
118
+ # dx_i = softmax(x_i) / N, i != y
119
+ # For label smoothing:
120
+ # dx_i = (softmax(x_y) - label_smoothing / V) / N, i != y
121
+ # dx_y = (softmax(x_y) - label_smoothing / V - (1 - label_smoothing)) / N
122
+ # = dx_i - (1 - label_smoothing) / N
123
+ for iv in range(0, NV):
124
+ o_v = iv * BV + tl.arange(0, BV)
125
+ b_logits = tl.load(logits + o_v, mask=o_v < V, other=float('-inf')) * logit_scale
126
+ if label_smoothing > 0:
127
+ # scale X beforehand to avoid overflow
128
+ b_z += tl.sum(tl.where(o_v < V, -eps * b_logits, 0.0))
129
+ b_p = (exp(b_logits - b_lse) - eps) * logit_scale
130
+ if reduction == "mean":
131
+ b_p = b_p / total
132
+ tl.store(logits + o_v, b_p, mask=o_v < V)
133
+
134
+ tl.debug_barrier()
135
+
136
+ # Orginal loss = H(q, p), with label smoothing regularization = H(q', p) and (label_smoothing / V) = eps
137
+ # H(q', p) = (1 - label_smoothing) * H(q, p) + label_smoothing * H(u, p)
138
+ # = (1 - label_smoothing) * H(q, p) + eps * sum(logsoftmax(x_i))
139
+ # By using m (global max of xi) and d (sum of e^(xi-m)), we can simplify as:
140
+ # = (1 - label_smoothing) * H(q, p) + (-sum(x_i * eps) + label_smoothing * (m + logd))
141
+ # Refer to H(q', p) in section 7 of the paper:
142
+ # https://arxiv.org/pdf/1512.00567
143
+ # pytorch:
144
+ # https://github.com/pytorch/pytorch/blob/2981534f54d49fa3a9755c9b0855e7929c2527f0/aten/src/ATen/native/LossNLL.cpp#L516
145
+ # See full derivation at https://github.com/linkedin/Liger-Kernel/pull/198#issuecomment-2333753087
146
+ if label_smoothing > 0:
147
+ b_loss = b_loss * (1 - label_smoothing) + (b_z + label_smoothing * b_lse)
148
+
149
+ # 6. Specially handle the i==y case where `dx_y = (softmax(x_y) - (1 - label_smoothing) / N`
150
+ b_l = tl.load(logits + b_y)
151
+
152
+ # Normalize the loss by the number of non-ignored elements if reduction is "mean"
153
+ if reduction == 'mean':
154
+ b_loss = b_loss / total
155
+ b_l += (label_smoothing - 1) / total * logit_scale
156
+ else:
157
+ b_l += (label_smoothing - 1) * logit_scale
158
+
159
+ tl.store(loss + i_n, b_loss)
160
+ tl.store(logits + b_y, b_l)
161
+
162
+
163
+ @triton.jit
164
+ def elementwise_mul_kernel(
165
+ x,
166
+ g,
167
+ N: tl.constexpr,
168
+ B: tl.constexpr
169
+ ):
170
+ """
171
+ This function multiplies each element of the tensor pointed by x with the value pointed by g.
172
+ The multiplication is performed in-place on the tensor pointed by x.
173
+
174
+ Parameters:
175
+ x:
176
+ Pointer to the input tensor.
177
+ g:
178
+ Pointer to the gradient output value.
179
+ N (int):
180
+ The number of columns in the input tensor.
181
+ B (int):
182
+ The block size for Triton operations.
183
+ """
184
+
185
+ # Get the program ID and convert it to int64 to avoid overflow
186
+ i_x = tl.program_id(0).to(tl.int64)
187
+ o_x = i_x * B + tl.arange(0, B)
188
+
189
+ # Load the gradient output value
190
+ b_g = tl.load(g)
191
+ b_x = tl.load(x + o_x, mask=o_x < N)
192
+ tl.store(x + o_x, b_x * b_g, mask=o_x < N)
193
+
194
+
195
+ def fused_linear_cross_entropy_forward(
196
+ x: torch.Tensor,
197
+ target: torch.LongTensor,
198
+ weight: torch.Tensor,
199
+ bias: torch.Tensor = None,
200
+ ignore_index: int = -100,
201
+ label_smoothing: float = 0.0,
202
+ logit_scale: float = 1.0,
203
+ num_chunks: int = 8,
204
+ reduction: str = "mean",
205
+ use_l2warp: bool = False,
206
+ l2_penalty_factor: float = 1e-4
207
+ ):
208
+ device = x.device
209
+ # inputs have shape: [N, H]
210
+ # materialized activations will have shape: [N, V]
211
+ # the increase in memory = [N, V]
212
+ # reduction can be achieved by partitioning the number of tokens N into smaller chunks.
213
+
214
+ # ideally, we would like to achieve the same memory consumption as [N, H],
215
+ # so the expected chunk size should be:
216
+ # NC = ceil(V / H)
217
+ # C = ceil(N / NC)
218
+ # for ex: N = 4096*4, V = 32000, H = 4096 ==> NC = 8, C = ceil(N / NC) = 2048
219
+ N, H, V = *x.shape, weight.shape[0]
220
+ BV = min(MAX_FUSED_SIZE, triton.next_power_of_2(V))
221
+ # TODO: in real cases, we may need to limit the number of chunks NC to
222
+ # ensure the precisions of accumulated gradients
223
+ NC = min(num_chunks, triton.cdiv(V, H))
224
+ C = triton.next_power_of_2(triton.cdiv(N, NC))
225
+ NC = triton.cdiv(N, C)
226
+
227
+ # [N, H]
228
+ dx = torch.zeros_like(x, device=device)
229
+ # [V, H]
230
+ dw = torch.zeros_like(weight, device=device, dtype=torch.float) if weight is not None else None
231
+ # [V]
232
+ db = torch.zeros_like(bias, device=device, dtype=torch.float) if bias is not None else None
233
+ # [N]
234
+ loss = torch.zeros(N, device=device, dtype=torch.float)
235
+
236
+ total = target.ne(ignore_index).sum().item()
237
+
238
+ for ic in range(NC):
239
+ start, end = ic * C, min((ic + 1) * C, N)
240
+ # [C, N]
241
+ c_x = x[start:end]
242
+ # when doing matmul, use the original precision
243
+ # [C, V]
244
+ c_logits = F.linear(c_x, weight, bias)
245
+ c_target = target[start:end]
246
+ # [C]
247
+ # keep lse in fp32 to maintain precision
248
+ c_lse = logsumexp_fwd(c_logits, scale=logit_scale, dtype=torch.float)
249
+
250
+ # unreduced loss
251
+ c_loss = loss[start:end]
252
+ if use_l2warp:
253
+ c_maxx, c_ids = torch.max(c_logits, -1, keepdim=True)
254
+
255
+ # Here we calculate the gradient of c_logits in place so we can save memory.
256
+ cross_entropy_kernel[(c_logits.shape[0],)](
257
+ logits=c_logits,
258
+ lse=c_lse,
259
+ target=c_target,
260
+ loss=c_loss,
261
+ total=total,
262
+ ignore_index=ignore_index,
263
+ label_smoothing=label_smoothing,
264
+ logit_scale=logit_scale,
265
+ reduction=reduction,
266
+ V=V,
267
+ BV=BV,
268
+ num_warps=STATIC_WARPS
269
+ )
270
+ if use_l2warp:
271
+ # a. Calculate the L2 gradient w.r.t logits (g_logits_l2)
272
+ g_logits_l2 = torch.zeros_like(c_logits)
273
+
274
+ # Normalize factor by B*T, which is the 'total' variable here
275
+ l2_factor = l2_penalty_factor / total if reduction == 'mean' else l2_penalty_factor
276
+ penalty_grad = c_maxx * l2_factor
277
+ g_logits_l2.scatter_(-1, c_ids, penalty_grad)
278
+
279
+ # b. Backpropagate g_logits_l2 to get its effect on dx, dw, db
280
+ # and add it to the main gradients.
281
+ # Total_dx = CE_dx + L2_dx
282
+ # Total_dw = CE_dw + L2_dw
283
+ # Total_db = CE_db + L2_db
284
+ if weight is not None:
285
+ dw.add_(g_logits_l2.t() @ c_x)
286
+ if bias is not None:
287
+ db.add_(g_logits_l2.sum(0))
288
+ # The dx contribution must be added to the final dx calculation
289
+ dx_l2_contribution = torch.mm(g_logits_l2, weight)
290
+ else:
291
+ dx_l2_contribution = 0.0
292
+
293
+ # gradient of logits is computed in-place by the above triton kernel and is of shape: C x V
294
+ # thus dx should be of shape: C x H
295
+ dx[start:end] = torch.mm(c_logits, weight) + dx_l2_contribution
296
+
297
+ # keep dw in fp32 to maintain precision
298
+ if weight is not None:
299
+ dw += c_logits.t() @ c_x
300
+
301
+ if bias is not None:
302
+ torch.add(input=db, other=c_logits.sum(0), out=db)
303
+
304
+ loss = loss.sum()
305
+ if dw is not None:
306
+ dw = dw.to(weight)
307
+ if db is not None:
308
+ db = db.to(bias)
309
+ return loss, dx, dw, db
310
+
311
+
312
+ def fused_linear_cross_entropy_backward(
313
+ do: torch.Tensor,
314
+ dx: torch.Tensor,
315
+ dw: torch.Tensor,
316
+ db: torch.Tensor
317
+ ):
318
+ # If cross entropy is the last layer, do is 1.0. Skip the mul to save time
319
+ if torch.ne(do, torch.tensor(1.0, device=do.device)):
320
+ # We use a Triton kernel instead of a PyTorch operation because modifying inputs in-place
321
+ # for gradient storage and backward multiple times causes anomalies with PyTorch but not with Triton.
322
+ N, H = dx.shape
323
+ B = min(MAX_FUSED_SIZE, triton.next_power_of_2(H))
324
+
325
+ elementwise_mul_kernel[(triton.cdiv(N * H, B),)](
326
+ x=dx,
327
+ g=do,
328
+ N=N*H,
329
+ B=B,
330
+ num_warps=STATIC_WARPS,
331
+ )
332
+
333
+ # handle dw
334
+ if dw is not None:
335
+ V, H = dw.shape
336
+ elementwise_mul_kernel[(triton.cdiv(V * H, B),)](
337
+ x=dw,
338
+ g=do,
339
+ N=V*H,
340
+ B=B,
341
+ num_warps=STATIC_WARPS,
342
+ )
343
+
344
+ if db is not None:
345
+ V = db.shape[0]
346
+ elementwise_mul_kernel[(triton.cdiv(V, B),)](
347
+ x=db,
348
+ g=do,
349
+ N=V,
350
+ B=B,
351
+ num_warps=STATIC_WARPS,
352
+ )
353
+ return dx, dw, db
354
+
355
+
356
+ class FusedLinearCrossEntropyFunction(torch.autograd.Function):
357
+
358
+ @staticmethod
359
+ @input_guard
360
+ def forward(
361
+ ctx,
362
+ x: torch.Tensor,
363
+ target: torch.LongTensor,
364
+ weight: torch.Tensor,
365
+ bias: torch.Tensor = None,
366
+ ignore_index: int = -100,
367
+ label_smoothing: float = 0.0,
368
+ logit_scale: float = 1.0,
369
+ num_chunks: int = 8,
370
+ reduction: str = "mean",
371
+ use_l2warp: bool = False,
372
+ l2_penalty_factor: float = 1e-4,
373
+ ):
374
+ """
375
+ Fusing the last linear layer with cross-entropy loss
376
+ Reference: https://github.com/mgmalek/efficient_cross_entropy
377
+
378
+ Handle the forward and backward pass of the final linear layer via cross-entropy loss by avoiding
379
+ the materialization of the large logits tensor. Since Cross Entropy Loss is the last layer, we can
380
+ compute the gradient at the forward pass. By doing so, we don't have to store the x and target
381
+ for the backward pass.
382
+
383
+ x (torch.Tensor): [batch_size * seq_len, hidden_size]
384
+ target (torch.LongTensor): [batch_size * seq_len]
385
+ where each value is in [0, vocab_size).
386
+ weight (torch.Tensor): [vocab_size, hidden_size]
387
+ where `vocab_size` is the number of classes.
388
+ bias (Optional[torch.Tensor]): [vocab_size]
389
+ where `vocab_size` is the number of classes.
390
+ ignore_index:
391
+ the index to ignore in the target.
392
+ label_smoothing:
393
+ the amount of smoothing when computing the loss, where 0.0 means no smoothing.
394
+ logit_scale: float = 1.0,
395
+ A scaling factor applied to the logits. Default: 1.0
396
+ num_chunks: int
397
+ The number of chunks to split the input tensor into for processing.
398
+ This can help optimize memory usage and computation speed.
399
+ Default: 8
400
+ reduction:
401
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
402
+ 'mean': the weighted mean of the output is taken,
403
+ 'sum': the output will be summed.
404
+ Default: 'mean'.
405
+ use_l2warp: bool = False,
406
+ Whether to use L2 regularization on the logits to prevent overconfidence.
407
+ Default: False
408
+ l2_penalty_factor: float = 1e-4,
409
+ """
410
+ loss, dx, dw, db = fused_linear_cross_entropy_forward(
411
+ x,
412
+ target,
413
+ weight,
414
+ bias,
415
+ ignore_index,
416
+ label_smoothing,
417
+ logit_scale,
418
+ num_chunks,
419
+ reduction,
420
+ use_l2warp,
421
+ l2_penalty_factor
422
+ )
423
+ # downcast to dtype and store for backward
424
+ ctx.save_for_backward(
425
+ dx.detach(),
426
+ dw.detach() if weight is not None else None,
427
+ db.detach() if bias is not None else None,
428
+ )
429
+ return loss
430
+
431
+ @staticmethod
432
+ @input_guard
433
+ def backward(ctx, do):
434
+ dx, dw, db = ctx.saved_tensors
435
+ dx, dw, db = fused_linear_cross_entropy_backward(do, dx, dw, db)
436
+ return dx, None, dw, db, None, None, None, None, None, None, None
437
+
438
+
439
+ def fused_linear_cross_entropy_loss(
440
+ x: torch.Tensor,
441
+ target: torch.LongTensor,
442
+ weight: torch.Tensor,
443
+ bias: torch.Tensor = None,
444
+ ignore_index: int = -100,
445
+ label_smoothing: float = 0.0,
446
+ logit_scale: float = 1.0,
447
+ num_chunks: int = 8,
448
+ reduction: str = "mean",
449
+ use_l2warp: bool = False,
450
+ l2_penalty_factor: float = 1e-4,
451
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
452
+ """
453
+ Args:
454
+ x (torch.Tensor): [batch_size * seq_len, hidden_size]
455
+ target (torch.LongTensor): [batch_size * seq_len]
456
+ where each value is in [0, vocab_size).
457
+ weight (torch.Tensor): [vocab_size, hidden_size]
458
+ where `vocab_size` is the number of classes.
459
+ bias (Optional[torch.Tensor]): [vocab_size]
460
+ where `vocab_size` is the number of classes.
461
+ ignore_index: int.
462
+ If target == ignore_index, the loss is set to 0.0.
463
+ label_smoothing: float
464
+ logit_scale: float
465
+ A scaling factor applied to the logits. Default: 1.0
466
+ num_chunks: int
467
+ The number of chunks to split the input tensor into for processing.
468
+ This can help optimize memory usage and computation speed.
469
+ Default: 8
470
+ reduction:
471
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
472
+ 'mean': the weighted mean of the output is taken,
473
+ 'sum': the output will be summed.
474
+ Default: 'mean'.
475
+ Returns:
476
+ losses: [batch,], float
477
+ """
478
+ return FusedLinearCrossEntropyFunction.apply(
479
+ x,
480
+ target,
481
+ weight,
482
+ bias,
483
+ ignore_index,
484
+ label_smoothing,
485
+ logit_scale,
486
+ num_chunks,
487
+ reduction,
488
+ use_l2warp,
489
+ l2_penalty_factor
490
+ )
491
+
492
+
493
+ class FusedLinearCrossEntropyLoss(nn.Module):
494
+
495
+ def __init__(
496
+ self,
497
+ ignore_index: int = -100,
498
+ label_smoothing: float = 0.0,
499
+ logit_scale: float = 1.0,
500
+ num_chunks: int = 8,
501
+ reduction: str = "mean",
502
+ use_l2warp: bool = False,
503
+ l2_penalty_factor: float = 1e-4,
504
+ ):
505
+ """
506
+ Args:
507
+ ignore_index: int.
508
+ If target == ignore_index, the loss is set to 0.0.
509
+ label_smoothing: float
510
+ logit_scale: float
511
+ A scaling factor applied to the logits. Default: 1.0
512
+ num_chunks: int
513
+ The number of chunks to split the input tensor into for processing.
514
+ This can help optimize memory usage and computation speed.
515
+ Default: 8
516
+ reduction:
517
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
518
+ 'mean': the weighted mean of the output is taken,
519
+ 'sum': the output will be summed.
520
+ Default: 'mean'.
521
+ """
522
+ super().__init__()
523
+
524
+ assert reduction in ["mean", "sum"], f"reduction: {reduction} is not supported"
525
+
526
+ self.ignore_index = ignore_index
527
+ self.label_smoothing = label_smoothing
528
+ self.logit_scale = logit_scale
529
+ self.num_chunks = num_chunks
530
+ self.reduction = reduction
531
+ self.use_l2warp = use_l2warp
532
+ self.l2_penalty_factor = l2_penalty_factor
533
+
534
+ @torch.compiler.disable
535
+ def forward(
536
+ self,
537
+ x: torch.Tensor,
538
+ target: torch.LongTensor,
539
+ weight: torch.Tensor,
540
+ bias: Optional[torch.Tensor] = None
541
+ ):
542
+ """
543
+ Args:
544
+ x (torch.Tensor): [batch_size, seq_len, hidden_size]
545
+ target (torch.LongTensor): [batch_size, seq_len]
546
+ where each value is in [0, V).
547
+ weight (torch.Tensor): [vocab_size, hidden_size]
548
+ where `vocab_size` is the number of classes.
549
+ bias (Optional[torch.Tensor]): [vocab_size]
550
+ where `vocab_size` is the number of classes.
551
+ Returns:
552
+ loss
553
+ """
554
+ loss = fused_linear_cross_entropy_loss(
555
+ x.view(-1, x.shape[-1]),
556
+ target.view(-1),
557
+ weight=weight,
558
+ bias=bias,
559
+ ignore_index=self.ignore_index,
560
+ label_smoothing=self.label_smoothing,
561
+ logit_scale=self.logit_scale,
562
+ num_chunks=self.num_chunks,
563
+ reduction=self.reduction,
564
+ use_l2warp=self.use_l2warp,
565
+ l2_penalty_factor=self.l2_penalty_factor
566
+ )
567
+ return loss
568
+
569
+
570
+ class LinearLossParallel(ParallelStyle):
571
+ def __init__(
572
+ self,
573
+ *,
574
+ sequence_dim: int = 1,
575
+ use_local_output: bool = False,
576
+ ):
577
+ super().__init__()
578
+
579
+ self.sequence_sharding = (Shard(sequence_dim),)
580
+ self.use_local_output = use_local_output
581
+
582
+ @staticmethod
583
+ def _prepare_input_fn(sequence_sharding, mod, inputs, device_mesh):
584
+ x, target, weight, bias = inputs
585
+
586
+ if not isinstance(x, DTensor):
587
+ # assume the input passed in already sharded on the sequence dim and create the DTensor
588
+ x = DTensor.from_local(x, device_mesh, sequence_sharding)
589
+ if x.placements != sequence_sharding:
590
+ x = x.redistribute(placements=sequence_sharding, async_op=True)
591
+ if not isinstance(target, DTensor):
592
+ target = DTensor.from_local(target, device_mesh, [Replicate()])
593
+ if target.placements != sequence_sharding:
594
+ target = target.redistribute(placements=sequence_sharding, async_op=True)
595
+
596
+ if not isinstance(weight, DTensor):
597
+ weight = DTensor.from_local(weight, device_mesh, [Replicate()])
598
+ if weight.placements != [Replicate()]:
599
+ # we replicate the weight/bias in FLCE
600
+ weight = weight.redistribute(placements=[Replicate()], async_op=True)
601
+
602
+ if bias is not None and not isinstance(bias, DTensor):
603
+ bias = DTensor.from_local(bias, device_mesh, [Replicate()])
604
+ if bias is not None and bias.placements != [Replicate()]:
605
+ bias = bias.redistribute(placements=[Replicate()], async_op=True)
606
+
607
+ return x.to_local(), target.to_local(), weight.to_local(), bias.to_local() if bias is not None else bias
608
+
609
+ @staticmethod
610
+ def _prepare_output_fn(use_local_output, mod, outputs, device_mesh):
611
+ return outputs.to_local() if use_local_output else outputs
612
+
613
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
614
+ return distribute_module(
615
+ module,
616
+ device_mesh,
617
+ partition_fn=None,
618
+ input_fn=partial(self._prepare_input_fn, self.sequence_sharding),
619
+ output_fn=partial(self._prepare_output_fn, self.use_local_output)
620
+ )