liger-kernel-nightly 0.0.1.dev20240819184814__py3-none-any.whl → 0.6.4.dev20251212103629__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 (126) 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 +366 -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 +307 -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 +63 -0
  18. liger_kernel/ops/__init__.py +141 -0
  19. liger_kernel/ops/backends/README.md +151 -0
  20. liger_kernel/ops/backends/__init__.py +13 -0
  21. liger_kernel/ops/backends/_ascend/__init__.py +5 -0
  22. liger_kernel/ops/backends/_ascend/ops/__init__.py +15 -0
  23. liger_kernel/ops/backends/registry.py +61 -0
  24. liger_kernel/ops/cross_entropy.py +383 -114
  25. liger_kernel/ops/dyt.py +160 -0
  26. liger_kernel/ops/experimental/embedding.py +141 -0
  27. liger_kernel/ops/experimental/mm_int8int2.py +349 -0
  28. liger_kernel/ops/fused_add_rms_norm.py +416 -0
  29. liger_kernel/ops/fused_linear_cross_entropy.py +346 -132
  30. liger_kernel/ops/fused_linear_jsd.py +228 -0
  31. liger_kernel/ops/fused_neighborhood_attention.py +1022 -0
  32. liger_kernel/ops/geglu.py +66 -64
  33. liger_kernel/ops/group_norm.py +306 -0
  34. liger_kernel/ops/grpo_loss.py +312 -0
  35. liger_kernel/ops/jsd.py +201 -0
  36. liger_kernel/ops/kl_div.py +262 -0
  37. liger_kernel/ops/layer_norm.py +320 -0
  38. liger_kernel/ops/llama4_rope.py +225 -0
  39. liger_kernel/ops/multi_token_attention.py +207 -0
  40. liger_kernel/ops/poly_norm.py +390 -0
  41. liger_kernel/ops/qwen2vl_mrope.py +222 -0
  42. liger_kernel/ops/rms_norm.py +484 -88
  43. liger_kernel/ops/rope.py +122 -117
  44. liger_kernel/ops/softmax.py +201 -0
  45. liger_kernel/ops/sparsemax.py +179 -0
  46. liger_kernel/ops/swiglu.py +68 -65
  47. liger_kernel/ops/tiled_mlp.py +136 -0
  48. liger_kernel/ops/tvd.py +207 -0
  49. liger_kernel/ops/utils.py +82 -3
  50. liger_kernel/transformers/__init__.py +218 -6
  51. liger_kernel/transformers/auto_model.py +38 -0
  52. liger_kernel/transformers/cross_entropy.py +52 -7
  53. liger_kernel/transformers/dyt.py +22 -0
  54. liger_kernel/transformers/experimental/__init__.py +5 -0
  55. liger_kernel/transformers/experimental/embedding.py +26 -0
  56. liger_kernel/transformers/fsdp.py +55 -0
  57. liger_kernel/transformers/functional.py +301 -0
  58. liger_kernel/transformers/fused_add_rms_norm.py +39 -0
  59. liger_kernel/transformers/fused_linear_cross_entropy.py +59 -10
  60. liger_kernel/transformers/fused_linear_jsd.py +95 -0
  61. liger_kernel/transformers/fused_neighborhood_attention.py +234 -0
  62. liger_kernel/transformers/geglu.py +6 -7
  63. liger_kernel/transformers/group_norm.py +50 -0
  64. liger_kernel/transformers/grpo_loss.py +153 -0
  65. liger_kernel/transformers/jsd.py +70 -0
  66. liger_kernel/transformers/kl_div.py +12 -0
  67. liger_kernel/transformers/layer_norm.py +24 -0
  68. liger_kernel/transformers/llama4_rope.py +93 -0
  69. liger_kernel/transformers/model/falcon_h1.py +122 -0
  70. liger_kernel/transformers/model/gemma.py +261 -0
  71. liger_kernel/transformers/model/gemma2.py +283 -0
  72. liger_kernel/transformers/model/gemma3.py +332 -0
  73. liger_kernel/transformers/model/glm4.py +141 -0
  74. liger_kernel/transformers/model/glm4v.py +163 -0
  75. liger_kernel/transformers/model/glm4v_moe.py +172 -0
  76. liger_kernel/transformers/model/gpt_oss.py +211 -0
  77. liger_kernel/transformers/model/hunyuan_v1.py +134 -0
  78. liger_kernel/transformers/model/internvl.py +157 -0
  79. liger_kernel/transformers/model/llama.py +221 -41
  80. liger_kernel/transformers/model/llama4.py +121 -0
  81. liger_kernel/transformers/model/llava.py +344 -0
  82. liger_kernel/transformers/model/loss_utils.py +95 -0
  83. liger_kernel/transformers/model/mistral.py +145 -0
  84. liger_kernel/transformers/model/mixtral.py +293 -0
  85. liger_kernel/transformers/model/mllama.py +269 -0
  86. liger_kernel/transformers/model/olmo2.py +141 -0
  87. liger_kernel/transformers/model/olmo3.py +142 -0
  88. liger_kernel/transformers/model/output_classes.py +147 -0
  89. liger_kernel/transformers/model/paligemma.py +433 -0
  90. liger_kernel/transformers/model/phi3.py +120 -0
  91. liger_kernel/transformers/model/qwen2.py +259 -0
  92. liger_kernel/transformers/model/qwen2_5_vl.py +163 -0
  93. liger_kernel/transformers/model/qwen2_vl.py +159 -0
  94. liger_kernel/transformers/model/qwen3.py +136 -0
  95. liger_kernel/transformers/model/qwen3_moe.py +152 -0
  96. liger_kernel/transformers/model/qwen3_next.py +146 -0
  97. liger_kernel/transformers/model/qwen3_vl.py +150 -0
  98. liger_kernel/transformers/model/qwen3_vl_moe.py +126 -0
  99. liger_kernel/transformers/model/smollm3.py +199 -0
  100. liger_kernel/transformers/model/smolvlm.py +158 -0
  101. liger_kernel/transformers/monkey_patch.py +2816 -21
  102. liger_kernel/transformers/multi_token_attention.py +64 -0
  103. liger_kernel/transformers/poly_norm.py +42 -0
  104. liger_kernel/transformers/qwen2vl_mrope.py +20 -0
  105. liger_kernel/transformers/rms_norm.py +75 -5
  106. liger_kernel/transformers/rope.py +47 -3
  107. liger_kernel/transformers/softmax.py +12 -0
  108. liger_kernel/transformers/sparsemax.py +16 -0
  109. liger_kernel/transformers/swiglu.py +62 -6
  110. liger_kernel/transformers/tiled_mlp.py +133 -0
  111. liger_kernel/transformers/trainer/__init__.py +4 -0
  112. liger_kernel/transformers/trainer/orpo_trainer.py +130 -0
  113. liger_kernel/transformers/trainer_integration.py +2 -45
  114. liger_kernel/transformers/tvd.py +13 -0
  115. liger_kernel/triton/__init__.py +1 -3
  116. liger_kernel/triton/monkey_patch.py +1 -5
  117. liger_kernel/utils.py +96 -0
  118. liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/METADATA +447 -0
  119. liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/NOTICE +58 -0
  120. liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/RECORD +124 -0
  121. {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/WHEEL +1 -1
  122. liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/METADATA +0 -21
  123. liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/NOTICE +0 -4
  124. liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/RECORD +0 -27
  125. {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/LICENSE +0 -0
  126. {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,433 @@
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
+ shift_labels = lm_kwargs.pop("shift_labels", None)
334
+ hidden_states = outputs[0]
335
+
336
+ loss = None
337
+ logits = None
338
+ token_accuracy = None
339
+
340
+ if skip_logits and labels is None:
341
+ raise ValueError("skip_logits is True, but labels is None")
342
+
343
+ if skip_logits is None:
344
+ skip_logits = self.training and (labels is not None)
345
+
346
+ if skip_logits:
347
+ shift_hidden_states = hidden_states[..., :-1, :]
348
+ shift_labels = labels[..., 1:]
349
+
350
+ hidden_device = shift_hidden_states.device
351
+
352
+ if attention_mask is not None:
353
+ # we use the input attention mask to shift the hidden_states and labels, because it is 2D.
354
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
355
+ shift_attention_mask = attention_mask[:, -shift_hidden_states.shape[1] :].to(hidden_device)
356
+ shift_hidden_states = shift_hidden_states[shift_attention_mask.to(hidden_device) != 0].contiguous()
357
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
358
+ else:
359
+ shift_hidden_states = shift_hidden_states.contiguous()
360
+ shift_labels = shift_labels.contiguous()
361
+
362
+ # Flatten hidden state
363
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.text_config.hidden_size)
364
+ shift_labels = shift_labels.view(-1).to(hidden_device)
365
+
366
+ # Use LigerForCausalLMLoss with accuracy support and pass already shifted labels
367
+ result = LigerForCausalLMLoss(
368
+ hidden_states=shift_hidden_states,
369
+ lm_head_weight=self.language_model.lm_head.weight,
370
+ labels=None,
371
+ shift_labels=shift_labels,
372
+ hidden_size=self.config.text_config.hidden_size,
373
+ **lm_kwargs,
374
+ )
375
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
376
+ else:
377
+ logits = self.language_model.lm_head(hidden_states)
378
+ if labels is not None:
379
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
380
+ logits = logits.float()
381
+ shift_logits = logits[..., :-1, :]
382
+ shift_labels = labels[..., 1:]
383
+ if attention_mask is not None:
384
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
385
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
386
+ shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
387
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
388
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
389
+ else:
390
+ shift_logits = shift_logits.contiguous()
391
+ shift_labels = shift_labels.contiguous()
392
+ # Flatten the tokens
393
+ loss_fct = CrossEntropyLoss()
394
+
395
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
396
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
397
+ loss = loss_fct(flat_logits, flat_labels)
398
+ elif shift_labels is not None:
399
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
400
+ logits = logits.float()
401
+ shift_logits = logits[..., :-1, :]
402
+ if attention_mask is not None:
403
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
404
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
405
+ shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
406
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
407
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
408
+ else:
409
+ shift_logits = shift_logits.contiguous()
410
+ shift_labels = shift_labels.contiguous()
411
+ # Flatten the tokens
412
+ loss_fct = CrossEntropyLoss()
413
+
414
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
415
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
416
+ loss = loss_fct(flat_logits, flat_labels)
417
+
418
+ if not return_dict:
419
+ output = (logits,) + outputs[1:]
420
+ output = (loss,) + output if loss is not None else output
421
+ output = output + (token_accuracy,) if token_accuracy is not None else output
422
+ return output
423
+
424
+ # Return PaliGemma output with token_accuracy field
425
+ return LigerPaliGemmaCausalLMOutputWithPast(
426
+ loss=loss,
427
+ logits=logits,
428
+ past_key_values=outputs.past_key_values,
429
+ hidden_states=outputs.hidden_states,
430
+ attentions=outputs.attentions,
431
+ image_hidden_states=image_features if pixel_values is not None else None,
432
+ token_accuracy=token_accuracy,
433
+ )
@@ -0,0 +1,120 @@
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.modeling_outputs import BaseModelOutputWithPast
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[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
+ skip_logits: Optional[bool] = None,
30
+ **kwargs,
31
+ ) -> Union[Tuple, LigerCausalLMOutputWithPast]:
32
+ r"""
33
+ Example:
34
+
35
+ ```python
36
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
37
+
38
+ >>> model = Phi3ForCausalLM.from_pretrained("meta-phi3/Phi3-2-7b-hf")
39
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-phi3/Phi3-2-7b-hf")
40
+
41
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
42
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
43
+
44
+ >>> # Generate
45
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
46
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
47
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
48
+ ```"""
49
+
50
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
51
+ output_hidden_states = (
52
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
53
+ )
54
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
55
+
56
+ outputs: BaseModelOutputWithPast = self.model(
57
+ input_ids=input_ids,
58
+ attention_mask=attention_mask,
59
+ position_ids=position_ids,
60
+ past_key_values=past_key_values,
61
+ inputs_embeds=inputs_embeds,
62
+ use_cache=use_cache,
63
+ cache_position=cache_position,
64
+ **kwargs,
65
+ )
66
+
67
+ hidden_states = outputs.last_hidden_state
68
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
69
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
70
+ kept_hidden_states = hidden_states[:, slice_indices, :]
71
+
72
+ shift_labels = kwargs.pop("shift_labels", None)
73
+ logits = None
74
+ loss = None
75
+ token_accuracy = None
76
+
77
+ if skip_logits and labels is None and shift_labels is None:
78
+ raise ValueError("skip_logits is True, but labels and shift_labels are None")
79
+
80
+ if skip_logits is None:
81
+ # By default, if in training mode, don't materialize logits
82
+ skip_logits = self.training and (labels is not None or shift_labels is not None)
83
+
84
+ # Compute loss
85
+ if skip_logits:
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
+ else:
96
+ logits = self.lm_head(kept_hidden_states)
97
+ if labels is not None or shift_labels is not None:
98
+ loss = self.loss_function(
99
+ logits=logits,
100
+ labels=labels,
101
+ shift_labels=shift_labels,
102
+ vocab_size=self.config.vocab_size,
103
+ **kwargs,
104
+ )
105
+
106
+ if not return_dict:
107
+ output_tuple = (logits,) + outputs[1:]
108
+ output = (loss,) + output_tuple if loss is not None else output_tuple
109
+ output = output + (token_accuracy,) if token_accuracy is not None else output
110
+ return output
111
+
112
+ # Return custom output class with token_accuracy field
113
+ return LigerCausalLMOutputWithPast(
114
+ loss=loss,
115
+ logits=logits,
116
+ past_key_values=outputs.past_key_values,
117
+ hidden_states=outputs.hidden_states,
118
+ attentions=outputs.attentions,
119
+ token_accuracy=token_accuracy,
120
+ )