liger-kernel 0.6.0__py3-none-any.whl → 0.6.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.
@@ -13,6 +13,7 @@ class LigerFusedLinearDPOFunction(LigerFusedLinearPreferenceBase):
13
13
  ref_chosen_logps=None,
14
14
  ref_rejected_logps=None,
15
15
  beta=0.1,
16
+ loss_type="sigmoid",
16
17
  ):
17
18
  """
18
19
  Paper: https://arxiv.org/pdf/2305.18290
@@ -48,8 +49,50 @@ class LigerFusedLinearDPOFunction(LigerFusedLinearPreferenceBase):
48
49
  chosen_rewards = beta * chosen_logratios
49
50
  rejected_rewards = beta * rejected_logratios
50
51
 
51
- logits_diff = beta * (chosen_logratios - rejected_logratios)
52
- loss = -F.logsigmoid(logits_diff).sum() / (full_target.shape[0] // 2)
52
+ if loss_type == "sigmoid":
53
+ logits_diff = beta * (chosen_logratios - rejected_logratios)
54
+ loss = -F.logsigmoid(logits_diff).sum() / (full_target.shape[0] // 2)
55
+
56
+ elif loss_type == "apo_zero":
57
+ # Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266)
58
+ # Use this loss when you believe the chosen outputs are better than your model's default output
59
+ losses_chosen = 1 - F.sigmoid(beta * chosen_logratios) # Increase chosen likelihood
60
+ losses_rejected = F.sigmoid(beta * rejected_logratios)
61
+ losses = losses_chosen + losses_rejected
62
+ loss = losses.sum() / (full_target.shape[0] // 2)
63
+
64
+ elif loss_type == "apo_down":
65
+ # Eqn (8) of the APO paper (https://huggingface.co/papers/2408.06266)
66
+ # Use this loss when you believe the chosen outputs are worse than your model's default output.
67
+ # Decrease chosen likelihood and decrease rejected likelihood more
68
+ losses_chosen = F.sigmoid(beta * chosen_logratios)
69
+ losses_rejected = 1 - F.sigmoid(beta * (chosen_logratios - rejected_logratios))
70
+ losses = losses_chosen + losses_rejected
71
+ loss = losses.sum() / (full_target.shape[0] // 2)
72
+
73
+ elif loss_type == "sppo_hard":
74
+ # In the paper (https://huggingface.co/papers/2405.00675), SPPO employs a soft probability approach,
75
+ # estimated using the PairRM score. The probability calculation is conducted outside of the trainer class.
76
+ # The version described here is the hard probability version, where P in Equation (4.7) of Algorithm 1 is
77
+ # set to 1 for the winner and 0 for the loser.
78
+ a = chosen_logps - ref_chosen_logps
79
+ b = rejected_logps - ref_rejected_logps
80
+ losses = (a - 0.5 / beta) ** 2 + (b + 0.5 / beta) ** 2
81
+ loss = losses.sum() / (full_target.shape[0] // 2)
82
+
83
+ elif loss_type == "nca_pair":
84
+ losses = (
85
+ -F.logsigmoid(chosen_rewards)
86
+ - 0.5 * F.logsigmoid(-chosen_rewards)
87
+ - 0.5 * F.logsigmoid(-rejected_rewards)
88
+ )
89
+ loss = losses.sum() / (full_target.shape[0] // 2)
90
+
91
+ else:
92
+ raise ValueError(
93
+ f"Unsupported loss_type: {loss_type}. Supported types are: sigmoid, apo_zero, apo_down, sppo_hard, nca_pair"
94
+ )
95
+
53
96
  return loss, chosen_rewards, rejected_rewards
54
97
 
55
98
  @classmethod
@@ -70,6 +113,7 @@ class LigerFusedLinearDPOFunction(LigerFusedLinearPreferenceBase):
70
113
  use_ref_model=True,
71
114
  average_log_prob=False,
72
115
  chunk_size=1,
116
+ loss_type="sigmoid",
73
117
  ):
74
118
  """
75
119
  Fused linear layer with DPO loss.
@@ -108,12 +152,13 @@ class LigerFusedLinearDPOFunction(LigerFusedLinearPreferenceBase):
108
152
  ref_bias=ref_bias,
109
153
  average_log_prob=average_log_prob,
110
154
  chunk_size=chunk_size,
