liger-kernel-nightly 0.5.4.dev20250225020243__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.
- liger_kernel/chunked_loss/cpo_loss.py +9 -8
- liger_kernel/chunked_loss/dpo_loss.py +4 -3
- liger_kernel/chunked_loss/fused_linear_distillation.py +3 -3
- liger_kernel/chunked_loss/fused_linear_preference.py +2 -2
- liger_kernel/chunked_loss/fused_linear_rlhf.py +10 -3
- liger_kernel/chunked_loss/fused_linear_unpaired_preference.py +112 -17
- liger_kernel/chunked_loss/grpo_loss.py +4 -3
- liger_kernel/chunked_loss/jsd_loss.py +24 -6
- liger_kernel/chunked_loss/kto_loss.py +22 -12
- liger_kernel/chunked_loss/orpo_loss.py +4 -3
- liger_kernel/chunked_loss/simpo_loss.py +4 -3
- liger_kernel/transformers/__init__.py +1 -0
- liger_kernel/transformers/model/qwen2_5_vl.py +205 -0
- liger_kernel/transformers/monkey_patch.py +68 -0
- {liger_kernel_nightly-0.5.4.dev20250225020243.dist-info → liger_kernel_nightly-0.5.4.dev20250304205249.dist-info}/METADATA +2 -1
- {liger_kernel_nightly-0.5.4.dev20250225020243.dist-info → liger_kernel_nightly-0.5.4.dev20250304205249.dist-info}/RECORD +20 -19
- {liger_kernel_nightly-0.5.4.dev20250225020243.dist-info → liger_kernel_nightly-0.5.4.dev20250304205249.dist-info}/LICENSE +0 -0
- {liger_kernel_nightly-0.5.4.dev20250225020243.dist-info → liger_kernel_nightly-0.5.4.dev20250304205249.dist-info}/NOTICE +0 -0
- {liger_kernel_nightly-0.5.4.dev20250225020243.dist-info → liger_kernel_nightly-0.5.4.dev20250304205249.dist-info}/WHEEL +0 -0
- {liger_kernel_nightly-0.5.4.dev20250225020243.dist-info → liger_kernel_nightly-0.5.4.dev20250304205249.dist-info}/top_level.txt +0 -0
|
@@ -39,8 +39,9 @@ class LigerFusedLinearCPOFunction(LigerFusedLinearPreferenceBase):
|
|
|
39
39
|
|
|
40
40
|
return loss, chosen_rewards, rejected_rewards
|
|
41
41
|
|
|
42
|
-
@
|
|
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
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
-
@
|
|
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
|
|
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=
|
|
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=
|
|
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=
|
|
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=
|
|
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=
|
|
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
|
-
(
|
|
107
|
-
|
|
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
|
-
|
|
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
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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["
|
|
324
|
+
loss_kwargs["ref_log_prob_chunk"] = ref_log_prob_chunk
|
|
241
325
|
|
|
242
|
-
|
|
243
|
-
|
|
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
|
-
@
|
|
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
|
|
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
|
-
@
|
|
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
|
|
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
|
-
|
|
73
|
-
|
|
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)[:
|
|
89
|
+
grads = LigerFusedLinearDistillationBase.backward(ctx, grad_output)[:6]
|
|
85
90
|
|
|
86
|
-
return (
|
|
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
|
-
|
|
10
|
+
log_prob_chunk,
|
|
11
11
|
preference_labels_chunk,
|
|
12
12
|
full_target,
|
|
13
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
56
|
-
logratios_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 =
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
@
|
|
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
|
|
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
|
-
@
|
|
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
|
|
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,
|
|
@@ -17,6 +17,7 @@ from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mllama
|
|
|
17
17
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_olmo2 # noqa: F401
|
|
18
18
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_phi3 # noqa: F401
|
|
19
19
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2 # noqa: F401
|
|
20
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2_5_vl # noqa: F401
|
|
20
21
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2_vl # noqa: F401
|
|
21
22
|
from liger_kernel.transformers.rms_norm import LigerRMSNorm # noqa: F401
|
|
22
23
|
from liger_kernel.transformers.rope import liger_rotary_pos_emb # noqa: F401
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from typing import Tuple
|
|
4
|
+
from typing import Union
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
|
|
8
|
+
from torch.nn import CrossEntropyLoss
|
|
9
|
+
from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import _CONFIG_FOR_DOC
|
|
10
|
+
from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import QWEN2_5_VL_INPUTS_DOCSTRING
|
|
11
|
+
from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLCausalLMOutputWithPast
|
|
12
|
+
from transformers.utils import add_start_docstrings_to_model_forward
|
|
13
|
+
from transformers.utils import replace_return_docstrings
|
|
14
|
+
|
|
15
|
+
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@add_start_docstrings_to_model_forward(QWEN2_5_VL_INPUTS_DOCSTRING)
|
|
19
|
+
@replace_return_docstrings(output_type=Qwen2_5_VLCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
|
20
|
+
def lce_forward(
|
|
21
|
+
self,
|
|
22
|
+
input_ids: torch.LongTensor = None,
|
|
23
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
24
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
25
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
26
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
27
|
+
labels: Optional[torch.LongTensor] = None,
|
|
28
|
+
use_cache: Optional[bool] = None,
|
|
29
|
+
output_attentions: Optional[bool] = None,
|
|
30
|
+
output_hidden_states: Optional[bool] = None,
|
|
31
|
+
return_dict: Optional[bool] = None,
|
|
32
|
+
pixel_values: Optional[torch.Tensor] = None,
|
|
33
|
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
|
34
|
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
35
|
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
36
|
+
rope_deltas: Optional[torch.LongTensor] = None,
|
|
37
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
38
|
+
second_per_grid_ts: Optional[torch.Tensor] = None,
|
|
39
|
+
) -> Union[Tuple, Qwen2_5_VLCausalLMOutputWithPast]:
|
|
40
|
+
r"""
|
|
41
|
+
Copy paste Qwen2_5_VL's forward but replace torch cross entropy with liger fused linear cross entropy
|
|
42
|
+
Args:
|
|
43
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
44
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
45
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
46
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
|
|
50
|
+
Example:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
>>> from PIL import Image
|
|
54
|
+
>>> import requests
|
|
55
|
+
>>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
|
|
56
|
+
|
|
57
|
+
>>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
|
|
58
|
+
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
|
|
59
|
+
|
|
60
|
+
>>> messages = [
|
|
61
|
+
{
|
|
62
|
+
"role": "user",
|
|
63
|
+
"content": [
|
|
64
|
+
{"type": "image"},
|
|
65
|
+
{"type": "text", "text": "What is shown in this image?"},
|
|
66
|
+
],
|
|
67
|
+
},
|
|
68
|
+
]
|
|
69
|
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
|
70
|
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
|
71
|
+
|
|
72
|
+
>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
73
|
+
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
|
|
74
|
+
|
|
75
|
+
>>> # Generate
|
|
76
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
77
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
78
|
+
"The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
|
|
79
|
+
```"""
|
|
80
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
81
|
+
output_hidden_states = (
|
|
82
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
83
|
+
)
|
|
84
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
85
|
+
|
|
86
|
+
if inputs_embeds is None:
|
|
87
|
+
inputs_embeds = self.model.embed_tokens(input_ids)
|
|
88
|
+
if pixel_values is not None:
|
|
89
|
+
pixel_values = pixel_values.type(self.visual.dtype)
|
|
90
|
+
image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
|
|
91
|
+
n_image_tokens = (input_ids == self.config.image_token_id).sum().item()
|
|
92
|
+
n_image_features = image_embeds.shape[0]
|
|
93
|
+
if n_image_tokens != n_image_features:
|
|
94
|
+
raise ValueError(
|
|
95
|
+
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
mask = input_ids == self.config.image_token_id
|
|
99
|
+
mask_unsqueezed = mask.unsqueeze(-1)
|
|
100
|
+
mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
|
|
101
|
+
image_mask = mask_expanded.to(inputs_embeds.device)
|
|
102
|
+
|
|
103
|
+
image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
104
|
+
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
|
|
105
|
+
|
|
106
|
+
if pixel_values_videos is not None:
|
|
107
|
+
pixel_values_videos = pixel_values_videos.type(self.visual.dtype)
|
|
108
|
+
video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
|
|
109
|
+
n_video_tokens = (input_ids == self.config.video_token_id).sum().item()
|
|
110
|
+
n_video_features = video_embeds.shape[0]
|
|
111
|
+
if n_video_tokens != n_video_features:
|
|
112
|
+
raise ValueError(
|
|
113
|
+
f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}"
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
mask = input_ids == self.config.video_token_id
|
|
117
|
+
mask_unsqueezed = mask.unsqueeze(-1)
|
|
118
|
+
mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
|
|
119
|
+
video_mask = mask_expanded.to(inputs_embeds.device)
|
|
120
|
+
|
|
121
|
+
video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
122
|
+
inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
|
|
123
|
+
|
|
124
|
+
if attention_mask is not None:
|
|
125
|
+
attention_mask = attention_mask.to(inputs_embeds.device)
|
|
126
|
+
|
|
127
|
+
# if we get 4D attention mask we cannot calculate rope deltas anymore. TODO @raushan fixme
|
|
128
|
+
if position_ids is None and (attention_mask is None or attention_mask.ndim == 2):
|
|
129
|
+
# calculate RoPE index once per generation in the pre-fill stage only
|
|
130
|
+
if (cache_position is not None and cache_position[0] == 0) or self.rope_deltas is None:
|
|
131
|
+
position_ids, rope_deltas = self.get_rope_index(
|
|
132
|
+
input_ids,
|
|
133
|
+
image_grid_thw,
|
|
134
|
+
video_grid_thw,
|
|
135
|
+
second_per_grid_ts,
|
|
136
|
+
attention_mask,
|
|
137
|
+
)
|
|
138
|
+
self.rope_deltas = rope_deltas
|
|
139
|
+
# then use the prev pre-calculated rope-deltas to get the correct position ids
|
|
140
|
+
else:
|
|
141
|
+
batch_size, seq_length, _ = inputs_embeds.shape
|
|
142
|
+
delta = (cache_position[0] + self.rope_deltas).to(inputs_embeds.device) if cache_position is not None else 0
|
|
143
|
+
position_ids = torch.arange(seq_length, device=inputs_embeds.device)
|
|
144
|
+
position_ids = position_ids.view(1, -1).expand(batch_size, -1)
|
|
145
|
+
if cache_position is not None: # otherwise `deltas` is an int `0`
|
|
146
|
+
delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0)
|
|
147
|
+
position_ids = position_ids.add(delta)
|
|
148
|
+
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
|
|
149
|
+
|
|
150
|
+
outputs = self.model(
|
|
151
|
+
input_ids=None,
|
|
152
|
+
position_ids=position_ids,
|
|
153
|
+
attention_mask=attention_mask,
|
|
154
|
+
past_key_values=past_key_values,
|
|
155
|
+
inputs_embeds=inputs_embeds,
|
|
156
|
+
use_cache=use_cache,
|
|
157
|
+
output_attentions=output_attentions,
|
|
158
|
+
output_hidden_states=output_hidden_states,
|
|
159
|
+
return_dict=return_dict,
|
|
160
|
+
cache_position=cache_position,
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
hidden_states = outputs[0]
|
|
164
|
+
|
|
165
|
+
loss = None
|
|
166
|
+
logits = None
|
|
167
|
+
|
|
168
|
+
if self.training and (labels is not None):
|
|
169
|
+
shift_hidden_states = hidden_states[..., :-1, :].contiguous()
|
|
170
|
+
shift_labels = labels[..., 1:].contiguous()
|
|
171
|
+
|
|
172
|
+
# Flatten tokens
|
|
173
|
+
shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
|
|
174
|
+
shift_labels = shift_labels.view(-1)
|
|
175
|
+
|
|
176
|
+
lce = LigerFusedLinearCrossEntropyLoss()
|
|
177
|
+
loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
178
|
+
else:
|
|
179
|
+
logits = self.lm_head(hidden_states)
|
|
180
|
+
if labels is not None:
|
|
181
|
+
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
|
182
|
+
logits = logits.float()
|
|
183
|
+
# Shift so that tokens < n predict n
|
|
184
|
+
shift_logits = logits[..., :-1, :].contiguous()
|
|
185
|
+
shift_labels = labels[..., 1:].contiguous()
|
|
186
|
+
# Flatten the tokens
|
|
187
|
+
loss_fct = CrossEntropyLoss()
|
|
188
|
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
|
189
|
+
shift_labels = shift_labels.view(-1)
|
|
190
|
+
# Enable model parallelism
|
|
191
|
+
shift_labels = shift_labels.to(shift_logits.device)
|
|
192
|
+
loss = loss_fct(shift_logits, shift_labels)
|
|
193
|
+
|
|
194
|
+
if not return_dict:
|
|
195
|
+
output = (logits,) + outputs[1:]
|
|
196
|
+
return (loss,) + output if loss is not None else output
|
|
197
|
+
|
|
198
|
+
return Qwen2_5_VLCausalLMOutputWithPast(
|
|
199
|
+
loss=loss,
|
|
200
|
+
logits=logits,
|
|
201
|
+
past_key_values=outputs.past_key_values,
|
|
202
|
+
hidden_states=outputs.hidden_states,
|
|
203
|
+
attentions=outputs.attentions,
|
|
204
|
+
rope_deltas=rope_deltas,
|
|
205
|
+
)
|
|
@@ -745,6 +745,73 @@ def apply_liger_kernel_to_qwen2_vl(
|
|
|
745
745
|
_patch_rms_norm_module(decoder_layer.post_attention_layernorm)
|
|
746
746
|
|
|
747
747
|
|
|
748
|
+
def apply_liger_kernel_to_qwen2_5_vl(
|
|
749
|
+
rope: bool = True,
|
|
750
|
+
cross_entropy: bool = False,
|
|
751
|
+
fused_linear_cross_entropy: bool = True,
|
|
752
|
+
rms_norm: bool = True,
|
|
753
|
+
swiglu: bool = True,
|
|
754
|
+
model: PreTrainedModel = None,
|
|
755
|
+
) -> None:
|
|
756
|
+
"""
|
|
757
|
+
Apply Liger kernels to replace original implementation in HuggingFace Qwen2.5-VL models.
|
|
758
|
+
NOTE: Qwen2.5-VL is not available in transformers<4.48.2
|
|
759
|
+
|
|
760
|
+
Args:
|
|
761
|
+
cross_entropy (bool): Whether to apply Liger's cross entropy loss. Default is False.
|
|
762
|
+
fused_linear_cross_entropy (bool):
|
|
763
|
+
Whether to apply Liger's fused linear cross entropy loss. Default is True.
|
|
764
|
+
`cross_entropy` and `fused_linear_cross_entropy` cannot both be True.
|
|
765
|
+
If `fused_linear_cross_entropy` is True, the logits will not be materialized but more memory efficient.
|
|
766
|
+
rms_norm (bool): Whether to apply Liger's RMSNorm. Default is True.
|
|
767
|
+
swiglu (bool): Whether to apply Liger's SwiGLU MLP. Default is True.
|
|
768
|
+
model (PreTrainedModel): The model instance to apply Liger kernels to, if the model has already been
|
|
769
|
+
loaded. Default is None.
|
|
770
|
+
"""
|
|
771
|
+
assert not (cross_entropy and fused_linear_cross_entropy), (
|
|
772
|
+
"cross_entropy and fused_linear_cross_entropy cannot both be True."
|
|
773
|
+
)
|
|
774
|
+
|
|
775
|
+
from transformers.models.qwen2_5_vl import modeling_qwen2_5_vl
|
|
776
|
+
from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLModel
|
|
777
|
+
|
|
778
|
+
from liger_kernel.transformers.model.qwen2_5_vl import lce_forward as qwen2_5_vl_lce_forward
|
|
779
|
+
|
|
780
|
+
if rope:
|
|
781
|
+
modeling_qwen2_5_vl.apply_multimodal_rotary_pos_emb = liger_multimodal_rotary_pos_emb
|
|
782
|
+
if rms_norm:
|
|
783
|
+
modeling_qwen2_5_vl.Qwen2RMSNorm = LigerRMSNorm
|
|
784
|
+
if cross_entropy:
|
|
785
|
+
modeling_qwen2_5_vl.CrossEntropyLoss = LigerCrossEntropyLoss
|
|
786
|
+
if fused_linear_cross_entropy:
|
|
787
|
+
modeling_qwen2_5_vl.Qwen2_5_VLForConditionalGeneration.forward = qwen2_5_vl_lce_forward
|
|
788
|
+
if swiglu:
|
|
789
|
+
modeling_qwen2_5_vl.Qwen2MLP = LigerSwiGLUMLP
|
|
790
|
+
|
|
791
|
+
if model is not None:
|
|
792
|
+
# The model instance already exists, so we need to additionally patch the
|
|
793
|
+
# instance variables that reference already-instantiated modules
|
|
794
|
+
|
|
795
|
+
# get the base model from the model instance
|
|
796
|
+
base_model: Qwen2_5_VLModel = getattr(model, model.base_model_prefix, model)
|
|
797
|
+
|
|
798
|
+
if hasattr(model, "visual"):
|
|
799
|
+
# Patch Qwen2_5_VisionTransformerPretrainedModel
|
|
800
|
+
for vision_block in model.visual.blocks:
|
|
801
|
+
if rms_norm:
|
|
802
|
+
_patch_rms_norm_module(vision_block.norm1)
|
|
803
|
+
_patch_rms_norm_module(vision_block.norm2)
|
|
804
|
+
|
|
805
|
+
if rms_norm:
|
|
806
|
+
_patch_rms_norm_module(base_model.norm)
|
|
807
|
+
for decoder_layer in base_model.layers:
|
|
808
|
+
if swiglu:
|
|
809
|
+
_bind_method_to_module(decoder_layer.mlp, "forward", LigerSwiGLUMLP.forward)
|
|
810
|
+
if rms_norm:
|
|
811
|
+
_patch_rms_norm_module(decoder_layer.input_layernorm)
|
|
812
|
+
_patch_rms_norm_module(decoder_layer.post_attention_layernorm)
|
|
813
|
+
|
|
814
|
+
|
|
748
815
|
def apply_liger_kernel_to_phi3(
|
|
749
816
|
rope: bool = True,
|
|
750
817
|
cross_entropy: bool = False,
|
|
@@ -890,6 +957,7 @@ MODEL_TYPE_TO_APPLY_LIGER_FN = {
|
|
|
890
957
|
"olmo2": apply_liger_kernel_to_olmo2,
|
|
891
958
|
"qwen2": apply_liger_kernel_to_qwen2,
|
|
892
959
|
"qwen2_vl": apply_liger_kernel_to_qwen2_vl,
|
|
960
|
+
"qwen2_5_vl": apply_liger_kernel_to_qwen2_5_vl,
|
|
893
961
|
"phi3": apply_liger_kernel_to_phi3,
|
|
894
962
|
}
|
|
895
963
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: liger_kernel_nightly
|
|
3
|
-
Version: 0.5.4.
|
|
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
|
|
@@ -312,6 +312,7 @@ loss.backward()
|
|
|
312
312
|
| Gemma2 | `liger_kernel.transformers.apply_liger_kernel_to_gemma2` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
|
|
313
313
|
| Qwen2, Qwen2.5, & QwQ | `liger_kernel.transformers.apply_liger_kernel_to_qwen2` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
|
|
314
314
|
| Qwen2-VL, & QVQ | `liger_kernel.transformers.apply_liger_kernel_to_qwen2_vl` | RMSNorm, LayerNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
|
|
315
|
+
| Qwen2.5-VL | `liger_kernel.transformers.apply_liger_kernel_to_qwen2_5_vl` | RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
|
|
315
316
|
| Phi3 & Phi3.5 | `liger_kernel.transformers.apply_liger_kernel_to_phi3` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
|
|
316
317
|
| Granite 3.0 & 3.1 | `liger_kernel.transformers.apply_liger_kernel_to_granite` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss |
|
|
317
318
|
| OLMo2 | `liger_kernel.transformers.apply_liger_kernel_to_olmo2` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
|
|
@@ -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=
|
|
7
|
-
liger_kernel/chunked_loss/dpo_loss.py,sha256=
|
|
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=
|
|
10
|
-
liger_kernel/chunked_loss/fused_linear_preference.py,sha256=
|
|
11
|
-
liger_kernel/chunked_loss/fused_linear_rlhf.py,sha256=
|
|
12
|
-
liger_kernel/chunked_loss/fused_linear_unpaired_preference.py,sha256=
|
|
13
|
-
liger_kernel/chunked_loss/grpo_loss.py,sha256=
|
|
14
|
-
liger_kernel/chunked_loss/jsd_loss.py,sha256=
|
|
15
|
-
liger_kernel/chunked_loss/kto_loss.py,sha256=
|
|
16
|
-
liger_kernel/chunked_loss/orpo_loss.py,sha256=
|
|
17
|
-
liger_kernel/chunked_loss/simpo_loss.py,sha256=
|
|
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
|
|
@@ -32,7 +32,7 @@ liger_kernel/ops/tvd.py,sha256=FHJtLQI95ijqgg9UtaHpMAjSCiPxB6CduPwPMcGxelc,6405
|
|
|
32
32
|
liger_kernel/ops/utils.py,sha256=uoFKQqo-34N2TWQNvXMFywqGiOMMXNEVBxVojzlUAa0,3836
|
|
33
33
|
liger_kernel/ops/experimental/embedding.py,sha256=tolj3tItkzpSb30zWqDN2_yX4ectflaQ8HMyKyFIQc8,4172
|
|
34
34
|
liger_kernel/ops/experimental/mm_int8int2.py,sha256=TrS9lpwekrik_w5qE7AhMJD1bcq-OidjtbsW80oZ6IM,13314
|
|
35
|
-
liger_kernel/transformers/__init__.py,sha256=
|
|
35
|
+
liger_kernel/transformers/__init__.py,sha256=4bwMPQhGHxmZ-WTFAMD9m-s0PYyfcvIRxhq_h3b0Wz0,2363
|
|
36
36
|
liger_kernel/transformers/auto_model.py,sha256=0qCTRZt280Bj_LcFdzo9hlaR-BWNazawXOGgoCZjgEg,1545
|
|
37
37
|
liger_kernel/transformers/cross_entropy.py,sha256=z3KTWQnFxr_IZaVjtYt0ZNEWQdDdYThN35xWkHlDGH0,1683
|
|
38
38
|
liger_kernel/transformers/functional.py,sha256=ShLD3eb--XKNtllznCrOYTbo4f-1KVwzi0KLMICdrn4,4942
|
|
@@ -43,7 +43,7 @@ liger_kernel/transformers/group_norm.py,sha256=6qMAWOprr4SzP0YhNVNGQIBpM5aUHplUD
|
|
|
43
43
|
liger_kernel/transformers/jsd.py,sha256=DGqRnxIZxsvxo0_tbbxX3b-sDbDjC_yKufyRIHCcScY,2979
|
|
44
44
|
liger_kernel/transformers/kl_div.py,sha256=WLffFbh1EExD2Eb1F7lN11fo9JJC-0751WJjZAF1Fj8,409
|
|
45
45
|
liger_kernel/transformers/layer_norm.py,sha256=c9pk3PEasOKYR0rhe5e5nNrnYKVCEW4VC8S6LpCq9EQ,906
|
|
46
|
-
liger_kernel/transformers/monkey_patch.py,sha256=
|
|
46
|
+
liger_kernel/transformers/monkey_patch.py,sha256=9ud9tv1LI9WIa9UDu0abGIiusIIkayO1fjAUMWgwwT0,47096
|
|
47
47
|
liger_kernel/transformers/qwen2vl_mrope.py,sha256=5EwSqrMdsL9MYspeBMXBsNJKvH0MOmRrtJXAJlnnlOI,1047
|
|
48
48
|
liger_kernel/transformers/rms_norm.py,sha256=GqCEJuGt0YdqqlMcToE0Wp4A8YFquDa4UUSyH2uFW2A,1191
|
|
49
49
|
liger_kernel/transformers/rope.py,sha256=ZTrTORSAyfcFIKjk6XEeYmk4ROH7xXED9L4g2NFntlE,999
|
|
@@ -61,14 +61,15 @@ liger_kernel/transformers/model/mllama.py,sha256=qWexBdskuN3gPJvPUwt4J0nU675tGD6
|
|
|
61
61
|
liger_kernel/transformers/model/olmo2.py,sha256=yyksS6E4fuWd8asEW8rEDBKqZpFmP4ITCM_bjIDZaoY,5124
|
|
62
62
|
liger_kernel/transformers/model/phi3.py,sha256=biRa8fph9qdnQmkD9I21t5XIjpIt1i6UKU4uk8Up8pU,10292
|
|
63
63
|
liger_kernel/transformers/model/qwen2.py,sha256=14UuPjxB-tjqWn85Tn4fqBFvVhVsth5iPEt8kJSMiew,9581
|
|
64
|
+
liger_kernel/transformers/model/qwen2_5_vl.py,sha256=l71WBfX0ptrisoURIRwXJH7MQ2vGKOvcRYMNsrydwlQ,9455
|
|
64
65
|
liger_kernel/transformers/model/qwen2_vl.py,sha256=yMLqsfSYcvhClUpTUjGoADiOxfLB2B8240VdrPP0c8s,9851
|
|
65
66
|
liger_kernel/transformers/trainer/__init__.py,sha256=p7yQfklV8-467qSz_ZMimkbDF7HHWHwku25A-GYL0WU,193
|
|
66
67
|
liger_kernel/transformers/trainer/orpo_trainer.py,sha256=pdekW7l6Qg_aqa5SYKYlSWUF8m3lkOFvFLcIMEHrz9s,8338
|
|
67
68
|
liger_kernel/triton/__init__.py,sha256=qCiCamzCRv6lpV8IqpAc9YMdNKC7GKurClWceQPnlis,92
|
|
68
69
|
liger_kernel/triton/monkey_patch.py,sha256=Rd0hUHAzDkFfHvnX7-PBaNK5EKnZhtfM_h-fgQH9HPY,1568
|
|
69
|
-
liger_kernel_nightly-0.5.4.
|
|
70
|
-
liger_kernel_nightly-0.5.4.
|
|
71
|
-
liger_kernel_nightly-0.5.4.
|
|
72
|
-
liger_kernel_nightly-0.5.4.
|
|
73
|
-
liger_kernel_nightly-0.5.4.
|
|
74
|
-
liger_kernel_nightly-0.5.4.
|
|
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,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|