liger-kernel 0.5.5__py3-none-any.whl → 0.5.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- liger_kernel/chunked_loss/functional.py +2 -0
- liger_kernel/chunked_loss/fused_linear_distillation.py +17 -2
- liger_kernel/chunked_loss/fused_linear_ppo.py +331 -0
- liger_kernel/chunked_loss/grpo_loss.py +103 -61
- liger_kernel/chunked_loss/jsd_loss.py +12 -7
- liger_kernel/ops/cross_entropy.py +3 -2
- liger_kernel/ops/dyt.py +225 -0
- liger_kernel/ops/fused_linear_jsd.py +2 -1
- liger_kernel/ops/jsd.py +30 -11
- liger_kernel/ops/kl_div.py +2 -2
- liger_kernel/transformers/__init__.py +3 -0
- liger_kernel/transformers/dyt.py +20 -0
- liger_kernel/transformers/functional.py +5 -0
- liger_kernel/transformers/model/gemma.py +8 -16
- liger_kernel/transformers/model/gemma2.py +7 -16
- liger_kernel/transformers/model/llama.py +8 -15
- liger_kernel/transformers/model/llava.py +369 -0
- liger_kernel/transformers/model/loss_utils.py +57 -0
- liger_kernel/transformers/model/mistral.py +9 -10
- liger_kernel/transformers/model/mixtral.py +8 -15
- liger_kernel/transformers/model/mllama.py +8 -15
- liger_kernel/transformers/model/olmo2.py +8 -16
- liger_kernel/transformers/model/paligemma.py +397 -0
- liger_kernel/transformers/model/phi3.py +8 -15
- liger_kernel/transformers/model/qwen2.py +8 -15
- liger_kernel/transformers/model/qwen2_5_vl.py +9 -10
- liger_kernel/transformers/model/qwen2_vl.py +9 -10
- liger_kernel/transformers/monkey_patch.py +219 -13
- {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.6.dist-info}/METADATA +9 -6
- {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.6.dist-info}/RECORD +34 -29
- {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.6.dist-info}/WHEEL +1 -1
- liger_kernel/chunked_loss/fused_linear_rlhf.py +0 -240
- {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.6.dist-info/licenses}/LICENSE +0 -0
- {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.6.dist-info/licenses}/NOTICE +0 -0
- {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.6.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,369 @@
|
|
|
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.models.llava.modeling_llava import _CONFIG_FOR_DOC
|
|
9
|
+
from transformers.models.llava.modeling_llava import LLAVA_INPUTS_DOCSTRING
|
|
10
|
+
from transformers.models.llava.modeling_llava import LlavaCausalLMOutputWithPast
|
|
11
|
+
from transformers.utils import add_start_docstrings_to_model_forward
|
|
12
|
+
from transformers.utils import is_torchdynamo_compiling
|
|
13
|
+
from transformers.utils import replace_return_docstrings
|
|
14
|
+
from transformers.utils.deprecation import deprecate_kwarg
|
|
15
|
+
|
|
16
|
+
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@add_start_docstrings_to_model_forward(LLAVA_INPUTS_DOCSTRING)
|
|
20
|
+
@replace_return_docstrings(output_type=LlavaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
|
21
|
+
def lce_forward_deprecated(
|
|
22
|
+
self,
|
|
23
|
+
input_ids: torch.LongTensor = None,
|
|
24
|
+
pixel_values: torch.FloatTensor = None,
|
|
25
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
26
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
27
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
28
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
29
|
+
vision_feature_layer: Optional[int] = None,
|
|
30
|
+
vision_feature_select_strategy: Optional[str] = None,
|
|
31
|
+
labels: Optional[torch.LongTensor] = None,
|
|
32
|
+
use_cache: Optional[bool] = None,
|
|
33
|
+
output_attentions: Optional[bool] = None,
|
|
34
|
+
output_hidden_states: Optional[bool] = None,
|
|
35
|
+
return_dict: Optional[bool] = None,
|
|
36
|
+
) -> Union[Tuple, LlavaCausalLMOutputWithPast]:
|
|
37
|
+
r"""
|
|
38
|
+
Args:
|
|
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
|
+
num_logits_to_keep (`int`, *optional*):
|
|
45
|
+
Calculate logits for the last `num_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
|
+
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
|
|
52
|
+
Example:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
>>> from PIL import Image
|
|
56
|
+
>>> import requests
|
|
57
|
+
>>> from transformers import AutoProcessor, LlavaForConditionalGeneration
|
|
58
|
+
|
|
59
|
+
>>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
|
|
60
|
+
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
|
|
61
|
+
|
|
62
|
+
>>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
|
|
63
|
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
|
64
|
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
|
65
|
+
|
|
66
|
+
>>> inputs = processor(images=image, text=prompt, return_tensors="pt")
|
|
67
|
+
|
|
68
|
+
>>> # Generate
|
|
69
|
+
>>> generate_ids = model.generate(**inputs, max_new_tokens=15)
|
|
70
|
+
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
71
|
+
"USER: \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
|
|
72
|
+
```"""
|
|
73
|
+
|
|
74
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
75
|
+
output_hidden_states = (
|
|
76
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
77
|
+
)
|
|
78
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
79
|
+
vision_feature_layer = (
|
|
80
|
+
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
|
81
|
+
)
|
|
82
|
+
vision_feature_select_strategy = (
|
|
83
|
+
vision_feature_select_strategy
|
|
84
|
+
if vision_feature_select_strategy is not None
|
|
85
|
+
else self.config.vision_feature_select_strategy
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
|
89
|
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
|
90
|
+
|
|
91
|
+
if pixel_values is not None and inputs_embeds is not None:
|
|
92
|
+
raise ValueError(
|
|
93
|
+
"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
if inputs_embeds is None:
|
|
97
|
+
# 1. Extra the input embeddings
|
|
98
|
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
|
99
|
+
|
|
100
|
+
# 2. Merge text and images
|
|
101
|
+
if pixel_values is not None and input_ids.shape[1] != 1:
|
|
102
|
+
image_outputs = self.vision_tower(pixel_values, output_hidden_states=True)
|
|
103
|
+
# this is not memory efficient at all (output_hidden_states=True) will save all the hidden stated.
|
|
104
|
+
selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
|
|
105
|
+
|
|
106
|
+
if vision_feature_select_strategy == "default":
|
|
107
|
+
selected_image_feature = selected_image_feature[:, 1:]
|
|
108
|
+
elif vision_feature_select_strategy == "full":
|
|
109
|
+
selected_image_feature = selected_image_feature
|
|
110
|
+
else:
|
|
111
|
+
raise ValueError(f"Unexpected select feature strategy: {self.config.vision_feature_select_strategy}")
|
|
112
|
+
|
|
113
|
+
image_features = self.multi_modal_projector(selected_image_feature)
|
|
114
|
+
inputs_embeds = inputs_embeds.to(image_features.dtype)
|
|
115
|
+
inputs_embeds, attention_mask, labels, position_ids = self._merge_input_ids_with_image_features(
|
|
116
|
+
image_features, inputs_embeds, input_ids, attention_mask, labels
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
# In case input_ids.shape[1] == 1 & pixel_values==None & past_key_values != None, we are in the case of
|
|
120
|
+
# generation with cache
|
|
121
|
+
elif past_key_values is not None and pixel_values is not None and input_ids.shape[1] == 1:
|
|
122
|
+
# Retrieve the first layer to inspect the logits and mask out the hidden states
|
|
123
|
+
# that are set to 0
|
|
124
|
+
first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]
|
|
125
|
+
|
|
126
|
+
# Sum all dimensions of head_dim (-2) to avoid random errors such as: https://github.com/huggingface/transformers/pull/28032#issuecomment-1863691941
|
|
127
|
+
batch_index, non_attended_tokens = torch.where(first_layer_past_key_value.float().sum(-2) == 0)
|
|
128
|
+
|
|
129
|
+
# Get the target length
|
|
130
|
+
target_length = input_ids.shape[1]
|
|
131
|
+
past_length = first_layer_past_key_value.shape[-1]
|
|
132
|
+
|
|
133
|
+
extended_attention_mask = torch.ones(
|
|
134
|
+
(attention_mask.shape[0], past_length),
|
|
135
|
+
dtype=attention_mask.dtype,
|
|
136
|
+
device=attention_mask.device,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
# Filter out only the tokens that can be un-attended, this can happen
|
|
140
|
+
# if one uses Llava + Fused modules where the cache on the
|
|
141
|
+
# first iteration is already big enough, or if one passes custom cache
|
|
142
|
+
valid_indices = non_attended_tokens < extended_attention_mask.size(-1)
|
|
143
|
+
new_batch_index = batch_index[valid_indices]
|
|
144
|
+
new_non_attended_tokens = non_attended_tokens[valid_indices]
|
|
145
|
+
|
|
146
|
+
# Zero-out the places where we don't need to attend
|
|
147
|
+
extended_attention_mask[new_batch_index, new_non_attended_tokens] = 0
|
|
148
|
+
|
|
149
|
+
attention_mask = torch.cat((extended_attention_mask, attention_mask[:, -target_length:]), dim=1)
|
|
150
|
+
position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
|
|
151
|
+
|
|
152
|
+
# TODO: @raushan retain only the new behavior after v4.47
|
|
153
|
+
elif image_features is not None:
|
|
154
|
+
n_image_tokens = (input_ids == self.config.image_token_index).sum().item()
|
|
155
|
+
n_image_features = image_features.shape[0] * image_features.shape[1]
|
|
156
|
+
|
|
157
|
+
if n_image_tokens != n_image_features:
|
|
158
|
+
raise ValueError(
|
|
159
|
+
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
|
|
160
|
+
)
|
|
161
|
+
special_image_mask = (
|
|
162
|
+
(input_ids == self.config.image_token_index).unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
|
163
|
+
)
|
|
164
|
+
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
165
|
+
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
|
166
|
+
|
|
167
|
+
outputs = self.language_model.model(
|
|
168
|
+
attention_mask=attention_mask,
|
|
169
|
+
position_ids=position_ids,
|
|
170
|
+
past_key_values=past_key_values,
|
|
171
|
+
inputs_embeds=inputs_embeds,
|
|
172
|
+
use_cache=use_cache,
|
|
173
|
+
output_attentions=output_attentions,
|
|
174
|
+
output_hidden_states=output_hidden_states,
|
|
175
|
+
return_dict=return_dict,
|
|
176
|
+
)
|
|
177
|
+
hidden_states = outputs[0]
|
|
178
|
+
|
|
179
|
+
loss = None
|
|
180
|
+
logits = None
|
|
181
|
+
|
|
182
|
+
if self.training and (labels is not None):
|
|
183
|
+
# Shift so that tokens < n predict n
|
|
184
|
+
if attention_mask is not None:
|
|
185
|
+
# we use the input attention mask to shift the logits and labels, because it is 2D.
|
|
186
|
+
# we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
|
|
187
|
+
shift_attention_mask = attention_mask[:, -(hidden_states.shape[1] - 1) :].to(hidden_states.device)
|
|
188
|
+
shift_hidden_states = hidden_states[..., :-1, :][
|
|
189
|
+
shift_attention_mask.to(hidden_states.device) != 0
|
|
190
|
+
].contiguous()
|
|
191
|
+
shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
|
|
192
|
+
else:
|
|
193
|
+
shift_hidden_states = hidden_states[..., :-1, :].contiguous()
|
|
194
|
+
shift_labels = labels[..., 1:].contiguous()
|
|
195
|
+
|
|
196
|
+
lce = LigerFusedLinearCrossEntropyLoss()
|
|
197
|
+
loss = lce(self.language_model.lm_head.weight, shift_hidden_states, shift_labels)
|
|
198
|
+
|
|
199
|
+
if not return_dict:
|
|
200
|
+
# NOTE: This part has not been tested.
|
|
201
|
+
output = outputs[1:]
|
|
202
|
+
return (loss,) + output if loss is not None else output
|
|
203
|
+
|
|
204
|
+
return LlavaCausalLMOutputWithPast(
|
|
205
|
+
loss=loss,
|
|
206
|
+
logits=logits,
|
|
207
|
+
past_key_values=outputs.past_key_values,
|
|
208
|
+
hidden_states=outputs.hidden_states,
|
|
209
|
+
attentions=outputs.attentions,
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@add_start_docstrings_to_model_forward(LLAVA_INPUTS_DOCSTRING)
|
|
214
|
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
|
215
|
+
@replace_return_docstrings(output_type=LlavaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
|
216
|
+
def lce_forward(
|
|
217
|
+
self,
|
|
218
|
+
input_ids: torch.LongTensor = None,
|
|
219
|
+
pixel_values: torch.FloatTensor = None,
|
|
220
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
221
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
222
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
223
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
224
|
+
vision_feature_layer: Optional[int] = None,
|
|
225
|
+
vision_feature_select_strategy: Optional[str] = None,
|
|
226
|
+
labels: Optional[torch.LongTensor] = None,
|
|
227
|
+
use_cache: Optional[bool] = None,
|
|
228
|
+
output_attentions: Optional[bool] = None,
|
|
229
|
+
output_hidden_states: Optional[bool] = None,
|
|
230
|
+
return_dict: Optional[bool] = None,
|
|
231
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
232
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
233
|
+
image_sizes: torch.Tensor = None,
|
|
234
|
+
**lm_kwargs,
|
|
235
|
+
) -> Union[Tuple, LlavaCausalLMOutputWithPast]:
|
|
236
|
+
r"""
|
|
237
|
+
Args:
|
|
238
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
239
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
240
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
241
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
242
|
+
|
|
243
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
244
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
245
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
246
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
247
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
248
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
Returns:
|
|
252
|
+
|
|
253
|
+
Example:
|
|
254
|
+
|
|
255
|
+
```python
|
|
256
|
+
>>> from PIL import Image
|
|
257
|
+
>>> import requests
|
|
258
|
+
>>> from transformers import AutoProcessor, LlavaForConditionalGeneration
|
|
259
|
+
|
|
260
|
+
>>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
|
|
261
|
+
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
|
|
262
|
+
|
|
263
|
+
>>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
|
|
264
|
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
|
265
|
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
|
266
|
+
|
|
267
|
+
>>> inputs = processor(images=image, text=prompt, return_tensors="pt")
|
|
268
|
+
|
|
269
|
+
>>> # Generate
|
|
270
|
+
>>> generate_ids = model.generate(**inputs, max_new_tokens=15)
|
|
271
|
+
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
272
|
+
"USER: \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
|
|
273
|
+
```"""
|
|
274
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
275
|
+
output_hidden_states = (
|
|
276
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
277
|
+
)
|
|
278
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
279
|
+
vision_feature_layer = (
|
|
280
|
+
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
|
281
|
+
)
|
|
282
|
+
vision_feature_select_strategy = (
|
|
283
|
+
vision_feature_select_strategy
|
|
284
|
+
if vision_feature_select_strategy is not None
|
|
285
|
+
else self.config.vision_feature_select_strategy
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
|
289
|
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
|
290
|
+
|
|
291
|
+
if pixel_values is not None and inputs_embeds is not None:
|
|
292
|
+
raise ValueError(
|
|
293
|
+
"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
if inputs_embeds is None:
|
|
297
|
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
|
298
|
+
|
|
299
|
+
if pixel_values is not None:
|
|
300
|
+
image_features = self.get_image_features(
|
|
301
|
+
pixel_values=pixel_values,
|
|
302
|
+
vision_feature_layer=vision_feature_layer,
|
|
303
|
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
304
|
+
image_sizes=image_sizes,
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
|
|
308
|
+
special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
|
|
309
|
+
if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
|
|
310
|
+
n_image_tokens = (input_ids == self.config.image_token_index).sum()
|
|
311
|
+
n_image_features = image_features.shape[0] * image_features.shape[1]
|
|
312
|
+
raise ValueError(
|
|
313
|
+
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
|
|
314
|
+
)
|
|
315
|
+
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
316
|
+
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
|
317
|
+
|
|
318
|
+
outputs = self.language_model.model(
|
|
319
|
+
attention_mask=attention_mask,
|
|
320
|
+
position_ids=position_ids,
|
|
321
|
+
past_key_values=past_key_values,
|
|
322
|
+
inputs_embeds=inputs_embeds,
|
|
323
|
+
use_cache=use_cache,
|
|
324
|
+
output_attentions=output_attentions,
|
|
325
|
+
output_hidden_states=output_hidden_states,
|
|
326
|
+
return_dict=return_dict,
|
|
327
|
+
cache_position=cache_position,
|
|
328
|
+
logits_to_keep=logits_to_keep,
|
|
329
|
+
**lm_kwargs,
|
|
330
|
+
)
|
|
331
|
+
hidden_states = outputs[0]
|
|
332
|
+
|
|
333
|
+
loss = None
|
|
334
|
+
logits = None
|
|
335
|
+
|
|
336
|
+
if self.training and (labels is not None):
|
|
337
|
+
# Shift so that tokens < n predict n
|
|
338
|
+
if attention_mask is not None:
|
|
339
|
+
# we use the input attention mask to shift the logits and labels, because it is 2D.
|
|
340
|
+
# we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
|
|
341
|
+
shift_attention_mask = attention_mask[:, -(hidden_states.shape[1] - 1) :].to(hidden_states.device)
|
|
342
|
+
shift_hidden_states = hidden_states[..., :-1, :][
|
|
343
|
+
shift_attention_mask.to(hidden_states.device) != 0
|
|
344
|
+
].contiguous()
|
|
345
|
+
shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
|
|
346
|
+
else:
|
|
347
|
+
shift_hidden_states = hidden_states[..., :-1, :].contiguous()
|
|
348
|
+
shift_labels = labels[..., 1:].contiguous()
|
|
349
|
+
|
|
350
|
+
lce = LigerFusedLinearCrossEntropyLoss()
|
|
351
|
+
loss = lce(
|
|
352
|
+
self.language_model.lm_head.weight,
|
|
353
|
+
shift_hidden_states.view(-1, shift_hidden_states.size(-1)),
|
|
354
|
+
shift_labels.view(-1).to(shift_hidden_states.device),
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
if not return_dict:
|
|
358
|
+
# NOTE: This part has not been tested.
|
|
359
|
+
output = outputs[1:]
|
|
360
|
+
return (loss,) + output if loss is not None else output
|
|
361
|
+
|
|
362
|
+
return LlavaCausalLMOutputWithPast(
|
|
363
|
+
loss=loss,
|
|
364
|
+
logits=logits,
|
|
365
|
+
past_key_values=outputs.past_key_values,
|
|
366
|
+
hidden_states=outputs.hidden_states,
|
|
367
|
+
attentions=outputs.attentions,
|
|
368
|
+
image_hidden_states=image_features if pixel_values is not None else None,
|
|
369
|
+
)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import torch.nn as nn
|
|
2
|
+
|
|
3
|
+
import liger_kernel.transformers.functional as F
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def fixed_fused_linear_cross_entropy(
|
|
7
|
+
hidden_states,
|
|
8
|
+
lm_head_weight,
|
|
9
|
+
target,
|
|
10
|
+
num_items_in_batch: int = None,
|
|
11
|
+
ignore_index: int = -100,
|
|
12
|
+
**kwargs,
|
|
13
|
+
):
|
|
14
|
+
reduction = "sum" if num_items_in_batch is not None else "mean"
|
|
15
|
+
loss = F.liger_fused_linear_cross_entropy(
|
|
16
|
+
hidden_states,
|
|
17
|
+
lm_head_weight,
|
|
18
|
+
target,
|
|
19
|
+
reduction=reduction,
|
|
20
|
+
ignore_index=ignore_index,
|
|
21
|
+
**kwargs,
|
|
22
|
+
)
|
|
23
|
+
if reduction == "sum":
|
|
24
|
+
loss = loss / num_items_in_batch
|
|
25
|
+
|
|
26
|
+
return loss
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def LigerForCausalLMLoss(
|
|
30
|
+
hidden_states,
|
|
31
|
+
lm_head_weight,
|
|
32
|
+
labels,
|
|
33
|
+
hidden_size: int,
|
|
34
|
+
num_items_in_batch: int = None,
|
|
35
|
+
ignore_index: int = -100,
|
|
36
|
+
**kwargs,
|
|
37
|
+
):
|
|
38
|
+
# Skip upcast since intermediate values for the loss are all fp32 in kernel
|
|
39
|
+
labels = labels.to(hidden_states.device)
|
|
40
|
+
# Shift so that token < n predict n
|
|
41
|
+
labels = nn.functional.pad(labels, (0, 1), value=ignore_index)
|
|
42
|
+
shift_labels = labels[..., 1:].contiguous()
|
|
43
|
+
|
|
44
|
+
# Flatten the tokens
|
|
45
|
+
hidden_states = hidden_states.view(-1, hidden_size)
|
|
46
|
+
shift_labels = shift_labels.view(-1)
|
|
47
|
+
# Enable model parallelism
|
|
48
|
+
shift_labels = shift_labels.to(hidden_states.device)
|
|
49
|
+
loss = fixed_fused_linear_cross_entropy(
|
|
50
|
+
hidden_states,
|
|
51
|
+
lm_head_weight,
|
|
52
|
+
shift_labels,
|
|
53
|
+
num_items_in_batch,
|
|
54
|
+
ignore_index,
|
|
55
|
+
**kwargs,
|
|
56
|
+
)
|
|
57
|
+
return loss
|
|
@@ -13,7 +13,7 @@ from transformers.models.mistral.modeling_mistral import MISTRAL_INPUTS_DOCSTRIN
|
|
|
13
13
|
from transformers.utils import add_start_docstrings_to_model_forward
|
|
14
14
|
from transformers.utils import replace_return_docstrings
|
|
15
15
|
|
|
16
|
-
from liger_kernel.transformers.
|
|
16
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
17
17
|
|
|
18
18
|
|
|
19
19
|
@add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
|
|
@@ -31,6 +31,7 @@ def lce_forward(
|
|
|
31
31
|
output_hidden_states: Optional[bool] = None,
|
|
32
32
|
return_dict: Optional[bool] = None,
|
|
33
33
|
cache_position: Optional[torch.LongTensor] = None,
|
|
34
|
+
**loss_kwargs,
|
|
34
35
|
) -> Union[Tuple, CausalLMOutputWithPast]:
|
|
35
36
|
r"""
|
|
36
37
|
Copy paste Mistral's forward but replace torch cross entropy with liger fused linear cross entropy
|
|
@@ -87,15 +88,13 @@ def lce_forward(
|
|
|
87
88
|
logits = None
|
|
88
89
|
|
|
89
90
|
if self.training and (labels is not None):
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
lce = LigerFusedLinearCrossEntropyLoss()
|
|
98
|
-
loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
91
|
+
loss = LigerForCausalLMLoss(
|
|
92
|
+
hidden_states=hidden_states,
|
|
93
|
+
lm_head_weight=self.lm_head.weight,
|
|
94
|
+
labels=labels,
|
|
95
|
+
hidden_size=self.config.hidden_size,
|
|
96
|
+
**loss_kwargs,
|
|
97
|
+
)
|
|
99
98
|
|
|
100
99
|
else:
|
|
101
100
|
logits = self.lm_head(hidden_states)
|
|
@@ -14,6 +14,7 @@ from transformers.utils import add_start_docstrings_to_model_forward
|
|
|
14
14
|
from transformers.utils import replace_return_docstrings
|
|
15
15
|
|
|
16
16
|
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
|
|
17
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
@add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)
|
|
@@ -225,21 +226,13 @@ def lce_forward(
|
|
|
225
226
|
loss = None
|
|
226
227
|
# if in training mode, don't materialize logits
|
|
227
228
|
if self.training and (labels is not None):
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
shift_labels = shift_labels.view(-1)
|
|
236
|
-
|
|
237
|
-
reduction = "sum" if "num_items_in_batch" in loss_kwargs else "mean"
|
|
238
|
-
lce = LigerFusedLinearCrossEntropyLoss(reduction=reduction)
|
|
239
|
-
|
|
240
|
-
loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
241
|
-
if reduction == "sum":
|
|
242
|
-
loss /= loss_kwargs["num_items_in_batch"]
|
|
229
|
+
loss = LigerForCausalLMLoss(
|
|
230
|
+
hidden_states=hidden_states,
|
|
231
|
+
lm_head_weight=self.lm_head.weight,
|
|
232
|
+
labels=labels,
|
|
233
|
+
hidden_size=self.config.hidden_size,
|
|
234
|
+
**loss_kwargs,
|
|
235
|
+
)
|
|
243
236
|
|
|
244
237
|
else: # if in inference mode materialize logits
|
|
245
238
|
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
|
@@ -13,6 +13,7 @@ from transformers.utils import add_start_docstrings_to_model_forward
|
|
|
13
13
|
from transformers.utils import replace_return_docstrings
|
|
14
14
|
|
|
15
15
|
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
|
|
16
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
16
17
|
|
|
17
18
|
|
|
18
19
|
@add_start_docstrings_to_model_forward(MLLAMA_INPUTS_DOCSTRING)
|
|
@@ -215,21 +216,13 @@ def lce_forward(
|
|
|
215
216
|
loss = None
|
|
216
217
|
# if in training mode, don't materialize logits
|
|
217
218
|
if self.training and (labels is not None):
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
shift_labels = shift_labels.view(-1)
|
|
226
|
-
|
|
227
|
-
reduction = "sum" if "num_items_in_batch" in loss_kwargs else "mean"
|
|
228
|
-
lce = LigerFusedLinearCrossEntropyLoss(reduction=reduction)
|
|
229
|
-
|
|
230
|
-
loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
231
|
-
if reduction == "sum":
|
|
232
|
-
loss /= loss_kwargs["num_items_in_batch"]
|
|
219
|
+
loss = LigerForCausalLMLoss(
|
|
220
|
+
hidden_states=hidden_states,
|
|
221
|
+
lm_head_weight=self.lm_head.weight,
|
|
222
|
+
labels=labels,
|
|
223
|
+
hidden_size=self.config.hidden_size,
|
|
224
|
+
**loss_kwargs,
|
|
225
|
+
)
|
|
233
226
|
|
|
234
227
|
else: # if in inference mode materialize logits
|
|
235
228
|
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
|
@@ -11,7 +11,7 @@ from transformers.models.olmo2.modeling_olmo2 import OLMO2_INPUTS_DOCSTRING
|
|
|
11
11
|
from transformers.utils import add_start_docstrings_to_model_forward
|
|
12
12
|
from transformers.utils import replace_return_docstrings
|
|
13
13
|
|
|
14
|
-
from liger_kernel.transformers.
|
|
14
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
@add_start_docstrings_to_model_forward(OLMO2_INPUTS_DOCSTRING)
|
|
@@ -89,21 +89,13 @@ def lce_forward(
|
|
|
89
89
|
loss = None
|
|
90
90
|
# if in training mode, don't materialize logits
|
|
91
91
|
if self.training and (labels is not None):
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
shift_labels = shift_labels.view(-1)
|
|
100
|
-
|
|
101
|
-
reduction = "sum" if "num_items_in_batch" in loss_kwargs else "mean"
|
|
102
|
-
lce = LigerFusedLinearCrossEntropyLoss(reduction=reduction)
|
|
103
|
-
|
|
104
|
-
loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
105
|
-
if reduction == "sum":
|
|
106
|
-
loss /= loss_kwargs["num_items_in_batch"]
|
|
92
|
+
loss = LigerForCausalLMLoss(
|
|
93
|
+
hidden_states=hidden_states,
|
|
94
|
+
lm_head_weight=self.lm_head.weight,
|
|
95
|
+
labels=labels,
|
|
96
|
+
hidden_size=self.config.hidden_size,
|
|
97
|
+
**loss_kwargs,
|
|
98
|
+
)
|
|
107
99
|
|
|
108
100
|
else: # if in inference mode materialize logits
|
|
109
101
|
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|