liger-kernel 0.5.5__py3-none-any.whl → 0.5.7__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.
Files changed (39) hide show
  1. liger_kernel/chunked_loss/functional.py +2 -0
  2. liger_kernel/chunked_loss/fused_linear_distillation.py +17 -2
  3. liger_kernel/chunked_loss/fused_linear_ppo.py +346 -0
  4. liger_kernel/chunked_loss/grpo_loss.py +134 -60
  5. liger_kernel/chunked_loss/jsd_loss.py +12 -7
  6. liger_kernel/ops/cross_entropy.py +3 -2
  7. liger_kernel/ops/dyt.py +225 -0
  8. liger_kernel/ops/fused_linear_jsd.py +2 -1
  9. liger_kernel/ops/jsd.py +32 -12
  10. liger_kernel/ops/kl_div.py +15 -8
  11. liger_kernel/ops/layer_norm.py +14 -1
  12. liger_kernel/ops/rms_norm.py +12 -1
  13. liger_kernel/transformers/__init__.py +133 -15
  14. liger_kernel/transformers/dyt.py +20 -0
  15. liger_kernel/transformers/functional.py +5 -0
  16. liger_kernel/transformers/gema3_rms.py +8 -0
  17. liger_kernel/transformers/model/gemma.py +17 -20
  18. liger_kernel/transformers/model/gemma2.py +17 -21
  19. liger_kernel/transformers/model/gemma3.py +335 -0
  20. liger_kernel/transformers/model/llama.py +17 -19
  21. liger_kernel/transformers/model/llava.py +369 -0
  22. liger_kernel/transformers/model/loss_utils.py +64 -0
  23. liger_kernel/transformers/model/mistral.py +28 -25
  24. liger_kernel/transformers/model/mixtral.py +20 -26
  25. liger_kernel/transformers/model/mllama.py +17 -19
  26. liger_kernel/transformers/model/olmo2.py +17 -20
  27. liger_kernel/transformers/model/paligemma.py +397 -0
  28. liger_kernel/transformers/model/phi3.py +17 -19
  29. liger_kernel/transformers/model/qwen2.py +17 -19
  30. liger_kernel/transformers/model/qwen2_5_vl.py +9 -10
  31. liger_kernel/transformers/model/qwen2_vl.py +9 -10
  32. liger_kernel/transformers/monkey_patch.py +392 -13
  33. {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.7.dist-info}/METADATA +11 -6
  34. {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.7.dist-info}/RECORD +38 -31
  35. {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.7.dist-info}/WHEEL +1 -1
  36. liger_kernel/chunked_loss/fused_linear_rlhf.py +0 -240
  37. {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.7.dist-info/licenses}/LICENSE +0 -0
  38. {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.7.dist-info/licenses}/NOTICE +0 -0
  39. {liger_kernel-0.5.5.dist-info → liger_kernel-0.5.7.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,64 @@
1
+ from typing import Optional
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+ import liger_kernel.transformers.functional as F
7
+
8
+
9
+ def fixed_fused_linear_cross_entropy(
10
+ hidden_states: torch.Tensor,
11
+ lm_head_weight: torch.Tensor,
12
+ target: torch.Tensor,
13
+ num_items_in_batch: Optional[int] = None,
14
+ ignore_index: int = -100,
15
+ final_logit_softcapping: Optional[float] = None,
16
+ **kwargs,
17
+ ):
18
+ reduction = "sum" if num_items_in_batch is not None else "mean"
19
+ loss = F.liger_fused_linear_cross_entropy(
20
+ hidden_states,
21
+ lm_head_weight,
22
+ target,
23
+ reduction=reduction,
24
+ ignore_index=ignore_index,
25
+ softcap=final_logit_softcapping,
26
+ )
27
+ if reduction == "sum":
28
+ loss = loss / num_items_in_batch
29
+
30
+ return loss
31
+
32
+
33
+ def LigerForCausalLMLoss(
34
+ hidden_states,
35
+ lm_head_weight,
36
+ labels,
37
+ hidden_size: int,
38
+ num_items_in_batch: Optional[int] = None,
39
+ ignore_index: int = -100,
40
+ shift_labels: Optional[torch.Tensor] = None,
41
+ final_logit_softcapping: Optional[float] = None,
42
+ **kwargs,
43
+ ):
44
+ # Skip upcast since intermediate values for the loss are all fp32 in kernel
45
+ if shift_labels is None:
46
+ # Shift so that token < n predict n
47
+ labels = nn.functional.pad(labels, (0, 1), value=ignore_index)
48
+ shift_labels = labels[..., 1:].contiguous()
49
+
50
+ # Flatten the tokens
51
+ hidden_states = hidden_states.view(-1, hidden_size)
52
+ shift_labels = shift_labels.view(-1)
53
+ # Enable model parallelism
54
+ shift_labels = shift_labels.to(hidden_states.device)
55
+ loss = fixed_fused_linear_cross_entropy(
56
+ hidden_states,
57
+ lm_head_weight,
58
+ shift_labels,
59
+ num_items_in_batch,
60
+ ignore_index,
61
+ final_logit_softcapping,
62
+ **kwargs,
63
+ )
64
+ return loss
@@ -5,17 +5,18 @@ from typing import Union
5
5
 
6
6
  import torch
7
7
 
8
- from torch.nn import CrossEntropyLoss
9
8
  from transformers.cache_utils import Cache
10
9
  from transformers.modeling_outputs import CausalLMOutputWithPast
11
10
  from transformers.models.mistral.modeling_mistral import _CONFIG_FOR_DOC
12
11
  from transformers.models.mistral.modeling_mistral import MISTRAL_INPUTS_DOCSTRING
13
12
  from transformers.utils import add_start_docstrings_to_model_forward
14
13
  from transformers.utils import replace_return_docstrings
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
15
 
16
- from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
16
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
17
17
 
18
18
 
19
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
19
20
  @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
20
21
  @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
21
22
  def lce_forward(
@@ -31,6 +32,8 @@ def lce_forward(
31
32
  output_hidden_states: Optional[bool] = None,
32
33
  return_dict: Optional[bool] = None,
33
34
  cache_position: Optional[torch.LongTensor] = None,
35
+ logits_to_keep: Union[int, torch.Tensor] = 0,
36
+ **loss_kwargs,
34
37
  ) -> Union[Tuple, CausalLMOutputWithPast]:
35
38
  r"""
36
39
  Copy paste Mistral's forward but replace torch cross entropy with liger fused linear cross entropy
@@ -42,6 +45,12 @@ def lce_forward(
42
45
  config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
43
46
  (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
44
47
 
48
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
49
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
50
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
51
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
52
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
53
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
45
54
  Returns:
46
55
 
47
56
  Example:
@@ -87,32 +96,26 @@ def lce_forward(
87
96
  logits = None
88
97
 
89
98
  if self.training and (labels is not None):
90
- shift_hidden_states = hidden_states[..., :-1, :].contiguous()
91
- shift_labels = labels[..., 1:].contiguous()
92
-
93
- # flatten tokens
94
- shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
95
- shift_labels = shift_labels.view(-1)
96
-
97
- lce = LigerFusedLinearCrossEntropyLoss()
98
- loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
99
+ loss = LigerForCausalLMLoss(
100
+ hidden_states=hidden_states,
101
+ lm_head_weight=self.lm_head.weight,
102
+ labels=labels,
103
+ hidden_size=self.config.hidden_size,
104
+ **loss_kwargs,
105
+ )
99
106
 
100
107
  else:
101
- logits = self.lm_head(hidden_states)
102
- if labels is not None:
103
- # Upcast to float if we need to compute the loss to avoid potential precision issues
104
- logits = logits.float()
105
- # Shift so that tokens < n predict n
106
- shift_logits = logits[..., :-1, :].contiguous()
107
- shift_labels = labels[..., 1:].contiguous()
108
- # Flatten the tokens
109
- shift_logits = shift_logits.view(-1, self.config.vocab_size)
110
- shift_labels = shift_labels.view(-1)
111
- # Ensure tensors are on the same device
112
- shift_labels = shift_labels.to(shift_logits.device)
113
- loss_fct = CrossEntropyLoss()
114
- loss = loss_fct(shift_logits, shift_labels)
108
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
109
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
115
110
 
111
+ loss = None
112
+ if labels is not None:
113
+ loss = self.loss_function(
114
+ logits=logits,
115
+ labels=labels,
116
+ vocab_size=self.config.vocab_size,
117
+ **loss_kwargs,
118
+ )
116
119
  if not return_dict:
117
120
  output = (logits,) + outputs[1:]
118
121
  return (loss,) + output if loss is not None else output
@@ -12,8 +12,10 @@ from transformers.models.mixtral.modeling_mixtral import MIXTRAL_INPUTS_DOCSTRIN
12
12
  from transformers.models.mixtral.modeling_mixtral import load_balancing_loss_func
13
13
  from transformers.utils import add_start_docstrings_to_model_forward
14
14
  from transformers.utils import replace_return_docstrings
15
+ from transformers.utils.deprecation import deprecate_kwarg
15
16
 
16
17
  from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
18
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
17
19
 
18
20
 
19
21
  @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)
@@ -143,6 +145,7 @@ def lce_forward_deprecated(
143
145
  )
144
146
 
145
147
 
148
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
146
149
  @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)
147
150
  @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
148
151
  # Ignore copy
@@ -160,7 +163,7 @@ def lce_forward(
160
163
  output_router_logits: Optional[bool] = None,
161
164
  return_dict: Optional[bool] = None,
162
165
  cache_position: Optional[torch.LongTensor] = None,
163
- num_logits_to_keep: int = 0,
166
+ logits_to_keep: Union[int, torch.Tensor] = 0,
164
167
  **loss_kwargs,
165
168
  ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
166
169
  r"""
@@ -170,10 +173,12 @@ def lce_forward(
170
173
  config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
171
174
  (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
172
175
 
173
- num_logits_to_keep (`int`, *optional*):
174
- Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
176
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
177
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
175
178
  `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
176
179
  token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
180
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
181
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
177
182
 
178
183
  Returns:
179
184
 
@@ -225,32 +230,21 @@ def lce_forward(
225
230
  loss = None
226
231
  # if in training mode, don't materialize logits
227
232
  if self.training and (labels is not None):
228
- # We do the same thing as ForCausalLMLoss but using Liger FLCE
229
-
230
- shift_hidden_states = hidden_states[..., :-1, :].contiguous()
231
- shift_labels = labels[..., 1:].contiguous()
232
-
233
- # flatten tokens
234
- shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
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"]
233
+ loss = LigerForCausalLMLoss(
234
+ hidden_states=hidden_states,
235
+ lm_head_weight=self.lm_head.weight,
236
+ labels=labels,
237
+ hidden_size=self.config.hidden_size,
238
+ **loss_kwargs,
239
+ )
243
240
 
244
241
  else: # if in inference mode materialize logits
245
- logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
246
- if labels is not None:
247
- loss = self.loss_function(
248
- logits=logits,
249
- labels=labels,
250
- vocab_size=self.config.vocab_size,
251
- **loss_kwargs,
252
- )
242
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
243
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
253
244
 
245
+ loss = None
246
+ if labels is not None:
247
+ loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
254
248
  aux_loss = None
255
249
  if output_router_logits:
256
250
  aux_loss = load_balancing_loss_func(