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,121 @@
|
|
|
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.cache_utils import Cache
|
|
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
|
+
def lce_forward(
|
|
16
|
+
self,
|
|
17
|
+
input_ids: torch.LongTensor = None,
|
|
18
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
19
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
20
|
+
past_key_values: Optional[Union[Cache, 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
|
+
return_dict: Optional[bool] = None,
|
|
27
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
28
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
29
|
+
**kwargs,
|
|
30
|
+
) -> Union[Tuple, LigerCausalLMOutputWithPast]:
|
|
31
|
+
r"""
|
|
32
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
33
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
34
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
35
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
36
|
+
|
|
37
|
+
Example:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
>>> from transformers import AutoTokenizer, Llama4ForCausalLM
|
|
41
|
+
|
|
42
|
+
>>> model = Llama4ForCausalLM.from_pretrained("meta-llama4/Llama4-2-7b-hf")
|
|
43
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama4/Llama4-2-7b-hf")
|
|
44
|
+
|
|
45
|
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
|
46
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
47
|
+
|
|
48
|
+
>>> # Generate
|
|
49
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
50
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
51
|
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
|
52
|
+
```"""
|
|
53
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
54
|
+
output_hidden_states = (
|
|
55
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
56
|
+
)
|
|
57
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
58
|
+
|
|
59
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
60
|
+
outputs = self.model(
|
|
61
|
+
input_ids=input_ids,
|
|
62
|
+
attention_mask=attention_mask,
|
|
63
|
+
position_ids=position_ids,
|
|
64
|
+
past_key_values=past_key_values,
|
|
65
|
+
inputs_embeds=inputs_embeds,
|
|
66
|
+
use_cache=use_cache,
|
|
67
|
+
output_attentions=output_attentions,
|
|
68
|
+
output_hidden_states=output_hidden_states,
|
|
69
|
+
return_dict=True,
|
|
70
|
+
cache_position=cache_position,
|
|
71
|
+
**kwargs,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
hidden_states = outputs[0]
|
|
75
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
76
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
77
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
78
|
+
|
|
79
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
80
|
+
logits = None
|
|
81
|
+
loss = None
|
|
82
|
+
token_accuracy = None
|
|
83
|
+
|
|
84
|
+
# Compute loss
|
|
85
|
+
if self.training and (labels is not None or shift_labels is not None):
|
|
86
|
+
result = LigerForCausalLMLoss(
|
|
87
|
+
hidden_states=kept_hidden_states,
|
|
88
|
+
lm_head_weight=self.lm_head.weight,
|
|
89
|
+
labels=labels,
|
|
90
|
+
shift_labels=shift_labels,
|
|
91
|
+
hidden_size=self.config.hidden_size,
|
|
92
|
+
**kwargs,
|
|
93
|
+
)
|
|
94
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
95
|
+
|
|
96
|
+
else: # if in inference mode materialize logits
|
|
97
|
+
logits = self.lm_head(kept_hidden_states)
|
|
98
|
+
if labels is not None or shift_labels is not None:
|
|
99
|
+
loss = self.loss_function(
|
|
100
|
+
logits=logits,
|
|
101
|
+
labels=labels,
|
|
102
|
+
shift_labels=shift_labels,
|
|
103
|
+
vocab_size=self.config.vocab_size,
|
|
104
|
+
**kwargs,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
if not return_dict:
|
|
108
|
+
output = (logits,) + outputs[1:]
|
|
109
|
+
output = ((loss,) + output) if loss is not None else output
|
|
110
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
111
|
+
return output
|
|
112
|
+
|
|
113
|
+
# Return custom output class with token_accuracy field
|
|
114
|
+
return LigerCausalLMOutputWithPast(
|
|
115
|
+
loss=loss,
|
|
116
|
+
logits=logits,
|
|
117
|
+
past_key_values=outputs.past_key_values,
|
|
118
|
+
hidden_states=outputs.hidden_states,
|
|
119
|
+
attentions=outputs.attentions,
|
|
120
|
+
token_accuracy=token_accuracy,
|
|
121
|
+
)
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from typing import Tuple
|
|
4
|
+
from typing import Union
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
|
|
8
|
+
from torch.nn import CrossEntropyLoss
|
|
9
|
+
from transformers.models.llava.modeling_llava import LlavaCausalLMOutputWithPast
|
|
10
|
+
from transformers.utils import is_torchdynamo_compiling
|
|
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 LigerLlavaCausalLMOutputWithPast
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def lce_forward_deprecated(
|
|
19
|
+
self,
|
|
20
|
+
input_ids: torch.LongTensor = None,
|
|
21
|
+
pixel_values: torch.FloatTensor = None,
|
|
22
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
23
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
24
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
25
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
26
|
+
vision_feature_layer: Optional[int] = None,
|
|
27
|
+
vision_feature_select_strategy: Optional[str] = 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
|
+
image_sizes: torch.Tensor = None,
|
|
36
|
+
skip_logits: Optional[bool] = None,
|
|
37
|
+
**lm_kwargs,
|
|
38
|
+
) -> Union[Tuple, LlavaCausalLMOutputWithPast]:
|
|
39
|
+
r"""
|
|
40
|
+
Args:
|
|
41
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
42
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
43
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
44
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
45
|
+
|
|
46
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
47
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
48
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
49
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
50
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
51
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
|
|
56
|
+
Example:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
>>> from PIL import Image
|
|
60
|
+
>>> import requests
|
|
61
|
+
>>> from transformers import AutoProcessor, LlavaForConditionalGeneration
|
|
62
|
+
|
|
63
|
+
>>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
|
|
64
|
+
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
|
|
65
|
+
|
|
66
|
+
>>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
|
|
67
|
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
|
68
|
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
|
69
|
+
|
|
70
|
+
>>> inputs = processor(images=image, text=prompt, return_tensors="pt")
|
|
71
|
+
|
|
72
|
+
>>> # Generate
|
|
73
|
+
>>> generate_ids = model.generate(**inputs, max_new_tokens=15)
|
|
74
|
+
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
75
|
+
"USER: \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
|
|
76
|
+
```"""
|
|
77
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
78
|
+
output_hidden_states = (
|
|
79
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
80
|
+
)
|
|
81
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
82
|
+
vision_feature_layer = (
|
|
83
|
+
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
|
84
|
+
)
|
|
85
|
+
vision_feature_select_strategy = (
|
|
86
|
+
vision_feature_select_strategy
|
|
87
|
+
if vision_feature_select_strategy is not None
|
|
88
|
+
else self.config.vision_feature_select_strategy
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
|
92
|
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
|
93
|
+
|
|
94
|
+
if pixel_values is not None and inputs_embeds is not None:
|
|
95
|
+
raise ValueError(
|
|
96
|
+
"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
if inputs_embeds is None:
|
|
100
|
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
|
101
|
+
|
|
102
|
+
if pixel_values is not None:
|
|
103
|
+
image_features = self.get_image_features(
|
|
104
|
+
pixel_values=pixel_values,
|
|
105
|
+
vision_feature_layer=vision_feature_layer,
|
|
106
|
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
107
|
+
image_sizes=image_sizes,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
|
|
111
|
+
special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
|
|
112
|
+
if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
|
|
113
|
+
n_image_tokens = (input_ids == self.config.image_token_index).sum()
|
|
114
|
+
n_image_features = image_features.shape[0] * image_features.shape[1]
|
|
115
|
+
raise ValueError(
|
|
116
|
+
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
|
|
117
|
+
)
|
|
118
|
+
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
119
|
+
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
|
120
|
+
|
|
121
|
+
outputs = self.language_model.model(
|
|
122
|
+
attention_mask=attention_mask,
|
|
123
|
+
position_ids=position_ids,
|
|
124
|
+
past_key_values=past_key_values,
|
|
125
|
+
inputs_embeds=inputs_embeds,
|
|
126
|
+
use_cache=use_cache,
|
|
127
|
+
output_attentions=output_attentions,
|
|
128
|
+
output_hidden_states=output_hidden_states,
|
|
129
|
+
return_dict=return_dict,
|
|
130
|
+
cache_position=cache_position,
|
|
131
|
+
logits_to_keep=logits_to_keep,
|
|
132
|
+
**lm_kwargs,
|
|
133
|
+
)
|
|
134
|
+
hidden_states = outputs[0]
|
|
135
|
+
|
|
136
|
+
loss = None
|
|
137
|
+
logits = None
|
|
138
|
+
|
|
139
|
+
# Overwrite skip_logits, since llava never materializes logits
|
|
140
|
+
skip_logits = labels is not None
|
|
141
|
+
|
|
142
|
+
if skip_logits:
|
|
143
|
+
# Shift so that tokens < n predict n
|
|
144
|
+
if attention_mask is not None:
|
|
145
|
+
# we use the input attention mask to shift the logits and labels, because it is 2D.
|
|
146
|
+
# we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
|
|
147
|
+
shift_attention_mask = attention_mask[:, -(hidden_states.shape[1] - 1) :].to(hidden_states.device)
|
|
148
|
+
shift_hidden_states = hidden_states[..., :-1, :][
|
|
149
|
+
shift_attention_mask.to(hidden_states.device) != 0
|
|
150
|
+
].contiguous()
|
|
151
|
+
shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
|
|
152
|
+
else:
|
|
153
|
+
shift_hidden_states = hidden_states[..., :-1, :].contiguous()
|
|
154
|
+
shift_labels = labels[..., 1:].contiguous()
|
|
155
|
+
|
|
156
|
+
lce = LigerFusedLinearCrossEntropyLoss()
|
|
157
|
+
loss = lce(
|
|
158
|
+
self.language_model.lm_head.weight,
|
|
159
|
+
shift_hidden_states.view(-1, shift_hidden_states.size(-1)),
|
|
160
|
+
shift_labels.view(-1).to(shift_hidden_states.device),
|
|
161
|
+
)
|
|
162
|
+
else:
|
|
163
|
+
logits = self.language_model.lm_head(hidden_states)
|
|
164
|
+
if labels is not None:
|
|
165
|
+
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
|
166
|
+
logits = logits.float()
|
|
167
|
+
shift_logits = logits[..., :-1, :]
|
|
168
|
+
shift_labels = labels[..., 1:]
|
|
169
|
+
if attention_mask is not None:
|
|
170
|
+
# we use the input attention mask to shift the logits and labels, because it is 2D.
|
|
171
|
+
# we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
|
|
172
|
+
shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
|
|
173
|
+
shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
|
|
174
|
+
shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
|
|
175
|
+
else:
|
|
176
|
+
shift_logits = shift_logits.contiguous()
|
|
177
|
+
shift_labels = shift_labels.contiguous()
|
|
178
|
+
# Flatten the tokens
|
|
179
|
+
loss_fct = CrossEntropyLoss()
|
|
180
|
+
|
|
181
|
+
flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
|
|
182
|
+
flat_labels = shift_labels.view(-1).to(shift_logits.device)
|
|
183
|
+
loss = loss_fct(flat_logits, flat_labels)
|
|
184
|
+
|
|
185
|
+
if not return_dict:
|
|
186
|
+
# NOTE: This part has not been tested.
|
|
187
|
+
output = outputs[1:]
|
|
188
|
+
return (loss,) + output if loss is not None else output
|
|
189
|
+
|
|
190
|
+
return LlavaCausalLMOutputWithPast(
|
|
191
|
+
loss=loss,
|
|
192
|
+
logits=logits,
|
|
193
|
+
past_key_values=outputs.past_key_values,
|
|
194
|
+
hidden_states=outputs.hidden_states,
|
|
195
|
+
attentions=outputs.attentions,
|
|
196
|
+
image_hidden_states=image_features if pixel_values is not None else None,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def lce_forward(
|
|
201
|
+
self,
|
|
202
|
+
input_ids: torch.LongTensor = None,
|
|
203
|
+
pixel_values: torch.FloatTensor = None,
|
|
204
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
205
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
206
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
207
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
208
|
+
vision_feature_layer: Optional[int] = None,
|
|
209
|
+
vision_feature_select_strategy: Optional[str] = None,
|
|
210
|
+
labels: Optional[torch.LongTensor] = None,
|
|
211
|
+
use_cache: Optional[bool] = None,
|
|
212
|
+
output_attentions: Optional[bool] = None,
|
|
213
|
+
output_hidden_states: Optional[bool] = None,
|
|
214
|
+
return_dict: Optional[bool] = None,
|
|
215
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
216
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
217
|
+
image_sizes: torch.Tensor = None,
|
|
218
|
+
skip_logits: Optional[bool] = None,
|
|
219
|
+
**lm_kwargs,
|
|
220
|
+
) -> Union[Tuple, LigerLlavaCausalLMOutputWithPast]:
|
|
221
|
+
r"""
|
|
222
|
+
Args:
|
|
223
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
224
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
225
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
226
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
227
|
+
|
|
228
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
229
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
230
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
231
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
232
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
233
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
Returns:
|
|
237
|
+
|
|
238
|
+
Example:
|
|
239
|
+
|
|
240
|
+
```python
|
|
241
|
+
>>> from PIL import Image
|
|
242
|
+
>>> import requests
|
|
243
|
+
>>> from transformers import AutoProcessor, LlavaForConditionalGeneration
|
|
244
|
+
|
|
245
|
+
>>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
|
|
246
|
+
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
|
|
247
|
+
|
|
248
|
+
>>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
|
|
249
|
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
|
250
|
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
|
251
|
+
|
|
252
|
+
>>> inputs = processor(images=image, text=prompt, return_tensors="pt")
|
|
253
|
+
|
|
254
|
+
>>> # Generate
|
|
255
|
+
>>> generate_ids = model.generate(**inputs, max_new_tokens=15)
|
|
256
|
+
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
257
|
+
"USER: \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
|
|
258
|
+
```"""
|
|
259
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
260
|
+
output_hidden_states = (
|
|
261
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
262
|
+
)
|
|
263
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
264
|
+
vision_feature_layer = (
|
|
265
|
+
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
|
266
|
+
)
|
|
267
|
+
vision_feature_select_strategy = (
|
|
268
|
+
vision_feature_select_strategy
|
|
269
|
+
if vision_feature_select_strategy is not None
|
|
270
|
+
else self.config.vision_feature_select_strategy
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
outputs = self.model(
|
|
274
|
+
input_ids=input_ids,
|
|
275
|
+
pixel_values=pixel_values,
|
|
276
|
+
attention_mask=attention_mask,
|
|
277
|
+
position_ids=position_ids,
|
|
278
|
+
past_key_values=past_key_values,
|
|
279
|
+
inputs_embeds=inputs_embeds,
|
|
280
|
+
vision_feature_layer=vision_feature_layer,
|
|
281
|
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
282
|
+
use_cache=use_cache,
|
|
283
|
+
output_attentions=output_attentions,
|
|
284
|
+
output_hidden_states=output_hidden_states,
|
|
285
|
+
return_dict=True,
|
|
286
|
+
cache_position=cache_position,
|
|
287
|
+
image_sizes=image_sizes,
|
|
288
|
+
**lm_kwargs,
|
|
289
|
+
)
|
|
290
|
+
hidden_states = outputs[0]
|
|
291
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
292
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
293
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
294
|
+
|
|
295
|
+
shift_labels = lm_kwargs.pop("shift_labels", None)
|
|
296
|
+
logits = None
|
|
297
|
+
loss = None
|
|
298
|
+
token_accuracy = None
|
|
299
|
+
|
|
300
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
301
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
302
|
+
|
|
303
|
+
if skip_logits is None:
|
|
304
|
+
# By default, if in training mode, don't materialize logits
|
|
305
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
306
|
+
|
|
307
|
+
if skip_logits:
|
|
308
|
+
result = LigerForCausalLMLoss(
|
|
309
|
+
hidden_states=kept_hidden_states,
|
|
310
|
+
lm_head_weight=self.lm_head.weight,
|
|
311
|
+
labels=labels,
|
|
312
|
+
shift_labels=shift_labels,
|
|
313
|
+
hidden_size=self.config.text_config.hidden_size,
|
|
314
|
+
**lm_kwargs,
|
|
315
|
+
)
|
|
316
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
317
|
+
|
|
318
|
+
else:
|
|
319
|
+
logits = self.lm_head(kept_hidden_states)
|
|
320
|
+
if labels is not None or shift_labels is not None:
|
|
321
|
+
loss = self.loss_function(
|
|
322
|
+
logits=logits,
|
|
323
|
+
labels=labels,
|
|
324
|
+
shift_labels=shift_labels,
|
|
325
|
+
vocab_size=self.config.text_config.vocab_size,
|
|
326
|
+
**lm_kwargs,
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
if not return_dict:
|
|
330
|
+
output = (logits,) + outputs[1:]
|
|
331
|
+
output = (loss,) + output if loss is not None else output
|
|
332
|
+
output = output + (token_accuracy,) if token_accuracy is not None else output
|
|
333
|
+
return output
|
|
334
|
+
|
|
335
|
+
# Return custom output class with token_accuracy field
|
|
336
|
+
return LigerLlavaCausalLMOutputWithPast(
|
|
337
|
+
loss=loss,
|
|
338
|
+
logits=logits,
|
|
339
|
+
past_key_values=outputs.past_key_values,
|
|
340
|
+
hidden_states=outputs.hidden_states,
|
|
341
|
+
attentions=outputs.attentions,
|
|
342
|
+
image_hidden_states=outputs.image_hidden_states,
|
|
343
|
+
token_accuracy=token_accuracy,
|
|
344
|
+
)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
from typing import Tuple
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
import torch.nn as nn
|
|
6
|
+
|
|
7
|
+
import liger_kernel.transformers.functional as F
|
|
8
|
+
|
|
9
|
+
from liger_kernel.transformers.functional import CrossEntropyOutput
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def unpack_cross_entropy_result(
|
|
13
|
+
result,
|
|
14
|
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]:
|
|
15
|
+
if isinstance(result, CrossEntropyOutput):
|
|
16
|
+
return result.loss, result.z_loss, result.token_accuracy
|
|
17
|
+
|
|
18
|
+
if isinstance(result, tuple):
|
|
19
|
+
loss = result[0]
|
|
20
|
+
z_loss = result[1] if len(result) > 1 else None
|
|
21
|
+
token_accuracy = result[2] if len(result) > 2 else None
|
|
22
|
+
return loss, z_loss, token_accuracy
|
|
23
|
+
|
|
24
|
+
return result, None, None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def fixed_fused_linear_cross_entropy(
|
|
28
|
+
hidden_states: torch.Tensor,
|
|
29
|
+
lm_head_weight: torch.Tensor,
|
|
30
|
+
target: torch.Tensor,
|
|
31
|
+
num_items_in_batch: Optional[int] = None,
|
|
32
|
+
ignore_index: int = -100,
|
|
33
|
+
final_logit_softcapping: Optional[float] = None,
|
|
34
|
+
accum_dtype: Optional[torch.dtype] = None,
|
|
35
|
+
return_token_accuracy: bool = False,
|
|
36
|
+
**kwargs,
|
|
37
|
+
):
|
|
38
|
+
reduction = "sum" if num_items_in_batch is not None else "mean"
|
|
39
|
+
result = F.liger_fused_linear_cross_entropy(
|
|
40
|
+
hidden_states,
|
|
41
|
+
lm_head_weight,
|
|
42
|
+
target,
|
|
43
|
+
reduction=reduction,
|
|
44
|
+
ignore_index=ignore_index,
|
|
45
|
+
softcap=final_logit_softcapping,
|
|
46
|
+
accum_dtype=accum_dtype,
|
|
47
|
+
return_token_accuracy=return_token_accuracy,
|
|
48
|
+
**kwargs,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
loss, _, token_accuracy = unpack_cross_entropy_result(result)
|
|
52
|
+
|
|
53
|
+
if reduction == "sum":
|
|
54
|
+
loss = loss / num_items_in_batch
|
|
55
|
+
|
|
56
|
+
if return_token_accuracy:
|
|
57
|
+
return CrossEntropyOutput(loss=loss, token_accuracy=token_accuracy)
|
|
58
|
+
|
|
59
|
+
return loss
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def LigerForCausalLMLoss(
|
|
63
|
+
hidden_states,
|
|
64
|
+
lm_head_weight,
|
|
65
|
+
labels,
|
|
66
|
+
hidden_size: int,
|
|
67
|
+
num_items_in_batch: Optional[int] = None,
|
|
68
|
+
ignore_index: int = -100,
|
|
69
|
+
shift_labels: Optional[torch.Tensor] = None,
|
|
70
|
+
final_logit_softcapping: Optional[float] = None,
|
|
71
|
+
return_token_accuracy: bool = False,
|
|
72
|
+
**kwargs,
|
|
73
|
+
):
|
|
74
|
+
# Skip upcast since intermediate values for the loss are all fp32 in kernel
|
|
75
|
+
if shift_labels is None:
|
|
76
|
+
# Shift so that token < n predict n
|
|
77
|
+
labels = nn.functional.pad(labels, (0, 1), value=ignore_index)
|
|
78
|
+
shift_labels = labels[..., 1:].contiguous()
|
|
79
|
+
|
|
80
|
+
# Flatten the tokens
|
|
81
|
+
hidden_states = hidden_states.view(-1, hidden_size)
|
|
82
|
+
shift_labels = shift_labels.view(-1)
|
|
83
|
+
# Enable model parallelism
|
|
84
|
+
shift_labels = shift_labels.to(hidden_states.device)
|
|
85
|
+
result = fixed_fused_linear_cross_entropy(
|
|
86
|
+
hidden_states,
|
|
87
|
+
lm_head_weight,
|
|
88
|
+
shift_labels,
|
|
89
|
+
num_items_in_batch,
|
|
90
|
+
ignore_index,
|
|
91
|
+
final_logit_softcapping,
|
|
92
|
+
return_token_accuracy=return_token_accuracy,
|
|
93
|
+
**kwargs,
|
|
94
|
+
)
|
|
95
|
+
return result
|