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,419 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright (c) 2023, Tri Dao.
4
+
5
+ from typing import Any, Tuple
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import triton
10
+ import triton.language as tl
11
+
12
+ from fla.ops.utils.op import exp, log
13
+ from fla.utils import input_guard
14
+
15
+ # `all_gather_into_tensor` and `reduce_scatter_tensor` are new placeholders for
16
+ # `_all_gather_base` and `_reduce_scatter_base`. They require the most recent
17
+ # version of PyTorch. The following 2 lines are for backward compatibility with
18
+ # older PyTorch.
19
+ if "all_gather_into_tensor" not in dir(torch.distributed):
20
+ torch.distributed.all_gather_into_tensor = torch.distributed._all_gather_base
21
+
22
+
23
+ @triton.heuristics({
24
+ "HAS_SMOOTHING": lambda args: args["label_smoothing"] > 0.0,
25
+ })
26
+ @triton.jit
27
+ def cross_entropy_fwd_kernel(
28
+ loss_ptr, # data ptrs
29
+ lse_ptr,
30
+ z_loss_ptr,
31
+ logits_ptr,
32
+ labels_ptr,
33
+ label_smoothing,
34
+ logit_scale,
35
+ lse_square_scale,
36
+ ignore_index,
37
+ total_classes,
38
+ class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes
39
+ n_cols, # shapes
40
+ n_rows,
41
+ logits_row_stride, # strides
42
+ BLOCK_SIZE: tl.constexpr,
43
+ HAS_SMOOTHING: tl.constexpr,
44
+ # if SPLIT (e.g. tensor parallel), don't include the LSE in the loss since it's not the final LSE
45
+ SPLIT: tl.constexpr,
46
+ ):
47
+ row_idx = tl.program_id(0)
48
+ col_block_idx = tl.program_id(1)
49
+ logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64)
50
+ col_offsets = col_block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
51
+ label_idx = tl.load(labels_ptr + row_idx)
52
+ logits = tl.load(logits_ptr + col_offsets, mask=col_offsets < n_cols, other=-float("inf"))
53
+ logits = logits.to(tl.float32) * logit_scale
54
+ max_logits = tl.max(logits, 0)
55
+ if HAS_SMOOTHING:
56
+ sum_logits = tl.sum(tl.where(col_offsets < n_cols, logits, 0.0), 0)
57
+ lse = log(tl.sum(exp(logits - max_logits), 0)) + max_logits
58
+ tl.store(lse_ptr + col_block_idx * n_rows + row_idx, lse)
59
+ if label_idx == ignore_index:
60
+ loss = 0.0
61
+ z_loss = 0.0
62
+ else:
63
+ label_idx -= class_start_idx
64
+ if label_idx >= col_block_idx * BLOCK_SIZE and label_idx < min(
65
+ n_cols, (col_block_idx + 1) * BLOCK_SIZE
66
+ ):
67
+ logits_label = tl.load(logits_ptr + label_idx) * logit_scale
68
+ if HAS_SMOOTHING:
69
+ loss = (
70
+ (lse if not SPLIT else 0.0)
71
+ - label_smoothing * sum_logits / total_classes
72
+ - (1 - label_smoothing) * logits_label
73
+ )
74
+ else:
75
+ loss = (lse if not SPLIT else 0.0) - logits_label
76
+ else:
77
+ # If label is out of bounds, we set the CE loss to 0.0. But we still want the label_smoothing loss
78
+ if HAS_SMOOTHING:
79
+ loss = label_smoothing * ((lse if not SPLIT else 0.0) - sum_logits / total_classes)
80
+ else:
81
+ loss = 0.0
82
+ if not SPLIT:
83
+ z_loss = lse_square_scale * lse * lse
84
+ loss += z_loss
85
+ else:
86
+ z_loss = 0.0
87
+ tl.store(loss_ptr + col_block_idx * n_rows + row_idx, loss)
88
+ if not SPLIT:
89
+ tl.store(z_loss_ptr + col_block_idx * n_rows + row_idx, z_loss)
90
+
91
+
92
+ @triton.heuristics({
93
+ "HAS_SMOOTHING": lambda args: args["label_smoothing"] > 0.0,
94
+ })
95
+ @triton.jit
96
+ def cross_entropy_bwd_kernel(
97
+ dlogits_ptr, # data ptrs
98
+ dloss_ptr,
99
+ logits_ptr,
100
+ lse_ptr,
101
+ labels_ptr,
102
+ label_smoothing,
103
+ logit_scale,
104
+ lse_square_scale,
105
+ ignore_index,
106
+ total_classes,
107
+ class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes
108
+ n_cols, # shapes
109
+ logits_row_stride, # strides
110
+ dlogits_row_stride,
111
+ dloss_row_stride,
112
+ BLOCK_SIZE: tl.constexpr,
113
+ HAS_SMOOTHING: tl.constexpr,
114
+ ):
115
+ row_idx = tl.program_id(0)
116
+ col_block_idx = tl.program_id(1)
117
+ logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64)
118
+ dlogits_ptr = dlogits_ptr + row_idx * dlogits_row_stride.to(tl.int64)
119
+ col_offsets = col_block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
120
+ label_idx = tl.load(labels_ptr + row_idx)
121
+ if label_idx != ignore_index:
122
+ dloss = tl.load(dloss_ptr + row_idx * dloss_row_stride)
123
+ else:
124
+ dloss = 0.0
125
+ logits = tl.load(logits_ptr + col_offsets, mask=col_offsets < n_cols, other=-float("inf")).to(
126
+ tl.float32
127
+ ) * logit_scale
128
+ lse = tl.load(lse_ptr + row_idx)
129
+ probs = exp(logits - lse)
130
+ probs += 2.0 * lse_square_scale * lse * probs
131
+ label_idx -= class_start_idx
132
+ if HAS_SMOOTHING:
133
+ smooth_negative = label_smoothing / total_classes
134
+ probs = tl.where(col_offsets == label_idx, probs - (1 - label_smoothing), probs) - smooth_negative
135
+ else:
136
+ probs = tl.where(col_offsets == label_idx, probs - 1.0, probs)
137
+ tl.store(dlogits_ptr + col_offsets, (dloss * logit_scale) * probs, mask=col_offsets < n_cols)
138
+
139
+
140
+ def fused_cross_entropy_forward(
141
+ logits: torch.Tensor,
142
+ target: torch.Tensor,
143
+ label_smoothing: float = 0.0,
144
+ logit_scale: float = 1.0,
145
+ lse_square_scale: float = 0.0,
146
+ ignore_index: int = -100,
147
+ process_group=None,
148
+ ):
149
+ n_rows, n_cols = logits.shape
150
+ assert target.shape == (n_rows,)
151
+ world_size = 1 if process_group is None else torch.distributed.get_world_size(process_group)
152
+ total_classes = world_size * n_cols
153
+ rank = 0 if process_group is None else torch.distributed.get_rank(process_group)
154
+ class_start_idx = rank * n_cols
155
+
156
+ if logits.stride(-1) != 1:
157
+ logits = logits.contiguous()
158
+ # Set these similar to https://github.com/openai/triton/blob/main/python/tutorials/02-fused-softmax.py
159
+ MAX_BLOCK_SIZE = 64 * 1024
160
+ BLOCK_SIZE = min(triton.next_power_of_2(n_cols), MAX_BLOCK_SIZE)
161
+ num_warps = (
162
+ 4
163
+ if BLOCK_SIZE < 2048
164
+ else (8 if BLOCK_SIZE < 8192 else (16 if BLOCK_SIZE < 128 * 1024 else 32))
165
+ )
166
+ # We may split the lse computation across multiple blocks, then do a reduction
167
+ # lse(local_lse) to get the final LSE. This is faster for large n_cols (e.g., > 64k)
168
+ # where having just one thread block processing more than 64k elements is slow.
169
+ split = world_size > 1 or n_cols > MAX_BLOCK_SIZE
170
+ n_splits = (n_cols + BLOCK_SIZE - 1) // BLOCK_SIZE
171
+ loss_shape = (n_splits, n_rows) if n_splits > 1 else (n_rows,)
172
+ losses = torch.empty(*loss_shape, dtype=torch.float, device=logits.device)
173
+ lse = torch.empty(*loss_shape, dtype=torch.float, device=logits.device)
174
+ z_losses = torch.empty(*loss_shape, dtype=torch.float, device=logits.device)
175
+
176
+ cross_entropy_fwd_kernel[(n_rows, n_splits)](
177
+ losses, # data ptrs
178
+ lse,
179
+ z_losses,
180
+ logits,
181
+ target,
182
+ label_smoothing,
183
+ logit_scale,
184
+ lse_square_scale,
185
+ ignore_index,
186
+ total_classes,
187
+ class_start_idx,
188
+ n_cols, # shapes
189
+ n_rows,
190
+ logits.stride(0), # strides
191
+ BLOCK_SIZE=BLOCK_SIZE, # constants
192
+ num_warps=num_warps,
193
+ SPLIT=split
194
+ )
195
+
196
+ if split:
197
+ # If there's no label_smoothing, if target are in the vocab of this partition, losses contains
198
+ # - predicted logit, and 0 otherwise.
199
+ # If there's label_smoothing=0.1, for target in the vocab of this partition, losses contains
200
+ # -0.9 * predicted logit - 0.1 * sum logit / total_classes.
201
+ # For target not in the vocab of this partition, losses contains
202
+ # -0.1 * sum logit / total_classes.
203
+ if n_splits > 1:
204
+ lse = torch.logsumexp(lse, dim=0)
205
+ losses = losses.sum(dim=0)
206
+ if world_size > 1:
207
+ lse_allgather = torch.empty(world_size, n_rows, dtype=lse.dtype, device=lse.device)
208
+ torch.distributed.all_gather_into_tensor(lse_allgather, lse, group=process_group)
209
+ handle_losses = torch.distributed.all_reduce(
210
+ losses, op=torch.distributed.ReduceOp.SUM, group=process_group, async_op=True
211
+ )
212
+ lse = torch.logsumexp(lse_allgather, dim=0)
213
+ handle_losses.wait()
214
+ # After the allreduce, if there's no label_smoothing, the total losses are - predicted_logit,
215
+ # we just have to add the (global) lse.
216
+ # If there's label_smoothing=0.1, the total losses are
217
+ # -0.9 * predicted_logit - 0.1 * sum logit / total_classes.
218
+ # Again, we just have to add the (global) lse.
219
+ losses += lse
220
+ if lse_square_scale != 0.0:
221
+ z_losses = lse_square_scale * lse.square()
222
+ z_losses.masked_fill_(target == ignore_index, 0.0)
223
+ losses += z_losses
224
+ else:
225
+ z_losses = torch.zeros_like(losses)
226
+ losses.masked_fill_(target == ignore_index, 0.0)
227
+
228
+ return losses, z_losses, lse, total_classes, class_start_idx
229
+
230
+
231
+ class CrossEntropyLossFunction(torch.autograd.Function):
232
+
233
+ @staticmethod
234
+ @input_guard
235
+ def forward(
236
+ ctx,
237
+ logits,
238
+ target,
239
+ label_smoothing=0.0,
240
+ logit_scale=1.0,
241
+ lse_square_scale=0.0,
242
+ ignore_index=-100,
243
+ inplace_backward=False,
244
+ process_group=None,
245
+ ):
246
+ losses, z_losses, lse, total_classes, class_start_idx = fused_cross_entropy_forward(
247
+ logits,
248
+ target,
249
+ label_smoothing,
250
+ logit_scale,
251
+ lse_square_scale,
252
+ ignore_index,
253
+ process_group,
254
+ )
255
+ ctx.save_for_backward(logits, lse, target)
256
+ ctx.mark_non_differentiable(z_losses)
257
+ ctx.label_smoothing = label_smoothing
258
+ ctx.logit_scale = logit_scale
259
+ ctx.lse_square_scale = lse_square_scale
260
+ ctx.ignore_index = ignore_index
261
+ ctx.total_classes = total_classes
262
+ ctx.class_start_idx = class_start_idx
263
+ ctx.inplace_backward = inplace_backward
264
+
265
+ return losses, z_losses
266
+
267
+ @staticmethod
268
+ @input_guard
269
+ def backward(ctx, grad_losses, grad_z_losses):
270
+ del grad_z_losses # z_losses are only for logging.
271
+
272
+ logits, lse, target = ctx.saved_tensors
273
+ dlogits = logits if ctx.inplace_backward else torch.empty_like(logits)
274
+ n_rows, n_cols = logits.shape
275
+ BLOCK_SIZE = min(triton.next_power_of_2(n_cols), 4 * 1024)
276
+ num_warps = 4 if BLOCK_SIZE < 2048 else (8 if BLOCK_SIZE < 8192 else 16)
277
+ def grid(META): return (n_rows, triton.cdiv(n_cols, META["BLOCK_SIZE"])) # noqa
278
+ cross_entropy_bwd_kernel[grid](
279
+ dlogits, # data ptrs
280
+ grad_losses,
281
+ logits,
282
+ lse,
283
+ target,
284
+ ctx.label_smoothing,
285
+ ctx.logit_scale,
286
+ ctx.lse_square_scale,
287
+ ctx.ignore_index,
288
+ ctx.total_classes,
289
+ ctx.class_start_idx,
290
+ n_cols, # shapes
291
+ logits.stride(0), # strides
292
+ dlogits.stride(0),
293
+ grad_losses.stride(0),
294
+ BLOCK_SIZE=BLOCK_SIZE, # constants
295
+ num_warps=num_warps,
296
+ )
297
+ return dlogits, None, None, None, None, None, None, None, None
298
+
299
+
300
+ def cross_entropy_loss(
301
+ logits: torch.Tensor,
302
+ target: torch.Tensor,
303
+ label_smoothing: float = 0.0,
304
+ logit_scale: float = 1.0,
305
+ lse_square_scale: float = 0.0,
306
+ ignore_index=-100,
307
+ inplace_backward: bool = False,
308
+ process_group=None,
309
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
310
+ """
311
+ Arguments:
312
+ logits: [batch, vocab_size]
313
+ target: [batch,]
314
+ label_smoothing: float
315
+ logit_scale: float.
316
+ Multiply logits by this scale before calculating the loss.
317
+ lse_square_scale: float.
318
+ If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss.
319
+ This is also referred to as "z-loss".
320
+ ignore_index: int.
321
+ If target == ignore_index, the loss is set to 0.0.
322
+ inplace_backward: bool.
323
+ If True, we do the backward pass in-place by modifying the logits.
324
+ This saves memory.
325
+ process_group:
326
+ if not None, we're doing Tensor Parallel: each process is responsible for
327
+ one part of the vocab. The loss will be aggregated across processes.
328
+ Returns:
329
+ losses: [batch,], float
330
+ z_losses: [batch,], float
331
+ """
332
+ return CrossEntropyLossFunction.apply(
333
+ logits,
334
+ target,
335
+ label_smoothing,
336
+ logit_scale,
337
+ lse_square_scale,
338
+ ignore_index,
339
+ inplace_backward,
340
+ process_group,
341
+ )
342
+
343
+
344
+ class FusedCrossEntropyLoss(nn.Module):
345
+ def __init__(
346
+ self,
347
+ ignore_index: int = -100,
348
+ reduction: str = "mean",
349
+ label_smoothing: float = 0.0,
350
+ logit_scale: float = 1.0,
351
+ lse_square_scale: float = 0.0,
352
+ inplace_backward: bool = False,
353
+ process_group: Any = None,
354
+ return_z_loss: bool = False,
355
+ ):
356
+ """
357
+ Arguments:
358
+ ignore_index: int. If target == ignore_index, the loss is set to 0.0.
359
+ label_smoothing: float
360
+ lse_square_scale: float. If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss.
361
+ This is also referred to as "z-loss".
362
+ inplace_backward: bool. If True, we do the backward pass in-place by modifying the logits.
363
+ This saves memory.
364
+ process_group: if not None, we're doing Tensor Parallel: each process is responsible for
365
+ one part of the vocab. The loss will be aggregated across processes.
366
+ return_z_loss: bool. If True, we return the component of the loss contributed by
367
+ the lse_square_scale value. This value is only for logging and does not support
368
+ backprop.
369
+ """
370
+ super().__init__()
371
+ if reduction not in ["mean", "none", "sum"]:
372
+ raise NotImplementedError("Only support reduction = 'mean' or 'none' or 'sum'")
373
+ self.ignore_index = ignore_index
374
+ self.reduction = reduction
375
+ self.label_smoothing = label_smoothing
376
+ self.logit_scale = logit_scale
377
+ self.lse_square_scale = lse_square_scale
378
+ self.inplace_backward = inplace_backward
379
+ self.process_group = process_group
380
+ self.return_z_loss = return_z_loss
381
+
382
+ def forward(self, input, target):
383
+ """
384
+ Arguments:
385
+ input: (batch, vocab_size)
386
+ target: (batch,)
387
+ Returns:
388
+ losses: (batch,) if reduction is 'none', else (1,), dtype float
389
+ z_loss: (batch,) if reduction is 'none', else (1,), dtype float (if self.return_z_loss)
390
+ """
391
+ assert input.is_cuda and target.is_cuda, "Only support CUDA tensors"
392
+ loss, z_loss = cross_entropy_loss(
393
+ input,
394
+ target,
395
+ label_smoothing=self.label_smoothing,
396
+ logit_scale=self.logit_scale,
397
+ lse_square_scale=self.lse_square_scale,
398
+ ignore_index=self.ignore_index,
399
+ inplace_backward=self.inplace_backward,
400
+ process_group=self.process_group,
401
+ )
402
+ if self.reduction == "mean":
403
+ loss = loss.sum() / (target != self.ignore_index).sum()
404
+ elif self.reduction == "sum":
405
+ loss = loss.sum()
406
+ else:
407
+ loss = loss
408
+
409
+ if not self.return_z_loss:
410
+ return loss
411
+
412
+ if self.reduction == "mean":
413
+ z_loss = z_loss.sum() / (target != self.ignore_index).sum()
414
+ elif self.reduction == "sum":
415
+ z_loss = z_loss.sum()
416
+ else:
417
+ z_loss = z_loss
418
+
419
+ return loss, z_loss