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