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.

Files changed (114) hide show
  1. liger_kernel/__init__.py +0 -0
  2. liger_kernel/chunked_loss/README.md +25 -0
  3. liger_kernel/chunked_loss/__init__.py +8 -0
  4. liger_kernel/chunked_loss/cosine_similarity_loss.py +136 -0
  5. liger_kernel/chunked_loss/cpo_loss.py +157 -0
  6. liger_kernel/chunked_loss/dpo_loss.py +229 -0
  7. liger_kernel/chunked_loss/functional.py +17 -0
  8. liger_kernel/chunked_loss/fused_linear_distillation.py +292 -0
  9. liger_kernel/chunked_loss/fused_linear_ppo.py +350 -0
  10. liger_kernel/chunked_loss/fused_linear_preference.py +433 -0
  11. liger_kernel/chunked_loss/fused_linear_unpaired_preference.py +341 -0
  12. liger_kernel/chunked_loss/grpo_loss.py +304 -0
  13. liger_kernel/chunked_loss/jsd_loss.py +200 -0
  14. liger_kernel/chunked_loss/kto_loss.py +210 -0
  15. liger_kernel/chunked_loss/orpo_loss.py +144 -0
  16. liger_kernel/chunked_loss/simpo_loss.py +165 -0
  17. liger_kernel/env_report.py +21 -4
  18. liger_kernel/ops/cross_entropy.py +235 -84
  19. liger_kernel/ops/dyt.py +157 -0
  20. liger_kernel/ops/experimental/embedding.py +1 -3
  21. liger_kernel/ops/experimental/mm_int8int2.py +3 -9
  22. liger_kernel/ops/fused_add_rms_norm.py +412 -0
  23. liger_kernel/ops/fused_linear_cross_entropy.py +197 -75
  24. liger_kernel/ops/fused_linear_jsd.py +17 -34
  25. liger_kernel/ops/fused_neighborhood_attention.py +1022 -0
  26. liger_kernel/ops/geglu.py +7 -18
  27. liger_kernel/ops/group_norm.py +305 -0
  28. liger_kernel/ops/grpo_loss.py +310 -0
  29. liger_kernel/ops/jsd.py +46 -21
  30. liger_kernel/ops/kl_div.py +23 -19
  31. liger_kernel/ops/layer_norm.py +150 -86
  32. liger_kernel/ops/llama4_rope.py +225 -0
  33. liger_kernel/ops/multi_token_attention.py +207 -0
  34. liger_kernel/ops/poly_norm.py +386 -0
  35. liger_kernel/ops/qwen2vl_mrope.py +222 -0
  36. liger_kernel/ops/rms_norm.py +314 -84
  37. liger_kernel/ops/rope.py +32 -34
  38. liger_kernel/ops/softmax.py +201 -0
  39. liger_kernel/ops/sparsemax.py +179 -0
  40. liger_kernel/ops/swiglu.py +5 -9
  41. liger_kernel/ops/tiled_mlp.py +136 -0
  42. liger_kernel/ops/tvd.py +207 -0
  43. liger_kernel/ops/utils.py +8 -4
  44. liger_kernel/transformers/__init__.py +199 -24
  45. liger_kernel/transformers/auto_model.py +6 -13
  46. liger_kernel/transformers/cross_entropy.py +33 -20
  47. liger_kernel/transformers/dyt.py +22 -0
  48. liger_kernel/transformers/experimental/__init__.py +5 -0
  49. liger_kernel/transformers/experimental/embedding.py +1 -3
  50. liger_kernel/transformers/fsdp.py +55 -0
  51. liger_kernel/transformers/functional.py +291 -13
  52. liger_kernel/transformers/fused_add_rms_norm.py +39 -0
  53. liger_kernel/transformers/fused_linear_cross_entropy.py +43 -14
  54. liger_kernel/transformers/fused_linear_jsd.py +1 -4
  55. liger_kernel/transformers/fused_neighborhood_attention.py +234 -0
  56. liger_kernel/transformers/geglu.py +1 -4
  57. liger_kernel/transformers/group_norm.py +50 -0
  58. liger_kernel/transformers/grpo_loss.py +98 -0
  59. liger_kernel/transformers/jsd.py +2 -7
  60. liger_kernel/transformers/kl_div.py +1 -3
  61. liger_kernel/transformers/layer_norm.py +3 -9
  62. liger_kernel/transformers/llama4_rope.py +93 -0
  63. liger_kernel/transformers/model/falcon_h1.py +122 -0
  64. liger_kernel/transformers/model/gemma.py +77 -77
  65. liger_kernel/transformers/model/gemma2.py +283 -0
  66. liger_kernel/transformers/model/gemma3.py +331 -0
  67. liger_kernel/transformers/model/glm4.py +141 -0
  68. liger_kernel/transformers/model/glm4v.py +163 -0
  69. liger_kernel/transformers/model/glm4v_moe.py +172 -0
  70. liger_kernel/transformers/model/internvl.py +157 -0
  71. liger_kernel/transformers/model/llama.py +128 -79
  72. liger_kernel/transformers/model/llama4.py +121 -0
  73. liger_kernel/transformers/model/llava.py +344 -0
  74. liger_kernel/transformers/model/loss_utils.py +95 -0
  75. liger_kernel/transformers/model/mistral.py +68 -64
  76. liger_kernel/transformers/model/mixtral.py +75 -91
  77. liger_kernel/transformers/model/mllama.py +63 -68
  78. liger_kernel/transformers/model/olmo2.py +141 -0
  79. liger_kernel/transformers/model/output_classes.py +147 -0
  80. liger_kernel/transformers/model/paligemma.py +432 -0
  81. liger_kernel/transformers/model/phi3.py +59 -213
  82. liger_kernel/transformers/model/qwen2.py +75 -72
  83. liger_kernel/transformers/model/qwen2_5_vl.py +163 -0
  84. liger_kernel/transformers/model/qwen2_vl.py +78 -98
  85. liger_kernel/transformers/model/qwen3.py +136 -0
  86. liger_kernel/transformers/model/qwen3_moe.py +152 -0
  87. liger_kernel/transformers/model/qwen3_next.py +146 -0
  88. liger_kernel/transformers/model/qwen3_vl.py +150 -0
  89. liger_kernel/transformers/model/qwen3_vl_moe.py +126 -0
  90. liger_kernel/transformers/model/smollm3.py +199 -0
  91. liger_kernel/transformers/model/smolvlm.py +158 -0
  92. liger_kernel/transformers/monkey_patch.py +2106 -289
  93. liger_kernel/transformers/multi_token_attention.py +64 -0
  94. liger_kernel/transformers/poly_norm.py +42 -0
  95. liger_kernel/transformers/qwen2vl_mrope.py +20 -0
  96. liger_kernel/transformers/rms_norm.py +57 -6
  97. liger_kernel/transformers/rope.py +45 -2
  98. liger_kernel/transformers/softmax.py +12 -0
  99. liger_kernel/transformers/sparsemax.py +16 -0
  100. liger_kernel/transformers/swiglu.py +23 -8
  101. liger_kernel/transformers/tiled_mlp.py +133 -0
  102. liger_kernel/transformers/trainer/__init__.py +4 -0
  103. liger_kernel/transformers/trainer/orpo_trainer.py +130 -0
  104. liger_kernel/transformers/tvd.py +13 -0
  105. liger_kernel/triton/__init__.py +1 -3
  106. liger_kernel/triton/monkey_patch.py +1 -3
  107. liger_kernel/utils.py +71 -0
  108. {liger_kernel_nightly-0.4.0.dev20241107052928.dist-info → liger_kernel_nightly-0.6.3.dev20251121010306.dist-info}/METADATA +150 -137
  109. liger_kernel_nightly-0.6.3.dev20251121010306.dist-info/RECORD +116 -0
  110. {liger_kernel_nightly-0.4.0.dev20241107052928.dist-info → liger_kernel_nightly-0.6.3.dev20251121010306.dist-info}/WHEEL +1 -1
  111. liger_kernel_nightly-0.4.0.dev20241107052928.dist-info/RECORD +0 -48
  112. {liger_kernel_nightly-0.4.0.dev20241107052928.dist-info → liger_kernel_nightly-0.6.3.dev20251121010306.dist-info}/LICENSE +0 -0
  113. {liger_kernel_nightly-0.4.0.dev20241107052928.dist-info → liger_kernel_nightly-0.6.3.dev20251121010306.dist-info}/NOTICE +0 -0
  114. {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,432 @@
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.cache_utils import Cache
10
+ from transformers.models.paligemma.modeling_paligemma import PaliGemmaCausalLMOutputWithPast
11
+ from transformers.utils import is_torchdynamo_compiling
12
+ from transformers.utils import logging
13
+ from transformers.utils.deprecation import deprecate_kwarg
14
+
15
+ from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
16
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
17
+ from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
18
+ from liger_kernel.transformers.model.output_classes import LigerPaliGemmaCausalLMOutputWithPast
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ def lce_forward_deprecated(
24
+ self,
25
+ input_ids: torch.LongTensor = None,
26
+ pixel_values: torch.FloatTensor = None,
27
+ attention_mask: Optional[torch.Tensor] = None,
28
+ position_ids: Optional[torch.LongTensor] = None,
29
+ past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None,
30
+ token_type_ids: Optional[torch.LongTensor] = None,
31
+ cache_position: Optional[torch.LongTensor] = None,
32
+ inputs_embeds: Optional[torch.FloatTensor] = None,
33
+ labels: Optional[torch.LongTensor] = None,
34
+ use_cache: Optional[bool] = None,
35
+ output_attentions: Optional[bool] = None,
36
+ output_hidden_states: Optional[bool] = None,
37
+ return_dict: Optional[bool] = None,
38
+ ) -> Union[Tuple, PaliGemmaCausalLMOutputWithPast]:
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
+ Returns:
47
+
48
+ Example:
49
+
50
+ ```python
51
+ >>> from PIL import Image
52
+ >>> import requests
53
+ >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
54
+
55
+ >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/PaliGemma-test-224px-hf")
56
+ >>> processor = AutoProcessor.from_pretrained("google/PaliGemma-test-224px-hf")
57
+
58
+ >>> prompt = "answer en Where is the cow standing?"
59
+ >>> url = "https://huggingface.co/gv-hf/PaliGemma-test-224px-hf/resolve/main/cow_beach_1.png"
60
+ >>> image = Image.open(requests.get(url, stream=True).raw)
61
+
62
+ >>> inputs = processor(text=prompt, images=image, return_tensors="pt")
63
+
64
+ >>> # Generate
65
+ >>> generate_ids = model.generate(**inputs, max_length=30)
66
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
67
+ "answer en Where is the cow standing?\nbeach"
68
+ ```"""
69
+
70
+ if (input_ids is None) ^ (inputs_embeds is not None):
71
+ raise ValueError(
72
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
73
+ )
74
+
75
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
76
+ output_hidden_states = (
77
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
78
+ )
79
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
80
+
81
+ # the attention mask is turned 4d after, we keep track of the original one
82
+ input_attention_mask = attention_mask
83
+
84
+ if inputs_embeds is None:
85
+ # 1. Extra the input embeddings
86
+ inputs_embeds = self.get_input_embeddings()(input_ids)
87
+
88
+ # 2. Merge text and images
89
+ if pixel_values is not None and input_ids.shape[1] != 1:
90
+ image_outputs = self.vision_tower(pixel_values.to(inputs_embeds.dtype))
91
+ selected_image_feature = image_outputs.last_hidden_state
92
+ image_features = self.multi_modal_projector(selected_image_feature)
93
+
94
+ if cache_position is None:
95
+ cache_position = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device)
96
+ inputs_embeds, attention_mask, labels, position_ids = self._merge_input_ids_with_image_features(
97
+ image_features, inputs_embeds, input_ids, attention_mask, labels, token_type_ids, cache_position
98
+ )
99
+
100
+ else:
101
+ # In case input_ids.shape[1] == 1 & pixel_values==None & past_key_values != None, we are in the case of
102
+ # generation with cache
103
+ if past_key_values is not None and pixel_values is not None and input_ids.shape[1] == 1:
104
+ # Retrieve the first layer to inspect the logits and mask out the hidden states
105
+ # that are set to 0
106
+ # TODO @molbap this will only work for dynamic cache.
107
+ first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]
108
+
109
+ # Sum all dimensions of head_dim (-2) to avoid random errors such as: https://github.com/huggingface/transformers/pull/28032#issuecomment-1863691941
110
+ batch_index, non_attended_tokens = torch.where(first_layer_past_key_value.float().sum(-2) == 0)
111
+
112
+ # Get the target length
113
+ target_seqlen = cache_position[-1] + 1
114
+ extended_attention_mask = torch.ones(
115
+ (attention_mask.shape[0], target_seqlen - attention_mask.shape[1] + 1),
116
+ dtype=attention_mask.dtype,
117
+ device=attention_mask.device,
118
+ )
119
+ # Filter out only the tokens that can be un-attended, this can happen
120
+ # if one uses PaliGemma+ Fused modules where the cache on the
121
+ # first iteration is already big enough, or if one passes custom cache
122
+ valid_indices = non_attended_tokens < extended_attention_mask.size(-1)
123
+ new_batch_index = batch_index[valid_indices]
124
+ new_non_attended_tokens = non_attended_tokens[valid_indices]
125
+
126
+ # Zero-out the places where we don't need to attend
127
+ extended_attention_mask[new_batch_index, new_non_attended_tokens] = 0
128
+
129
+ attention_mask = torch.cat((attention_mask, extended_attention_mask), dim=1)
130
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
131
+
132
+ attention_mask = attention_mask.to(inputs_embeds.dtype)
133
+ outputs = self.language_model.model(
134
+ attention_mask=attention_mask,
135
+ position_ids=position_ids,
136
+ past_key_values=past_key_values,
137
+ inputs_embeds=inputs_embeds,
138
+ use_cache=use_cache,
139
+ output_attentions=output_attentions,
140
+ output_hidden_states=output_hidden_states,
141
+ return_dict=return_dict,
142
+ cache_position=cache_position,
143
+ )
144
+
145
+ hidden_states = outputs[0]
146
+
147
+ loss = None
148
+ logits = None
149
+
150
+ if self.training and (labels is not None):
151
+ shift_hidden_states = hidden_states[..., :-1, :]
152
+ shift_labels = labels[..., 1:]
153
+
154
+ hidden_device = shift_hidden_states.device
155
+
156
+ if attention_mask is not None:
157
+ # we use the input attention mask to shift the hidden_states and labels, because it is 2D.
158
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
159
+ shift_attention_mask = attention_mask[:, -shift_hidden_states.shape[1] :].to(hidden_device)
160
+ shift_hidden_states = shift_hidden_states[shift_attention_mask.to(hidden_device) != 0].contiguous()
161
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
162
+ else:
163
+ shift_hidden_states = shift_hidden_states.contiguous()
164
+ shift_labels = shift_labels.contiguous()
165
+
166
+ # Flatten hidden state
167
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.text_config.hidden_size)
168
+ shift_labels = shift_labels.view(-1).to(hidden_device)
169
+
170
+ lce = LigerFusedLinearCrossEntropyLoss()
171
+ loss = lce(self.language_model.lm_head.weight, shift_hidden_states, shift_labels)
172
+
173
+ else:
174
+ logits = self.language_model.lm_head(hidden_states)
175
+ if labels is not None:
176
+ shift_logits = logits[..., :-1, :]
177
+ shift_labels = labels[..., 1:]
178
+ if input_attention_mask is not None:
179
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
180
+ shift_attention_mask = input_attention_mask[..., 1:]
181
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
182
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
183
+ else:
184
+ shift_logits = shift_logits.contiguous()
185
+ shift_labels = shift_labels.contiguous()
186
+ # Flatten the tokens
187
+ loss_fct = CrossEntropyLoss()
188
+
189
+ flat_logits = shift_logits.view(-1, self.config.vocab_size)
190
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
191
+ loss = loss_fct(flat_logits, flat_labels)
192
+ if not return_dict:
193
+ output = (logits,) + outputs[1:]
194
+ return (loss,) + output if loss is not None else output
195
+
196
+ return PaliGemmaCausalLMOutputWithPast(
197
+ loss=loss,
198
+ logits=logits,
199
+ past_key_values=outputs.past_key_values,
200
+ hidden_states=outputs.hidden_states,
201
+ attentions=outputs.attentions,
202
+ )
203
+
204
+
205
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
206
+ def lce_forward(
207
+ self,
208
+ input_ids: torch.LongTensor = None,
209
+ pixel_values: torch.FloatTensor = None,
210
+ attention_mask: Optional[torch.Tensor] = None,
211
+ position_ids: Optional[torch.LongTensor] = None,
212
+ past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None,
213
+ token_type_ids: Optional[torch.LongTensor] = None,
214
+ cache_position: Optional[torch.LongTensor] = None,
215
+ inputs_embeds: Optional[torch.FloatTensor] = None,
216
+ labels: Optional[torch.LongTensor] = None,
217
+ use_cache: Optional[bool] = None,
218
+ output_attentions: Optional[bool] = None,
219
+ output_hidden_states: Optional[bool] = None,
220
+ return_dict: Optional[bool] = None,
221
+ logits_to_keep: Union[int, torch.Tensor] = 0,
222
+ skip_logits: Optional[bool] = None,
223
+ **lm_kwargs,
224
+ ) -> Union[Tuple, LigerPaliGemmaCausalLMOutputWithPast]:
225
+ r"""
226
+ Args:
227
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
228
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
229
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
230
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
231
+
232
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
233
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
234
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
235
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
236
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
237
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
238
+
239
+ Returns:
240
+
241
+ Example:
242
+
243
+ ```python
244
+ >>> from PIL import Image
245
+ >>> import requests
246
+ >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
247
+
248
+ >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/PaliGemma-test-224px-hf")
249
+ >>> processor = AutoProcessor.from_pretrained("google/PaliGemma-test-224px-hf")
250
+
251
+ >>> prompt = "answer en Where is the cow standing?"
252
+ >>> url = "https://huggingface.co/gv-hf/PaliGemma-test-224px-hf/resolve/main/cow_beach_1.png"
253
+ >>> image = Image.open(requests.get(url, stream=True).raw)
254
+
255
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
256
+
257
+ >>> # Generate
258
+ >>> generate_ids = model.generate(**inputs, max_length=30)
259
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
260
+ "answer en Where is the cow standing?\nbeach"
261
+ ```"""
262
+
263
+ if (input_ids is None) ^ (inputs_embeds is not None):
264
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
265
+
266
+ if pixel_values is not None and inputs_embeds is not None:
267
+ raise ValueError(
268
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
269
+ )
270
+
271
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
272
+ output_hidden_states = (
273
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
274
+ )
275
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
276
+
277
+ is_training = token_type_ids is not None and labels is not None
278
+
279
+ if inputs_embeds is None:
280
+ inputs_embeds = self.get_input_embeddings()(input_ids)
281
+
282
+ if cache_position is None:
283
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
284
+ cache_position = torch.arange(
285
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
286
+ )
287
+
288
+ if position_ids is None:
289
+ position_ids = cache_position.unsqueeze(0) + 1 # Paligemma positions are 1-indexed
290
+
291
+ # Merge text and images
292
+ if pixel_values is not None:
293
+ image_features = self.get_image_features(pixel_values)
294
+
295
+ special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
296
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
297
+ if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
298
+ image_tokens_in_text = torch.sum(input_ids == self.config.image_token_index)
299
+ raise ValueError(
300
+ f"Number of images does not match number of special image tokens in the input text. "
301
+ f"Got {image_tokens_in_text} image tokens in the text but {image_features.shape[0] * image_features.shape[1]} "
302
+ "tokens from image embeddings."
303
+ )
304
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
305
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
306
+
307
+ # mask out pad-token-ids in labels for BC
308
+ if labels is not None and self.pad_token_id in labels:
309
+ logger.warning_once(
310
+ "`labels` contains `pad_token_id` which will be masked with `config.ignore_index`. "
311
+ "You have to mask out `pad_token_id` when preparing `labels`, this behavior will be removed in v.4.46.",
312
+ )
313
+ labels = torch.where(input_ids == self.pad_token_id, self.config.ignore_index, labels)
314
+
315
+ causal_mask = self._update_causal_mask(
316
+ attention_mask, token_type_ids, past_key_values, cache_position, inputs_embeds, is_training
317
+ )
318
+
319
+ outputs = self.language_model.model(
320
+ attention_mask=causal_mask,
321
+ position_ids=position_ids,
322
+ past_key_values=past_key_values,
323
+ inputs_embeds=inputs_embeds,
324
+ use_cache=use_cache,
325
+ output_attentions=output_attentions,
326
+ output_hidden_states=output_hidden_states,
327
+ return_dict=return_dict,
328
+ cache_position=cache_position,
329
+ logits_to_keep=logits_to_keep,
330
+ **lm_kwargs,
331
+ )
332
+
333
+ hidden_states = outputs[0]
334
+
335
+ loss = None
336
+ logits = None
337
+ token_accuracy = None
338
+
339
+ if skip_logits and labels is None:
340
+ raise ValueError("skip_logits is True, but labels is None")
341
+
342
+ if skip_logits is None:
343
+ skip_logits = self.training and (labels is not None)
344
+
345
+ if skip_logits:
346
+ shift_hidden_states = hidden_states[..., :-1, :]
347
+ shift_labels = labels[..., 1:]
348
+
349
+ hidden_device = shift_hidden_states.device
350
+
351
+ if attention_mask is not None:
352
+ # we use the input attention mask to shift the hidden_states and labels, because it is 2D.
353
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
354
+ shift_attention_mask = attention_mask[:, -shift_hidden_states.shape[1] :].to(hidden_device)
355
+ shift_hidden_states = shift_hidden_states[shift_attention_mask.to(hidden_device) != 0].contiguous()
356
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
357
+ else:
358
+ shift_hidden_states = shift_hidden_states.contiguous()
359
+ shift_labels = shift_labels.contiguous()
360
+
361
+ # Flatten hidden state
362
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.text_config.hidden_size)
363
+ shift_labels = shift_labels.view(-1).to(hidden_device)
364
+
365
+ # Use LigerForCausalLMLoss with accuracy support and pass already shifted labels
366
+ result = LigerForCausalLMLoss(
367
+ hidden_states=shift_hidden_states,
368
+ lm_head_weight=self.language_model.lm_head.weight,
369
+ labels=None,
370
+ shift_labels=shift_labels,
371
+ hidden_size=self.config.text_config.hidden_size,
372
+ **lm_kwargs,
373
+ )
374
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
375
+ else:
376
+ logits = self.language_model.lm_head(hidden_states)
377
+ if labels is not None:
378
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
379
+ logits = logits.float()
380
+ shift_logits = logits[..., :-1, :]
381
+ shift_labels = labels[..., 1:]
382
+ if attention_mask is not None:
383
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
384
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
385
+ shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
386
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
387
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
388
+ else:
389
+ shift_logits = shift_logits.contiguous()
390
+ shift_labels = shift_labels.contiguous()
391
+ # Flatten the tokens
392
+ loss_fct = CrossEntropyLoss()
393
+
394
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
395
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
396
+ loss = loss_fct(flat_logits, flat_labels)
397
+ elif shift_labels is not None:
398
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
399
+ logits = logits.float()
400
+ shift_logits = logits[..., :-1, :]
401
+ if attention_mask is not None:
402
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
403
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
404
+ shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
405
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
406
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
407
+ else:
408
+ shift_logits = shift_logits.contiguous()
409
+ shift_labels = shift_labels.contiguous()
410
+ # Flatten the tokens
411
+ loss_fct = CrossEntropyLoss()
412
+
413
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
414
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
415
+ loss = loss_fct(flat_logits, flat_labels)
416
+
417
+ if not return_dict:
418
+ output = (logits,) + outputs[1:]
419
+ output = (loss,) + output if loss is not None else output
420
+ output = output + (token_accuracy,) if token_accuracy is not None else output
421
+ return output
422
+
423
+ # Return PaliGemma output with token_accuracy field
424
+ return LigerPaliGemmaCausalLMOutputWithPast(
425
+ loss=loss,
426
+ logits=logits,
427
+ past_key_values=outputs.past_key_values,
428
+ hidden_states=outputs.hidden_states,
429
+ attentions=outputs.attentions,
430
+ image_hidden_states=image_features if pixel_values is not None else None,
431
+ token_accuracy=token_accuracy,
432
+ )