liger-kernel-nightly 0.0.1.dev20240819184814__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/__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 +366 -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 +307 -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 +63 -0
- 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 +383 -114
- liger_kernel/ops/dyt.py +160 -0
- liger_kernel/ops/experimental/embedding.py +141 -0
- liger_kernel/ops/experimental/mm_int8int2.py +349 -0
- liger_kernel/ops/fused_add_rms_norm.py +416 -0
- liger_kernel/ops/fused_linear_cross_entropy.py +346 -132
- liger_kernel/ops/fused_linear_jsd.py +228 -0
- liger_kernel/ops/fused_neighborhood_attention.py +1022 -0
- liger_kernel/ops/geglu.py +66 -64
- liger_kernel/ops/group_norm.py +306 -0
- liger_kernel/ops/grpo_loss.py +312 -0
- liger_kernel/ops/jsd.py +201 -0
- liger_kernel/ops/kl_div.py +262 -0
- liger_kernel/ops/layer_norm.py +320 -0
- 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/qwen2vl_mrope.py +222 -0
- liger_kernel/ops/rms_norm.py +484 -88
- liger_kernel/ops/rope.py +122 -117
- liger_kernel/ops/softmax.py +201 -0
- liger_kernel/ops/sparsemax.py +179 -0
- liger_kernel/ops/swiglu.py +68 -65
- liger_kernel/ops/tiled_mlp.py +136 -0
- liger_kernel/ops/tvd.py +207 -0
- liger_kernel/ops/utils.py +82 -3
- liger_kernel/transformers/__init__.py +218 -6
- liger_kernel/transformers/auto_model.py +38 -0
- liger_kernel/transformers/cross_entropy.py +52 -7
- liger_kernel/transformers/dyt.py +22 -0
- liger_kernel/transformers/experimental/__init__.py +5 -0
- liger_kernel/transformers/experimental/embedding.py +26 -0
- liger_kernel/transformers/fsdp.py +55 -0
- liger_kernel/transformers/functional.py +301 -0
- liger_kernel/transformers/fused_add_rms_norm.py +39 -0
- liger_kernel/transformers/fused_linear_cross_entropy.py +59 -10
- liger_kernel/transformers/fused_linear_jsd.py +95 -0
- liger_kernel/transformers/fused_neighborhood_attention.py +234 -0
- liger_kernel/transformers/geglu.py +6 -7
- liger_kernel/transformers/group_norm.py +50 -0
- liger_kernel/transformers/grpo_loss.py +153 -0
- liger_kernel/transformers/jsd.py +70 -0
- liger_kernel/transformers/kl_div.py +12 -0
- liger_kernel/transformers/layer_norm.py +24 -0
- liger_kernel/transformers/llama4_rope.py +93 -0
- liger_kernel/transformers/model/falcon_h1.py +122 -0
- liger_kernel/transformers/model/gemma.py +261 -0
- liger_kernel/transformers/model/gemma2.py +283 -0
- liger_kernel/transformers/model/gemma3.py +332 -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/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 +221 -41
- 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 +145 -0
- liger_kernel/transformers/model/mixtral.py +293 -0
- liger_kernel/transformers/model/mllama.py +269 -0
- liger_kernel/transformers/model/olmo2.py +141 -0
- liger_kernel/transformers/model/olmo3.py +142 -0
- liger_kernel/transformers/model/output_classes.py +147 -0
- liger_kernel/transformers/model/paligemma.py +433 -0
- liger_kernel/transformers/model/phi3.py +120 -0
- liger_kernel/transformers/model/qwen2.py +259 -0
- liger_kernel/transformers/model/qwen2_5_vl.py +163 -0
- liger_kernel/transformers/model/qwen2_vl.py +159 -0
- 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 +2816 -21
- 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 +75 -5
- liger_kernel/transformers/rope.py +47 -3
- liger_kernel/transformers/softmax.py +12 -0
- liger_kernel/transformers/sparsemax.py +16 -0
- liger_kernel/transformers/swiglu.py +62 -6
- 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/trainer_integration.py +2 -45
- liger_kernel/transformers/tvd.py +13 -0
- liger_kernel/triton/__init__.py +1 -3
- liger_kernel/triton/monkey_patch.py +1 -5
- liger_kernel/utils.py +96 -0
- liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/METADATA +447 -0
- liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/NOTICE +58 -0
- liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/RECORD +124 -0
- {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/WHEEL +1 -1
- liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/METADATA +0 -21
- liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/NOTICE +0 -4
- liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/RECORD +0 -27
- {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/LICENSE +0 -0
- {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,259 @@
|
|
|
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.modeling_outputs import CausalLMOutputWithPast
|
|
10
|
+
from transformers.utils.deprecation import deprecate_kwarg
|
|
11
|
+
|
|
12
|
+
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
|
|
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
|
+
|
|
17
|
+
|
|
18
|
+
def lce_forward_deprecated(
|
|
19
|
+
self,
|
|
20
|
+
input_ids: torch.LongTensor = None,
|
|
21
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
22
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
23
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
24
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
25
|
+
labels: Optional[torch.LongTensor] = None,
|
|
26
|
+
use_cache: Optional[bool] = None,
|
|
27
|
+
output_attentions: Optional[bool] = None,
|
|
28
|
+
output_hidden_states: Optional[bool] = None,
|
|
29
|
+
return_dict: Optional[bool] = None,
|
|
30
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
31
|
+
skip_logits: Optional[bool] = None,
|
|
32
|
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
|
33
|
+
r"""
|
|
34
|
+
Copy paste Qwen2's forward but replace torch cross entropy with liger fused linear cross entropy
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
Args:
|
|
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
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
|
|
45
|
+
Example:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
|
49
|
+
|
|
50
|
+
>>> model = Qwen2ForCausalLM.from_pretrained("Qwen/Qwen2-1.5B")
|
|
51
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-1.5B")
|
|
52
|
+
|
|
53
|
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
|
54
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
55
|
+
|
|
56
|
+
>>> # Generate
|
|
57
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
58
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
59
|
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
|
60
|
+
```"""
|
|
61
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
62
|
+
output_hidden_states = (
|
|
63
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
64
|
+
)
|
|
65
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
66
|
+
|
|
67
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
68
|
+
outputs = self.model(
|
|
69
|
+
input_ids=input_ids,
|
|
70
|
+
attention_mask=attention_mask,
|
|
71
|
+
position_ids=position_ids,
|
|
72
|
+
past_key_values=past_key_values,
|
|
73
|
+
inputs_embeds=inputs_embeds,
|
|
74
|
+
use_cache=use_cache,
|
|
75
|
+
output_attentions=output_attentions,
|
|
76
|
+
output_hidden_states=output_hidden_states,
|
|
77
|
+
return_dict=return_dict,
|
|
78
|
+
cache_position=cache_position,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
hidden_states = outputs[0]
|
|
82
|
+
|
|
83
|
+
loss = None
|
|
84
|
+
logits = None
|
|
85
|
+
|
|
86
|
+
if skip_logits and labels is None:
|
|
87
|
+
raise ValueError("skip_logits is True, but labels is None")
|
|
88
|
+
|
|
89
|
+
if skip_logits is None:
|
|
90
|
+
# By default, if in training mode, don't materialize logits
|
|
91
|
+
skip_logits = self.training and labels is not None
|
|
92
|
+
|
|
93
|
+
if self.training and (labels is not None):
|
|
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
|
+
lce = LigerFusedLinearCrossEntropyLoss()
|
|
102
|
+
loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
103
|
+
|
|
104
|
+
else:
|
|
105
|
+
logits = self.lm_head(hidden_states)
|
|
106
|
+
if labels is not None:
|
|
107
|
+
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
|
108
|
+
logits = logits.float()
|
|
109
|
+
# Shift so that tokens < n predict n
|
|
110
|
+
shift_logits = logits[..., :-1, :].contiguous()
|
|
111
|
+
shift_labels = labels[..., 1:].contiguous()
|
|
112
|
+
# Flatten the tokens
|
|
113
|
+
loss_fct = CrossEntropyLoss()
|
|
114
|
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
|
115
|
+
shift_labels = shift_labels.view(-1)
|
|
116
|
+
# Enable model parallelism
|
|
117
|
+
shift_labels = shift_labels.to(shift_logits.device)
|
|
118
|
+
loss = loss_fct(shift_logits, shift_labels)
|
|
119
|
+
|
|
120
|
+
if not return_dict:
|
|
121
|
+
output = (logits,) + outputs[1:]
|
|
122
|
+
return (loss,) + output if loss is not None else output
|
|
123
|
+
|
|
124
|
+
return CausalLMOutputWithPast(
|
|
125
|
+
loss=loss,
|
|
126
|
+
logits=logits,
|
|
127
|
+
past_key_values=outputs.past_key_values,
|
|
128
|
+
hidden_states=outputs.hidden_states,
|
|
129
|
+
attentions=outputs.attentions,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
|
134
|
+
def lce_forward(
|
|
135
|
+
self,
|
|
136
|
+
input_ids: torch.LongTensor = None,
|
|
137
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
138
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
139
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
140
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
141
|
+
labels: Optional[torch.LongTensor] = None,
|
|
142
|
+
use_cache: Optional[bool] = None,
|
|
143
|
+
output_attentions: Optional[bool] = None,
|
|
144
|
+
output_hidden_states: Optional[bool] = None,
|
|
145
|
+
return_dict: Optional[bool] = None,
|
|
146
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
147
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
148
|
+
skip_logits: Optional[bool] = None,
|
|
149
|
+
**kwargs,
|
|
150
|
+
) -> Union[Tuple, LigerCausalLMOutputWithPast]:
|
|
151
|
+
r"""
|
|
152
|
+
Args:
|
|
153
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
154
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
155
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
156
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
157
|
+
|
|
158
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
159
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
160
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
161
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
162
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
163
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
|
|
167
|
+
Example:
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
>>> from transformers import AutoTokenizer, Qwen2ForCausalLM
|
|
171
|
+
|
|
172
|
+
>>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
|
173
|
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
|
174
|
+
|
|
175
|
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
|
176
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
177
|
+
|
|
178
|
+
>>> # Generate
|
|
179
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
180
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
181
|
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
|
182
|
+
```"""
|
|
183
|
+
|
|
184
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
185
|
+
output_hidden_states = (
|
|
186
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
187
|
+
)
|
|
188
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
189
|
+
|
|
190
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
191
|
+
outputs = self.model(
|
|
192
|
+
input_ids=input_ids,
|
|
193
|
+
attention_mask=attention_mask,
|
|
194
|
+
position_ids=position_ids,
|
|
195
|
+
past_key_values=past_key_values,
|
|
196
|
+
inputs_embeds=inputs_embeds,
|
|
197
|
+
use_cache=use_cache,
|
|
198
|
+
output_attentions=output_attentions,
|
|
199
|
+
output_hidden_states=output_hidden_states,
|
|
200
|
+
return_dict=return_dict,
|
|
201
|
+
cache_position=cache_position,
|
|
202
|
+
**kwargs,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
hidden_states = outputs[0]
|
|
206
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
207
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
208
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
209
|
+
|
|
210
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
211
|
+
logits = None
|
|
212
|
+
loss = None
|
|
213
|
+
token_accuracy = None
|
|
214
|
+
|
|
215
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
216
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
217
|
+
|
|
218
|
+
if skip_logits is None:
|
|
219
|
+
# By default, if in training mode, don't materialize logits
|
|
220
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
221
|
+
|
|
222
|
+
# Compute loss
|
|
223
|
+
if skip_logits:
|
|
224
|
+
result = LigerForCausalLMLoss(
|
|
225
|
+
hidden_states=kept_hidden_states,
|
|
226
|
+
lm_head_weight=self.lm_head.weight,
|
|
227
|
+
labels=labels,
|
|
228
|
+
shift_labels=shift_labels,
|
|
229
|
+
hidden_size=self.config.hidden_size,
|
|
230
|
+
**kwargs,
|
|
231
|
+
)
|
|
232
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
233
|
+
|
|
234
|
+
else:
|
|
235
|
+
logits = self.lm_head(kept_hidden_states)
|
|
236
|
+
if labels is not None or shift_labels is not None:
|
|
237
|
+
loss = self.loss_function(
|
|
238
|
+
logits=logits,
|
|
239
|
+
labels=labels,
|
|
240
|
+
shift_labels=shift_labels,
|
|
241
|
+
vocab_size=self.config.vocab_size,
|
|
242
|
+
**kwargs,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
if not return_dict:
|
|
246
|
+
output_tuple = (logits,) + outputs[1:]
|
|
247
|
+
output = (loss,) + output_tuple if loss is not None else output_tuple
|
|
248
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
249
|
+
return output
|
|
250
|
+
|
|
251
|
+
# Return custom output class with token accuracy field
|
|
252
|
+
return LigerCausalLMOutputWithPast(
|
|
253
|
+
loss=loss,
|
|
254
|
+
logits=logits,
|
|
255
|
+
past_key_values=outputs.past_key_values,
|
|
256
|
+
hidden_states=outputs.hidden_states,
|
|
257
|
+
attentions=outputs.attentions,
|
|
258
|
+
token_accuracy=token_accuracy,
|
|
259
|
+
)
|
|
@@ -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
|
+
)
|
|
@@ -0,0 +1,159 @@
|
|
|
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 LigerQwen2VLCausalLMOutputWithPast
|
|
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
|
+
skip_logits: Optional[bool] = None,
|
|
35
|
+
**kwargs,
|
|
36
|
+
) -> Union[Tuple, LigerQwen2VLCausalLMOutputWithPast]:
|
|
37
|
+
r"""
|
|
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
|
+
|
|
53
|
+
Example:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
>>> from PIL import Image
|
|
57
|
+
>>> import requests
|
|
58
|
+
>>> from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
|
|
59
|
+
|
|
60
|
+
>>> model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
|
|
61
|
+
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
|
|
62
|
+
|
|
63
|
+
>>> messages = [
|
|
64
|
+
{
|
|
65
|
+
"role": "user",
|
|
66
|
+
"content": [
|
|
67
|
+
{"type": "image"},
|
|
68
|
+
{"type": "text", "text": "What is shown in this image?"},
|
|
69
|
+
],
|
|
70
|
+
},
|
|
71
|
+
]
|
|
72
|
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
|
73
|
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
|
74
|
+
|
|
75
|
+
>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
76
|
+
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
|
|
77
|
+
|
|
78
|
+
>>> # Generate
|
|
79
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
80
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
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
|
+
```"""
|
|
83
|
+
|
|
84
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
85
|
+
output_hidden_states = (
|
|
86
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
87
|
+
)
|
|
88
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
89
|
+
|
|
90
|
+
outputs = self.model(
|
|
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,
|
|
96
|
+
position_ids=position_ids,
|
|
97
|
+
attention_mask=attention_mask,
|
|
98
|
+
past_key_values=past_key_values,
|
|
99
|
+
inputs_embeds=inputs_embeds,
|
|
100
|
+
use_cache=use_cache,
|
|
101
|
+
output_attentions=output_attentions,
|
|
102
|
+
output_hidden_states=output_hidden_states,
|
|
103
|
+
return_dict=return_dict,
|
|
104
|
+
cache_position=cache_position,
|
|
105
|
+
**kwargs,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
hidden_states = outputs[0]
|
|
109
|
+
|
|
110
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
111
|
+
loss = None
|
|
112
|
+
logits = None
|
|
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)
|
|
132
|
+
else:
|
|
133
|
+
logits = self.lm_head(hidden_states)
|
|
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
|
+
)
|
|
143
|
+
|
|
144
|
+
if not return_dict:
|
|
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
|
|
149
|
+
|
|
150
|
+
# Return Qwen2VL output with token accuracy
|
|
151
|
+
return LigerQwen2VLCausalLMOutputWithPast(
|
|
152
|
+
loss=loss,
|
|
153
|
+
logits=logits,
|
|
154
|
+
past_key_values=outputs.past_key_values,
|
|
155
|
+
hidden_states=outputs.hidden_states,
|
|
156
|
+
attentions=outputs.attentions,
|
|
157
|
+
rope_deltas=outputs.rope_deltas,
|
|
158
|
+
token_accuracy=token_accuracy,
|
|
159
|
+
)
|