liger-kernel-nightly 0.5.5.dev20250402185702__py3-none-any.whl → 0.6.4.dev20260112233432__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/chunked_loss/__init__.py +1 -0
- liger_kernel/chunked_loss/cosine_similarity_loss.py +142 -0
- liger_kernel/chunked_loss/dpo_loss.py +61 -3
- liger_kernel/chunked_loss/functional.py +2 -0
- liger_kernel/chunked_loss/fused_linear_distillation.py +23 -5
- liger_kernel/chunked_loss/fused_linear_ppo.py +36 -0
- liger_kernel/chunked_loss/fused_linear_preference.py +0 -1
- liger_kernel/chunked_loss/grpo_loss.py +76 -5
- liger_kernel/chunked_loss/jsd_loss.py +46 -15
- 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/ascend-ub-manager-design.md +485 -0
- liger_kernel/ops/backends/_ascend/ops/__init__.py +49 -0
- liger_kernel/ops/backends/_ascend/ops/geglu.py +266 -0
- liger_kernel/ops/backends/_ascend/ops/qwen2vl_mrope.py +285 -0
- liger_kernel/ops/backends/_ascend/ops/rope.py +290 -0
- liger_kernel/ops/backends/_ascend/ops/swiglu.py +142 -0
- liger_kernel/ops/backends/_ascend/ops/tvd.py +221 -0
- liger_kernel/ops/backends/_ascend/ub_manager.py +349 -0
- liger_kernel/ops/backends/registry.py +61 -0
- liger_kernel/ops/cross_entropy.py +134 -65
- liger_kernel/ops/dyt.py +115 -180
- liger_kernel/ops/fused_add_rms_norm.py +416 -0
- liger_kernel/ops/fused_linear_cross_entropy.py +117 -23
- liger_kernel/ops/fused_neighborhood_attention.py +1022 -0
- liger_kernel/ops/geglu.py +6 -4
- liger_kernel/ops/group_norm.py +7 -7
- liger_kernel/ops/grpo_loss.py +312 -0
- liger_kernel/ops/jsd.py +2 -1
- liger_kernel/ops/kl_div.py +9 -5
- liger_kernel/ops/layer_norm.py +146 -78
- liger_kernel/ops/llama4_rope.py +225 -0
- liger_kernel/ops/multi_token_attention.py +207 -0
- liger_kernel/ops/poly_norm.py +390 -0
- liger_kernel/ops/rms_norm.py +398 -99
- liger_kernel/ops/rope.py +1 -1
- liger_kernel/ops/softmax.py +201 -0
- liger_kernel/ops/sparsemax.py +179 -0
- liger_kernel/ops/swiglu.py +1 -1
- liger_kernel/ops/tiled_mlp.py +136 -0
- liger_kernel/ops/utils.py +14 -0
- liger_kernel/transformers/__init__.py +208 -17
- liger_kernel/transformers/auto_model.py +21 -0
- liger_kernel/transformers/cross_entropy.py +9 -4
- liger_kernel/transformers/dyt.py +6 -4
- liger_kernel/transformers/experimental/__init__.py +5 -0
- liger_kernel/transformers/experimental/embedding.py +1 -1
- liger_kernel/transformers/fsdp.py +55 -0
- liger_kernel/transformers/functional.py +122 -20
- liger_kernel/transformers/fused_add_rms_norm.py +39 -0
- liger_kernel/transformers/fused_linear_cross_entropy.py +16 -5
- liger_kernel/transformers/fused_linear_jsd.py +1 -1
- liger_kernel/transformers/fused_neighborhood_attention.py +234 -0
- liger_kernel/transformers/geglu.py +1 -1
- liger_kernel/transformers/group_norm.py +1 -1
- liger_kernel/transformers/grpo_loss.py +153 -0
- liger_kernel/transformers/jsd.py +1 -1
- liger_kernel/transformers/kl_div.py +1 -1
- liger_kernel/transformers/layer_norm.py +1 -1
- liger_kernel/transformers/llama4_rope.py +93 -0
- liger_kernel/transformers/model/exaone4.py +136 -0
- liger_kernel/transformers/model/falcon_h1.py +122 -0
- liger_kernel/transformers/model/gemma.py +57 -27
- liger_kernel/transformers/model/gemma2.py +65 -28
- 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/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 +109 -27
- liger_kernel/transformers/model/llama4.py +121 -0
- liger_kernel/transformers/model/llava.py +111 -136
- liger_kernel/transformers/model/loss_utils.py +50 -12
- liger_kernel/transformers/model/mistral.py +51 -34
- liger_kernel/transformers/model/mixtral.py +50 -29
- liger_kernel/transformers/model/mllama.py +46 -24
- liger_kernel/transformers/model/olmo2.py +47 -22
- liger_kernel/transformers/model/olmo3.py +142 -0
- liger_kernel/transformers/model/output_classes.py +147 -0
- liger_kernel/transformers/model/paligemma.py +50 -14
- liger_kernel/transformers/model/phi3.py +47 -172
- liger_kernel/transformers/model/qwen2.py +55 -23
- liger_kernel/transformers/model/qwen2_5_vl.py +62 -103
- liger_kernel/transformers/model/qwen2_vl.py +59 -108
- liger_kernel/transformers/model/qwen3.py +136 -0
- liger_kernel/transformers/model/qwen3_moe.py +152 -0
- liger_kernel/transformers/model/qwen3_next.py +146 -0
- liger_kernel/transformers/model/qwen3_vl.py +150 -0
- liger_kernel/transformers/model/qwen3_vl_moe.py +126 -0
- liger_kernel/transformers/model/smollm3.py +199 -0
- liger_kernel/transformers/model/smolvlm.py +158 -0
- liger_kernel/transformers/monkey_patch.py +2018 -244
- liger_kernel/transformers/multi_token_attention.py +64 -0
- liger_kernel/transformers/poly_norm.py +42 -0
- liger_kernel/transformers/qwen2vl_mrope.py +1 -1
- liger_kernel/transformers/rms_norm.py +54 -6
- liger_kernel/transformers/rope.py +45 -1
- liger_kernel/transformers/softmax.py +12 -0
- liger_kernel/transformers/sparsemax.py +16 -0
- liger_kernel/transformers/swiglu.py +39 -1
- liger_kernel/transformers/tiled_mlp.py +125 -0
- liger_kernel/transformers/trainer/orpo_trainer.py +1 -53
- liger_kernel/transformers/tvd.py +1 -1
- liger_kernel/utils.py +63 -0
- {liger_kernel_nightly-0.5.5.dev20250402185702.dist-info → liger_kernel_nightly-0.6.4.dev20260112233432.dist-info}/METADATA +73 -39
- liger_kernel_nightly-0.6.4.dev20260112233432.dist-info/RECORD +132 -0
- liger_kernel_nightly-0.5.5.dev20250402185702.dist-info/RECORD +0 -80
- {liger_kernel_nightly-0.5.5.dev20250402185702.dist-info → liger_kernel_nightly-0.6.4.dev20260112233432.dist-info}/LICENSE +0 -0
- {liger_kernel_nightly-0.5.5.dev20250402185702.dist-info → liger_kernel_nightly-0.6.4.dev20260112233432.dist-info}/NOTICE +0 -0
- {liger_kernel_nightly-0.5.5.dev20250402185702.dist-info → liger_kernel_nightly-0.6.4.dev20260112233432.dist-info}/WHEEL +0 -0
- {liger_kernel_nightly-0.5.5.dev20250402185702.dist-info → liger_kernel_nightly-0.6.4.dev20260112233432.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from typing import Union
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
8
|
+
from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
|
|
9
|
+
from liger_kernel.transformers.model.output_classes import LigerCausalLMOutputWithPast
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def lce_forward(
|
|
13
|
+
self,
|
|
14
|
+
input_ids: Optional[torch.LongTensor] = None,
|
|
15
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
16
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
17
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
18
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
19
|
+
labels: Optional[torch.LongTensor] = None,
|
|
20
|
+
use_cache: Optional[bool] = None,
|
|
21
|
+
output_attentions: Optional[bool] = None,
|
|
22
|
+
output_hidden_states: Optional[bool] = None,
|
|
23
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
24
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
25
|
+
skip_logits: Optional[bool] = None,
|
|
26
|
+
return_dict: Optional[bool] = None,
|
|
27
|
+
**kwargs,
|
|
28
|
+
) -> LigerCausalLMOutputWithPast:
|
|
29
|
+
r"""
|
|
30
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
31
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
32
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
33
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
34
|
+
|
|
35
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
36
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
37
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
38
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
39
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
40
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
|
|
44
|
+
Example:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
>>> from transformers import AutoTokenizer, Qwen3ForCausalLM
|
|
48
|
+
|
|
49
|
+
>>> model = Qwen3ForCausalLM.from_pretrained("Qwen/Qwen3-8B")
|
|
50
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
|
|
51
|
+
|
|
52
|
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
|
53
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
54
|
+
|
|
55
|
+
>>> # Generate
|
|
56
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
57
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
58
|
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
|
59
|
+
```"""
|
|
60
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
61
|
+
output_hidden_states = (
|
|
62
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
63
|
+
)
|
|
64
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
65
|
+
|
|
66
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
67
|
+
outputs = self.model(
|
|
68
|
+
input_ids=input_ids,
|
|
69
|
+
attention_mask=attention_mask,
|
|
70
|
+
position_ids=position_ids,
|
|
71
|
+
past_key_values=past_key_values,
|
|
72
|
+
inputs_embeds=inputs_embeds,
|
|
73
|
+
use_cache=use_cache,
|
|
74
|
+
output_attentions=output_attentions,
|
|
75
|
+
output_hidden_states=output_hidden_states,
|
|
76
|
+
cache_position=cache_position,
|
|
77
|
+
**kwargs,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
hidden_states = outputs[0]
|
|
81
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
82
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
83
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
84
|
+
|
|
85
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
86
|
+
# Remove output-control parameters that shouldn't be passed to loss functions
|
|
87
|
+
kwargs.pop("return_dict", None)
|
|
88
|
+
logits = None
|
|
89
|
+
loss = None
|
|
90
|
+
token_accuracy = None
|
|
91
|
+
|
|
92
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
93
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
94
|
+
|
|
95
|
+
if skip_logits is None:
|
|
96
|
+
# By default, if in training mode, don't materialize logits
|
|
97
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
98
|
+
|
|
99
|
+
# Compute loss
|
|
100
|
+
if skip_logits:
|
|
101
|
+
result = LigerForCausalLMLoss(
|
|
102
|
+
hidden_states=kept_hidden_states,
|
|
103
|
+
lm_head_weight=self.lm_head.weight,
|
|
104
|
+
labels=labels,
|
|
105
|
+
shift_labels=shift_labels,
|
|
106
|
+
hidden_size=self.config.hidden_size,
|
|
107
|
+
**kwargs,
|
|
108
|
+
)
|
|
109
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
110
|
+
|
|
111
|
+
else:
|
|
112
|
+
logits = self.lm_head(kept_hidden_states)
|
|
113
|
+
if labels is not None or shift_labels is not None:
|
|
114
|
+
loss = self.loss_function(
|
|
115
|
+
logits=logits,
|
|
116
|
+
labels=labels,
|
|
117
|
+
shift_labels=shift_labels,
|
|
118
|
+
vocab_size=self.config.vocab_size,
|
|
119
|
+
**kwargs,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
if not return_dict:
|
|
123
|
+
output = (logits,) + outputs[1:]
|
|
124
|
+
output = ((loss,) + output) if loss is not None else output
|
|
125
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
126
|
+
return output
|
|
127
|
+
|
|
128
|
+
# Return custom output class with accuracy field
|
|
129
|
+
return LigerCausalLMOutputWithPast(
|
|
130
|
+
loss=loss,
|
|
131
|
+
logits=logits,
|
|
132
|
+
past_key_values=outputs.past_key_values,
|
|
133
|
+
hidden_states=outputs.hidden_states,
|
|
134
|
+
attentions=outputs.attentions,
|
|
135
|
+
token_accuracy=token_accuracy,
|
|
136
|
+
)
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from typing import Union
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from transformers.modeling_outputs import MoeModelOutputWithPast
|
|
8
|
+
from transformers.models.mixtral.modeling_mixtral import load_balancing_loss_func
|
|
9
|
+
|
|
10
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
11
|
+
from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
|
|
12
|
+
from liger_kernel.transformers.model.output_classes import LigerMoeCausalLMOutputWithPast
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def lce_forward(
|
|
16
|
+
self,
|
|
17
|
+
input_ids: Optional[torch.LongTensor] = None,
|
|
18
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
19
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
20
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
21
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
22
|
+
labels: Optional[torch.LongTensor] = None,
|
|
23
|
+
use_cache: Optional[bool] = None,
|
|
24
|
+
output_attentions: Optional[bool] = None,
|
|
25
|
+
output_hidden_states: Optional[bool] = None,
|
|
26
|
+
output_router_logits: Optional[bool] = None,
|
|
27
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
28
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
29
|
+
skip_logits: Optional[bool] = None,
|
|
30
|
+
return_dict: Optional[bool] = None,
|
|
31
|
+
**kwargs,
|
|
32
|
+
) -> LigerMoeCausalLMOutputWithPast:
|
|
33
|
+
r"""
|
|
34
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
35
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
36
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
37
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
38
|
+
|
|
39
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
40
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
41
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
42
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
43
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
44
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
|
|
48
|
+
Example:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
>>> from transformers import AutoTokenizer, Qwen3MoeForCausalLM
|
|
52
|
+
|
|
53
|
+
>>> model = Qwen3MoeForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
|
|
54
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
|
|
55
|
+
|
|
56
|
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
|
57
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
58
|
+
|
|
59
|
+
>>> # Generate
|
|
60
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
61
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
62
|
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
|
63
|
+
```"""
|
|
64
|
+
|
|
65
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
66
|
+
output_router_logits = (
|
|
67
|
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
|
68
|
+
)
|
|
69
|
+
output_hidden_states = (
|
|
70
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
71
|
+
)
|
|
72
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
73
|
+
|
|
74
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
75
|
+
outputs: MoeModelOutputWithPast = self.model(
|
|
76
|
+
input_ids=input_ids,
|
|
77
|
+
attention_mask=attention_mask,
|
|
78
|
+
position_ids=position_ids,
|
|
79
|
+
past_key_values=past_key_values,
|
|
80
|
+
inputs_embeds=inputs_embeds,
|
|
81
|
+
use_cache=use_cache,
|
|
82
|
+
output_attentions=output_attentions,
|
|
83
|
+
output_hidden_states=output_hidden_states,
|
|
84
|
+
output_router_logits=output_router_logits,
|
|
85
|
+
cache_position=cache_position,
|
|
86
|
+
**kwargs,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
hidden_states = outputs.last_hidden_state
|
|
90
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
91
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
92
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
93
|
+
|
|
94
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
95
|
+
logits = None
|
|
96
|
+
loss = None
|
|
97
|
+
token_accuracy = None
|
|
98
|
+
|
|
99
|
+
if skip_logits is None:
|
|
100
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
101
|
+
|
|
102
|
+
# Compute loss
|
|
103
|
+
if skip_logits:
|
|
104
|
+
result = LigerForCausalLMLoss(
|
|
105
|
+
hidden_states=kept_hidden_states,
|
|
106
|
+
lm_head_weight=self.lm_head.weight,
|
|
107
|
+
labels=labels,
|
|
108
|
+
shift_labels=shift_labels,
|
|
109
|
+
hidden_size=self.config.hidden_size,
|
|
110
|
+
**kwargs,
|
|
111
|
+
)
|
|
112
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
113
|
+
else: # if in inference model materialize logits
|
|
114
|
+
logits = self.lm_head(kept_hidden_states)
|
|
115
|
+
if labels is not None or shift_labels is not None:
|
|
116
|
+
loss = self.loss_function(
|
|
117
|
+
logits=logits,
|
|
118
|
+
labels=labels,
|
|
119
|
+
shift_labels=shift_labels,
|
|
120
|
+
vocab_size=self.vocab_size,
|
|
121
|
+
**kwargs,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
aux_loss = None
|
|
125
|
+
if output_router_logits:
|
|
126
|
+
aux_loss = load_balancing_loss_func(
|
|
127
|
+
outputs.router_logits,
|
|
128
|
+
self.num_experts,
|
|
129
|
+
self.num_experts_per_tok,
|
|
130
|
+
attention_mask,
|
|
131
|
+
)
|
|
132
|
+
if labels is not None:
|
|
133
|
+
loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
|
|
134
|
+
|
|
135
|
+
if not return_dict:
|
|
136
|
+
output = (logits,) + outputs[1:]
|
|
137
|
+
output = ((aux_loss,) + output) if aux_loss is not None else output
|
|
138
|
+
output = ((loss,) + output) if loss is not None else output
|
|
139
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
140
|
+
return output
|
|
141
|
+
|
|
142
|
+
# Return custom output class with accuracy field
|
|
143
|
+
return LigerMoeCausalLMOutputWithPast(
|
|
144
|
+
loss=loss,
|
|
145
|
+
aux_loss=aux_loss,
|
|
146
|
+
logits=logits,
|
|
147
|
+
past_key_values=outputs.past_key_values,
|
|
148
|
+
hidden_states=outputs.hidden_states,
|
|
149
|
+
attentions=outputs.attentions,
|
|
150
|
+
router_logits=outputs.router_logits,
|
|
151
|
+
token_accuracy=token_accuracy,
|
|
152
|
+
)
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING
|
|
2
|
+
from typing import List
|
|
3
|
+
from typing import Optional
|
|
4
|
+
from typing import Union
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
|
|
8
|
+
from transformers.modeling_outputs import MoeModelOutputWithPast
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from transformers.models.qwen3_next.modeling_qwen3_next import load_balancing_loss_func
|
|
12
|
+
|
|
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 LigerMoeCausalLMOutputWithPast
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def lce_forward(
|
|
19
|
+
self,
|
|
20
|
+
input_ids: Optional[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
|
+
output_router_logits: Optional[bool] = None,
|
|
30
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
31
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
32
|
+
skip_logits: Optional[bool] = None,
|
|
33
|
+
return_dict: Optional[bool] = None,
|
|
34
|
+
**kwargs,
|
|
35
|
+
) -> LigerMoeCausalLMOutputWithPast:
|
|
36
|
+
r"""
|
|
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
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
43
|
+
If an `int`, compute logits for the last `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
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
47
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
|
|
51
|
+
Example:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
>>> from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
55
|
+
|
|
56
|
+
>>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Next-80B-A3B-Instruct")
|
|
57
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-Next-80B-A3B-Instruct")
|
|
58
|
+
|
|
59
|
+
>>> prompt = "Give me a short introduction to large language model."
|
|
60
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
61
|
+
|
|
62
|
+
>>> # Generate
|
|
63
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
64
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
65
|
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
|
66
|
+
```"""
|
|
67
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
68
|
+
output_router_logits = (
|
|
69
|
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
|
70
|
+
)
|
|
71
|
+
output_hidden_states = (
|
|
72
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
73
|
+
)
|
|
74
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
75
|
+
|
|
76
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
77
|
+
outputs: MoeModelOutputWithPast = self.model(
|
|
78
|
+
input_ids=input_ids,
|
|
79
|
+
attention_mask=attention_mask,
|
|
80
|
+
position_ids=position_ids,
|
|
81
|
+
past_key_values=past_key_values,
|
|
82
|
+
inputs_embeds=inputs_embeds,
|
|
83
|
+
use_cache=use_cache,
|
|
84
|
+
output_attentions=output_attentions,
|
|
85
|
+
output_hidden_states=output_hidden_states,
|
|
86
|
+
output_router_logits=output_router_logits,
|
|
87
|
+
cache_position=cache_position,
|
|
88
|
+
**kwargs,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
hidden_states = outputs.last_hidden_state
|
|
92
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
93
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
94
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
95
|
+
|
|
96
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
97
|
+
logits = None
|
|
98
|
+
loss = None
|
|
99
|
+
token_accuracy = None
|
|
100
|
+
|
|
101
|
+
if skip_logits is None:
|
|
102
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
103
|
+
|
|
104
|
+
if skip_logits:
|
|
105
|
+
result = LigerForCausalLMLoss(
|
|
106
|
+
hidden_states=kept_hidden_states,
|
|
107
|
+
lm_head_weight=self.lm_head.weight,
|
|
108
|
+
labels=labels,
|
|
109
|
+
shift_labels=shift_labels,
|
|
110
|
+
hidden_size=self.config.hidden_size,
|
|
111
|
+
**kwargs,
|
|
112
|
+
)
|
|
113
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
114
|
+
else: # if in inference model materialize logits
|
|
115
|
+
logits = self.lm_head(kept_hidden_states)
|
|
116
|
+
if labels is not None or shift_labels is not None:
|
|
117
|
+
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
|
118
|
+
|
|
119
|
+
aux_loss = None
|
|
120
|
+
if output_router_logits:
|
|
121
|
+
aux_loss = load_balancing_loss_func(
|
|
122
|
+
outputs.router_logits,
|
|
123
|
+
self.num_experts,
|
|
124
|
+
self.num_experts_per_tok,
|
|
125
|
+
attention_mask,
|
|
126
|
+
)
|
|
127
|
+
if labels is not None:
|
|
128
|
+
loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
|
|
129
|
+
|
|
130
|
+
if not return_dict:
|
|
131
|
+
output = (logits,) + outputs[1:]
|
|
132
|
+
output = ((aux_loss,) + output) if aux_loss is not None else output
|
|
133
|
+
output = ((loss,) + output) if loss is not None else output
|
|
134
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
135
|
+
return output
|
|
136
|
+
|
|
137
|
+
return LigerMoeCausalLMOutputWithPast(
|
|
138
|
+
loss=loss,
|
|
139
|
+
aux_loss=aux_loss,
|
|
140
|
+
logits=logits,
|
|
141
|
+
past_key_values=outputs.past_key_values,
|
|
142
|
+
hidden_states=outputs.hidden_states,
|
|
143
|
+
attentions=outputs.attentions,
|
|
144
|
+
router_logits=outputs.router_logits,
|
|
145
|
+
token_accuracy=token_accuracy,
|
|
146
|
+
)
|
|
@@ -0,0 +1,150 @@
|
|
|
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 LigerQwen3VLCausalLMOutputWithPast
|
|
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, LigerQwen3VLCausalLMOutputWithPast]:
|
|
38
|
+
"""
|
|
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
|
+
Example:
|
|
56
|
+
```python
|
|
57
|
+
>>> from PIL import Image
|
|
58
|
+
>>> import requests
|
|
59
|
+
>>> from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
|
|
60
|
+
>>> model = Qwen3VLForConditionalGeneration.from_pretrained("Qwen/Qwen3-VL")
|
|
61
|
+
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-VL")
|
|
62
|
+
>>> messages = [
|
|
63
|
+
{
|
|
64
|
+
"role": "user",
|
|
65
|
+
"content": [
|
|
66
|
+
{"type": "image"},
|
|
67
|
+
{"type": "text", "text": "What is shown in this image?"},
|
|
68
|
+
],
|
|
69
|
+
},
|
|
70
|
+
]
|
|
71
|
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
|
72
|
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
|
73
|
+
>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
74
|
+
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
|
|
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
|
+
|
|
81
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
82
|
+
output_hidden_states = (
|
|
83
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
84
|
+
)
|
|
85
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
86
|
+
|
|
87
|
+
outputs = self.model(
|
|
88
|
+
input_ids=input_ids,
|
|
89
|
+
pixel_values=pixel_values,
|
|
90
|
+
pixel_values_videos=pixel_values_videos,
|
|
91
|
+
image_grid_thw=image_grid_thw,
|
|
92
|
+
video_grid_thw=video_grid_thw,
|
|
93
|
+
second_per_grid_ts=second_per_grid_ts,
|
|
94
|
+
position_ids=position_ids,
|
|
95
|
+
attention_mask=attention_mask,
|
|
96
|
+
past_key_values=past_key_values,
|
|
97
|
+
inputs_embeds=inputs_embeds,
|
|
98
|
+
use_cache=use_cache,
|
|
99
|
+
output_attentions=output_attentions,
|
|
100
|
+
output_hidden_states=output_hidden_states,
|
|
101
|
+
return_dict=return_dict,
|
|
102
|
+
cache_position=cache_position,
|
|
103
|
+
**kwargs,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
hidden_states = outputs[0]
|
|
107
|
+
|
|
108
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
109
|
+
loss = None
|
|
110
|
+
logits = None
|
|
111
|
+
token_accuracy = None
|
|
112
|
+
|
|
113
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
114
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
115
|
+
|
|
116
|
+
if skip_logits is None:
|
|
117
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
118
|
+
|
|
119
|
+
if skip_logits:
|
|
120
|
+
result = LigerForCausalLMLoss(
|
|
121
|
+
hidden_states=hidden_states,
|
|
122
|
+
lm_head_weight=self.lm_head.weight,
|
|
123
|
+
labels=labels,
|
|
124
|
+
shift_labels=shift_labels,
|
|
125
|
+
hidden_size=self.config.text_config.hidden_size,
|
|
126
|
+
**kwargs,
|
|
127
|
+
)
|
|
128
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
129
|
+
else:
|
|
130
|
+
logits = self.lm_head(hidden_states)
|
|
131
|
+
|
|
132
|
+
loss = None
|
|
133
|
+
if labels is not None:
|
|
134
|
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
|
|
135
|
+
|
|
136
|
+
if not return_dict:
|
|
137
|
+
output = (logits,) + outputs[1:]
|
|
138
|
+
output = (loss,) + output if loss is not None else output
|
|
139
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
140
|
+
return output
|
|
141
|
+
|
|
142
|
+
return LigerQwen3VLCausalLMOutputWithPast(
|
|
143
|
+
loss=loss,
|
|
144
|
+
logits=logits,
|
|
145
|
+
past_key_values=outputs.past_key_values,
|
|
146
|
+
hidden_states=outputs.hidden_states,
|
|
147
|
+
attentions=outputs.attentions,
|
|
148
|
+
rope_deltas=outputs.rope_deltas,
|
|
149
|
+
token_accuracy=token_accuracy,
|
|
150
|
+
)
|