155
+ loss_type=loss_type,
111
156
  )
112
157
 
113
158
  @staticmethod
114
159
  def backward(ctx, *grad_output):
115
160
  grads = LigerFusedLinearPreferenceBase.backward(ctx, grad_output)[:4]
116
- return *grads, None, None, None, None, None, None, None, None, None, None
161
+ return *grads, None, None, None, None, None, None, None, None, None, None, None
117
162
 
118
163
 
119
164
  class LigerFusedLinearDPOLoss(torch.nn.Module):
@@ -130,6 +175,7 @@ class LigerFusedLinearDPOLoss(torch.nn.Module):
130
175
  use_ref_model: bool = True,
131
176
  average_log_prob: bool = False,
132
177
  chunk_size: int = 1,
178
+ loss_type: str = "sigmoid",
133
179
  ):
134
180
  """
135
181
  Args:
@@ -149,6 +195,10 @@ class LigerFusedLinearDPOLoss(torch.nn.Module):
149
195
  self.use_ref_model = use_ref_model
150
196
  self.average_log_prob = average_log_prob
151
197
  self.chunk_size = chunk_size
198
+ self.loss_type = loss_type
199
+ supported_loss_types = {"sigmoid", "apo_zero", "apo_down", "sppo_hard", "nca_pair"}
200
+ if self.loss_type not in supported_loss_types:
201
+ raise ValueError(f"Unsupported loss_type: {self.loss_type}. Supported types are: {supported_loss_types}")
152
202
 
153
203
  def forward(
154
204
  self,
@@ -175,4 +225,5 @@ class LigerFusedLinearDPOLoss(torch.nn.Module):
175
225
  self.use_ref_model,
176
226
  self.average_log_prob,
177
227
  self.chunk_size,
228
+ self.loss_type,
178
229
  )
@@ -0,0 +1,412 @@
1
+ import math
2
+ import operator
3
+
4
+ import torch
5
+ import triton
6
+ import triton.language as tl
7
+
8
+ from liger_kernel.ops.utils import calculate_settings
9
+ from liger_kernel.ops.utils import compare_version
10
+ from liger_kernel.ops.utils import ensure_contiguous
11
+ from liger_kernel.ops.utils import torch_to_triton_dtype
12
+
13
+ if compare_version("triton", operator.ge, "3.0.0"):
14
+ try:
15
+ # typical import path with dispatch available
16
+ from triton.language.extra.libdevice import rsqrt
17
+ except ModuleNotFoundError:
18
+ # for working with NGC containers
19
+ from triton.language.extra.cuda.libdevice import rsqrt
20
+ else:
21
+ from triton.language.math import rsqrt
22
+
23
+
24
+ _CASTING_MODE_NONE: tl.constexpr = tl.constexpr(-1)
25
+ _CASTING_MODE_LLAMA: tl.constexpr = tl.constexpr(0)
26
+ _CASTING_MODE_GEMMA: tl.constexpr = tl.constexpr(1)
27
+
28
+
29
+ @triton.jit
30
+ def _fused_add_rms_norm_forward_kernel(
31
+ Y_ptr,
32
+ Y_row_stride,
33
+ S_ptr, # output residual
34
+ S_row_stride,
35
+ X_ptr,
36
+ X_row_stride,
37
+ R_ptr, # input residual
38
+ R_row_stride,
39
+ W_ptr,
40
+ W_row_stride,
41
+ RSTD_ptr,
42
+ RSTD_row_stride,
43
+ n_cols,
44
+ eps,
45
+ offset,
46
+ casting_mode: tl.constexpr, # constexpr so the `if` blocks can be optimized out
47
+ BLOCK_SIZE: tl.constexpr,
48
+ ):
49
+ """
50
+ This kernel computes the following:
51
+ 1. hidden_states = residual + hidden_states
52
+ 2. residual = hidden_states
53
+ 3. hidden_states = rmsnorm(hidden_states)
54
+
55
+ This is a commonly used pattern in the decoder layers of LLMs.
56
+ Some examples:
57
+ 1. https://github.com/huggingface/transformers/blob/0dc2df5ddafe3cb5824ad24e85beba13e0aa6726/src/transformers/models/qwen3/modeling_qwen3.py#L271
58
+ 2. https://github.com/huggingface/transformers/blob/0dc2df5ddafe3cb5824ad24e85beba13e0aa6726/src/transformers/models/llama4/modeling_llama4.py#L393
59
+
60
+ This kernel is inspired by the rms_norm forward kernel, and is adapted to support the residual addition in the forward pass.
61
+ The backward pass is also adapted to support the residual addition in the backward pass.
62
+ """
63
+
64
+ row_idx = tl.program_id(0).to(tl.int64)
65
+ col_offsets = tl.arange(0, BLOCK_SIZE)
66
+ mask = col_offsets < n_cols
67
+
68
+ Y_ptr += row_idx * Y_row_stride
69
+ S_ptr += row_idx * S_row_stride
70
+ X_ptr += row_idx * X_row_stride
71
+ R_ptr += row_idx * R_row_stride
72
+ RSTD_ptr += row_idx * RSTD_row_stride
73
+
74
+ X_row = tl.load(X_ptr + col_offsets, mask=mask, other=0)
75
+ R_row = tl.load(R_ptr + col_offsets, mask=mask, other=0)
76
+ S_row = X_row + R_row
77
+ tl.store(S_ptr + col_offsets, S_row, mask=mask)
78
+ S_row_dtype = S_row.dtype
79
+ W_row = tl.load(W_ptr + col_offsets, mask=mask, other=0)
80
+
81
+ # On Llama, only rstd is computed on fp32
82
+ if casting_mode == _CASTING_MODE_LLAMA:
83
+ S_row = S_row.to(tl.float32)
84
+
85
+ # Gemma computes everything on fp32, and then casts back the output to the original dtype
86
+ if casting_mode == _CASTING_MODE_GEMMA:
87
+ W_row = W_row.to(tl.float32)
88
+ S_row = S_row.to(tl.float32)
89
+
90
+ if casting_mode == _CASTING_MODE_NONE:
91
+ eps = eps.to(S_row_dtype)
92
+ offset = offset.to(S_row_dtype)
93
+
94
+ mean_square = tl.sum(S_row * S_row, axis=0) / n_cols
95
+ rstd = rsqrt(mean_square + eps)
96
+
97
+ # We can save time by caching rms with minimal memory overhead
98
+ # because rms is much smaller compared to X_row, as rms is for each row.
99
+ # However, on the computation side, it can save 4 operations (*, sum, /, sqrt).
100
+ tl.store(RSTD_ptr, rstd)
101
+
102
+ S_row = S_row * rstd
103
+
104
+ # On Llama, the multiplication with the weight is done on the original dtype
105
+ if casting_mode == _CASTING_MODE_LLAMA:
106
+ S_row = S_row.to(S_row_dtype)
107
+
108
+ Y_row = S_row * (offset + W_row)
109
+
110
+ if casting_mode == _CASTING_MODE_GEMMA:
111
+ Y_row = Y_row.to(S_row_dtype)
112
+
113
+ tl.store(Y_ptr + col_offsets, Y_row, mask=mask)
114
+
115
+
116
+ @triton.jit
117
+ def _fused_add_rms_norm_backward_kernel(
118
+ dY_ptr,
119
+ dY_row_stride,
120
+ dS_out_ptr,
121
+ dS_out_row_stride,
122
+ dX_ptr,
123
+ dX_row_stride,
124
+ X_ptr,
125
+ X_row_stride,
126
+ X_dtype: tl.constexpr,
127
+ W_ptr,
128
+ W_row_stride,
129
+ RSTD_ptr,
130
+ RSTD_row_stride,
131
+ dW_ptr,
132
+ dW_row_stride,
133
+ n_rows,
134
+ n_cols,
135
+ offset,
136
+ rows_per_program: tl.constexpr,
137
+ casting_mode: tl.constexpr,
138
+ BLOCK_SIZE: tl.constexpr,
139
+ has_dS_out: tl.constexpr,
140
+ ):
141
+ """
142
+ This kernel is adapted from the rms_norm backward kernel, and is adapted to support the residual
143
+ addition in the backward pass. For the following code pattern:
144
+ 1. hidden_states = residual + hidden_states
145
+ 2. residual = hidden_states
146
+ 3. hidden_states = rmsnorm(hidden_states)
147
+
148
+ The gradient of hidden_states and residual comes out be exactly same. The value of this gradient is
149
+ the sum of the gradient of the hidden_states in step 3 and the gradient of the residual in step 2.
150
+
151
+ The backward pass computation logic is same as the rms_norm backward kernel, except that the gradient
152
+ of the hidden_states in step 3 and the gradient of the residual in step 2 are summed up.
153
+ """
154
+
155
+ row_block_id = tl.program_id(0).to(tl.int64)
156
+ row_start = row_block_id * rows_per_program
157
+ row_end = min((row_block_id + 1) * rows_per_program, n_rows)
158
+ col_offsets = tl.arange(0, BLOCK_SIZE)
159
+ mask = col_offsets < n_cols
160
+
161
+ dW_row = tl.zeros((BLOCK_SIZE,), dtype=tl.float32)
162
+
163
+ dY_ptr += row_start * dY_row_stride
164
+ dX_ptr += row_start * dX_row_stride
165
+ if has_dS_out:
166
+ dS_out_ptr += row_start * dS_out_row_stride
167
+
168
+ X_ptr += row_start * X_row_stride
169
+ RSTD_ptr += row_start
170
+
171
+ W_row = tl.load(W_ptr + col_offsets, mask=mask, other=0.0)
172
+ W_row = W_row + offset
173
+
174
+ for _ in range(row_start, row_end):
175
+ dY_row = tl.load(dY_ptr + col_offsets, mask=mask, other=0.0)
176
+ X_row = tl.load(X_ptr + col_offsets, mask=mask, other=0.0)
177
+
178
+ # Get cached rms
179
+ rstd_row = tl.load(RSTD_ptr)
180
+
181
+ X_row = X_row.to(tl.float32)
182
+
183
+ # Different bacward graphs for different casting modes
184
+ if casting_mode == _CASTING_MODE_LLAMA:
185
+ m = (dY_row * W_row).to(tl.float32)
186
+
187
+ elif casting_mode == _CASTING_MODE_GEMMA:
188
+ dY_row = dY_row.to(tl.float32)
189
+ m = dY_row * W_row
190
+ else:
191
+ m = dY_row * W_row
192
+
193
+ dX_row = rstd_row * m
194
+
195
+ if has_dS_out:
196
+ dS_out_row = tl.load(dS_out_ptr + col_offsets, mask=mask, other=0.0)
197
+ dX_row += (rstd_row) * (
198
+ -(1 / n_cols) * rstd_row * rstd_row * tl.sum(m * X_row, axis=0) * X_row
199
+ ) + dS_out_row
200
+ dS_out_ptr += dS_out_row_stride
201
+ else:
202
+ dX_row += (rstd_row) * (-(1 / n_cols) * rstd_row * rstd_row * tl.sum(m * X_row, axis=0) * X_row)
203
+
204
+ # calculate the gradient of W
205
+ if casting_mode == _CASTING_MODE_LLAMA:
206
+ dW_row += dY_row * (X_row * rstd_row).to(X_dtype)
207
+ else:
208
+ # here X_row is already in fp32 (see previous if block)
209
+ dW_row += dY_row * (X_row * rstd_row)
210
+
211
+ tl.store(dX_ptr + col_offsets, dX_row.to(X_dtype), mask=mask)
212
+
213
+ dY_ptr += dY_row_stride
214
+ dX_ptr += dX_row_stride
215
+ X_ptr += X_row_stride
216
+ RSTD_ptr += RSTD_row_stride
217
+
218
+ tl.store(dW_ptr + row_block_id * dW_row_stride + col_offsets, dW_row, mask=mask)
219
+
220
+
221
+ _str_to_casting_mode = {
222
+ "llama": _CASTING_MODE_LLAMA.value,
223
+ "gemma": _CASTING_MODE_GEMMA.value,
224
+ "none": _CASTING_MODE_NONE.value,
225
+ }
226
+
227
+
228
+ def fused_add_rms_norm_forward(X, R, W, eps, offset, casting_mode):
229
+ if not isinstance(casting_mode, int):
230
+ assert casting_mode in _str_to_casting_mode, f"Invalid casting mode: {casting_mode}"
231
+ casting_mode = _str_to_casting_mode[casting_mode]
232
+ else:
233
+ assert casting_mode in _str_to_casting_mode.values(), f"Invalid casting mode: {casting_mode}"
234
+
235
+ shape = X.shape
236
+ dim = shape[-1]
237
+ X = X.view(-1, dim)
238
+ R = R.view(-1, dim)
239
+ n_rows, n_cols = X.shape
240
+ BLOCK_SIZE, num_warps = calculate_settings(n_cols)
241
+
242
+ Y = torch.empty((n_rows, n_cols), dtype=X.dtype, device=X.device)
243
+ S = torch.empty((n_rows, n_cols), dtype=X.dtype, device=X.device)
244
+ # RSTD is to cache rstd for each row
245
+ # RSTD is always computed/stored in fp32 if we are using Llama or Gemma casting mode
246
+ rstd_dtype = torch.float32 if casting_mode in (_CASTING_MODE_LLAMA.value, _CASTING_MODE_GEMMA.value) else X.dtype
247
+ RSTD = torch.empty(n_rows, dtype=rstd_dtype, device=X.device)
248
+
249
+ # Check constraints.
250
+ assert X.shape[1] == W.shape[0], "Incompatible hidden size dimension between tensor1.shape[1] and tensor2.shape[0]"
251
+
252
+ # XPU-specific optimization
253
+ kernel_args = {}
254
+ if X.device.type == "xpu":
255
+ kernel_args["grf_mode"] = "large"
256
+
257
+ # TODO: add _block_fused_add_rms_norm_forward_kernel
258
+ _fused_add_rms_norm_forward_kernel[(n_rows,)](
259
+ Y,
260
+ Y.stride(0),
261
+ S,
262
+ S.stride(0),
263
+ X,
264
+ X.stride(0),
265
+ R,
266
+ R.stride(0),
267
+ W,
268
+ W.stride(0),
269
+ RSTD,
270
+ RSTD.stride(0),
271
+ n_cols,
272
+ eps,
273
+ offset,
274
+ casting_mode,
275
+ BLOCK_SIZE=BLOCK_SIZE,
276
+ num_warps=num_warps,
277
+ **kernel_args, # XPU-specific optimization
278
+ )
279
+
280
+ return Y.view(*shape), S.view(*shape), RSTD, BLOCK_SIZE, num_warps, casting_mode
281
+
282
+
283
+ def fused_add_rms_norm_backward(dY, dS_out, S, W, RSTD, offset, casting_mode, BLOCK_SIZE, num_warps, in_place):
284
+ shape = dY.shape
285
+ dim = shape[-1]
286
+ dY = dY.view(-1, dim)
287
+ dS_out = dS_out.view(-1, dim)
288
+ S = S.view(-1, dim)
289
+ n_rows, n_cols = dY.shape
290
+
291
+ sm_count = 1
292
+ if S.device.type == "cuda":
293
+ sm_count = torch.cuda.get_device_properties(S.device).multi_processor_count
294
+ elif S.device.type == "xpu":
295
+ sm_count = torch.xpu.get_device_properties(S.device).gpu_eu_count
296
+
297
+ # fp32 for numerical stability especially.
298
+ _dW = torch.empty((sm_count, n_cols), dtype=torch.float32, device=W.device)
299
+
300
+ if n_cols > BLOCK_SIZE:
301
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
302
+ rows_per_program = math.ceil(n_rows / sm_count)
303
+ grid = (sm_count,)
304
+
305
+ if in_place is True:
306
+ dX = dY
307
+ else:
308
+ dX = torch.empty_like(dY)
309
+
310
+ # XPU-specific optimization
311
+ kernel_args = {}
312
+ if S.device.type == "xpu":
313
+ kernel_args["grf_mode"] = "large"
314
+
315
+ # TODO: add _block_fused_add_rms_norm_backward_kernel
316
+ _fused_add_rms_norm_backward_kernel[grid](
317
+ dY,
318
+ dY.stride(0),
319
+ dS_out,
320
+ dS_out.stride(0),
321
+ dX,
322
+ dX.stride(0),
323
+ S,
324
+ S.stride(0),
325
+ torch_to_triton_dtype[S.dtype],
326
+ W,
327
+ W.stride(0),
328
+ RSTD,
329
+ RSTD.stride(0),
330
+ _dW,
331
+ _dW.stride(0),
332
+ n_rows,
333
+ n_cols,
334
+ offset,
335
+ rows_per_program,
336
+ casting_mode,
337
+ BLOCK_SIZE=BLOCK_SIZE,
338
+ num_warps=num_warps,
339
+ has_dS_out=dS_out is not None,
340
+ **kernel_args, # XPU-specific optimization
341
+ )
342
+
343
+ dX = dX.view(*shape)
344
+ dW = _dW.sum(dim=0).to(W.dtype)
345
+
346
+ return dX, dX, dW # dR is equal to dX
347
+
348
+
349
+ class LigerFusedAddRMSNormFunction(torch.autograd.Function):
350
+ """
351
+ Performs a fused operation that first adds a residual tensor to the hidden_states tensor (`X`), then applies RMSNorm (Root Mean Square Normalization) to the result using the weight tensor `W`, with optional offset and casting mode.
352
+
353
+ This class implements the following sequence, commonly used in transformer decoder layers:
354
+ 1. hidden_states = residual + hidden_states
355
+ 2. residual = hidden_states (after addition)
356
+ 3. hidden_states = rmsnorm(hidden_states)
357
+
358
+ Both the normalized hidden_states and the updated residual are returned as outputs.
359
+
360
+ Some models use an 'offset' to shift the weight tensor `W` by a constant value. For example, Gemma
361
+ uses an offset of 1.0, so the computation becomes `(X / RMS(X)) * (W + 1.0)` instead of the usual
362
+ `(X / RMS(X)) * W`. You can pass the offset value as an argument to the forward function.
363
+
364
+ In addition, different models cast their inputs at different places during RMSNorm computation. For
365
+ example, Gemma casts everything to fp32 before starting the computation, while Llama casts only the
366
+ inverse RMS to fp32. You can specify the casting mode using the `casting_mode` argument. We currently
367
+ support the following casting modes (they match HuggingFace Transformers' implementations):
368
+ - 'llama': matches the Llama implementation, where only the inverse RMS is computed on fp32.
369
+ - 'gemma': matches the Gemma implementation, where everything is cast to fp32, then computed, then cast back to the original dtype.
370
+ - 'none': no casting is done. The computation is done in the original dtype. This saves memory and is slightly faster, but has more error w.r.t. the original implementation.
371
+
372
+ The `in_place` option determines whether to modify dY in-place to store dX. This defaults to `True` to save memory.
373
+ """
374
+
375
+ @staticmethod
376
+ @ensure_contiguous
377
+ def forward(ctx, X, R, W, eps, offset=0.0, casting_mode="llama", in_place=False):
378
+ """
379
+ X: (B, T, H) or (BxT, H)
380
+ W: (H,)
381
+ """
382
+ # TODO: add row_mode
383
+ Y, S, RSTD, BLOCK_SIZE, num_warps, casting_mode = fused_add_rms_norm_forward(X, R, W, eps, offset, casting_mode)
384
+ ctx.offset = offset
385
+ ctx.casting_mode = casting_mode
386
+ ctx.in_place = in_place
387
+ ctx.BLOCK_SIZE = BLOCK_SIZE
388
+ ctx.num_warps = num_warps
389
+ ctx.save_for_backward(S, W, RSTD)
390
+ return Y, S
391
+
392
+ @staticmethod
393
+ @ensure_contiguous
394
+ def backward(ctx, dY, dS_out):
395
+ """
396
+ Y: (B, T, H) or (BxT, H)
397
+ """
398
+ S, W, RSTD = ctx.saved_tensors
399
+ dX, dR, dW = fused_add_rms_norm_backward(
400
+ dY,
401
+ dS_out,
402
+ S,
403
+ W,
404
+ RSTD,
405
+ ctx.offset,
406
+ ctx.casting_mode,
407
+ ctx.BLOCK_SIZE,
408
+ ctx.num_warps,
409
+ ctx.in_place,
410
+ )
411
+
412
+ return dX, dR, dW, None, None, None, None, None
@@ -25,6 +25,7 @@ def fused_linear_cross_entropy_forward(
25
25
  reduction="mean",
26
26
  softcap=None,
27
27
  return_z_loss=False,
28
+ accum_dtype=None,
28
29
  ):
29
30
  assert isinstance(return_z_loss, bool), f"return_z_loss must be True or False. Got: {return_z_loss}"
30
31
  device = _input.device
@@ -44,10 +45,16 @@ def fused_linear_cross_entropy_forward(
44
45
  chunk_size = triton.next_power_of_2(triton.cdiv(BT, inc_factor)) # (BT + inc_factor - 1) // inc_factor
45
46
  num_chunks = triton.cdiv(BT, chunk_size) # (BT + chunk_size - 1) // chunk_size
46
47
 
47
- grad_weight = torch.zeros_like(weight, device=device) if weight.requires_grad else None
48
48
  grad_input = torch.zeros_like(_input, device=device)
49
- grad_bias = torch.zeros_like(bias, device=device) if bias is not None else None
50
- # we use fp32 for loss accumulator
49
+
50
+ # we use fp32 for loss and gradients accumulator
51
+ if accum_dtype is None:
52
+ grad_weight = torch.zeros_like(weight, device=device) if weight.requires_grad else None
53
+ grad_bias = torch.zeros_like(bias, device=device) if bias is not None else None
54
+ else:
55
+ grad_weight = torch.zeros_like(weight, dtype=accum_dtype, device=device) if weight.requires_grad else None
56
+ grad_bias = torch.zeros_like(bias, dtype=accum_dtype, device=device) if bias is not None else None
57
+
51
58
  loss_1d = torch.zeros(BT, dtype=torch.float32, device=device)
52
59
  z_loss_1d = torch.zeros(BT, dtype=_input.dtype, device=_input.device) if return_z_loss else None
53
60
 
@@ -124,16 +131,7 @@ def fused_linear_cross_entropy_forward(
124
131
  grad_input[start_idx:end_idx] = grad_logits_chunk @ weight
125
132
 
126
133
  if grad_weight is not None:
127
- torch.addmm(
128
- input=grad_weight,
129
- mat1=logits_chunk.t().to(
130
- _input_chunk.dtype
131
- ), # In an autocast scenario without bias, differing logits_chunk data types will cause an addmm operation error.
132
- mat2=_input_chunk,
133
- out=grad_weight,
134
- alpha=1.0,
135
- beta=1.0,
136
- )
134
+ grad_weight += torch.mm(grad_logits_chunk.t(), _input_chunk).float()
137
135
 
138
136
  if bias is not None:
139
137
  torch.add(
@@ -151,6 +149,11 @@ def fused_linear_cross_entropy_forward(
151
149
  else:
152
150
  loss = torch.sum(loss_1d)
153
151
  z_loss = torch.sum(z_loss_1d) if return_z_loss else None
152
+
153
+ # Cast back to original dtype
154
+ grad_weight = grad_weight.to(weight.dtype) if grad_weight is not None else None
155
+ grad_bias = grad_bias.to(bias.dtype) if grad_bias is not None else None
156
+
154
157
  return loss, z_loss, grad_input, grad_weight, grad_bias
155
158
 
156
159
 
@@ -217,6 +220,7 @@ class LigerFusedLinearCrossEntropyFunction(torch.autograd.Function):
217
220
  reduction="mean",
218
221
  softcap=None,
219
222
  return_z_loss: bool = False,
223
+ accum_dtype=None,
220
224
  ):
221
225
  """
222
226
  Fusing the last linear layer with cross-entropy loss
@@ -235,6 +239,8 @@ class LigerFusedLinearCrossEntropyFunction(torch.autograd.Function):
235
239
  ignore_index: the index to ignore in the target
236
240
  label_smoothing (float): The amount of smoothing when computing the loss, where 0.0 means no smoothing.
237
241
  reduction: reduction to apply
242
+ accum_dtype (torch.dtype): the dtype of intermediate result buffers for weight and bias gradient accumulations.
243
+ Recommended to set `accum_dtype` to higher precision, e.g. `torch.float32`, if the training is unstable with original dtype. Default: `None`, performing accumulations in original dtype
238
244
  """
239
245
 
240
246
  loss, z_loss, grad_input, grad_weight, grad_bias = fused_linear_cross_entropy_forward(
@@ -249,6 +255,7 @@ class LigerFusedLinearCrossEntropyFunction(torch.autograd.Function):
249
255
  reduction=reduction,
250
256
  softcap=softcap,
251
257
  return_z_loss=return_z_loss,
258
+ accum_dtype=accum_dtype,
252
259
  )
253
260
  # downcast to dtype and store for backward
254
261
  ctx.save_for_backward(
@@ -280,4 +287,5 @@ class LigerFusedLinearCrossEntropyFunction(torch.autograd.Function):
280
287
  None,
281
288
  None,
282
289
  None,
290
+ None,
283
291
  )