liger-kernel-nightly 0.4.0.dev20241107052928__py3-none-any.whl → 0.6.3.dev20251121010306__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/__init__.py +0 -0
- liger_kernel/chunked_loss/README.md +25 -0
- liger_kernel/chunked_loss/__init__.py +8 -0
- liger_kernel/chunked_loss/cosine_similarity_loss.py +136 -0
- liger_kernel/chunked_loss/cpo_loss.py +157 -0
- liger_kernel/chunked_loss/dpo_loss.py +229 -0
- liger_kernel/chunked_loss/functional.py +17 -0
- liger_kernel/chunked_loss/fused_linear_distillation.py +292 -0
- liger_kernel/chunked_loss/fused_linear_ppo.py +350 -0
- liger_kernel/chunked_loss/fused_linear_preference.py +433 -0
- liger_kernel/chunked_loss/fused_linear_unpaired_preference.py +341 -0
- liger_kernel/chunked_loss/grpo_loss.py +304 -0
- liger_kernel/chunked_loss/jsd_loss.py +200 -0
- liger_kernel/chunked_loss/kto_loss.py +210 -0
- liger_kernel/chunked_loss/orpo_loss.py +144 -0
- liger_kernel/chunked_loss/simpo_loss.py +165 -0
- liger_kernel/env_report.py +21 -4
- liger_kernel/ops/cross_entropy.py +235 -84
- liger_kernel/ops/dyt.py +157 -0
- liger_kernel/ops/experimental/embedding.py +1 -3
- liger_kernel/ops/experimental/mm_int8int2.py +3 -9
- liger_kernel/ops/fused_add_rms_norm.py +412 -0
- liger_kernel/ops/fused_linear_cross_entropy.py +197 -75
- liger_kernel/ops/fused_linear_jsd.py +17 -34
- liger_kernel/ops/fused_neighborhood_attention.py +1022 -0
- liger_kernel/ops/geglu.py +7 -18
- liger_kernel/ops/group_norm.py +305 -0
- liger_kernel/ops/grpo_loss.py +310 -0
- liger_kernel/ops/jsd.py +46 -21
- liger_kernel/ops/kl_div.py +23 -19
- liger_kernel/ops/layer_norm.py +150 -86
- liger_kernel/ops/llama4_rope.py +225 -0
- liger_kernel/ops/multi_token_attention.py +207 -0
- liger_kernel/ops/poly_norm.py +386 -0
- liger_kernel/ops/qwen2vl_mrope.py +222 -0
- liger_kernel/ops/rms_norm.py +314 -84
- liger_kernel/ops/rope.py +32 -34
- liger_kernel/ops/softmax.py +201 -0
- liger_kernel/ops/sparsemax.py +179 -0
- liger_kernel/ops/swiglu.py +5 -9
- liger_kernel/ops/tiled_mlp.py +136 -0
- liger_kernel/ops/tvd.py +207 -0
- liger_kernel/ops/utils.py +8 -4
- liger_kernel/transformers/__init__.py +199 -24
- liger_kernel/transformers/auto_model.py +6 -13
- liger_kernel/transformers/cross_entropy.py +33 -20
- liger_kernel/transformers/dyt.py +22 -0
- liger_kernel/transformers/experimental/__init__.py +5 -0
- liger_kernel/transformers/experimental/embedding.py +1 -3
- liger_kernel/transformers/fsdp.py +55 -0
- liger_kernel/transformers/functional.py +291 -13
- liger_kernel/transformers/fused_add_rms_norm.py +39 -0
- liger_kernel/transformers/fused_linear_cross_entropy.py +43 -14
- liger_kernel/transformers/fused_linear_jsd.py +1 -4
- liger_kernel/transformers/fused_neighborhood_attention.py +234 -0
- liger_kernel/transformers/geglu.py +1 -4
- liger_kernel/transformers/group_norm.py +50 -0
- liger_kernel/transformers/grpo_loss.py +98 -0
- liger_kernel/transformers/jsd.py +2 -7
- liger_kernel/transformers/kl_div.py +1 -3
- liger_kernel/transformers/layer_norm.py +3 -9
- liger_kernel/transformers/llama4_rope.py +93 -0
- liger_kernel/transformers/model/falcon_h1.py +122 -0
- liger_kernel/transformers/model/gemma.py +77 -77
- liger_kernel/transformers/model/gemma2.py +283 -0
- liger_kernel/transformers/model/gemma3.py +331 -0
- 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/internvl.py +157 -0
- liger_kernel/transformers/model/llama.py +128 -79
- liger_kernel/transformers/model/llama4.py +121 -0
- liger_kernel/transformers/model/llava.py +344 -0
- liger_kernel/transformers/model/loss_utils.py +95 -0
- liger_kernel/transformers/model/mistral.py +68 -64
- liger_kernel/transformers/model/mixtral.py +75 -91
- liger_kernel/transformers/model/mllama.py +63 -68
- liger_kernel/transformers/model/olmo2.py +141 -0
- liger_kernel/transformers/model/output_classes.py +147 -0
- liger_kernel/transformers/model/paligemma.py +432 -0
- liger_kernel/transformers/model/phi3.py +59 -213
- liger_kernel/transformers/model/qwen2.py +75 -72
- liger_kernel/transformers/model/qwen2_5_vl.py +163 -0
- liger_kernel/transformers/model/qwen2_vl.py +78 -98
- 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 +2106 -289
- liger_kernel/transformers/multi_token_attention.py +64 -0
- liger_kernel/transformers/poly_norm.py +42 -0
- liger_kernel/transformers/qwen2vl_mrope.py +20 -0
- liger_kernel/transformers/rms_norm.py +57 -6
- liger_kernel/transformers/rope.py +45 -2
- liger_kernel/transformers/softmax.py +12 -0
- liger_kernel/transformers/sparsemax.py +16 -0
- liger_kernel/transformers/swiglu.py +23 -8
- liger_kernel/transformers/tiled_mlp.py +133 -0
- liger_kernel/transformers/trainer/__init__.py +4 -0
- liger_kernel/transformers/trainer/orpo_trainer.py +130 -0
- liger_kernel/transformers/tvd.py +13 -0
- liger_kernel/triton/__init__.py +1 -3
- liger_kernel/triton/monkey_patch.py +1 -3
- liger_kernel/utils.py +71 -0
- {liger_kernel_nightly-0.4.0.dev20241107052928.dist-info → liger_kernel_nightly-0.6.3.dev20251121010306.dist-info}/METADATA +150 -137
- liger_kernel_nightly-0.6.3.dev20251121010306.dist-info/RECORD +116 -0
- {liger_kernel_nightly-0.4.0.dev20241107052928.dist-info → liger_kernel_nightly-0.6.3.dev20251121010306.dist-info}/WHEEL +1 -1
- liger_kernel_nightly-0.4.0.dev20241107052928.dist-info/RECORD +0 -48
- {liger_kernel_nightly-0.4.0.dev20241107052928.dist-info → liger_kernel_nightly-0.6.3.dev20251121010306.dist-info}/LICENSE +0 -0
- {liger_kernel_nightly-0.4.0.dev20241107052928.dist-info → liger_kernel_nightly-0.6.3.dev20251121010306.dist-info}/NOTICE +0 -0
- {liger_kernel_nightly-0.4.0.dev20241107052928.dist-info → liger_kernel_nightly-0.6.3.dev20251121010306.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,163 @@
|
|
|
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 import can_return_tuple
|
|
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 LigerQwen2_5_VLCausalLMOutputWithPast
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@can_return_tuple
|
|
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
|
+
pixel_values: Optional[torch.Tensor] = None,
|
|
29
|
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
|
30
|
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
31
|
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
32
|
+
rope_deltas: Optional[torch.LongTensor] = None,
|
|
33
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
34
|
+
second_per_grid_ts: Optional[torch.Tensor] = None,
|
|
35
|
+
skip_logits: Optional[bool] = None,
|
|
36
|
+
**kwargs,
|
|
37
|
+
) -> Union[Tuple, LigerQwen2_5_VLCausalLMOutputWithPast]:
|
|
38
|
+
r"""
|
|
39
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
40
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
41
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
42
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
43
|
+
pixel_values_videos (`torch.FloatTensor` of shape `(seq_length, num_channels * temporal_size * image_size * image_size)):
|
|
44
|
+
The tensors corresponding to the input videos. Pixel values can be obtained using
|
|
45
|
+
[`AutoImageProcessor`]. See [`Qwen2_5_VLImageProcessor.__call__`] for details. [`Qwen2_5_VLProcessor`] uses
|
|
46
|
+
[`Qwen2_5_VLImageProcessor`] for processing videos.
|
|
47
|
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
|
48
|
+
The temporal, height and width of feature shape of each image in LLM.
|
|
49
|
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
|
50
|
+
The temporal, height and width of feature shape of each video in LLM.
|
|
51
|
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
|
52
|
+
The rope index difference between sequence length and multimodal rope.
|
|
53
|
+
second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*):
|
|
54
|
+
The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
|
|
55
|
+
|
|
56
|
+
Example:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
>>> from PIL import Image
|
|
60
|
+
>>> import requests
|
|
61
|
+
>>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
|
|
62
|
+
|
|
63
|
+
>>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
|
|
64
|
+
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
|
|
65
|
+
|
|
66
|
+
>>> messages = [
|
|
67
|
+
{
|
|
68
|
+
"role": "user",
|
|
69
|
+
"content": [
|
|
70
|
+
{"type": "image"},
|
|
71
|
+
{"type": "text", "text": "What is shown in this image?"},
|
|
72
|
+
],
|
|
73
|
+
},
|
|
74
|
+
]
|
|
75
|
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
|
76
|
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
|
77
|
+
|
|
78
|
+
>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
79
|
+
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
|
|
80
|
+
|
|
81
|
+
>>> # Generate
|
|
82
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
83
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
84
|
+
"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 ..."
|
|
85
|
+
```"""
|
|
86
|
+
|
|
87
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
88
|
+
output_hidden_states = (
|
|
89
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
90
|
+
)
|
|
91
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
92
|
+
|
|
93
|
+
outputs = self.model(
|
|
94
|
+
input_ids=input_ids,
|
|
95
|
+
pixel_values=pixel_values,
|
|
96
|
+
pixel_values_videos=pixel_values_videos,
|
|
97
|
+
image_grid_thw=image_grid_thw,
|
|
98
|
+
video_grid_thw=video_grid_thw,
|
|
99
|
+
second_per_grid_ts=second_per_grid_ts,
|
|
100
|
+
position_ids=position_ids,
|
|
101
|
+
attention_mask=attention_mask,
|
|
102
|
+
past_key_values=past_key_values,
|
|
103
|
+
inputs_embeds=inputs_embeds,
|
|
104
|
+
use_cache=use_cache,
|
|
105
|
+
output_attentions=output_attentions,
|
|
106
|
+
output_hidden_states=output_hidden_states,
|
|
107
|
+
return_dict=return_dict,
|
|
108
|
+
cache_position=cache_position,
|
|
109
|
+
**kwargs,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
hidden_states = outputs[0]
|
|
113
|
+
|
|
114
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
115
|
+
loss = None
|
|
116
|
+
logits = None
|
|
117
|
+
token_accuracy = None
|
|
118
|
+
|
|
119
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
120
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
121
|
+
|
|
122
|
+
if skip_logits is None:
|
|
123
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
124
|
+
|
|
125
|
+
# Compute loss
|
|
126
|
+
if skip_logits:
|
|
127
|
+
result = LigerForCausalLMLoss(
|
|
128
|
+
hidden_states=hidden_states,
|
|
129
|
+
lm_head_weight=self.lm_head.weight,
|
|
130
|
+
labels=labels,
|
|
131
|
+
shift_labels=shift_labels,
|
|
132
|
+
hidden_size=self.config.hidden_size,
|
|
133
|
+
**kwargs,
|
|
134
|
+
)
|
|
135
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
136
|
+
else:
|
|
137
|
+
logits = self.lm_head(hidden_states)
|
|
138
|
+
|
|
139
|
+
loss = None
|
|
140
|
+
if labels is not None or shift_labels is not None:
|
|
141
|
+
loss = self.loss_function(
|
|
142
|
+
logits=logits,
|
|
143
|
+
labels=labels,
|
|
144
|
+
shift_labels=shift_labels,
|
|
145
|
+
vocab_size=self.config.vocab_size,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
if not return_dict:
|
|
149
|
+
output_tuple = (logits,) + outputs[1:]
|
|
150
|
+
output = (loss,) + output_tuple if loss is not None else output_tuple
|
|
151
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
152
|
+
return output
|
|
153
|
+
|
|
154
|
+
# Return Qwen2.5-VL output with token accuracy
|
|
155
|
+
return LigerQwen2_5_VLCausalLMOutputWithPast(
|
|
156
|
+
loss=loss,
|
|
157
|
+
logits=logits,
|
|
158
|
+
past_key_values=outputs.past_key_values,
|
|
159
|
+
hidden_states=outputs.hidden_states,
|
|
160
|
+
attentions=outputs.attentions,
|
|
161
|
+
rope_deltas=outputs.rope_deltas,
|
|
162
|
+
token_accuracy=token_accuracy,
|
|
163
|
+
)
|
|
@@ -1,26 +1,18 @@
|
|
|
1
|
-
from typing import List
|
|
1
|
+
from typing import List
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from typing import Tuple
|
|
4
|
+
from typing import Union
|
|
2
5
|
|
|
3
6
|
import torch
|
|
4
|
-
|
|
5
|
-
from transformers.
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
)
|
|
14
|
-
|
|
15
|
-
from liger_kernel.transformers.fused_linear_cross_entropy import (
|
|
16
|
-
LigerFusedLinearCrossEntropyLoss,
|
|
17
|
-
)
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
@add_start_docstrings_to_model_forward(QWEN2_VL_INPUTS_DOCSTRING)
|
|
21
|
-
@replace_return_docstrings(
|
|
22
|
-
output_type=Qwen2VLCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
|
|
23
|
-
)
|
|
7
|
+
|
|
8
|
+
from transformers.utils import can_return_tuple
|
|
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 LigerQwen2VLCausalLMOutputWithPast
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@can_return_tuple
|
|
24
16
|
def lce_forward(
|
|
25
17
|
self,
|
|
26
18
|
input_ids: torch.LongTensor = None,
|
|
@@ -38,17 +30,25 @@ def lce_forward(
|
|
|
38
30
|
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
39
31
|
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
40
32
|
rope_deltas: Optional[torch.LongTensor] = None,
|
|
41
|
-
|
|
33
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
34
|
+
skip_logits: Optional[bool] = None,
|
|
35
|
+
**kwargs,
|
|
36
|
+
) -> Union[Tuple, LigerQwen2VLCausalLMOutputWithPast]:
|
|
42
37
|
r"""
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
38
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
39
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
40
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
41
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
42
|
+
pixel_values_videos (`torch.FloatTensor` of shape `(seq_length, num_channels * temporal_size * image_size * image_size)):
|
|
43
|
+
The tensors corresponding to the input videos. Pixel values can be obtained using
|
|
44
|
+
[`AutoImageProcessor`]. See [`Qwen2VLImageProcessor.__call__`] for details. [`Qwen2VLProcessor`] uses
|
|
45
|
+
[`Qwen2VLImageProcessor`] for processing videos.
|
|
46
|
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
|
47
|
+
The temporal, height and width of feature shape of each image in LLM.
|
|
48
|
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
|
49
|
+
The temporal, height and width of feature shape of each video in LLM.
|
|
50
|
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
|
51
|
+
The rope index difference between sequence length and multimodal rope.
|
|
52
52
|
|
|
53
53
|
Example:
|
|
54
54
|
|
|
@@ -80,50 +80,19 @@ def lce_forward(
|
|
|
80
80
|
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
81
81
|
"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 ..."
|
|
82
82
|
```"""
|
|
83
|
-
# FIXME: The code is outdated and not compatible with transformer >= 4.46.1
|
|
84
83
|
|
|
85
|
-
output_attentions =
|
|
86
|
-
output_attentions
|
|
87
|
-
if output_attentions is not None
|
|
88
|
-
else self.config.output_attentions
|
|
89
|
-
)
|
|
84
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
90
85
|
output_hidden_states = (
|
|
91
|
-
output_hidden_states
|
|
92
|
-
if output_hidden_states is not None
|
|
93
|
-
else self.config.output_hidden_states
|
|
86
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
94
87
|
)
|
|
95
|
-
return_dict =
|
|
96
|
-
return_dict if return_dict is not None else self.config.use_return_dict
|
|
97
|
-
)
|
|
98
|
-
|
|
99
|
-
if inputs_embeds is None:
|
|
100
|
-
inputs_embeds = self.model.embed_tokens(input_ids)
|
|
101
|
-
if pixel_values is not None:
|
|
102
|
-
pixel_values = pixel_values.type(self.visual.get_dtype())
|
|
103
|
-
image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw).to(
|
|
104
|
-
inputs_embeds.device
|
|
105
|
-
)
|
|
106
|
-
image_mask = input_ids == self.config.image_token_id
|
|
107
|
-
if self.training:
|
|
108
|
-
inputs_embeds = inputs_embeds.clone()
|
|
109
|
-
inputs_embeds[image_mask] = image_embeds
|
|
110
|
-
if pixel_values_videos is not None:
|
|
111
|
-
pixel_values_videos = pixel_values_videos.type(self.visual.get_dtype())
|
|
112
|
-
video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw).to(
|
|
113
|
-
inputs_embeds.device
|
|
114
|
-
)
|
|
115
|
-
video_mask = input_ids == self.config.video_token_id
|
|
116
|
-
inputs_embeds[video_mask] = video_embeds
|
|
117
|
-
if attention_mask is not None:
|
|
118
|
-
attention_mask = attention_mask.to(inputs_embeds.device)
|
|
119
|
-
# The code is copied from https://github.com/huggingface/transformers/pull/33487
|
|
120
|
-
if position_ids is None and input_ids is not None:
|
|
121
|
-
position_ids, _ = self.get_rope_index(
|
|
122
|
-
input_ids, image_grid_thw, video_grid_thw, attention_mask
|
|
123
|
-
)
|
|
88
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
124
89
|
|
|
125
90
|
outputs = self.model(
|
|
126
|
-
input_ids=
|
|
91
|
+
input_ids=input_ids,
|
|
92
|
+
pixel_values=pixel_values,
|
|
93
|
+
pixel_values_videos=pixel_values_videos,
|
|
94
|
+
image_grid_thw=image_grid_thw,
|
|
95
|
+
video_grid_thw=video_grid_thw,
|
|
127
96
|
position_ids=position_ids,
|
|
128
97
|
attention_mask=attention_mask,
|
|
129
98
|
past_key_values=past_key_values,
|
|
@@ -132,48 +101,59 @@ def lce_forward(
|
|
|
132
101
|
output_attentions=output_attentions,
|
|
133
102
|
output_hidden_states=output_hidden_states,
|
|
134
103
|
return_dict=return_dict,
|
|
104
|
+
cache_position=cache_position,
|
|
105
|
+
**kwargs,
|
|
135
106
|
)
|
|
136
107
|
|
|
137
108
|
hidden_states = outputs[0]
|
|
138
109
|
|
|
110
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
139
111
|
loss = None
|
|
140
112
|
logits = None
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
113
|
+
token_accuracy = None
|
|
114
|
+
|
|
115
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
116
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
117
|
+
|
|
118
|
+
if skip_logits is None:
|
|
119
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
120
|
+
|
|
121
|
+
# Compute loss
|
|
122
|
+
if skip_logits:
|
|
123
|
+
result = LigerForCausalLMLoss(
|
|
124
|
+
hidden_states=hidden_states,
|
|
125
|
+
lm_head_weight=self.lm_head.weight,
|
|
126
|
+
labels=labels,
|
|
127
|
+
shift_labels=shift_labels,
|
|
128
|
+
hidden_size=self.config.hidden_size,
|
|
129
|
+
**kwargs,
|
|
130
|
+
)
|
|
131
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
152
132
|
else:
|
|
153
133
|
logits = self.lm_head(hidden_states)
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
shift_labels = shift_labels.view(-1)
|
|
164
|
-
# Enable model parallelism
|
|
165
|
-
shift_labels = shift_labels.to(shift_logits.device)
|
|
166
|
-
loss = loss_fct(shift_logits, shift_labels)
|
|
134
|
+
|
|
135
|
+
loss = None
|
|
136
|
+
if labels is not None or shift_labels is not None:
|
|
137
|
+
loss = self.loss_function(
|
|
138
|
+
logits=logits,
|
|
139
|
+
labels=labels,
|
|
140
|
+
shift_labels=shift_labels,
|
|
141
|
+
vocab_size=self.config.vocab_size,
|
|
142
|
+
)
|
|
167
143
|
|
|
168
144
|
if not return_dict:
|
|
169
|
-
|
|
170
|
-
|
|
145
|
+
output_tuple = (logits,) + outputs[1:]
|
|
146
|
+
output = (loss,) + output_tuple if loss is not None else output_tuple
|
|
147
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
148
|
+
return output
|
|
171
149
|
|
|
172
|
-
|
|
150
|
+
# Return Qwen2VL output with token accuracy
|
|
151
|
+
return LigerQwen2VLCausalLMOutputWithPast(
|
|
173
152
|
loss=loss,
|
|
174
153
|
logits=logits,
|
|
175
154
|
past_key_values=outputs.past_key_values,
|
|
176
155
|
hidden_states=outputs.hidden_states,
|
|
177
156
|
attentions=outputs.attentions,
|
|
178
|
-
rope_deltas=rope_deltas,
|
|
157
|
+
rope_deltas=outputs.rope_deltas,
|
|
158
|
+
token_accuracy=token_accuracy,
|
|
179
159
|
)
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from typing import Union
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
8
|
+
from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
|
|
9
|
+
from liger_kernel.transformers.model.output_classes import LigerCausalLMOutputWithPast
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def lce_forward(
|
|
13
|
+
self,
|
|
14
|
+
input_ids: Optional[torch.LongTensor] = None,
|
|
15
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
16
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
17
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
18
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
19
|
+
labels: Optional[torch.LongTensor] = None,
|
|
20
|
+
use_cache: Optional[bool] = None,
|
|
21
|
+
output_attentions: Optional[bool] = None,
|
|
22
|
+
output_hidden_states: Optional[bool] = None,
|
|
23
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
24
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
25
|
+
skip_logits: Optional[bool] = None,
|
|
26
|
+
return_dict: Optional[bool] = None,
|
|
27
|
+
**kwargs,
|
|
28
|
+
) -> LigerCausalLMOutputWithPast:
|
|
29
|
+
r"""
|
|
30
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
31
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
32
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
33
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
34
|
+
|
|
35
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
36
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
37
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
38
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
39
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
40
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
|
|
44
|
+
Example:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
>>> from transformers import AutoTokenizer, Qwen3ForCausalLM
|
|
48
|
+
|
|
49
|
+
>>> model = Qwen3ForCausalLM.from_pretrained("Qwen/Qwen3-8B")
|
|
50
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
|
|
51
|
+
|
|
52
|
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
|
53
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
54
|
+
|
|
55
|
+
>>> # Generate
|
|
56
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
57
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
58
|
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
|
59
|
+
```"""
|
|
60
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
61
|
+
output_hidden_states = (
|
|
62
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
63
|
+
)
|
|
64
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
65
|
+
|
|
66
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
67
|
+
outputs = self.model(
|
|
68
|
+
input_ids=input_ids,
|
|
69
|
+
attention_mask=attention_mask,
|
|
70
|
+
position_ids=position_ids,
|
|
71
|
+
past_key_values=past_key_values,
|
|
72
|
+
inputs_embeds=inputs_embeds,
|
|
73
|
+
use_cache=use_cache,
|
|
74
|
+
output_attentions=output_attentions,
|
|
75
|
+
output_hidden_states=output_hidden_states,
|
|
76
|
+
cache_position=cache_position,
|
|
77
|
+
**kwargs,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
hidden_states = outputs[0]
|
|
81
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
82
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
83
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
84
|
+
|
|
85
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
86
|
+
# Remove output-control parameters that shouldn't be passed to loss functions
|
|
87
|
+
kwargs.pop("return_dict", None)
|
|
88
|
+
logits = None
|
|
89
|
+
loss = None
|
|
90
|
+
token_accuracy = None
|
|
91
|
+
|
|
92
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
93
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
94
|
+
|
|
95
|
+
if skip_logits is None:
|
|
96
|
+
# By default, if in training mode, don't materialize logits
|
|
97
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
98
|
+
|
|
99
|
+
# Compute loss
|
|
100
|
+
if skip_logits:
|
|
101
|
+
result = LigerForCausalLMLoss(
|
|
102
|
+
hidden_states=kept_hidden_states,
|
|
103
|
+
lm_head_weight=self.lm_head.weight,
|
|
104
|
+
labels=labels,
|
|
105
|
+
shift_labels=shift_labels,
|
|
106
|
+
hidden_size=self.config.hidden_size,
|
|
107
|
+
**kwargs,
|
|
108
|
+
)
|
|
109
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
110
|
+
|
|
111
|
+
else:
|
|
112
|
+
logits = self.lm_head(kept_hidden_states)
|
|
113
|
+
if labels is not None or shift_labels is not None:
|
|
114
|
+
loss = self.loss_function(
|
|
115
|
+
logits=logits,
|
|
116
|
+
labels=labels,
|
|
117
|
+
shift_labels=shift_labels,
|
|
118
|
+
vocab_size=self.config.vocab_size,
|
|
119
|
+
**kwargs,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
if not return_dict:
|
|
123
|
+
output = (logits,) + outputs[1:]
|
|
124
|
+
output = ((loss,) + output) if loss is not None else output
|
|
125
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
126
|
+
return output
|
|
127
|
+
|
|
128
|
+
# Return custom output class with accuracy field
|
|
129
|
+
return LigerCausalLMOutputWithPast(
|
|
130
|
+
loss=loss,
|
|
131
|
+
logits=logits,
|
|
132
|
+
past_key_values=outputs.past_key_values,
|
|
133
|
+
hidden_states=outputs.hidden_states,
|
|
134
|
+
attentions=outputs.attentions,
|
|
135
|
+
token_accuracy=token_accuracy,
|
|
136
|
+
)
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from typing import Union
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from transformers.modeling_outputs import MoeModelOutputWithPast
|
|
8
|
+
from transformers.models.mixtral.modeling_mixtral import load_balancing_loss_func
|
|
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 LigerMoeCausalLMOutputWithPast
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def lce_forward(
|
|
16
|
+
self,
|
|
17
|
+
input_ids: Optional[torch.LongTensor] = None,
|
|
18
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
19
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
20
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
21
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
22
|
+
labels: Optional[torch.LongTensor] = None,
|
|
23
|
+
use_cache: Optional[bool] = None,
|
|
24
|
+
output_attentions: Optional[bool] = None,
|
|
25
|
+
output_hidden_states: Optional[bool] = None,
|
|
26
|
+
output_router_logits: Optional[bool] = None,
|
|
27
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
28
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
29
|
+
skip_logits: Optional[bool] = None,
|
|
30
|
+
return_dict: Optional[bool] = None,
|
|
31
|
+
**kwargs,
|
|
32
|
+
) -> LigerMoeCausalLMOutputWithPast:
|
|
33
|
+
r"""
|
|
34
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
35
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
36
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
37
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
38
|
+
|
|
39
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
40
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
41
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
42
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
43
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
44
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
|
|
48
|
+
Example:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
>>> from transformers import AutoTokenizer, Qwen3MoeForCausalLM
|
|
52
|
+
|
|
53
|
+
>>> model = Qwen3MoeForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
|
|
54
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
|
|
55
|
+
|
|
56
|
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
|
57
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
58
|
+
|
|
59
|
+
>>> # Generate
|
|
60
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
61
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
62
|
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
|
63
|
+
```"""
|
|
64
|
+
|
|
65
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
66
|
+
output_router_logits = (
|
|
67
|
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
|
68
|
+
)
|
|
69
|
+
output_hidden_states = (
|
|
70
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
71
|
+
)
|
|
72
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
73
|
+
|
|
74
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
75
|
+
outputs: MoeModelOutputWithPast = self.model(
|
|
76
|
+
input_ids=input_ids,
|
|
77
|
+
attention_mask=attention_mask,
|
|
78
|
+
position_ids=position_ids,
|
|
79
|
+
past_key_values=past_key_values,
|
|
80
|
+
inputs_embeds=inputs_embeds,
|
|
81
|
+
use_cache=use_cache,
|
|
82
|
+
output_attentions=output_attentions,
|
|
83
|
+
output_hidden_states=output_hidden_states,
|
|
84
|
+
output_router_logits=output_router_logits,
|
|
85
|
+
cache_position=cache_position,
|
|
86
|
+
**kwargs,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
hidden_states = outputs.last_hidden_state
|
|
90
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
91
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
92
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
93
|
+
|
|
94
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
95
|
+
logits = None
|
|
96
|
+
loss = None
|
|
97
|
+
token_accuracy = None
|
|
98
|
+
|
|
99
|
+
if skip_logits is None:
|
|
100
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
101
|
+
|
|
102
|
+
# Compute loss
|
|
103
|
+
if skip_logits:
|
|
104
|
+
result = LigerForCausalLMLoss(
|
|
105
|
+
hidden_states=kept_hidden_states,
|
|
106
|
+
lm_head_weight=self.lm_head.weight,
|
|
107
|
+
labels=labels,
|
|
108
|
+
shift_labels=shift_labels,
|
|
109
|
+
hidden_size=self.config.hidden_size,
|
|
110
|
+
**kwargs,
|
|
111
|
+
)
|
|
112
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
113
|
+
else: # if in inference model materialize logits
|
|
114
|
+
logits = self.lm_head(kept_hidden_states)
|
|
115
|
+
if labels is not None or shift_labels is not None:
|
|
116
|
+
loss = self.loss_function(
|
|
117
|
+
logits=logits,
|
|
118
|
+
labels=labels,
|
|
119
|
+
shift_labels=shift_labels,
|
|
120
|
+
vocab_size=self.vocab_size,
|
|
121
|
+
**kwargs,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
aux_loss = None
|
|
125
|
+
if output_router_logits:
|
|
126
|
+
aux_loss = load_balancing_loss_func(
|
|
127
|
+
outputs.router_logits,
|
|
128
|
+
self.num_experts,
|
|
129
|
+
self.num_experts_per_tok,
|
|
130
|
+
attention_mask,
|
|
131
|
+
)
|
|
132
|
+
if labels is not None:
|
|
133
|
+
loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
|
|
134
|
+
|
|
135
|
+
if not return_dict:
|
|
136
|
+
output = (logits,) + outputs[1:]
|
|
137
|
+
output = ((aux_loss,) + output) if aux_loss is not None else output
|
|
138
|
+
output = ((loss,) + output) if loss is not None else output
|
|
139
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
140
|
+
return output
|
|
141
|
+
|
|
142
|
+
# Return custom output class with accuracy field
|
|
143
|
+
return LigerMoeCausalLMOutputWithPast(
|
|
144
|
+
loss=loss,
|
|
145
|
+
aux_loss=aux_loss,
|
|
146
|
+
logits=logits,
|
|
147
|
+
past_key_values=outputs.past_key_values,
|
|
148
|
+
hidden_states=outputs.hidden_states,
|
|
149
|
+
attentions=outputs.attentions,
|
|
150
|
+
router_logits=outputs.router_logits,
|
|
151
|
+
token_accuracy=token_accuracy,
|
|
152
|
+
)
|