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,331 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
from typing import Tuple
|
|
3
|
+
from typing import Union
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
import torch.nn as nn
|
|
7
|
+
|
|
8
|
+
from transformers.cache_utils import Cache
|
|
9
|
+
from transformers.cache_utils import HybridCache
|
|
10
|
+
from transformers.utils import logging
|
|
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
|
+
from liger_kernel.transformers.model.output_classes import LigerGemma3CausalLMOutputWithPast
|
|
17
|
+
|
|
18
|
+
logger = logging.get_logger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def causal_forward(
|
|
22
|
+
self,
|
|
23
|
+
input_ids: torch.LongTensor = None,
|
|
24
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
25
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
26
|
+
past_key_values: Optional[HybridCache] = None,
|
|
27
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
28
|
+
labels: Optional[torch.LongTensor] = None,
|
|
29
|
+
use_cache: Optional[bool] = None,
|
|
30
|
+
output_attentions: Optional[bool] = None,
|
|
31
|
+
output_hidden_states: Optional[bool] = None,
|
|
32
|
+
return_dict: Optional[bool] = None,
|
|
33
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
34
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
35
|
+
skip_logits: Optional[bool] = None,
|
|
36
|
+
**loss_kwargs,
|
|
37
|
+
) -> Union[Tuple, LigerCausalLMOutputWithPast]:
|
|
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
|
+
|
|
44
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
45
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
46
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
47
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
48
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
49
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
|
|
53
|
+
Example:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
>>> from transformers import AutoTokenizer, Gemma3ForCausalLM
|
|
57
|
+
|
|
58
|
+
>>> model = Gemma3ForCausalLM.from_pretrained("google/gemma-2-9b")
|
|
59
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
|
|
60
|
+
|
|
61
|
+
>>> prompt = "What is your favorite condiment?"
|
|
62
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
63
|
+
|
|
64
|
+
>>> # Generate
|
|
65
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
66
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
67
|
+
"What is your favorite condiment?"
|
|
68
|
+
```"""
|
|
69
|
+
|
|
70
|
+
if self.training and self.config._attn_implementation != "eager":
|
|
71
|
+
logger.warning_once(
|
|
72
|
+
"It is strongly recommended to train Gemma3 models with the `eager` attention implementation "
|
|
73
|
+
f"instead of `{self.config._attn_implementation}`. Use `eager` with `AutoModelForCausalLM.from_pretrained('<path-to-checkpoint>', attn_implementation='eager')`."
|
|
74
|
+
)
|
|
75
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
76
|
+
output_hidden_states = (
|
|
77
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
78
|
+
)
|
|
79
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
80
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
81
|
+
outputs = self.model(
|
|
82
|
+
input_ids=input_ids,
|
|
83
|
+
attention_mask=attention_mask,
|
|
84
|
+
position_ids=position_ids,
|
|
85
|
+
past_key_values=past_key_values,
|
|
86
|
+
inputs_embeds=inputs_embeds,
|
|
87
|
+
use_cache=use_cache,
|
|
88
|
+
output_attentions=output_attentions,
|
|
89
|
+
output_hidden_states=output_hidden_states,
|
|
90
|
+
return_dict=return_dict,
|
|
91
|
+
cache_position=cache_position,
|
|
92
|
+
**loss_kwargs,
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
hidden_states = outputs[0]
|
|
96
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
97
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
98
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
99
|
+
shift_labels = loss_kwargs.pop("shift_labels", None)
|
|
100
|
+
loss = None
|
|
101
|
+
logits = None
|
|
102
|
+
token_accuracy = None
|
|
103
|
+
|
|
104
|
+
if skip_logits is None:
|
|
105
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
106
|
+
|
|
107
|
+
# Compute loss
|
|
108
|
+
if skip_logits:
|
|
109
|
+
result = LigerForCausalLMLoss(
|
|
110
|
+
hidden_states=kept_hidden_states,
|
|
111
|
+
lm_head_weight=self.lm_head.weight,
|
|
112
|
+
labels=labels,
|
|
113
|
+
shift_labels=shift_labels,
|
|
114
|
+
hidden_size=self.config.hidden_size,
|
|
115
|
+
final_logit_softcapping=self.config.final_logit_softcapping,
|
|
116
|
+
**loss_kwargs,
|
|
117
|
+
)
|
|
118
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
119
|
+
else:
|
|
120
|
+
logits = self.lm_head(kept_hidden_states)
|
|
121
|
+
if self.config.final_logit_softcapping is not None:
|
|
122
|
+
logits = logits / self.config.final_logit_softcapping
|
|
123
|
+
logits = torch.tanh(logits)
|
|
124
|
+
logits = logits * self.config.final_logit_softcapping
|
|
125
|
+
if labels is not None or shift_labels is not None:
|
|
126
|
+
loss = self.loss_function(
|
|
127
|
+
logits=logits,
|
|
128
|
+
labels=labels,
|
|
129
|
+
shift_labels=shift_labels,
|
|
130
|
+
vocab_size=self.vocab_size,
|
|
131
|
+
**loss_kwargs,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
if not return_dict:
|
|
135
|
+
output_tuple = (logits,) + outputs[1:]
|
|
136
|
+
output_tuple = (loss,) + output_tuple if loss is not None else output_tuple
|
|
137
|
+
output_tuple = output_tuple + (token_accuracy,) if token_accuracy is not None else output_tuple
|
|
138
|
+
return output_tuple
|
|
139
|
+
|
|
140
|
+
# Return custom output class with token_accuracy field
|
|
141
|
+
return LigerCausalLMOutputWithPast(
|
|
142
|
+
loss=loss,
|
|
143
|
+
logits=logits,
|
|
144
|
+
past_key_values=outputs.past_key_values,
|
|
145
|
+
hidden_states=outputs.hidden_states,
|
|
146
|
+
attentions=outputs.attentions,
|
|
147
|
+
token_accuracy=token_accuracy,
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def multimodal_forward(
|
|
152
|
+
self,
|
|
153
|
+
input_ids: torch.LongTensor = None,
|
|
154
|
+
pixel_values: torch.FloatTensor = None,
|
|
155
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
156
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
157
|
+
past_key_values: Optional[Union[list[torch.FloatTensor], Cache]] = None,
|
|
158
|
+
token_type_ids: Optional[torch.LongTensor] = None,
|
|
159
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
160
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
161
|
+
labels: Optional[torch.LongTensor] = None,
|
|
162
|
+
use_cache: Optional[bool] = None,
|
|
163
|
+
output_attentions: Optional[bool] = None,
|
|
164
|
+
output_hidden_states: Optional[bool] = None,
|
|
165
|
+
return_dict: Optional[bool] = None,
|
|
166
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
167
|
+
skip_logits: Optional[bool] = None,
|
|
168
|
+
**lm_kwargs,
|
|
169
|
+
) -> Union[tuple, LigerGemma3CausalLMOutputWithPast]:
|
|
170
|
+
r"""
|
|
171
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
172
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
173
|
+
config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
174
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
|
|
175
|
+
|
|
176
|
+
Example:
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
>>> from PIL import Image
|
|
180
|
+
>>> import requests
|
|
181
|
+
>>> from transformers import AutoProcessor, Gemma3ForConditionalGeneration
|
|
182
|
+
|
|
183
|
+
>>> model = Gemma3ForConditionalGeneration.from_pretrained("google/gemma-3-4b-it")
|
|
184
|
+
>>> processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it")
|
|
185
|
+
|
|
186
|
+
>>> messages = [
|
|
187
|
+
... {
|
|
188
|
+
... "role": "system",
|
|
189
|
+
... "content": [
|
|
190
|
+
... {"type": "text", "text": "You are a helpful assistant."}
|
|
191
|
+
... ]
|
|
192
|
+
... },
|
|
193
|
+
... {
|
|
194
|
+
... "role": "user", "content": [
|
|
195
|
+
... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
|
|
196
|
+
... {"type": "text", "text": "Where is the cat standing?"},
|
|
197
|
+
... ]
|
|
198
|
+
... },
|
|
199
|
+
... ]
|
|
200
|
+
|
|
201
|
+
>>> inputs = processor.apply_chat_template(
|
|
202
|
+
... messages,
|
|
203
|
+
... tokenize=True,
|
|
204
|
+
... return_dict=True,
|
|
205
|
+
... return_tensors="pt",
|
|
206
|
+
... add_generation_prompt=True
|
|
207
|
+
... )
|
|
208
|
+
>>> # Generate
|
|
209
|
+
>>> generate_ids = model.generate(**inputs)
|
|
210
|
+
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
211
|
+
"user\nYou are a helpful assistant.\n\n\n\n\n\nWhere is the cat standing?\nmodel\nBased on the image, the cat is standing in a snowy area, likely outdoors. It appears to"
|
|
212
|
+
```
|
|
213
|
+
"""
|
|
214
|
+
|
|
215
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
216
|
+
output_hidden_states = (
|
|
217
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
218
|
+
)
|
|
219
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
220
|
+
|
|
221
|
+
outputs = self.model(
|
|
222
|
+
input_ids=input_ids,
|
|
223
|
+
pixel_values=pixel_values,
|
|
224
|
+
token_type_ids=token_type_ids,
|
|
225
|
+
attention_mask=attention_mask,
|
|
226
|
+
position_ids=position_ids,
|
|
227
|
+
past_key_values=past_key_values,
|
|
228
|
+
inputs_embeds=inputs_embeds,
|
|
229
|
+
use_cache=use_cache,
|
|
230
|
+
labels=labels,
|
|
231
|
+
output_attentions=output_attentions,
|
|
232
|
+
output_hidden_states=output_hidden_states,
|
|
233
|
+
return_dict=return_dict,
|
|
234
|
+
cache_position=cache_position,
|
|
235
|
+
**lm_kwargs,
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
hidden_states = outputs[0]
|
|
239
|
+
|
|
240
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
241
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
242
|
+
|
|
243
|
+
loss = None
|
|
244
|
+
logits = None
|
|
245
|
+
token_accuracy = None
|
|
246
|
+
if skip_logits and labels is None:
|
|
247
|
+
raise ValueError("skip_logits is True, but labels is None")
|
|
248
|
+
|
|
249
|
+
if skip_logits is None:
|
|
250
|
+
skip_logits = self.training and (labels is not None)
|
|
251
|
+
|
|
252
|
+
if skip_logits:
|
|
253
|
+
shift_hidden_states = kept_hidden_states[..., :-1, :]
|
|
254
|
+
shift_labels = labels[..., 1:]
|
|
255
|
+
|
|
256
|
+
hidden_device = shift_hidden_states.device
|
|
257
|
+
if attention_mask is not None:
|
|
258
|
+
# we use the input attention mask to shift the hidden_states and labels, because it is 2D.
|
|
259
|
+
# we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
|
|
260
|
+
shift_attention_mask = attention_mask[:, -shift_hidden_states.shape[1] :].to(hidden_device)
|
|
261
|
+
shift_hidden_states = shift_hidden_states[shift_attention_mask.to(hidden_device) != 0].contiguous()
|
|
262
|
+
shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
|
|
263
|
+
else:
|
|
264
|
+
shift_hidden_states = shift_hidden_states.contiguous()
|
|
265
|
+
shift_labels = shift_labels.contiguous()
|
|
266
|
+
|
|
267
|
+
# Flatten hidden state
|
|
268
|
+
shift_hidden_states = shift_hidden_states.view(-1, self.config.text_config.hidden_size)
|
|
269
|
+
shift_labels = shift_labels.view(-1).to(hidden_device)
|
|
270
|
+
|
|
271
|
+
lce = LigerFusedLinearCrossEntropyLoss()
|
|
272
|
+
result = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
273
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
274
|
+
|
|
275
|
+
else:
|
|
276
|
+
logits = self.lm_head(kept_hidden_states)
|
|
277
|
+
if labels is not None:
|
|
278
|
+
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
|
279
|
+
logits = logits.float()
|
|
280
|
+
shift_logits = logits[..., :-1, :]
|
|
281
|
+
shift_labels = labels[..., 1:]
|
|
282
|
+
if attention_mask is not None:
|
|
283
|
+
# we use the input attention mask to shift the logits and labels, because it is 2D.
|
|
284
|
+
# we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
|
|
285
|
+
shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
|
|
286
|
+
shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
|
|
287
|
+
shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
|
|
288
|
+
else:
|
|
289
|
+
shift_logits = shift_logits.contiguous()
|
|
290
|
+
shift_labels = shift_labels.contiguous()
|
|
291
|
+
# Flatten the tokens
|
|
292
|
+
loss_fct = nn.CrossEntropyLoss()
|
|
293
|
+
|
|
294
|
+
flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
|
|
295
|
+
flat_labels = shift_labels.view(-1).to(shift_logits.device)
|
|
296
|
+
loss = loss_fct(flat_logits, flat_labels)
|
|
297
|
+
elif shift_labels is not None:
|
|
298
|
+
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
|
299
|
+
logits = logits.float()
|
|
300
|
+
shift_logits = logits[..., :-1, :]
|
|
301
|
+
if attention_mask is not None:
|
|
302
|
+
# we use the input attention mask to shift the logits and labels, because it is 2D.
|
|
303
|
+
# we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
|
|
304
|
+
shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
|
|
305
|
+
shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
|
|
306
|
+
shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
|
|
307
|
+
else:
|
|
308
|
+
shift_logits = shift_logits.contiguous()
|
|
309
|
+
shift_labels = shift_labels.contiguous()
|
|
310
|
+
# Flatten the tokens
|
|
311
|
+
loss_fct = nn.CrossEntropyLoss()
|
|
312
|
+
|
|
313
|
+
flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
|
|
314
|
+
flat_labels = shift_labels.view(-1).to(shift_logits.device)
|
|
315
|
+
loss = loss_fct(flat_logits, flat_labels)
|
|
316
|
+
|
|
317
|
+
if not return_dict:
|
|
318
|
+
output = (logits,) + outputs[1:]
|
|
319
|
+
output = (loss,) + output if loss is not None else output
|
|
320
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
321
|
+
return output
|
|
322
|
+
|
|
323
|
+
return LigerGemma3CausalLMOutputWithPast(
|
|
324
|
+
loss=loss,
|
|
325
|
+
logits=logits,
|
|
326
|
+
past_key_values=outputs.past_key_values,
|
|
327
|
+
hidden_states=outputs.hidden_states,
|
|
328
|
+
attentions=outputs.attentions,
|
|
329
|
+
image_hidden_states=outputs.image_hidden_states,
|
|
330
|
+
token_accuracy=token_accuracy,
|
|
331
|
+
)
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from typing import Tuple
|
|
4
|
+
from typing import Union
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
|
|
8
|
+
from transformers.utils.deprecation import deprecate_kwarg
|
|
9
|
+
|
|
10
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
11
|
+
from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
|
|
12
|
+
from liger_kernel.transformers.model.output_classes import LigerCausalLMOutputWithPast
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
|
16
|
+
def lce_forward(
|
|
17
|
+
self,
|
|
18
|
+
input_ids: torch.LongTensor = None,
|
|
19
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
20
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
21
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
22
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
23
|
+
labels: Optional[torch.LongTensor] = None,
|
|
24
|
+
use_cache: Optional[bool] = None,
|
|
25
|
+
output_attentions: Optional[bool] = None,
|
|
26
|
+
output_hidden_states: Optional[bool] = None,
|
|
27
|
+
return_dict: Optional[bool] = None,
|
|
28
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
29
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
30
|
+
skip_logits: Optional[bool] = None,
|
|
31
|
+
**kwargs,
|
|
32
|
+
) -> Union[Tuple, LigerCausalLMOutputWithPast]:
|
|
33
|
+
r"""
|
|
34
|
+
Args:
|
|
35
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
36
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
37
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
38
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
39
|
+
|
|
40
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
41
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
42
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
43
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
44
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
45
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
|
|
49
|
+
Example:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
>>> from transformers import AutoTokenizer, Glm4ForCausalLM
|
|
53
|
+
|
|
54
|
+
>>> model = Glm4ForCausalLM.from_pretrained("THUDM/GLM-4-9B-0414")
|
|
55
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("THUDM/GLM-4-9B-0414")
|
|
56
|
+
|
|
57
|
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
|
58
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
59
|
+
|
|
60
|
+
>>> # Generate
|
|
61
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
62
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
63
|
+
'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m'
|
|
64
|
+
```
|
|
65
|
+
"""
|
|
66
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
67
|
+
output_hidden_states = (
|
|
68
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
69
|
+
)
|
|
70
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
71
|
+
|
|
72
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
73
|
+
outputs = self.model(
|
|
74
|
+
input_ids=input_ids,
|
|
75
|
+
attention_mask=attention_mask,
|
|
76
|
+
position_ids=position_ids,
|
|
77
|
+
past_key_values=past_key_values,
|
|
78
|
+
inputs_embeds=inputs_embeds,
|
|
79
|
+
use_cache=use_cache,
|
|
80
|
+
output_attentions=output_attentions,
|
|
81
|
+
output_hidden_states=output_hidden_states,
|
|
82
|
+
return_dict=return_dict,
|
|
83
|
+
cache_position=cache_position,
|
|
84
|
+
**kwargs,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
hidden_states = outputs[0]
|
|
88
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
89
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
90
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
91
|
+
|
|
92
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
93
|
+
logits = None
|
|
94
|
+
loss = None
|
|
95
|
+
token_accuracy = None
|
|
96
|
+
|
|
97
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
98
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
99
|
+
|
|
100
|
+
if skip_logits is None:
|
|
101
|
+
# By default, if in training mode, don't materialize logits
|
|
102
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
103
|
+
|
|
104
|
+
# Compute loss
|
|
105
|
+
if skip_logits:
|
|
106
|
+
result = LigerForCausalLMLoss(
|
|
107
|
+
hidden_states=kept_hidden_states,
|
|
108
|
+
lm_head_weight=self.lm_head.weight,
|
|
109
|
+
labels=labels,
|
|
110
|
+
shift_labels=shift_labels,
|
|
111
|
+
hidden_size=self.config.hidden_size,
|
|
112
|
+
**kwargs,
|
|
113
|
+
)
|
|
114
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
115
|
+
|
|
116
|
+
else:
|
|
117
|
+
logits = self.lm_head(kept_hidden_states)
|
|
118
|
+
if labels is not None or shift_labels is not None:
|
|
119
|
+
loss = self.loss_function(
|
|
120
|
+
logits=logits,
|
|
121
|
+
labels=labels,
|
|
122
|
+
shift_labels=shift_labels,
|
|
123
|
+
vocab_size=self.config.vocab_size,
|
|
124
|
+
**kwargs,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
if not return_dict:
|
|
128
|
+
output = (logits,) + outputs[1:]
|
|
129
|
+
output = ((loss,) + output) if loss is not None else output
|
|
130
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
131
|
+
return output
|
|
132
|
+
|
|
133
|
+
# Return custom output class with token_accuracy field
|
|
134
|
+
return LigerCausalLMOutputWithPast(
|
|
135
|
+
loss=loss,
|
|
136
|
+
logits=logits,
|
|
137
|
+
past_key_values=outputs.past_key_values,
|
|
138
|
+
hidden_states=outputs.hidden_states,
|
|
139
|
+
attentions=outputs.attentions,
|
|
140
|
+
token_accuracy=token_accuracy,
|
|
141
|
+
)
|
|
@@ -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.deprecation import deprecate_kwarg
|
|
9
|
+
|
|
10
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
11
|
+
from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
|
|
12
|
+
from liger_kernel.transformers.model.output_classes import LigerCausalLMOutputWithPast
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
|
16
|
+
def lce_forward(
|
|
17
|
+
self,
|
|
18
|
+
input_ids: torch.LongTensor = None,
|
|
19
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
20
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
21
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
22
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
23
|
+
labels: Optional[torch.LongTensor] = None,
|
|
24
|
+
use_cache: Optional[bool] = None,
|
|
25
|
+
output_attentions: Optional[bool] = None,
|
|
26
|
+
output_hidden_states: Optional[bool] = None,
|
|
27
|
+
return_dict: Optional[bool] = None,
|
|
28
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
29
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
30
|
+
skip_logits: Optional[bool] = None,
|
|
31
|
+
**kwargs,
|
|
32
|
+
) -> Union[Tuple, LigerCausalLMOutputWithPast]:
|
|
33
|
+
r"""
|
|
34
|
+
Args:
|
|
35
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
36
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
37
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
38
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
39
|
+
|
|
40
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
41
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
42
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
43
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
44
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
45
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
|
|
49
|
+
Example:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
>>> from PIL import Image
|
|
53
|
+
>>> from transformers import AutoTokenizer, Glm4vForConditionalGeneration
|
|
54
|
+
|
|
55
|
+
>>> MODEL_PATH = "THUDM/GLM-4.1V-9B-Thinking"
|
|
56
|
+
>>> messages = [
|
|
57
|
+
{
|
|
58
|
+
"role": "user",
|
|
59
|
+
"content": [
|
|
60
|
+
{
|
|
61
|
+
"type": "image",
|
|
62
|
+
"url": "https://upload.wikimedia.org/wikipedia/commons/f/fa/Grayscale_8bits_palette_sample_image.png"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
"type": "text",
|
|
66
|
+
"text": "describe this image"
|
|
67
|
+
}
|
|
68
|
+
],
|
|
69
|
+
}
|
|
70
|
+
]
|
|
71
|
+
>>> processor = AutoProcessor.from_pretrained(MODEL_PATH, use_fast=True)
|
|
72
|
+
>>> model = Glm4vForConditionalGeneration.from_pretrained(
|
|
73
|
+
pretrained_model_name_or_path=MODEL_PATH,
|
|
74
|
+
dtype=torch.bfloat16,
|
|
75
|
+
device_map="auto",
|
|
76
|
+
)
|
|
77
|
+
>>> inputs = processor.apply_chat_template(
|
|
78
|
+
messages,
|
|
79
|
+
tokenize=True,
|
|
80
|
+
add_generation_prompt=True,
|
|
81
|
+
return_dict=True,
|
|
82
|
+
return_tensors="pt"
|
|
83
|
+
).to(model.device)
|
|
84
|
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=8192)
|
|
85
|
+
output_text = processor.decode(generated_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=False)
|
|
86
|
+
<think>Got it, let's describe the image. First, there's a vintage car, specifically a Volkswagen Beetle
|
|
87
|
+
```"""
|
|
88
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
89
|
+
output_hidden_states = (
|
|
90
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
91
|
+
)
|
|
92
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
93
|
+
|
|
94
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
95
|
+
outputs = self.model(
|
|
96
|
+
input_ids=input_ids,
|
|
97
|
+
attention_mask=attention_mask,
|
|
98
|
+
position_ids=position_ids,
|
|
99
|
+
past_key_values=past_key_values,
|
|
100
|
+
inputs_embeds=inputs_embeds,
|
|
101
|
+
use_cache=use_cache,
|
|
102
|
+
output_attentions=output_attentions,
|
|
103
|
+
output_hidden_states=output_hidden_states,
|
|
104
|
+
return_dict=return_dict,
|
|
105
|
+
cache_position=cache_position,
|
|
106
|
+
**kwargs,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
hidden_states = outputs[0]
|
|
110
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
111
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
112
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
113
|
+
|
|
114
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
115
|
+
logits = None
|
|
116
|
+
loss = 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
|
+
# By default, if in training mode, don't materialize logits
|
|
124
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
125
|
+
|
|
126
|
+
# Compute loss
|
|
127
|
+
if skip_logits:
|
|
128
|
+
result = LigerForCausalLMLoss(
|
|
129
|
+
hidden_states=kept_hidden_states,
|
|
130
|
+
lm_head_weight=self.lm_head.weight,
|
|
131
|
+
labels=labels,
|
|
132
|
+
shift_labels=shift_labels,
|
|
133
|
+
hidden_size=self.config.hidden_size,
|
|
134
|
+
**kwargs,
|
|
135
|
+
)
|
|
136
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
137
|
+
|
|
138
|
+
else:
|
|
139
|
+
logits = self.lm_head(kept_hidden_states)
|
|
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
|
+
**kwargs,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
if not return_dict:
|
|
150
|
+
output = (logits,) + outputs[1:]
|
|
151
|
+
output = ((loss,) + output) if loss is not None else output
|
|
152
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
153
|
+
return output
|
|
154
|
+
|
|
155
|
+
# Return custom output class with token_accuracy field
|
|
156
|
+
return LigerCausalLMOutputWithPast(
|
|
157
|
+
loss=loss,
|
|
158
|
+
logits=logits,
|
|
159
|
+
past_key_values=outputs.past_key_values,
|
|
160
|
+
hidden_states=outputs.hidden_states,
|
|
161
|
+
attentions=outputs.attentions,
|
|
162
|
+
token_accuracy=token_accuracy,
|
|
163
|
+
)
|