liger-kernel-nightly 0.5.6.dev20250403190551__py3-none-any.whl → 0.6.4.dev20251212103629__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.
- liger_kernel/chunked_loss/__init__.py +1 -0
- liger_kernel/chunked_loss/cosine_similarity_loss.py +136 -0
- liger_kernel/chunked_loss/dpo_loss.py +61 -3
- liger_kernel/chunked_loss/functional.py +2 -0
- liger_kernel/chunked_loss/fused_linear_distillation.py +13 -2
- liger_kernel/chunked_loss/fused_linear_ppo.py +35 -0
- liger_kernel/chunked_loss/fused_linear_preference.py +0 -1
- liger_kernel/chunked_loss/grpo_loss.py +76 -5
- liger_kernel/chunked_loss/jsd_loss.py +25 -9
- liger_kernel/ops/__init__.py +141 -0
- liger_kernel/ops/backends/README.md +151 -0
- liger_kernel/ops/backends/__init__.py +13 -0
- liger_kernel/ops/backends/_ascend/__init__.py +5 -0
- liger_kernel/ops/backends/_ascend/ops/__init__.py +15 -0
- liger_kernel/ops/backends/registry.py +61 -0
- liger_kernel/ops/cross_entropy.py +124 -64
- liger_kernel/ops/dyt.py +115 -180
- liger_kernel/ops/fused_add_rms_norm.py +416 -0
- liger_kernel/ops/fused_linear_cross_entropy.py +115 -22
- liger_kernel/ops/fused_neighborhood_attention.py +1022 -0
- liger_kernel/ops/geglu.py +3 -2
- liger_kernel/ops/group_norm.py +2 -1
- liger_kernel/ops/grpo_loss.py +312 -0
- liger_kernel/ops/jsd.py +2 -1
- liger_kernel/ops/kl_div.py +13 -6
- liger_kernel/ops/layer_norm.py +146 -78
- liger_kernel/ops/llama4_rope.py +225 -0
- liger_kernel/ops/multi_token_attention.py +207 -0
- liger_kernel/ops/poly_norm.py +390 -0
- liger_kernel/ops/rms_norm.py +283 -56
- liger_kernel/ops/rope.py +1 -1
- liger_kernel/ops/softmax.py +201 -0
- liger_kernel/ops/sparsemax.py +179 -0
- liger_kernel/ops/swiglu.py +1 -1
- liger_kernel/ops/tiled_mlp.py +136 -0
- liger_kernel/ops/utils.py +2 -0
- liger_kernel/transformers/__init__.py +205 -19
- liger_kernel/transformers/cross_entropy.py +9 -4
- liger_kernel/transformers/dyt.py +6 -4
- liger_kernel/transformers/experimental/__init__.py +5 -0
- liger_kernel/transformers/experimental/embedding.py +1 -1
- liger_kernel/transformers/fsdp.py +55 -0
- liger_kernel/transformers/functional.py +122 -20
- liger_kernel/transformers/fused_add_rms_norm.py +39 -0
- liger_kernel/transformers/fused_linear_cross_entropy.py +16 -5
- liger_kernel/transformers/fused_linear_jsd.py +1 -1
- liger_kernel/transformers/fused_neighborhood_attention.py +234 -0
- liger_kernel/transformers/geglu.py +1 -1
- liger_kernel/transformers/group_norm.py +1 -1
- liger_kernel/transformers/grpo_loss.py +153 -0
- liger_kernel/transformers/jsd.py +1 -1
- liger_kernel/transformers/kl_div.py +1 -1
- liger_kernel/transformers/layer_norm.py +1 -1
- liger_kernel/transformers/llama4_rope.py +93 -0
- liger_kernel/transformers/model/falcon_h1.py +122 -0
- liger_kernel/transformers/model/gemma.py +50 -25
- liger_kernel/transformers/model/gemma2.py +55 -23
- liger_kernel/transformers/model/gemma3.py +117 -120
- liger_kernel/transformers/model/glm4.py +141 -0
- liger_kernel/transformers/model/glm4v.py +163 -0
- liger_kernel/transformers/model/glm4v_moe.py +172 -0
- liger_kernel/transformers/model/gpt_oss.py +211 -0
- liger_kernel/transformers/model/hunyuan_v1.py +134 -0
- liger_kernel/transformers/model/internvl.py +157 -0
- liger_kernel/transformers/model/llama.py +102 -25
- liger_kernel/transformers/model/llama4.py +121 -0
- liger_kernel/transformers/model/llava.py +111 -136
- liger_kernel/transformers/model/loss_utils.py +50 -12
- liger_kernel/transformers/model/mistral.py +36 -23
- liger_kernel/transformers/model/mixtral.py +45 -25
- liger_kernel/transformers/model/mllama.py +39 -22
- liger_kernel/transformers/model/olmo2.py +40 -20
- liger_kernel/transformers/model/olmo3.py +142 -0
- liger_kernel/transformers/model/output_classes.py +147 -0
- liger_kernel/transformers/model/paligemma.py +50 -14
- liger_kernel/transformers/model/phi3.py +47 -177
- liger_kernel/transformers/model/qwen2.py +48 -21
- liger_kernel/transformers/model/qwen2_5_vl.py +62 -103
- liger_kernel/transformers/model/qwen2_vl.py +59 -108
- liger_kernel/transformers/model/qwen3.py +136 -0
- liger_kernel/transformers/model/qwen3_moe.py +152 -0
- liger_kernel/transformers/model/qwen3_next.py +146 -0
- liger_kernel/transformers/model/qwen3_vl.py +150 -0
- liger_kernel/transformers/model/qwen3_vl_moe.py +126 -0
- liger_kernel/transformers/model/smollm3.py +199 -0
- liger_kernel/transformers/model/smolvlm.py +158 -0
- liger_kernel/transformers/monkey_patch.py +1678 -160
- liger_kernel/transformers/multi_token_attention.py +64 -0
- liger_kernel/transformers/poly_norm.py +42 -0
- liger_kernel/transformers/qwen2vl_mrope.py +1 -1
- liger_kernel/transformers/rms_norm.py +48 -5
- liger_kernel/transformers/rope.py +45 -1
- liger_kernel/transformers/softmax.py +12 -0
- liger_kernel/transformers/sparsemax.py +16 -0
- liger_kernel/transformers/swiglu.py +39 -1
- liger_kernel/transformers/tiled_mlp.py +133 -0
- liger_kernel/transformers/trainer/orpo_trainer.py +1 -53
- liger_kernel/transformers/tvd.py +1 -1
- liger_kernel/utils.py +36 -0
- {liger_kernel_nightly-0.5.6.dev20250403190551.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/METADATA +68 -38
- liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/RECORD +124 -0
- liger_kernel/transformers/gema3_rms.py +0 -8
- liger_kernel_nightly-0.5.6.dev20250403190551.dist-info/RECORD +0 -82
- {liger_kernel_nightly-0.5.6.dev20250403190551.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/LICENSE +0 -0
- {liger_kernel_nightly-0.5.6.dev20250403190551.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/NOTICE +0 -0
- {liger_kernel_nightly-0.5.6.dev20250403190551.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/WHEEL +0 -0
- {liger_kernel_nightly-0.5.6.dev20250403190551.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/top_level.txt +0 -0
|
@@ -9,14 +9,12 @@ import torch
|
|
|
9
9
|
from torch.nn import CrossEntropyLoss
|
|
10
10
|
from transformers.cache_utils import HybridCache
|
|
11
11
|
from transformers.modeling_outputs import CausalLMOutputWithPast
|
|
12
|
-
from transformers.models.gemma2.modeling_gemma2 import _CONFIG_FOR_DOC
|
|
13
|
-
from transformers.models.gemma2.modeling_gemma2 import GEMMA2_INPUTS_DOCSTRING
|
|
14
|
-
from transformers.utils import add_start_docstrings_to_model_forward
|
|
15
|
-
from transformers.utils import replace_return_docstrings
|
|
16
12
|
from transformers.utils.deprecation import deprecate_kwarg
|
|
17
13
|
|
|
18
14
|
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
|
|
19
15
|
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
16
|
+
from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
|
|
17
|
+
from liger_kernel.transformers.model.output_classes import LigerCausalLMOutputWithPast
|
|
20
18
|
|
|
21
19
|
logger = logging.getLogger(__name__)
|
|
22
20
|
|
|
@@ -34,6 +32,8 @@ def lce_forward_deprecated(
|
|
|
34
32
|
output_hidden_states: Optional[bool] = None,
|
|
35
33
|
return_dict: Optional[bool] = None,
|
|
36
34
|
cache_position: Optional[torch.LongTensor] = None,
|
|
35
|
+
skip_logits: Optional[bool] = None,
|
|
36
|
+
**kwargs,
|
|
37
37
|
) -> Union[Tuple, CausalLMOutputWithPast]:
|
|
38
38
|
r"""
|
|
39
39
|
Args:
|
|
@@ -80,6 +80,7 @@ def lce_forward_deprecated(
|
|
|
80
80
|
output_hidden_states=output_hidden_states,
|
|
81
81
|
return_dict=return_dict,
|
|
82
82
|
cache_position=cache_position,
|
|
83
|
+
**kwargs,
|
|
83
84
|
)
|
|
84
85
|
|
|
85
86
|
hidden_states = outputs[0]
|
|
@@ -87,7 +88,14 @@ def lce_forward_deprecated(
|
|
|
87
88
|
loss = None
|
|
88
89
|
logits = None
|
|
89
90
|
|
|
90
|
-
if
|
|
91
|
+
if skip_logits and labels is None:
|
|
92
|
+
raise ValueError("skip_logits is True, but labels is None")
|
|
93
|
+
|
|
94
|
+
if skip_logits is None:
|
|
95
|
+
# By default, if in training mode, don't materialize logits
|
|
96
|
+
skip_logits = self.training and labels is not None
|
|
97
|
+
|
|
98
|
+
if skip_logits:
|
|
91
99
|
shift_hidden_states = hidden_states[..., :-1, :].contiguous()
|
|
92
100
|
shift_labels = labels[..., 1:].contiguous()
|
|
93
101
|
|
|
@@ -136,8 +144,6 @@ def lce_forward_deprecated(
|
|
|
136
144
|
|
|
137
145
|
|
|
138
146
|
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
|
139
|
-
@add_start_docstrings_to_model_forward(GEMMA2_INPUTS_DOCSTRING)
|
|
140
|
-
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
|
141
147
|
def lce_forward(
|
|
142
148
|
self,
|
|
143
149
|
input_ids: torch.LongTensor = None,
|
|
@@ -152,8 +158,9 @@ def lce_forward(
|
|
|
152
158
|
return_dict: Optional[bool] = None,
|
|
153
159
|
cache_position: Optional[torch.LongTensor] = None,
|
|
154
160
|
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
155
|
-
|
|
156
|
-
|
|
161
|
+
skip_logits: Optional[bool] = None,
|
|
162
|
+
**kwargs,
|
|
163
|
+
) -> Union[Tuple, LigerCausalLMOutputWithPast]:
|
|
157
164
|
r"""
|
|
158
165
|
Args:
|
|
159
166
|
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
@@ -209,43 +216,68 @@ def lce_forward(
|
|
|
209
216
|
output_hidden_states=output_hidden_states,
|
|
210
217
|
return_dict=return_dict,
|
|
211
218
|
cache_position=cache_position,
|
|
219
|
+
**kwargs,
|
|
212
220
|
)
|
|
213
221
|
|
|
214
222
|
hidden_states = outputs[0]
|
|
223
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
224
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
225
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
215
226
|
|
|
227
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
216
228
|
logits = None
|
|
217
229
|
loss = None
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
230
|
+
token_accuracy = None
|
|
231
|
+
|
|
232
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
233
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
234
|
+
|
|
235
|
+
if skip_logits is None:
|
|
236
|
+
# By default, if in training mode, don't materialize logits
|
|
237
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
238
|
+
|
|
239
|
+
# Compute loss
|
|
240
|
+
if skip_logits:
|
|
241
|
+
result = LigerForCausalLMLoss(
|
|
242
|
+
hidden_states=kept_hidden_states,
|
|
222
243
|
lm_head_weight=self.lm_head.weight,
|
|
223
244
|
labels=labels,
|
|
245
|
+
shift_labels=shift_labels,
|
|
224
246
|
hidden_size=self.config.hidden_size,
|
|
225
|
-
|
|
226
|
-
**
|
|
247
|
+
final_logit_softcapping=self.config.final_logit_softcapping,
|
|
248
|
+
**kwargs,
|
|
227
249
|
)
|
|
250
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
228
251
|
|
|
229
|
-
else:
|
|
230
|
-
|
|
231
|
-
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
|
252
|
+
else:
|
|
253
|
+
logits = self.lm_head(kept_hidden_states)
|
|
232
254
|
if self.config.final_logit_softcapping is not None:
|
|
233
255
|
logits = logits / self.config.final_logit_softcapping
|
|
234
256
|
logits = torch.tanh(logits)
|
|
235
257
|
logits = logits * self.config.final_logit_softcapping
|
|
236
258
|
|
|
237
259
|
loss = None
|
|
238
|
-
if labels is not None:
|
|
239
|
-
loss = self.loss_function(
|
|
260
|
+
if labels is not None or shift_labels is not None:
|
|
261
|
+
loss = self.loss_function(
|
|
262
|
+
logits=logits,
|
|
263
|
+
labels=labels,
|
|
264
|
+
shift_labels=shift_labels,
|
|
265
|
+
vocab_size=self.vocab_size,
|
|
266
|
+
**kwargs,
|
|
267
|
+
)
|
|
240
268
|
|
|
241
269
|
if not return_dict:
|
|
242
|
-
|
|
243
|
-
|
|
270
|
+
output_tuple = (logits,) + outputs[1:]
|
|
271
|
+
output_tuple = (loss,) + output_tuple if loss is not None else output_tuple
|
|
272
|
+
output_tuple = output_tuple + (token_accuracy,) if token_accuracy is not None else output_tuple
|
|
273
|
+
return output_tuple
|
|
244
274
|
|
|
245
|
-
|
|
275
|
+
# Return custom output class with token_accuracy field
|
|
276
|
+
return LigerCausalLMOutputWithPast(
|
|
246
277
|
loss=loss,
|
|
247
278
|
logits=logits,
|
|
248
279
|
past_key_values=outputs.past_key_values,
|
|
249
280
|
hidden_states=outputs.hidden_states,
|
|
250
281
|
attentions=outputs.attentions,
|
|
282
|
+
token_accuracy=token_accuracy,
|
|
251
283
|
)
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
from typing import List
|
|
2
1
|
from typing import Optional
|
|
3
2
|
from typing import Tuple
|
|
4
3
|
from typing import Union
|
|
@@ -8,25 +7,17 @@ import torch.nn as nn
|
|
|
8
7
|
|
|
9
8
|
from transformers.cache_utils import Cache
|
|
10
9
|
from transformers.cache_utils import HybridCache
|
|
11
|
-
from transformers.modeling_outputs import CausalLMOutputWithPast
|
|
12
|
-
from transformers.models.gemma3.modeling_gemma3 import _CONFIG_FOR_DOC
|
|
13
|
-
from transformers.models.gemma3.modeling_gemma3 import GEMMA3_INPUTS_DOCSTRING
|
|
14
|
-
from transformers.models.gemma3.modeling_gemma3 import Gemma3CausalLMOutputWithPast
|
|
15
|
-
from transformers.utils import add_start_docstrings_to_model_forward
|
|
16
|
-
from transformers.utils import is_torchdynamo_compiling
|
|
17
10
|
from transformers.utils import logging
|
|
18
|
-
from transformers.utils import replace_return_docstrings
|
|
19
|
-
from transformers.utils.deprecation import deprecate_kwarg
|
|
20
11
|
|
|
21
12
|
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
|
|
22
13
|
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
14
|
+
from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
|
|
15
|
+
from liger_kernel.transformers.model.output_classes import LigerCausalLMOutputWithPast
|
|
16
|
+
from liger_kernel.transformers.model.output_classes import LigerGemma3CausalLMOutputWithPast
|
|
23
17
|
|
|
24
18
|
logger = logging.get_logger(__name__)
|
|
25
19
|
|
|
26
20
|
|
|
27
|
-
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
|
28
|
-
@add_start_docstrings_to_model_forward(GEMMA3_INPUTS_DOCSTRING)
|
|
29
|
-
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
|
30
21
|
def causal_forward(
|
|
31
22
|
self,
|
|
32
23
|
input_ids: torch.LongTensor = None,
|
|
@@ -41,8 +32,9 @@ def causal_forward(
|
|
|
41
32
|
return_dict: Optional[bool] = None,
|
|
42
33
|
cache_position: Optional[torch.LongTensor] = None,
|
|
43
34
|
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
35
|
+
skip_logits: Optional[bool] = None,
|
|
44
36
|
**loss_kwargs,
|
|
45
|
-
) -> Union[Tuple,
|
|
37
|
+
) -> Union[Tuple, LigerCausalLMOutputWithPast]:
|
|
46
38
|
r"""
|
|
47
39
|
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
48
40
|
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
@@ -104,50 +96,65 @@ def causal_forward(
|
|
|
104
96
|
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
105
97
|
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
106
98
|
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
99
|
+
shift_labels = loss_kwargs.pop("shift_labels", None)
|
|
107
100
|
loss = None
|
|
108
101
|
logits = None
|
|
109
|
-
|
|
110
|
-
|
|
102
|
+
token_accuracy = None
|
|
103
|
+
|
|
104
|
+
if skip_logits is None:
|
|
105
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
106
|
+
|
|
107
|
+
# Compute loss
|
|
108
|
+
if skip_logits:
|
|
109
|
+
result = LigerForCausalLMLoss(
|
|
111
110
|
hidden_states=kept_hidden_states,
|
|
112
111
|
lm_head_weight=self.lm_head.weight,
|
|
113
112
|
labels=labels,
|
|
113
|
+
shift_labels=shift_labels,
|
|
114
114
|
hidden_size=self.config.hidden_size,
|
|
115
|
-
|
|
115
|
+
final_logit_softcapping=self.config.final_logit_softcapping,
|
|
116
116
|
**loss_kwargs,
|
|
117
117
|
)
|
|
118
|
-
|
|
118
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
119
119
|
else:
|
|
120
120
|
logits = self.lm_head(kept_hidden_states)
|
|
121
121
|
if self.config.final_logit_softcapping is not None:
|
|
122
122
|
logits = logits / self.config.final_logit_softcapping
|
|
123
123
|
logits = torch.tanh(logits)
|
|
124
124
|
logits = logits * self.config.final_logit_softcapping
|
|
125
|
-
if labels is not None:
|
|
126
|
-
loss = self.loss_function(
|
|
125
|
+
if labels is not None or shift_labels is not None:
|
|
126
|
+
loss = self.loss_function(
|
|
127
|
+
logits=logits,
|
|
128
|
+
labels=labels,
|
|
129
|
+
shift_labels=shift_labels,
|
|
130
|
+
vocab_size=self.vocab_size,
|
|
131
|
+
**loss_kwargs,
|
|
132
|
+
)
|
|
127
133
|
|
|
128
134
|
if not return_dict:
|
|
129
|
-
|
|
130
|
-
|
|
135
|
+
output_tuple = (logits,) + outputs[1:]
|
|
136
|
+
output_tuple = (loss,) + output_tuple if loss is not None else output_tuple
|
|
137
|
+
output_tuple = output_tuple + (token_accuracy,) if token_accuracy is not None else output_tuple
|
|
138
|
+
return output_tuple
|
|
131
139
|
|
|
132
|
-
|
|
140
|
+
# Return custom output class with token_accuracy field
|
|
141
|
+
return LigerCausalLMOutputWithPast(
|
|
133
142
|
loss=loss,
|
|
134
143
|
logits=logits,
|
|
135
144
|
past_key_values=outputs.past_key_values,
|
|
136
145
|
hidden_states=outputs.hidden_states,
|
|
137
146
|
attentions=outputs.attentions,
|
|
147
|
+
token_accuracy=token_accuracy,
|
|
138
148
|
)
|
|
139
149
|
|
|
140
150
|
|
|
141
|
-
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
|
142
|
-
@add_start_docstrings_to_model_forward(GEMMA3_INPUTS_DOCSTRING)
|
|
143
|
-
@replace_return_docstrings(output_type=Gemma3CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
|
144
151
|
def multimodal_forward(
|
|
145
152
|
self,
|
|
146
153
|
input_ids: torch.LongTensor = None,
|
|
147
154
|
pixel_values: torch.FloatTensor = None,
|
|
148
155
|
attention_mask: Optional[torch.Tensor] = None,
|
|
149
156
|
position_ids: Optional[torch.LongTensor] = None,
|
|
150
|
-
past_key_values: Optional[Union[
|
|
157
|
+
past_key_values: Optional[Union[list[torch.FloatTensor], Cache]] = None,
|
|
151
158
|
token_type_ids: Optional[torch.LongTensor] = None,
|
|
152
159
|
cache_position: Optional[torch.LongTensor] = None,
|
|
153
160
|
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
@@ -157,22 +164,14 @@ def multimodal_forward(
|
|
|
157
164
|
output_hidden_states: Optional[bool] = None,
|
|
158
165
|
return_dict: Optional[bool] = None,
|
|
159
166
|
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
167
|
+
skip_logits: Optional[bool] = None,
|
|
160
168
|
**lm_kwargs,
|
|
161
|
-
) -> Union[
|
|
169
|
+
) -> Union[tuple, LigerGemma3CausalLMOutputWithPast]:
|
|
162
170
|
r"""
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
169
|
-
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
170
|
-
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
171
|
-
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
172
|
-
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
173
|
-
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
174
|
-
|
|
175
|
-
Returns:
|
|
171
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
172
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
173
|
+
config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
174
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
|
|
176
175
|
|
|
177
176
|
Example:
|
|
178
177
|
|
|
@@ -181,23 +180,37 @@ def multimodal_forward(
|
|
|
181
180
|
>>> import requests
|
|
182
181
|
>>> from transformers import AutoProcessor, Gemma3ForConditionalGeneration
|
|
183
182
|
|
|
184
|
-
>>> model = Gemma3ForConditionalGeneration.from_pretrained("google/
|
|
185
|
-
>>> processor = AutoProcessor.from_pretrained("google/
|
|
186
|
-
|
|
187
|
-
>>>
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
183
|
+
>>> model = Gemma3ForConditionalGeneration.from_pretrained("google/gemma-3-4b-it")
|
|
184
|
+
>>> processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it")
|
|
185
|
+
|
|
186
|
+
>>> messages = [
|
|
187
|
+
... {
|
|
188
|
+
... "role": "system",
|
|
189
|
+
... "content": [
|
|
190
|
+
... {"type": "text", "text": "You are a helpful assistant."}
|
|
191
|
+
... ]
|
|
192
|
+
... },
|
|
193
|
+
... {
|
|
194
|
+
... "role": "user", "content": [
|
|
195
|
+
... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
|
|
196
|
+
... {"type": "text", "text": "Where is the cat standing?"},
|
|
197
|
+
... ]
|
|
198
|
+
... },
|
|
199
|
+
... ]
|
|
200
|
+
|
|
201
|
+
>>> inputs = processor.apply_chat_template(
|
|
202
|
+
... messages,
|
|
203
|
+
... tokenize=True,
|
|
204
|
+
... return_dict=True,
|
|
205
|
+
... return_tensors="pt",
|
|
206
|
+
... add_generation_prompt=True
|
|
207
|
+
... )
|
|
193
208
|
>>> # Generate
|
|
194
|
-
>>> generate_ids = model.generate(**inputs
|
|
209
|
+
>>> generate_ids = model.generate(**inputs)
|
|
195
210
|
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
196
|
-
"
|
|
197
|
-
```
|
|
198
|
-
|
|
199
|
-
if (input_ids is None) ^ (inputs_embeds is not None):
|
|
200
|
-
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
|
211
|
+
"user\nYou are a helpful assistant.\n\n\n\n\n\nWhere is the cat standing?\nmodel\nBased on the image, the cat is standing in a snowy area, likely outdoors. It appears to"
|
|
212
|
+
```
|
|
213
|
+
"""
|
|
201
214
|
|
|
202
215
|
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
203
216
|
output_hidden_states = (
|
|
@@ -205,81 +218,40 @@ def multimodal_forward(
|
|
|
205
218
|
)
|
|
206
219
|
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
207
220
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
llm_input_ids = input_ids.clone()
|
|
214
|
-
llm_input_ids[special_image_mask] = 0
|
|
215
|
-
else:
|
|
216
|
-
llm_input_ids = input_ids
|
|
217
|
-
|
|
218
|
-
if inputs_embeds is None:
|
|
219
|
-
inputs_embeds = self.get_input_embeddings()(llm_input_ids)
|
|
220
|
-
|
|
221
|
-
if cache_position is None:
|
|
222
|
-
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
|
223
|
-
cache_position = torch.arange(
|
|
224
|
-
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
|
225
|
-
)
|
|
226
|
-
|
|
227
|
-
if position_ids is None:
|
|
228
|
-
position_ids = cache_position.unsqueeze(0) + 1 # Gemma3 positions are 1-indexed
|
|
229
|
-
|
|
230
|
-
# Merge text and images
|
|
231
|
-
if pixel_values is not None:
|
|
232
|
-
image_features = self.get_image_features(pixel_values)
|
|
233
|
-
|
|
234
|
-
if input_ids is None:
|
|
235
|
-
special_image_mask = inputs_embeds == self.get_input_embeddings()(
|
|
236
|
-
torch.tensor(self.config.image_token_index, dtype=torch.long, device=inputs_embeds.device)
|
|
237
|
-
)
|
|
238
|
-
else:
|
|
239
|
-
special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
|
|
240
|
-
special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
|
|
241
|
-
|
|
242
|
-
if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
|
|
243
|
-
image_tokens_in_text = (special_image_mask).sum(dim=1).sum(dim=0)[0]
|
|
244
|
-
raise ValueError(
|
|
245
|
-
f"Number of images does not match number of special image tokens in the input text. "
|
|
246
|
-
f"Got {image_tokens_in_text} image tokens in the text but {image_features.shape[0] * image_features.shape[1]} "
|
|
247
|
-
"tokens from image embeddings."
|
|
248
|
-
)
|
|
249
|
-
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
250
|
-
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
|
251
|
-
|
|
252
|
-
# mask out pad-token-ids in labels for BC
|
|
253
|
-
if labels is not None and self.pad_token_id in labels:
|
|
254
|
-
logger.warning_once(
|
|
255
|
-
"`labels` contains `pad_token_id` which will be masked with `config.ignore_index`. "
|
|
256
|
-
"You have to mask out `pad_token_id` when preparing `labels`, this behavior will be removed in v.4.46.",
|
|
257
|
-
)
|
|
258
|
-
labels = torch.where(input_ids == self.pad_token_id, self.config.ignore_index, labels)
|
|
259
|
-
|
|
260
|
-
causal_mask = self._update_causal_mask(
|
|
261
|
-
attention_mask, token_type_ids, past_key_values, cache_position, inputs_embeds, is_training
|
|
262
|
-
)
|
|
263
|
-
outputs = self.language_model.model(
|
|
264
|
-
attention_mask=causal_mask,
|
|
221
|
+
outputs = self.model(
|
|
222
|
+
input_ids=input_ids,
|
|
223
|
+
pixel_values=pixel_values,
|
|
224
|
+
token_type_ids=token_type_ids,
|
|
225
|
+
attention_mask=attention_mask,
|
|
265
226
|
position_ids=position_ids,
|
|
266
227
|
past_key_values=past_key_values,
|
|
267
228
|
inputs_embeds=inputs_embeds,
|
|
268
229
|
use_cache=use_cache,
|
|
230
|
+
labels=labels,
|
|
269
231
|
output_attentions=output_attentions,
|
|
270
232
|
output_hidden_states=output_hidden_states,
|
|
271
233
|
return_dict=return_dict,
|
|
272
234
|
cache_position=cache_position,
|
|
273
|
-
logits_to_keep=logits_to_keep,
|
|
274
235
|
**lm_kwargs,
|
|
275
236
|
)
|
|
276
237
|
|
|
238
|
+
shift_labels = lm_kwargs.pop("shift_labels", None)
|
|
277
239
|
hidden_states = outputs[0]
|
|
240
|
+
|
|
241
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
242
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
243
|
+
|
|
278
244
|
loss = None
|
|
279
245
|
logits = None
|
|
246
|
+
token_accuracy = None
|
|
247
|
+
if skip_logits and labels is None:
|
|
248
|
+
raise ValueError("skip_logits is True, but labels is None")
|
|
280
249
|
|
|
281
|
-
if
|
|
282
|
-
|
|
250
|
+
if skip_logits is None:
|
|
251
|
+
skip_logits = self.training and (labels is not None)
|
|
252
|
+
|
|
253
|
+
if skip_logits:
|
|
254
|
+
shift_hidden_states = kept_hidden_states[..., :-1, :]
|
|
283
255
|
shift_labels = labels[..., 1:]
|
|
284
256
|
|
|
285
257
|
hidden_device = shift_hidden_states.device
|
|
@@ -298,9 +270,11 @@ def multimodal_forward(
|
|
|
298
270
|
shift_labels = shift_labels.view(-1).to(hidden_device)
|
|
299
271
|
|
|
300
272
|
lce = LigerFusedLinearCrossEntropyLoss()
|
|
301
|
-
|
|
273
|
+
result = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
274
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
275
|
+
|
|
302
276
|
else:
|
|
303
|
-
logits = self.
|
|
277
|
+
logits = self.lm_head(kept_hidden_states)
|
|
304
278
|
if labels is not None:
|
|
305
279
|
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
|
306
280
|
logits = logits.float()
|
|
@@ -321,15 +295,38 @@ def multimodal_forward(
|
|
|
321
295
|
flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
|
|
322
296
|
flat_labels = shift_labels.view(-1).to(shift_logits.device)
|
|
323
297
|
loss = loss_fct(flat_logits, flat_labels)
|
|
298
|
+
elif shift_labels is not None:
|
|
299
|
+
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
|
300
|
+
logits = logits.float()
|
|
301
|
+
shift_logits = logits[..., :-1, :]
|
|
302
|
+
if attention_mask is not None:
|
|
303
|
+
# we use the input attention mask to shift the logits and labels, because it is 2D.
|
|
304
|
+
# we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
|
|
305
|
+
shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
|
|
306
|
+
shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
|
|
307
|
+
shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
|
|
308
|
+
else:
|
|
309
|
+
shift_logits = shift_logits.contiguous()
|
|
310
|
+
shift_labels = shift_labels.contiguous()
|
|
311
|
+
# Flatten the tokens
|
|
312
|
+
loss_fct = nn.CrossEntropyLoss()
|
|
313
|
+
|
|
314
|
+
flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
|
|
315
|
+
flat_labels = shift_labels.view(-1).to(shift_logits.device)
|
|
316
|
+
loss = loss_fct(flat_logits, flat_labels)
|
|
317
|
+
|
|
324
318
|
if not return_dict:
|
|
325
319
|
output = (logits,) + outputs[1:]
|
|
326
|
-
|
|
320
|
+
output = (loss,) + output if loss is not None else output
|
|
321
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
322
|
+
return output
|
|
327
323
|
|
|
328
|
-
return
|
|
324
|
+
return LigerGemma3CausalLMOutputWithPast(
|
|
329
325
|
loss=loss,
|
|
330
326
|
logits=logits,
|
|
331
327
|
past_key_values=outputs.past_key_values,
|
|
332
328
|
hidden_states=outputs.hidden_states,
|
|
333
329
|
attentions=outputs.attentions,
|
|
334
|
-
image_hidden_states=
|
|
330
|
+
image_hidden_states=outputs.image_hidden_states,
|
|
331
|
+
token_accuracy=token_accuracy,
|
|
335
332
|
)
|
|
@@ -0,0 +1,141 @@
|
|
|
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 transformers.utils.deprecation import deprecate_kwarg
|
|
9
|
+
|
|
10
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
11
|
+
from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
|
|
12
|
+
from liger_kernel.transformers.model.output_classes import LigerCausalLMOutputWithPast
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
|
16
|
+
def lce_forward(
|
|
17
|
+
self,
|
|
18
|
+
input_ids: torch.LongTensor = None,
|
|
19
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
20
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
21
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
22
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
23
|
+
labels: Optional[torch.LongTensor] = None,
|
|
24
|
+
use_cache: Optional[bool] = None,
|
|
25
|
+
output_attentions: Optional[bool] = None,
|
|
26
|
+
output_hidden_states: Optional[bool] = None,
|
|
27
|
+
return_dict: Optional[bool] = None,
|
|
28
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
29
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
30
|
+
skip_logits: Optional[bool] = None,
|
|
31
|
+
**kwargs,
|
|
32
|
+
) -> Union[Tuple, LigerCausalLMOutputWithPast]:
|
|
33
|
+
r"""
|
|
34
|
+
Args:
|
|
35
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
36
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
37
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
38
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
39
|
+
|
|
40
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
41
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
42
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
43
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
44
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
45
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
|
|
49
|
+
Example:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
>>> from transformers import AutoTokenizer, Glm4ForCausalLM
|
|
53
|
+
|
|
54
|
+
>>> model = Glm4ForCausalLM.from_pretrained("THUDM/GLM-4-9B-0414")
|
|
55
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("THUDM/GLM-4-9B-0414")
|
|
56
|
+
|
|
57
|
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
|
58
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
59
|
+
|
|
60
|
+
>>> # Generate
|
|
61
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
62
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
63
|
+
'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m'
|
|
64
|
+
```
|
|
65
|
+
"""
|
|
66
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
67
|
+
output_hidden_states = (
|
|
68
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
69
|
+
)
|
|
70
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
71
|
+
|
|
72
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
73
|
+
outputs = self.model(
|
|
74
|
+
input_ids=input_ids,
|
|
75
|
+
attention_mask=attention_mask,
|
|
76
|
+
position_ids=position_ids,
|
|
77
|
+
past_key_values=past_key_values,
|
|
78
|
+
inputs_embeds=inputs_embeds,
|
|
79
|
+
use_cache=use_cache,
|
|
80
|
+
output_attentions=output_attentions,
|
|
81
|
+
output_hidden_states=output_hidden_states,
|
|
82
|
+
return_dict=return_dict,
|
|
83
|
+
cache_position=cache_position,
|
|
84
|
+
**kwargs,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
hidden_states = outputs[0]
|
|
88
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
89
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
90
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
91
|
+
|
|
92
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
93
|
+
logits = None
|
|
94
|
+
loss = None
|
|
95
|
+
token_accuracy = None
|
|
96
|
+
|
|
97
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
98
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
99
|
+
|
|
100
|
+
if skip_logits is None:
|
|
101
|
+
# By default, if in training mode, don't materialize logits
|
|
102
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
103
|
+
|
|
104
|
+
# Compute loss
|
|
105
|
+
if skip_logits:
|
|
106
|
+
result = LigerForCausalLMLoss(
|
|
107
|
+
hidden_states=kept_hidden_states,
|
|
108
|
+
lm_head_weight=self.lm_head.weight,
|
|
109
|
+
labels=labels,
|
|
110
|
+
shift_labels=shift_labels,
|
|
111
|
+
hidden_size=self.config.hidden_size,
|
|
112
|
+
**kwargs,
|
|
113
|
+
)
|
|
114
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
115
|
+
|
|
116
|
+
else:
|
|
117
|
+
logits = self.lm_head(kept_hidden_states)
|
|
118
|
+
if labels is not None or shift_labels is not None:
|
|
119
|
+
loss = self.loss_function(
|
|
120
|
+
logits=logits,
|
|
121
|
+
labels=labels,
|
|
122
|
+
shift_labels=shift_labels,
|
|
123
|
+
vocab_size=self.config.vocab_size,
|
|
124
|
+
**kwargs,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
if not return_dict:
|
|
128
|
+
output = (logits,) + outputs[1:]
|
|
129
|
+
output = ((loss,) + output) if loss is not None else output
|
|
130
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
131
|
+
return output
|
|
132
|
+
|
|
133
|
+
# Return custom output class with token_accuracy field
|
|
134
|
+
return LigerCausalLMOutputWithPast(
|
|
135
|
+
loss=loss,
|
|
136
|
+
logits=logits,
|
|
137
|
+
past_key_values=outputs.past_key_values,
|
|
138
|
+
hidden_states=outputs.hidden_states,
|
|
139
|
+
attentions=outputs.attentions,
|
|
140
|
+
token_accuracy=token_accuracy,
|
|
141
|
+
)
|