liger-kernel 0.5.3__py3-none-any.whl → 0.5.5__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/cpo_loss.py +51 -11
- liger_kernel/chunked_loss/dpo_loss.py +30 -4
- 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 +240 -0
- liger_kernel/chunked_loss/fused_linear_unpaired_preference.py +112 -17
- liger_kernel/chunked_loss/grpo_loss.py +194 -0
- liger_kernel/chunked_loss/jsd_loss.py +31 -6
- liger_kernel/chunked_loss/kto_loss.py +53 -15
- liger_kernel/chunked_loss/orpo_loss.py +37 -5
- liger_kernel/chunked_loss/simpo_loss.py +47 -11
- liger_kernel/ops/cross_entropy.py +7 -3
- liger_kernel/ops/fused_linear_cross_entropy.py +3 -3
- liger_kernel/ops/fused_linear_jsd.py +3 -3
- liger_kernel/ops/jsd.py +3 -3
- liger_kernel/ops/layer_norm.py +20 -7
- liger_kernel/ops/tvd.py +207 -0
- liger_kernel/ops/utils.py +1 -2
- liger_kernel/transformers/__init__.py +4 -0
- liger_kernel/transformers/cross_entropy.py +3 -3
- liger_kernel/transformers/functional.py +17 -0
- liger_kernel/transformers/fused_linear_cross_entropy.py +3 -3
- liger_kernel/transformers/group_norm.py +6 -6
- liger_kernel/transformers/model/olmo2.py +124 -0
- liger_kernel/transformers/model/qwen2_5_vl.py +205 -0
- liger_kernel/transformers/monkey_patch.py +239 -27
- liger_kernel/transformers/tvd.py +13 -0
- liger_kernel/utils.py +48 -1
- {liger_kernel-0.5.3.dist-info → liger_kernel-0.5.5.dist-info}/METADATA +19 -4
- {liger_kernel-0.5.3.dist-info → liger_kernel-0.5.5.dist-info}/RECORD +35 -29
- {liger_kernel-0.5.3.dist-info → liger_kernel-0.5.5.dist-info}/WHEEL +1 -1
- {liger_kernel-0.5.3.dist-info → liger_kernel-0.5.5.dist-info}/LICENSE +0 -0
- {liger_kernel-0.5.3.dist-info → liger_kernel-0.5.5.dist-info}/NOTICE +0 -0
- {liger_kernel-0.5.3.dist-info → liger_kernel-0.5.5.dist-info}/top_level.txt +0 -0
liger_kernel/ops/utils.py
CHANGED
|
@@ -49,8 +49,7 @@ def calculate_settings(n):
|
|
|
49
49
|
BLOCK_SIZE = triton.next_power_of_2(n)
|
|
50
50
|
if BLOCK_SIZE > MAX_FUSED_SIZE:
|
|
51
51
|
raise RuntimeError(
|
|
52
|
-
f"Cannot launch Triton kernel since n = {n} exceeds "
|
|
53
|
-
f"the recommended Triton blocksize = {MAX_FUSED_SIZE}."
|
|
52
|
+
f"Cannot launch Triton kernel since n = {n} exceeds the recommended Triton blocksize = {MAX_FUSED_SIZE}."
|
|
54
53
|
)
|
|
55
54
|
|
|
56
55
|
num_warps = 4
|
|
@@ -9,15 +9,19 @@ from liger_kernel.transformers.monkey_patch import _apply_liger_kernel # noqa:
|
|
|
9
9
|
from liger_kernel.transformers.monkey_patch import _apply_liger_kernel_to_instance # noqa: F401
|
|
10
10
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_gemma # noqa: F401
|
|
11
11
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_gemma2 # noqa: F401
|
|
12
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_granite # noqa: F401
|
|
12
13
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_llama # noqa: F401
|
|
13
14
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mistral # noqa: F401
|
|
14
15
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mixtral # noqa: F401
|
|
15
16
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mllama # noqa: F401
|
|
17
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_olmo2 # noqa: F401
|
|
16
18
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_phi3 # noqa: F401
|
|
17
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
|
|
18
21
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2_vl # noqa: F401
|
|
19
22
|
from liger_kernel.transformers.rms_norm import LigerRMSNorm # noqa: F401
|
|
20
23
|
from liger_kernel.transformers.rope import liger_rotary_pos_emb # noqa: F401
|
|
21
24
|
from liger_kernel.transformers.swiglu import LigerBlockSparseTop2MLP # noqa: F401
|
|
22
25
|
from liger_kernel.transformers.swiglu import LigerPhi3SwiGLUMLP # noqa: F401
|
|
23
26
|
from liger_kernel.transformers.swiglu import LigerSwiGLUMLP # noqa: F401
|
|
27
|
+
from liger_kernel.transformers.tvd import LigerTVDLoss # noqa: F401
|
|
@@ -17,9 +17,9 @@ class LigerCrossEntropyLoss(torch.nn.Module):
|
|
|
17
17
|
return_z_loss: bool = False,
|
|
18
18
|
):
|
|
19
19
|
super().__init__()
|
|
20
|
-
assert (label_smoothing >= 0) and (
|
|
21
|
-
label_smoothing
|
|
22
|
-
)
|
|
20
|
+
assert (label_smoothing >= 0) and (label_smoothing <= 1), (
|
|
21
|
+
f"label_smoothing must be between 0.0 and 1.0. Got: {label_smoothing}"
|
|
22
|
+
)
|
|
23
23
|
assert reduction in {
|
|
24
24
|
"mean",
|
|
25
25
|
"sum",
|
|
@@ -12,6 +12,7 @@ from liger_kernel.ops.qwen2vl_mrope import LigerQwen2VLMRopeFunction
|
|
|
12
12
|
from liger_kernel.ops.rms_norm import LigerRMSNormFunction
|
|
13
13
|
from liger_kernel.ops.rope import LigerRopeFunction
|
|
14
14
|
from liger_kernel.ops.swiglu import LigerSiLUMulFunction
|
|
15
|
+
from liger_kernel.ops.tvd import LigerTVDLossFunction
|
|
15
16
|
|
|
16
17
|
|
|
17
18
|
# conform to the function signature in https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html
|
|
@@ -157,6 +158,22 @@ def liger_kl_div(
|
|
|
157
158
|
)
|
|
158
159
|
|
|
159
160
|
|
|
161
|
+
def liger_tvd(
|
|
162
|
+
input,
|
|
163
|
+
target,
|
|
164
|
+
shift_labels=None,
|
|
165
|
+
reduction: str = "mean",
|
|
166
|
+
ignore_index: int = -100,
|
|
167
|
+
):
|
|
168
|
+
return LigerTVDLossFunction.apply(
|
|
169
|
+
input,
|
|
170
|
+
target,
|
|
171
|
+
shift_labels,
|
|
172
|
+
reduction,
|
|
173
|
+
ignore_index,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
160
177
|
def liger_layer_norm(X, W, B, eps):
|
|
161
178
|
return LigerLayerNormFunction.apply(X, W, B, eps)
|
|
162
179
|
|
|
@@ -17,9 +17,9 @@ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
|
|
|
17
17
|
return_z_loss: bool = False,
|
|
18
18
|
):
|
|
19
19
|
super().__init__()
|
|
20
|
-
assert (label_smoothing >= 0) and (
|
|
21
|
-
label_smoothing
|
|
22
|
-
)
|
|
20
|
+
assert (label_smoothing >= 0) and (label_smoothing <= 1), (
|
|
21
|
+
f"label_smoothing must be between 0.0 and 1.0. Got: {label_smoothing}"
|
|
22
|
+
)
|
|
23
23
|
assert reduction in {
|
|
24
24
|
"mean",
|
|
25
25
|
"sum",
|
|
@@ -21,9 +21,9 @@ class LigerGroupNorm(nn.Module):
|
|
|
21
21
|
"zeros",
|
|
22
22
|
], f"init_fn must be either 'ones' or 'zeros', got {init_fn}"
|
|
23
23
|
|
|
24
|
-
assert (
|
|
25
|
-
num_channels
|
|
26
|
-
)
|
|
24
|
+
assert num_channels % num_groups == 0, (
|
|
25
|
+
f"Number of channels {num_channels} must be divisible by num_groups {num_groups}"
|
|
26
|
+
)
|
|
27
27
|
self.num_channels = num_channels
|
|
28
28
|
self.num_groups = num_groups
|
|
29
29
|
self.eps = eps
|
|
@@ -34,9 +34,9 @@ class LigerGroupNorm(nn.Module):
|
|
|
34
34
|
def forward(self, hidden_states):
|
|
35
35
|
# hidden_states: (batch_size, num_channels, *)
|
|
36
36
|
assert hidden_states.dim() >= 3, f"Input must have atleast 3 dimensions, got {hidden_states.dim()}"
|
|
37
|
-
assert (
|
|
38
|
-
hidden_states.size(1)
|
|
39
|
-
)
|
|
37
|
+
assert hidden_states.size(1) == self.num_channels, (
|
|
38
|
+
f"Input tensor must have {self.num_channels} channels, got {hidden_states.size(1)}"
|
|
39
|
+
)
|
|
40
40
|
return LigerGroupNormFunction.apply(
|
|
41
41
|
hidden_states,
|
|
42
42
|
self.weight,
|
|
@@ -0,0 +1,124 @@
|
|
|
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.modeling_outputs import CausalLMOutputWithPast
|
|
9
|
+
from transformers.models.olmo2.modeling_olmo2 import _CONFIG_FOR_DOC
|
|
10
|
+
from transformers.models.olmo2.modeling_olmo2 import OLMO2_INPUTS_DOCSTRING
|
|
11
|
+
from transformers.utils import add_start_docstrings_to_model_forward
|
|
12
|
+
from transformers.utils import replace_return_docstrings
|
|
13
|
+
|
|
14
|
+
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@add_start_docstrings_to_model_forward(OLMO2_INPUTS_DOCSTRING)
|
|
18
|
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
|
19
|
+
def lce_forward(
|
|
20
|
+
self,
|
|
21
|
+
input_ids: torch.LongTensor = None,
|
|
22
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
23
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
24
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
25
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
26
|
+
labels: Optional[torch.LongTensor] = None,
|
|
27
|
+
use_cache: Optional[bool] = None,
|
|
28
|
+
output_attentions: Optional[bool] = None,
|
|
29
|
+
output_hidden_states: Optional[bool] = None,
|
|
30
|
+
return_dict: Optional[bool] = None,
|
|
31
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
32
|
+
num_logits_to_keep: int = 0,
|
|
33
|
+
**loss_kwargs,
|
|
34
|
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
|
35
|
+
r"""
|
|
36
|
+
Args:
|
|
37
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
38
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
39
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
40
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
41
|
+
|
|
42
|
+
num_logits_to_keep (`int`, *optional*):
|
|
43
|
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
|
44
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
45
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
|
|
49
|
+
Example:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
>>> from transformers import AutoTokenizer, Olmo2ForCausalLM
|
|
53
|
+
|
|
54
|
+
>>> model = Olmo2ForCausalLM.from_pretrained("allenai/Olmo2-1B-hf")
|
|
55
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/Olmo2-1B-hf")
|
|
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
|
+
)
|
|
85
|
+
|
|
86
|
+
hidden_states = outputs[0]
|
|
87
|
+
|
|
88
|
+
logits = None
|
|
89
|
+
loss = None
|
|
90
|
+
# if in training mode, don't materialize logits
|
|
91
|
+
if self.training and (labels is not None):
|
|
92
|
+
# We do the same thing as ForCausalLMLoss but using Liger FLCE
|
|
93
|
+
|
|
94
|
+
shift_hidden_states = hidden_states[..., :-1, :].contiguous()
|
|
95
|
+
shift_labels = labels[..., 1:].contiguous()
|
|
96
|
+
|
|
97
|
+
# flatten tokens
|
|
98
|
+
shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
|
|
99
|
+
shift_labels = shift_labels.view(-1)
|
|
100
|
+
|
|
101
|
+
reduction = "sum" if "num_items_in_batch" in loss_kwargs else "mean"
|
|
102
|
+
lce = LigerFusedLinearCrossEntropyLoss(reduction=reduction)
|
|
103
|
+
|
|
104
|
+
loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
105
|
+
if reduction == "sum":
|
|
106
|
+
loss /= loss_kwargs["num_items_in_batch"]
|
|
107
|
+
|
|
108
|
+
else: # if in inference mode materialize logits
|
|
109
|
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
|
110
|
+
if labels is not None:
|
|
111
|
+
loss = self.loss_function(
|
|
112
|
+
logits=logits,
|
|
113
|
+
labels=labels,
|
|
114
|
+
vocab_size=self.config.vocab_size,
|
|
115
|
+
**loss_kwargs,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
return CausalLMOutputWithPast(
|
|
119
|
+
loss=loss,
|
|
120
|
+
logits=logits,
|
|
121
|
+
past_key_values=outputs.past_key_values,
|
|
122
|
+
hidden_states=outputs.hidden_states,
|
|
123
|
+
attentions=outputs.attentions,
|
|
124
|
+
)
|
|
@@ -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
|
+
)
|