liger-kernel-nightly 0.5.4.dev20250227064037__py3-none-any.whl → 0.5.4.dev20250304205249__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.

Potentially problematic release.


This version of liger-kernel-nightly might be problematic. Click here for more details.

@@ -39,8 +39,9 @@ class LigerFusedLinearCPOFunction(LigerFusedLinearPreferenceBase):
39
39
 
40
40
  return loss, chosen_rewards, rejected_rewards
41
41
 
42
- @staticmethod
42
+ @classmethod
43
43
  def forward(
44
+ cls,
44
45
  ctx,
45
46
  _input,
46
47
  weight,
@@ -53,13 +54,13 @@ class LigerFusedLinearCPOFunction(LigerFusedLinearPreferenceBase):
53
54
  compute_nll_loss=True,
54
55
  compiled=True,
55
56
  ):
56
- return LigerFusedLinearPreferenceBase.forward(
57
- ctx,
58
- _input,
59
- weight,
60
- target,
61
- bias,
62
- loss_fn=LigerFusedLinearCPOFunction.preference_loss_fn,
57
+ return super().forward(
58
+ cls=cls,
59
+ ctx=ctx,
60
+ _input=_input,
61
+ weight=weight,
62
+ target=target,
63
+ bias=bias,
63
64
  ignore_index=ignore_index,
64
65
  alpha=alpha,
65
66
  beta=beta,
@@ -52,8 +52,9 @@ class LigerFusedLinearDPOFunction(LigerFusedLinearPreferenceBase):
52
52
  loss = -F.logsigmoid(logits_diff).sum() / (full_target.shape[0] // 2)
53
53
  return loss, chosen_rewards, rejected_rewards
54
54
 
55
- @staticmethod
55
+ @classmethod
56
56
  def forward(
57
+ cls,
57
58
  ctx,
58
59
  _input,
59
60
  weight,
@@ -68,13 +69,13 @@ class LigerFusedLinearDPOFunction(LigerFusedLinearPreferenceBase):
68
69
  compiled=True,
69
70
  use_ref_model=True,
70
71
  ):
71
- return LigerFusedLinearPreferenceBase.forward(
72
+ return super().forward(
73
+ cls=cls,
72
74
  ctx=ctx,
73
75
  _input=_input,
74
76
  weight=weight,
75
77
  target=target,
76
78
  bias=bias,
77
- loss_fn=LigerFusedLinearDPOFunction.preference_loss_fn,
78
79
  ignore_index=ignore_index,
79
80
  beta=beta,
80
81
  compute_nll_loss=compute_nll_loss,
@@ -125,6 +125,7 @@ class LigerFusedLinearDistillationBase(torch.autograd.Function):
125
125
 
126
126
  @staticmethod
127
127
  def forward(
128
+ cls,
128
129
  ctx,
129
130
  student_input,
130
131
  student_weight,
@@ -133,7 +134,6 @@ class LigerFusedLinearDistillationBase(torch.autograd.Function):
133
134
  target,
134
135
  student_bias=None,
135
136
  teacher_bias=None,
136
- loss_fn=None,
137
137
  chunk_size=1024,
138
138
  ignore_index=-100,
139
139
  weight_hard_loss=0.5,
@@ -175,7 +175,7 @@ class LigerFusedLinearDistillationBase(torch.autograd.Function):
175
175
 
176
176
  loss_func_to_call = partial(
177
177
  LigerFusedLinearDistillationBase._compute_loss,
178
- distillation_loss_fn=loss_fn,
178
+ distillation_loss_fn=cls.distillation_loss_fn,
179
179
  full_target=target,
180
180
  ignore_index=ignore_index,
181
181
  weight_hard_loss=weight_hard_loss,
@@ -263,4 +263,4 @@ class LigerFusedLinearDistillationBase(torch.autograd.Function):
263
263
  grad_weight = grad_weight * grad_output
264
264
  grad_bias = grad_bias * grad_output if grad_bias is not None else None
265
265
 
266
- return grad_input, grad_weight, None, grad_bias
266
+ return grad_input, grad_weight, None, None, None, grad_bias
@@ -16,12 +16,12 @@ class LigerFusedLinearPreferenceBase(torch.autograd.Function):
16
16
 
17
17
  @staticmethod
18
18
  def forward(
19
+ cls,
19
20
  ctx,
20
21
  _input,
21
22
  weight,
22
23
  target,
23
24
  bias=None,
24
- loss_fn=None,
25
25
  chunk_size=1,
26
26
  ignore_index=-100,
27
27
  alpha=1.0,
@@ -89,7 +89,7 @@ class LigerFusedLinearPreferenceBase(torch.autograd.Function):
89
89
 
90
90
  compute_loss = partial(
91
91
  LigerFusedLinearPreferenceBase._compute_loss,
92
- preference_loss_fn=loss_fn,
92
+ preference_loss_fn=cls.preference_loss_fn,
93
93
  ignore_index=ignore_index,
94
94
  alpha=alpha,
95
95
  beta=beta,
@@ -1,3 +1,4 @@
1
+ from abc import abstractmethod
1
2
  from functools import partial
2
3
 
3
4
  import torch
@@ -5,15 +6,22 @@ import torch.nn.functional as F
5
6
 
6
7
 
7
8
  class LigerFusedLinearRLHFBase(torch.autograd.Function):
9
+ @abstractmethod
10
+ def rlhf_loss_fn(*args, **kwargs):
11
+ """
12
+ To be extended by subclasses.
13
+ """
14
+ raise NotImplementedError("RLHF loss function must be implemented.")
15
+
8
16
  @staticmethod
9
17
  def forward(
18
+ cls,
10
19
  ctx,
11
20
  _input,
12
21
  weight,
13
22
  attention_mask,
14
23
  rewards,
15
24
  bias=None,
16
- loss_fn=None,
17
25
  num_generations=4,
18
26
  beta=0.1,
19
27
  compiled=True,
@@ -41,7 +49,7 @@ class LigerFusedLinearRLHFBase(torch.autograd.Function):
41
49
  use_ref_model=use_ref_model,
42
50
  ref_weight=ref_weight,
43
51
  ref_bias=ref_bias,
44
- rlhf_loss_fn=loss_fn,
52
+ rlhf_loss_fn=cls.rlhf_loss_fn,
45
53
  )
46
54
 
47
55
  def fused_fwd_bwd(input_chunk, attention_mask_chunk, rewards_chunk, ref_input_chunk):
@@ -202,7 +210,6 @@ class LigerFusedLinearRLHFBase(torch.autograd.Function):
202
210
  None, # grad_attention_mask
203
211
  None, # grad_rewards
204
212
  grad_bias,
205
- None, # grad_loss_fn
206
213
  None, # grad_chunk_size
207
214
  None, # grad_beta
208
215
  None, # grad_compiled
@@ -16,13 +16,13 @@ class LigerFusedLinearUnpairedPreferenceBase(torch.autograd.Function):
16
16
 
17
17
  @staticmethod
18
18
  def forward(
19
+ cls,
19
20
  ctx,
20
21
  _input,
21
22
  weight,
22
23
  target,
23
24
  preference_labels,
24
25
  bias=None,
25
- loss_fn=None,
26
26
  chunk_size=1,
27
27
  ignore_index=-100,
28
28
  compiled=True,
@@ -30,6 +30,7 @@ class LigerFusedLinearUnpairedPreferenceBase(torch.autograd.Function):
30
30
  ref_input=None,
31
31
  ref_weight=None,
32
32
  ref_bias=None,
33
+ average_log_prob=False,
33
34
  **loss_kwargs,
34
35
  ):
35
36
  """
@@ -59,6 +60,7 @@ class LigerFusedLinearUnpairedPreferenceBase(torch.autograd.Function):
59
60
  Shape: (batch_size,).
60
61
  ref_weight (torch.Tensor): Reference weight tensor. Shape: (vocab_size, hidden_size).
61
62
  ref_bias (torch.Tensor, optional): Reference bias tensor. Shape: (vocab_size,).
63
+ average_log_prob (bool): Whether to average the log probability per non-masked token.
62
64
  loss_kwargs (dict): Other possible arguments that a loss function might need
63
65
  """
64
66
  # TODO: Tune CHUNK_SIZE to fully utilize the GPU
@@ -72,14 +74,22 @@ class LigerFusedLinearUnpairedPreferenceBase(torch.autograd.Function):
72
74
  # Loss to be accumulated
73
75
  loss_acc = torch.zeros((), device=_input.device)
74
76
 
77
+ # Metrics to be recorded
78
+ chosen_logps_sum = torch.zeros((), device=_input.device)
79
+ rejected_logps_sum = torch.zeros((), device=_input.device)
80
+ chosen_logits_sum = torch.zeros((), device=_input.device)
81
+ rejected_logits_sum = torch.zeros((), device=_input.device)
82
+ aggregated_aux_outputs = []
83
+
75
84
  compute_loss = partial(
76
85
  LigerFusedLinearUnpairedPreferenceBase._compute_loss,
77
- preference_loss_fn=loss_fn,
86
+ preference_loss_fn=cls.preference_loss_fn,
78
87
  full_target=target,
79
88
  ignore_index=ignore_index,
80
89
  use_ref_model=use_ref_model,
81
90
  ref_weight=ref_weight,
82
91
  ref_bias=ref_bias,
92
+ average_log_prob=average_log_prob,
83
93
  **loss_kwargs,
84
94
  )
85
95
 
@@ -88,7 +98,7 @@ class LigerFusedLinearUnpairedPreferenceBase(torch.autograd.Function):
88
98
  Fused forward and backward pass for a chunk of input and target.
89
99
  """
90
100
  argnums = (0, 1, 4) if bias is not None else (0, 1)
91
- return torch.func.grad_and_value(compute_loss, argnums=argnums, has_aux=False)(
101
+ return torch.func.grad_and_value(compute_loss, argnums=argnums, has_aux=True)(
92
102
  input_chunk,
93
103
  weight,
94
104
  target_chunk,
@@ -103,9 +113,19 @@ class LigerFusedLinearUnpairedPreferenceBase(torch.autograd.Function):
103
113
  preference_labels_chunk=None,
104
114
  ref_input_chunk=None,
105
115
  ):
106
- (chunk_grad_input, chunk_grad_weight, *chunk_grad_bias), (chunk_loss) = fused_fwd_bwd(
107
- input_chunk, target_chunk, preference_labels_chunk, ref_input_chunk
108
- )
116
+ (
117
+ (chunk_grad_input, chunk_grad_weight, *chunk_grad_bias),
118
+ (
119
+ chunk_loss,
120
+ (
121
+ chunk_chosen_logps_sum,
122
+ chunk_rejected_logps_sum,
123
+ chunk_chosen_logits_sum,
124
+ chunk_rejected_logits_sum,
125
+ *aux_outputs,
126
+ ),
127
+ ),
128
+ ) = fused_fwd_bwd(input_chunk, target_chunk, preference_labels_chunk, ref_input_chunk)
109
129
  if bias is not None:
110
130
  grad_bias.add_(chunk_grad_bias[0]) # accumulate bias gradient
111
131
 
@@ -116,6 +136,23 @@ class LigerFusedLinearUnpairedPreferenceBase(torch.autograd.Function):
116
136
  # Accumulate loss
117
137
  loss_acc.add_(chunk_loss)
118
138
 
139
+ # Accumulate metrics
140
+ chosen_logps_sum.add_(chunk_chosen_logps_sum)
141
+ rejected_logps_sum.add_(chunk_rejected_logps_sum)
142
+ chosen_logits_sum.add_(chunk_chosen_logits_sum)
143
+ rejected_logits_sum.add_(chunk_rejected_logits_sum)
144
+
145
+ # aux_outputs
146
+ # Initialize storage for aux_outputs
147
+ if len(aggregated_aux_outputs) == 0:
148
+ for aux in aux_outputs:
149
+ aggregated_aux_outputs.append(torch.zeros((), device=aux.device))
150
+
151
+ # Process each aux_output
152
+ for i, aux in enumerate(aux_outputs):
153
+ if aux.ndim == 0:
154
+ aggregated_aux_outputs[i].add_(aux)
155
+
119
156
  if compiled:
120
157
  fused_fwd_bwd = torch.compile(fused_fwd_bwd)
121
158
 
@@ -151,12 +188,25 @@ class LigerFusedLinearUnpairedPreferenceBase(torch.autograd.Function):
151
188
  # accumulate loss, gradients, and metrics
152
189
  accumulate_chunk(input_chunk, target_chunk, preference_labels_chunk, ref_input_chunk)
153
190
 
191
+ # Aggregate aux outputs lists into tensors
192
+ for i, aux in enumerate(aggregated_aux_outputs):
193
+ if isinstance(aux, list):
194
+ aggregated_aux_outputs[i] = torch.cat(aux, dim=0)
195
+
154
196
  ctx.save_for_backward(
155
197
  torch.cat(grad_inputs, dim=0),
156
198
  grad_weight,
157
199
  grad_bias,
158
200
  )
159
- return loss_acc
201
+
202
+ return_vars = (
203
+ chosen_logps_sum,
204
+ rejected_logps_sum,
205
+ chosen_logits_sum,
206
+ rejected_logits_sum,
207
+ )
208
+
209
+ return loss_acc, (*return_vars, *aggregated_aux_outputs)
160
210
 
161
211
  @staticmethod
162
212
  def backward(ctx, *grad_output):
@@ -173,21 +223,37 @@ class LigerFusedLinearUnpairedPreferenceBase(torch.autograd.Function):
173
223
  input_chunk,
174
224
  weight,
175
225
  target_chunk,
226
+ preference_labels_chunk,
176
227
  bias=None,
177
228
  ignore_index=-100,
229
+ average_log_prob=False,
178
230
  ):
179
231
  logits_chunk = input_chunk @ weight.t()
180
232
  if bias is not None:
181
233
  logits_chunk = logits_chunk + bias
182
234
  log_probs_chunk = F.log_softmax(logits_chunk.float(), dim=-1)
183
-
184
235
  loss_mask_chunk = target_chunk != ignore_index
185
236
  label_chunk = torch.where(loss_mask_chunk, target_chunk, 0)
186
237
 
187
238
  per_token_logps_chunk = log_probs_chunk.gather(-1, label_chunk.unsqueeze(-1)).squeeze(-1)
188
- average_log_prob_chunk = (per_token_logps_chunk * loss_mask_chunk).sum(-1) / loss_mask_chunk.sum(-1)
189
-
190
- return average_log_prob_chunk
239
+ if average_log_prob:
240
+ log_probs = (per_token_logps_chunk * loss_mask_chunk).sum(-1) / loss_mask_chunk.sum(-1)
241
+ else:
242
+ log_probs = (per_token_logps_chunk * loss_mask_chunk).sum(-1)
243
+
244
+ chosen_logps_sum = (log_probs * preference_labels_chunk.unsqueeze(1)).sum()
245
+ rejected_logps_sum = (log_probs * (~preference_labels_chunk).unsqueeze(1)).sum()
246
+
247
+ chosen_logits_sum = (logits_chunk * preference_labels_chunk.unsqueeze(1)).sum()
248
+ rejected_logits_sum = (logits_chunk * (~preference_labels_chunk).unsqueeze(1)).sum()
249
+
250
+ return (
251
+ log_probs,
252
+ chosen_logps_sum,
253
+ rejected_logps_sum,
254
+ chosen_logits_sum,
255
+ rejected_logits_sum,
256
+ )
191
257
 
192
258
  @staticmethod
193
259
  def _compute_loss(
@@ -203,6 +269,7 @@ class LigerFusedLinearUnpairedPreferenceBase(torch.autograd.Function):
203
269
  ref_input_chunk=None,
204
270
  ref_weight=None,
205
271
  ref_bias=None,
272
+ average_log_prob=False,
206
273
  **loss_kwargs,
207
274
  ):
208
275
  """
@@ -218,29 +285,57 @@ class LigerFusedLinearUnpairedPreferenceBase(torch.autograd.Function):
218
285
  use_ref_model (bool): Whether to use a reference model for the alignment loss.
219
286
  ref_weight (torch.Tensor): Reference weight tensor. Shape: (vocab_size, hidden_size).
220
287
  ref_bias (torch.Tensor, optional): Reference bias tensor. Shape: (vocab_size,).
288
+ average_log_prob (bool): Whether to average the log probability per non-masked token.
221
289
  loss_kwargs (dict): Additional arguments for the loss function.
222
290
  """
223
- average_log_prob_chunk = LigerFusedLinearUnpairedPreferenceBase.chunk_forward(
291
+ (
292
+ log_prob_chunk,
293
+ chosen_logps_sum,
294
+ rejected_logps_sum,
295
+ chosen_logits_sum,
296
+ rejected_logits_sum,
297
+ ) = LigerFusedLinearUnpairedPreferenceBase.chunk_forward(
224
298
  input_chunk,
225
299
  weight,
226
300
  target_chunk,
301
+ preference_labels_chunk,
227
302
  bias=bias,
228
303
  ignore_index=ignore_index,
304
+ average_log_prob=average_log_prob,
229
305
  )
230
306
 
231
307
  if use_ref_model:
232
308
  with torch.no_grad():
233
- ref_average_log_prob_chunk = LigerFusedLinearUnpairedPreferenceBase.chunk_forward(
309
+ (
310
+ ref_log_prob_chunk,
311
+ _,
312
+ _,
313
+ _,
314
+ _,
315
+ ) = LigerFusedLinearUnpairedPreferenceBase.chunk_forward(
234
316
  ref_input_chunk,
235
317
  ref_weight,
236
318
  target_chunk,
319
+ preference_labels_chunk,
237
320
  ref_bias,
238
321
  ignore_index=ignore_index,
322
+ average_log_prob=average_log_prob,
239
323
  )
240
- loss_kwargs["ref_average_log_prob_chunk"] = ref_average_log_prob_chunk
324
+ loss_kwargs["ref_log_prob_chunk"] = ref_log_prob_chunk
241
325
 
242
- preference_loss_chunk = preference_loss_fn(
243
- average_log_prob_chunk, preference_labels_chunk, full_target, **loss_kwargs
326
+ preference_loss_outputs = preference_loss_fn(
327
+ log_prob_chunk, preference_labels_chunk, full_target, **loss_kwargs
328
+ )
329
+ if isinstance(preference_loss_outputs, tuple):
330
+ preference_loss_chunk, *aux_outputs = preference_loss_outputs
331
+ else:
332
+ preference_loss_chunk, aux_outputs = preference_loss_outputs, []
333
+
334
+ return_vars = (
335
+ chosen_logps_sum,
336
+ rejected_logps_sum,
337
+ chosen_logits_sum,
338
+ rejected_logits_sum,
244
339
  )
245
340
 
246
- return preference_loss_chunk
341
+ return preference_loss_chunk, (*return_vars, *aux_outputs)
@@ -63,8 +63,9 @@ class LigerFusedLinearGRPOFunction(LigerFusedLinearRLHFBase):
63
63
 
64
64
  return loss, metrics
65
65
 
66
- @staticmethod
66
+ @classmethod
67
67
  def forward(
68
+ cls,
68
69
  ctx,
69
70
  _input,
70
71
  weight,
@@ -79,12 +80,12 @@ class LigerFusedLinearGRPOFunction(LigerFusedLinearRLHFBase):
79
80
  use_ref_model=True,
80
81
  num_generations=1,
81
82
  ):
82
- return LigerFusedLinearRLHFBase.forward(
83
+ return super().forward(
84
+ cls=cls,
83
85
  ctx=ctx,
84
86
  _input=_input,
85
87
  weight=weight,
86
88
  attention_mask=attention_mask,
87
- loss_fn=LigerFusedLinearGRPOFunction.rlhf_loss_fn,
88
89
  rewards=rewards,
89
90
  bias=bias,
90
91
  ref_input=ref_input,
@@ -30,14 +30,17 @@ class LigerFusedLinearJSDFunction(LigerFusedLinearDistillationBase):
30
30
  jsd_loss = beta * teacher_kl + (1 - beta) * student_kl
31
31
  return jsd_loss
32
32
 
33
- @staticmethod
33
+ @classmethod
34
34
  def forward(
35
+ cls,
35
36
  ctx,
36
37
  student_input: torch.Tensor,
37
38
  student_weight: torch.Tensor,
38
39
  teacher_input: torch.Tensor,
39
40
  teacher_weight: torch.Tensor,
40
41
  true_labels: torch.LongTensor,
42
+ student_bias: torch.Tensor,
43
+ teacher_bias: torch.Tensor,
41
44
  weight_hard_loss: float = 0.5,
42
45
  weight_soft_loss: float = 0.5,
43
46
  beta: float = 0.5,
@@ -62,15 +65,17 @@ class LigerFusedLinearJSDFunction(LigerFusedLinearDistillationBase):
62
65
  Returns:
63
66
  torch.Tensor: Computed loss
64
67
  """
65
- return LigerFusedLinearDistillationBase.forward(
68
+ return super().forward(
69
+ cls=cls,
66
70
  ctx=ctx,
67
71
  student_input=student_input,
68
72
  student_weight=student_weight,
69
73
  teacher_input=teacher_input,
70
74
  teacher_weight=teacher_weight,
71
75
  target=true_labels,
72
- loss_fn=LigerFusedLinearJSDFunction.distillation_loss_fn,
73
- chunk_size=1,
76
+ student_bias=student_bias,
77
+ teacher_bias=teacher_bias,
78
+ chunk_size=1024,
74
79
  weight_hard_loss=weight_hard_loss,
75
80
  weight_soft_loss=weight_soft_loss,
76
81
  beta=beta,
@@ -81,9 +86,18 @@ class LigerFusedLinearJSDFunction(LigerFusedLinearDistillationBase):
81
86
 
82
87
  @staticmethod
83
88
  def backward(ctx, grad_output):
84
- grads = LigerFusedLinearDistillationBase.backward(ctx, grad_output)[:4]
89
+ grads = LigerFusedLinearDistillationBase.backward(ctx, grad_output)[:6]
85
90
 
86
- return (*grads, None, None, None, None, None, None, None)
91
+ return (
92
+ *grads,
93
+ None, # teacher_bias
94
+ None, # weight_hard_loss
95
+ None, # weight_soft_loss
96
+ None, # beta
97
+ None, # ignore_index
98
+ None, # temperature
99
+ None, # compiled
100
+ )
87
101
 
88
102
 
89
103
  class LigerFusedLinearJSDLoss(torch.nn.Module):
@@ -125,6 +139,8 @@ class LigerFusedLinearJSDLoss(torch.nn.Module):
125
139
  teacher_input: torch.Tensor,
126
140
  teacher_weight: torch.Tensor,
127
141
  true_labels: torch.LongTensor,
142
+ student_bias: torch.Tensor,
143
+ teacher_bias: torch.Tensor,
128
144
  ) -> torch.Tensor:
129
145
  """
130
146
  Compute the JSD distillation loss.
@@ -145,6 +161,8 @@ class LigerFusedLinearJSDLoss(torch.nn.Module):
145
161
  teacher_input,
146
162
  teacher_weight,
147
163
  true_labels,
164
+ student_bias,
165
+ teacher_bias,
148
166
  self.weight_hard_loss,
149
167
  self.weight_soft_loss,
150
168
  self.beta,
@@ -7,10 +7,10 @@ from liger_kernel.chunked_loss.fused_linear_unpaired_preference import LigerFuse
7
7
  class LigerFusedLinearKTOFunction(LigerFusedLinearUnpairedPreferenceBase):
8
8
  @staticmethod
9
9
  def preference_loss_fn(
10
- average_log_prob_chunk,
10
+ log_prob_chunk,
11
11
  preference_labels_chunk,
12
12
  full_target,
13
- ref_average_log_prob_chunk=None,
13
+ ref_log_prob_chunk=None,
14
14
  beta=0.1,
15
15
  kl=None,
16
16
  ):
@@ -43,30 +43,34 @@ class LigerFusedLinearKTOFunction(LigerFusedLinearUnpairedPreferenceBase):
43
43
  3. Maintain reasonable distance from the reference model
44
44
 
45
45
  Args:
46
- average_log_prob_chunk: Log probabilities for the chunk (batch_size,)
46
+ log_prob_chunk: Log probabilities for the chunk (batch_size,)
47
47
  preference_labels_chunk: Preference labels for the chunk (batch_size,)
48
48
  full_target: Non chunked full target tensor
49
- ref_average_log_prob_chunk: Reference log probs for the chunk (batch_size,)
49
+ ref_log_prob_chunk: Reference log probs for the chunk (batch_size,)
50
50
  beta: Weight for the KTO loss
51
51
  kl: KL divergence between the policy model and the reference model for the chosen responses. Shape: (batch_size,)
52
52
  Returns:
53
53
  - loss: The KTO loss value
54
54
  """
55
- if ref_average_log_prob_chunk is not None:
56
- logratios_chunk = average_log_prob_chunk - ref_average_log_prob_chunk
55
+ if ref_log_prob_chunk is not None:
56
+ logratios_chunk = log_prob_chunk - ref_log_prob_chunk
57
57
  else:
58
- logratios_chunk = average_log_prob_chunk
59
-
58
+ logratios_chunk = log_prob_chunk
60
59
  multiplier_chunk = torch.where(preference_labels_chunk, 1, -1)
61
60
  if kl is not None:
62
61
  losses = 1 - F.sigmoid(beta * (logratios_chunk - kl) * multiplier_chunk)
63
62
  else:
64
63
  losses = 1 - F.sigmoid(beta * logratios_chunk * multiplier_chunk)
65
64
 
66
- return losses.sum() / (full_target.shape[0])
65
+ rewards = beta * logratios_chunk
66
+ chosen_rewards_sum = (rewards * preference_labels_chunk.unsqueeze(1)).sum()
67
+ rejected_rewards_sum = (rewards * (~preference_labels_chunk).unsqueeze(1)).sum()
67
68
 
68
- @staticmethod
69
+ return losses.sum() / (full_target.shape[0]), chosen_rewards_sum, rejected_rewards_sum
70
+
71
+ @classmethod
69
72
  def forward(
73
+ cls,
70
74
  ctx,
71
75
  _input,
72
76
  weight,
@@ -81,15 +85,16 @@ class LigerFusedLinearKTOFunction(LigerFusedLinearUnpairedPreferenceBase):
81
85
  beta=0.1,
82
86
  compiled=True,
83
87
  use_ref_model=True,
88
+ average_log_prob=False,
84
89
  ):
85
- return LigerFusedLinearUnpairedPreferenceBase.forward(
90
+ return super().forward(
91
+ cls=cls,
86
92
  ctx=ctx,
87
93
  _input=_input,
88
94
  weight=weight,
89
95
  target=target,
90
96
  preference_labels=preference_labels,
91
97
  bias=bias,
92
- loss_fn=LigerFusedLinearKTOFunction.preference_loss_fn,
93
98
  ignore_index=ignore_index,
94
99
  beta=beta,
95
100
  compiled=compiled,
@@ -97,6 +102,7 @@ class LigerFusedLinearKTOFunction(LigerFusedLinearUnpairedPreferenceBase):
97
102
  ref_input=ref_input,
98
103
  ref_weight=ref_weight,
99
104
  ref_bias=ref_bias,
105
+ average_log_prob=average_log_prob,
100
106
  kl=kl,
101
107
  )
102
108
 
@@ -129,6 +135,7 @@ class LigerFusedLinearKTOLoss(torch.nn.Module):
129
135
  beta: float = 0.1,
130
136
  compiled: bool = True,
131
137
  use_ref_model: bool = False,
138
+ average_log_prob: bool = False,
132
139
  ):
133
140
  """
134
141
  Args:
@@ -136,12 +143,14 @@ class LigerFusedLinearKTOLoss(torch.nn.Module):
136
143
  beta (float): Temperature parameter for the KTO loss
137
144
  compiled (bool): Whether to use compiled operations
138
145
  use_ref_model (bool): Whether to use a reference model for the DPO loss.
146
+ average_log_prob (bool): Whether to average the log probability per non-masked token.
139
147
  """
140
148
  super().__init__()
141
149
  self.ignore_index = ignore_index
142
150
  self.beta = beta
143
151
  self.compiled = compiled
144
152
  self.use_ref_model = use_ref_model
153
+ self.average_log_prob = average_log_prob
145
154
 
146
155
  def forward(
147
156
  self,
@@ -169,4 +178,5 @@ class LigerFusedLinearKTOLoss(torch.nn.Module):
169
178
  self.beta,
170
179
  self.compiled,
171
180
  self.use_ref_model,
181
+ self.average_log_prob,
172
182
  )
@@ -42,8 +42,9 @@ class LigerFusedLinearORPOFunction(LigerFusedLinearPreferenceBase):
42
42
 
43
43
  return loss, chosen_rewards, rejected_rewards, log_odds_ratio, log_odds_chosen
44
44
 
45
- @staticmethod
45
+ @classmethod
46
46
  def forward(
47
+ cls,
47
48
  ctx,
48
49
  _input,
49
50
  weight,
@@ -55,13 +56,13 @@ class LigerFusedLinearORPOFunction(LigerFusedLinearPreferenceBase):
55
56
  nll_target=None,
56
57
  compiled=True,
57
58
  ):
58
- return LigerFusedLinearPreferenceBase.forward(
59
+ return super().forward(
60
+ cls=cls,
59
61
  ctx=ctx,
60
62
  _input=_input,
61
63
  weight=weight,
62
64
  target=target,
63
65
  bias=bias,
64
- loss_fn=LigerFusedLinearORPOFunction.preference_loss_fn,
65
66
  ignore_index=ignore_index,
66
67
  beta=beta,
67
68
  compute_nll_loss=compute_nll_loss,
@@ -47,8 +47,9 @@ class LigerFusedLinearSimPOFunction(LigerFusedLinearPreferenceBase):
47
47
 
48
48
  return loss, chosen_rewards, rejected_rewards
49
49
 
50
- @staticmethod
50
+ @classmethod
51
51
  def forward(
52
+ cls,
52
53
  ctx,
53
54
  _input,
54
55
  weight,
@@ -62,13 +63,13 @@ class LigerFusedLinearSimPOFunction(LigerFusedLinearPreferenceBase):
62
63
  compiled=True,
63
64
  gamma=0.5,
64
65
  ):
65
- return LigerFusedLinearPreferenceBase.forward(
66
+ return super().forward(
67
+ cls,
66
68
  ctx,
67
69
  _input,
68
70
  weight,
69
71
  target,
70
72
  bias,
71
- loss_fn=LigerFusedLinearSimPOFunction.preference_loss_fn,
72
73
  compute_nll_loss=compute_nll_loss,
73
74
  ignore_index=ignore_index,
74
75
  alpha=alpha,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: liger_kernel_nightly
3
- Version: 0.5.4.dev20250227064037
3
+ Version: 0.5.4.dev20250304205249
4
4
  Summary: Efficient Triton kernels for LLM Training
5
5
  License: BSD 2-CLAUSE LICENSE
6
6
  Copyright 2024 LinkedIn Corporation
@@ -3,18 +3,18 @@ liger_kernel/env_report.py,sha256=uhdEC8OydxoZlb7B6YYcAaBF3crGFdIck-4cxaW4NJY,17
3
3
  liger_kernel/utils.py,sha256=178Hn8uD-VauDT6FjqMyXLbKLod8ObIpaTtapHwfEK0,1861
4
4
  liger_kernel/chunked_loss/README.md,sha256=0FmkFC3hKBqyoDT5uTlIYmrvRkF-EOCR1y-EBU1LpWU,2248
5
5
  liger_kernel/chunked_loss/__init__.py,sha256=ATu-xX5Fc49Cr6yBOGBRNTo593ZrU5ZCsIuvoIbJWw4,603
6
- liger_kernel/chunked_loss/cpo_loss.py,sha256=OdBR8WYdHTKpLI_c9DcuwqKSWPeAAeTyREz46Vu_cAY,3682
7
- liger_kernel/chunked_loss/dpo_loss.py,sha256=wgjnwzLfrMUwV5mXgrq6G1YfQKWnbiFJegaP48BGJHY,4509
6
+ liger_kernel/chunked_loss/cpo_loss.py,sha256=LZr2mVe2EUQuKQ9uB30vxmuCfuK_yxJZraG62kH-qSY,3654
7
+ liger_kernel/chunked_loss/dpo_loss.py,sha256=MMTiHviJUg7htStKevMgqpyXkQfaKcqahaBz1dzXM1A,4451
8
8
  liger_kernel/chunked_loss/functional.py,sha256=THWWpCnRVhTVfnPnyvQjdBvo1JDtxhwLmtZE_yiBBqM,817
9
- liger_kernel/chunked_loss/fused_linear_distillation.py,sha256=5V8rdva89WyHVbmJ8JOmC4DYNOR6ByXfx3qlUieOZkI,11002
10
- liger_kernel/chunked_loss/fused_linear_preference.py,sha256=idK9V9NivoVITqVpiG0fEGUHSvinYWkn9-EYXZjR-KQ,18356
11
- liger_kernel/chunked_loss/fused_linear_rlhf.py,sha256=sAApL4GQ3YL2F-ymIAF61GCpFfBgFcWF5LB4Gzd7LgY,8044
12
- liger_kernel/chunked_loss/fused_linear_unpaired_preference.py,sha256=ZqYlXXhIphkJPxOS7iI70avgrr6x0skEtgpckZTYau0,9819
13
- liger_kernel/chunked_loss/grpo_loss.py,sha256=M5qlQR-v5Rh8N3P3dPGNhOKygDFJ4516_rJaVPzU_-c,4980
14
- liger_kernel/chunked_loss/jsd_loss.py,sha256=yRCQdvd3ruTWP4A_BfU8VcZ6LepSUfO0Ob7stGnueQY,6052
15
- liger_kernel/chunked_loss/kto_loss.py,sha256=b3ffJyk97e-6XdXd4HFrYyx8wW4A-CU4gOaJSimKLtA,5476
16
- liger_kernel/chunked_loss/orpo_loss.py,sha256=yjcrrbVeemLYodoSKT-FMSnaPtyKAZ3aOrvPD6tTY6Y,3617
17
- liger_kernel/chunked_loss/simpo_loss.py,sha256=3TTc7U79Orjgi-Wu81WZkWk5MgsdqKXIOBHgIvDazPw,3865
9
+ liger_kernel/chunked_loss/fused_linear_distillation.py,sha256=FJh7k3sry-fqnBApLSngf7h-lHQEiXtOY_tiRDVanPM,11022
10
+ liger_kernel/chunked_loss/fused_linear_preference.py,sha256=ojB42jYPu0c4ki96Ft-hy7Sf6fh_WikG-aWNrlZzSio,18362
11
+ liger_kernel/chunked_loss/fused_linear_rlhf.py,sha256=Dxtj6fOfZ8jGoX5uvC9z3An6np39Zdz3c2B2fF39WAA,8240
12
+ liger_kernel/chunked_loss/fused_linear_unpaired_preference.py,sha256=RiuK3UtRwH9T6jZ36sA8Urj-TVuOLOO2syLg_JOQapY,13437
13
+ liger_kernel/chunked_loss/grpo_loss.py,sha256=6RPYSIzTgjmCSIkULvpmbU_jsEM4awU9OgScBkWsXj0,4933
14
+ liger_kernel/chunked_loss/jsd_loss.py,sha256=NbT_D0ybYL68p7Rh9hdKeRR8HkHKEyX2ab5n_RxWz-0,6481
15
+ liger_kernel/chunked_loss/kto_loss.py,sha256=4NHloq8gAwkD4Q8-PNa4Yz_uNyu80PokOdFTOnH1138,5903
16
+ liger_kernel/chunked_loss/orpo_loss.py,sha256=WXX_eCSSIDoi9bHOK8-DYFgx3-vEZhvDvLyXK3mVW6U,3558
17
+ liger_kernel/chunked_loss/simpo_loss.py,sha256=V2YN7aB7o-5rMplgYTon04JKYhKNYxLMqZezUOG5OPc,3801
18
18
  liger_kernel/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
19
  liger_kernel/ops/cross_entropy.py,sha256=yKKhN63I7r9NxJye4wTLBvvKAyrXQt6jf4nBo3lJyVg,18860
20
20
  liger_kernel/ops/fused_linear_cross_entropy.py,sha256=1Y3Uk_TCSjqKgoG2eot1ptnWXJXXQESqGvOmqAW1gsM,10912
@@ -67,9 +67,9 @@ liger_kernel/transformers/trainer/__init__.py,sha256=p7yQfklV8-467qSz_ZMimkbDF7H
67
67
  liger_kernel/transformers/trainer/orpo_trainer.py,sha256=pdekW7l6Qg_aqa5SYKYlSWUF8m3lkOFvFLcIMEHrz9s,8338
68
68
  liger_kernel/triton/__init__.py,sha256=qCiCamzCRv6lpV8IqpAc9YMdNKC7GKurClWceQPnlis,92
69
69
  liger_kernel/triton/monkey_patch.py,sha256=Rd0hUHAzDkFfHvnX7-PBaNK5EKnZhtfM_h-fgQH9HPY,1568
70
- liger_kernel_nightly-0.5.4.dev20250227064037.dist-info/LICENSE,sha256=OhzLDHJ0to4a8sodVLELZiCFylZ1NAAYLs-HrjPy0ag,1312
71
- liger_kernel_nightly-0.5.4.dev20250227064037.dist-info/METADATA,sha256=cLJkyLwqe07PHRuASpIGhgOq-5abocy-sHrijROBnts,22389
72
- liger_kernel_nightly-0.5.4.dev20250227064037.dist-info/NOTICE,sha256=njwnoPZLh9AN8SJQzxvCGLHi-8X__AvWRze6joNXIY8,2066
73
- liger_kernel_nightly-0.5.4.dev20250227064037.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
74
- liger_kernel_nightly-0.5.4.dev20250227064037.dist-info/top_level.txt,sha256=2eghu4hA3LnkM7ElW92tQ8zegWKgSbeo-k-aGe1YnvY,13
75
- liger_kernel_nightly-0.5.4.dev20250227064037.dist-info/RECORD,,
70
+ liger_kernel_nightly-0.5.4.dev20250304205249.dist-info/LICENSE,sha256=OhzLDHJ0to4a8sodVLELZiCFylZ1NAAYLs-HrjPy0ag,1312
71
+ liger_kernel_nightly-0.5.4.dev20250304205249.dist-info/METADATA,sha256=AFWOuf67EudNiAgUU006ngrmfAzKB3bYTnjYtUCYZb0,22389
72
+ liger_kernel_nightly-0.5.4.dev20250304205249.dist-info/NOTICE,sha256=njwnoPZLh9AN8SJQzxvCGLHi-8X__AvWRze6joNXIY8,2066
73
+ liger_kernel_nightly-0.5.4.dev20250304205249.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
74
+ liger_kernel_nightly-0.5.4.dev20250304205249.dist-info/top_level.txt,sha256=2eghu4hA3LnkM7ElW92tQ8zegWKgSbeo-k-aGe1YnvY,13
75
+ liger_kernel_nightly-0.5.4.dev20250304205249.dist-info/RECORD,,