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,293 @@
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.modeling_outputs import MoeCausalLMOutputWithPast
10
+ from transformers.models.mixtral.modeling_mixtral import load_balancing_loss_func
11
+ from transformers.utils.deprecation import deprecate_kwarg
12
+
13
+ from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
14
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
15
+ from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
16
+ from liger_kernel.transformers.model.output_classes import LigerMoeCausalLMOutputWithPast
17
+
18
+
19
+ def lce_forward_deprecated(
20
+ self,
21
+ input_ids: torch.LongTensor = 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
+ labels: Optional[torch.LongTensor] = None,
27
+ use_cache: Optional[bool] = None,
28
+ output_attentions: Optional[bool] = None,
29
+ output_hidden_states: Optional[bool] = None,
30
+ output_router_logits: Optional[bool] = None,
31
+ return_dict: Optional[bool] = None,
32
+ cache_position: Optional[torch.LongTensor] = None,
33
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
34
+ r"""
35
+ Copy paste Mixtral's forward from transformers v4.44.2 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
+ Returns:
45
+
46
+ Example:
47
+
48
+ ```python
49
+ >>> from transformers import AutoTokenizer, MixtralForCausalLM
50
+
51
+ >>> model = MixtralForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
52
+ >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
53
+
54
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
55
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
56
+
57
+ >>> # Generate
58
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
59
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
60
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
61
+ ```"""
62
+
63
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
64
+ output_router_logits = (
65
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
66
+ )
67
+
68
+ output_hidden_states = (
69
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
70
+ )
71
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
72
+
73
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
74
+ outputs = self.model(
75
+ input_ids=input_ids,
76
+ attention_mask=attention_mask,
77
+ position_ids=position_ids,
78
+ past_key_values=past_key_values,
79
+ inputs_embeds=inputs_embeds,
80
+ use_cache=use_cache,
81
+ output_attentions=output_attentions,
82
+ output_hidden_states=output_hidden_states,
83
+ output_router_logits=output_router_logits,
84
+ return_dict=return_dict,
85
+ cache_position=cache_position,
86
+ )
87
+
88
+ hidden_states = outputs[0]
89
+ logits = self.lm_head(hidden_states)
90
+
91
+ loss = None
92
+ if self.training and (labels is not None):
93
+ shift_hidden_states = hidden_states[..., :-1, :].contiguous()
94
+ shift_labels = labels[..., 1:].contiguous()
95
+ # Flatten the tokens
96
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
97
+ shift_labels = shift_labels.view(-1)
98
+
99
+ lce = LigerFusedLinearCrossEntropyLoss()
100
+ loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
101
+ elif labels is not None:
102
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
103
+ logits = logits.float()
104
+ # Shift so that tokens < n predict n
105
+ shift_logits = logits[..., :-1, :].contiguous()
106
+ shift_labels = labels[..., 1:].contiguous()
107
+ # Flatten the tokens
108
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
109
+ shift_labels = shift_labels.view(-1)
110
+ # Enable model parallelism
111
+ shift_labels = shift_labels.to(shift_logits.device)
112
+
113
+ loss_fct = CrossEntropyLoss()
114
+ loss = loss_fct(logits.weight, shift_labels)
115
+
116
+ aux_loss = None
117
+ if output_router_logits:
118
+ aux_loss = load_balancing_loss_func(
119
+ outputs.router_logits if return_dict else outputs[-1],
120
+ self.num_experts,
121
+ self.num_experts_per_tok,
122
+ attention_mask,
123
+ )
124
+ if labels is not None:
125
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
126
+
127
+ if not return_dict:
128
+ output = (logits,) + outputs[1:]
129
+ if output_router_logits:
130
+ output = (aux_loss,) + output
131
+ return (loss,) + output if loss is not None else output
132
+
133
+ return MoeCausalLMOutputWithPast(
134
+ loss=loss,
135
+ aux_loss=aux_loss,
136
+ logits=logits,
137
+ past_key_values=outputs.past_key_values,
138
+ hidden_states=outputs.hidden_states,
139
+ attentions=outputs.attentions,
140
+ router_logits=outputs.router_logits,
141
+ )
142
+
143
+
144
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
145
+ # Ignore copy
146
+ def lce_forward(
147
+ self,
148
+ input_ids: torch.LongTensor = None,
149
+ attention_mask: Optional[torch.Tensor] = None,
150
+ position_ids: Optional[torch.LongTensor] = None,
151
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
152
+ inputs_embeds: Optional[torch.FloatTensor] = None,
153
+ labels: Optional[torch.LongTensor] = None,
154
+ use_cache: Optional[bool] = None,
155
+ output_attentions: Optional[bool] = None,
156
+ output_hidden_states: Optional[bool] = None,
157
+ output_router_logits: Optional[bool] = None,
158
+ return_dict: Optional[bool] = None,
159
+ cache_position: Optional[torch.LongTensor] = None,
160
+ logits_to_keep: Union[int, torch.Tensor] = 0,
161
+ skip_logits: Optional[bool] = None,
162
+ **kwargs,
163
+ ) -> Union[Tuple, LigerMoeCausalLMOutputWithPast]:
164
+ r"""
165
+ Args:
166
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
167
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
168
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
169
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
170
+
171
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
172
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
173
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
174
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
175
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
176
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
177
+
178
+ Returns:
179
+
180
+ Example:
181
+
182
+ ```python
183
+ >>> from transformers import AutoTokenizer, MixtralForCausalLM
184
+
185
+ >>> model = MixtralForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
186
+ >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
187
+
188
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
189
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
190
+
191
+ >>> # Generate
192
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
193
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
194
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
195
+ ```"""
196
+
197
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
198
+ output_router_logits = (
199
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
200
+ )
201
+
202
+ output_hidden_states = (
203
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
204
+ )
205
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
206
+
207
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
208
+ outputs = self.model(
209
+ input_ids=input_ids,
210
+ attention_mask=attention_mask,
211
+ position_ids=position_ids,
212
+ past_key_values=past_key_values,
213
+ inputs_embeds=inputs_embeds,
214
+ use_cache=use_cache,
215
+ output_attentions=output_attentions,
216
+ output_hidden_states=output_hidden_states,
217
+ output_router_logits=output_router_logits,
218
+ return_dict=return_dict,
219
+ cache_position=cache_position,
220
+ **kwargs,
221
+ )
222
+
223
+ hidden_states = outputs[0]
224
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
225
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
226
+ kept_hidden_states = hidden_states[:, slice_indices, :]
227
+
228
+ shift_labels = kwargs.pop("shift_labels", None)
229
+ logits = None
230
+ loss = None
231
+ token_accuracy = None
232
+
233
+ if skip_logits and labels is None and shift_labels is None:
234
+ raise ValueError("skip_logits is True, but labels and shift_labels are None")
235
+
236
+ if skip_logits is None:
237
+ # By default, if in training mode, don't materialize logits
238
+ skip_logits = self.training and (labels is not None or shift_labels is not None)
239
+
240
+ # Compute loss
241
+ if skip_logits:
242
+ result = LigerForCausalLMLoss(
243
+ hidden_states=kept_hidden_states,
244
+ lm_head_weight=self.lm_head.weight,
245
+ labels=labels,
246
+ shift_labels=shift_labels,
247
+ hidden_size=self.config.hidden_size,
248
+ **kwargs,
249
+ )
250
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
251
+
252
+ else:
253
+ logits = self.lm_head(kept_hidden_states)
254
+
255
+ loss = None
256
+ if labels is not None or shift_labels is not None:
257
+ loss = self.loss_function(
258
+ logits=logits,
259
+ labels=labels,
260
+ shift_labels=shift_labels,
261
+ vocab_size=self.vocab_size,
262
+ **kwargs,
263
+ )
264
+ aux_loss = None
265
+ if output_router_logits:
266
+ aux_loss = load_balancing_loss_func(
267
+ outputs.router_logits if return_dict else outputs[-1],
268
+ self.num_experts,
269
+ self.num_experts_per_tok,
270
+ attention_mask,
271
+ )
272
+ if labels is not None:
273
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
274
+
275
+ if not return_dict:
276
+ output_tuple = (logits,) + outputs[1:]
277
+ if output_router_logits:
278
+ output_tuple = (aux_loss,) + output_tuple
279
+ if token_accuracy is not None:
280
+ output_tuple = output_tuple + (token_accuracy,)
281
+ return (loss,) + output_tuple if loss is not None else output_tuple
282
+
283
+ # Return custom output class with token_accuracy field
284
+ return LigerMoeCausalLMOutputWithPast(
285
+ loss=loss,
286
+ aux_loss=aux_loss,
287
+ logits=logits,
288
+ past_key_values=outputs.past_key_values,
289
+ hidden_states=outputs.hidden_states,
290
+ attentions=outputs.attentions,
291
+ router_logits=outputs.router_logits if return_dict else outputs[-1],
292
+ token_accuracy=token_accuracy,
293
+ )
@@ -0,0 +1,269 @@
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.modeling_outputs import CausalLMOutputWithPast
11
+ from transformers.utils.deprecation import deprecate_kwarg
12
+
13
+ from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
14
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
15
+ from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
16
+ from liger_kernel.transformers.model.output_classes import LigerCausalLMOutputWithPast
17
+
18
+
19
+ def lce_forward_deprecated(
20
+ self,
21
+ input_ids: torch.LongTensor = None,
22
+ attention_mask: Optional[torch.Tensor] = None,
23
+ position_ids: Optional[torch.LongTensor] = None,
24
+ cross_attention_states: Optional[torch.LongTensor] = None,
25
+ cross_attention_mask: Optional[torch.LongTensor] = None,
26
+ full_text_row_masked_out_mask: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
27
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
28
+ inputs_embeds: Optional[torch.FloatTensor] = None,
29
+ labels: Optional[torch.LongTensor] = None,
30
+ use_cache: Optional[bool] = None,
31
+ output_attentions: Optional[bool] = None,
32
+ output_hidden_states: Optional[bool] = None,
33
+ return_dict: Optional[bool] = None,
34
+ cache_position: Optional[torch.LongTensor] = None,
35
+ num_logits_to_keep: int = 0,
36
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
37
+ r"""
38
+ Copy paste mllama forward but replace torch cross entropy with liger fused linear cross entropy
39
+
40
+
41
+ Args:
42
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
43
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
44
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
45
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
46
+ num_logits_to_keep (`int`, *optional*):
47
+ Calculate logits for the last `num_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
+ Returns:
51
+ Example:
52
+ ```python
53
+ >>> from transformers import AutoTokenizer, MllamaForCausalLM
54
+ >>> model = MllamaForCausalLM.from_pretrained("Llama-3.2-11B-Vision")
55
+ >>> tokenizer = AutoTokenizer.from_pretrained("Llama-3.2-11B-Vision")
56
+ >>> prompt = "If I had to write a haiku, it would be:"
57
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
58
+ >>> # Generate
59
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=40, do_sample=True, temperature=0.6)
60
+ >>> result = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
61
+ >>> print(result)
62
+ If I had to write a haiku, it would be: "Snowflakes gently fall" - simple, yet peaceful.
63
+ I love the idea of snowflakes gently falling, each one
64
+ ```
65
+ """
66
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
67
+ output_hidden_states = (
68
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
69
+ )
70
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
71
+
72
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
73
+ outputs = self.model(
74
+ input_ids=input_ids,
75
+ cross_attention_states=cross_attention_states,
76
+ attention_mask=attention_mask,
77
+ position_ids=position_ids,
78
+ cross_attention_mask=cross_attention_mask,
79
+ full_text_row_masked_out_mask=full_text_row_masked_out_mask,
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
+ )
88
+
89
+ hidden_states = outputs[0]
90
+
91
+ loss = None
92
+ logits = None
93
+
94
+ if self.training and (labels is not None):
95
+ kept_hidden_states = hidden_states[:, -num_logits_to_keep:, :]
96
+
97
+ shift_hidden_states = kept_hidden_states[..., :-1, :].contiguous()
98
+ shift_labels = labels[..., 1:].contiguous()
99
+
100
+ # flatten tokens
101
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
102
+ shift_labels = shift_labels.view(-1)
103
+
104
+ lce = LigerFusedLinearCrossEntropyLoss()
105
+ loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
106
+
107
+ else:
108
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]).float()
109
+ if labels is not None:
110
+ # Shift so that tokens < n predict n
111
+ shift_logits = logits[..., :-1, :].contiguous()
112
+ shift_labels = labels[..., 1:].contiguous()
113
+ # Flatten the tokens
114
+ loss_fct = CrossEntropyLoss()
115
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
116
+ shift_labels = shift_labels.view(-1)
117
+ # Enable model parallelism
118
+ shift_labels = shift_labels.to(shift_logits.device)
119
+ loss = loss_fct(shift_logits, shift_labels)
120
+
121
+ if not return_dict:
122
+ output = (logits,) + outputs[1:]
123
+ return (loss,) + output if loss is not None else output
124
+
125
+ return CausalLMOutputWithPast(
126
+ loss=loss,
127
+ logits=logits,
128
+ past_key_values=outputs.past_key_values,
129
+ hidden_states=outputs.hidden_states,
130
+ attentions=outputs.attentions,
131
+ )
132
+
133
+
134
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
135
+ def lce_forward(
136
+ self,
137
+ input_ids: torch.LongTensor = None,
138
+ attention_mask: Optional[torch.Tensor] = None,
139
+ position_ids: Optional[torch.LongTensor] = None,
140
+ cross_attention_states: Optional[torch.LongTensor] = None,
141
+ cross_attention_mask: Optional[torch.LongTensor] = None,
142
+ full_text_row_masked_out_mask: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
143
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
144
+ inputs_embeds: Optional[torch.FloatTensor] = None,
145
+ labels: Optional[torch.LongTensor] = None,
146
+ use_cache: Optional[bool] = None,
147
+ output_attentions: Optional[bool] = None,
148
+ output_hidden_states: Optional[bool] = None,
149
+ return_dict: Optional[bool] = None,
150
+ cache_position: Optional[torch.LongTensor] = None,
151
+ logits_to_keep: Union[int, torch.Tensor] = 0,
152
+ skip_logits: Optional[bool] = None,
153
+ **kwargs,
154
+ ) -> Union[Tuple, LigerCausalLMOutputWithPast]:
155
+ r"""
156
+ Args:
157
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
158
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
159
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
160
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
161
+
162
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
163
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
164
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
165
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
166
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
167
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
168
+
169
+ Returns:
170
+
171
+ Example:
172
+
173
+ ```python
174
+ >>> from transformers import AutoTokenizer, MllamaForCausalLM
175
+
176
+ >>> model = MllamaForCausalLM.from_pretrained("Llama-3.2-11B-Vision")
177
+ >>> tokenizer = AutoTokenizer.from_pretrained("Llama-3.2-11B-Vision")
178
+
179
+ >>> prompt = "If I had to write a haiku, it would be:"
180
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
181
+
182
+ >>> # Generate
183
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=40, do_sample=True, temperature=0.6)
184
+ >>> result = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
185
+ >>> print(result)
186
+ If I had to write a haiku, it would be: "Snowflakes gently fall" - simple, yet peaceful.
187
+ I love the idea of snowflakes gently falling, each one
188
+ ```
189
+ """
190
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
191
+ output_hidden_states = (
192
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
193
+ )
194
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
195
+ # Filter out accum_dtype from kwargs for model call as MllamaTextModel doesn't accept it in transformers 4.49.0
196
+ # but preserve it for loss function calls
197
+ model_kwargs = {k: v for k, v in kwargs.items() if k != "accum_dtype"}
198
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
199
+ outputs = self.model(
200
+ input_ids=input_ids,
201
+ cross_attention_states=cross_attention_states,
202
+ attention_mask=attention_mask,
203
+ position_ids=position_ids,
204
+ cross_attention_mask=cross_attention_mask,
205
+ full_text_row_masked_out_mask=full_text_row_masked_out_mask,
206
+ past_key_values=past_key_values,
207
+ inputs_embeds=inputs_embeds,
208
+ use_cache=use_cache,
209
+ output_attentions=output_attentions,
210
+ output_hidden_states=output_hidden_states,
211
+ return_dict=return_dict,
212
+ cache_position=cache_position,
213
+ **model_kwargs,
214
+ )
215
+
216
+ hidden_states = outputs[0]
217
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
218
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
219
+ kept_hidden_states = hidden_states[:, slice_indices, :]
220
+
221
+ shift_labels = kwargs.pop("shift_labels", None)
222
+ logits = None
223
+ loss = None
224
+ token_accuracy = None
225
+
226
+ if skip_logits and labels is None and shift_labels is None:
227
+ raise ValueError("skip_logits is True, but labels and shift_labels are None")
228
+
229
+ if skip_logits is None:
230
+ # By default, if in training mode, don't materialize logits
231
+ skip_logits = self.training and (labels is not None or shift_labels is not None)
232
+
233
+ if skip_logits:
234
+ result = LigerForCausalLMLoss(
235
+ hidden_states=kept_hidden_states,
236
+ lm_head_weight=self.lm_head.weight,
237
+ labels=labels,
238
+ shift_labels=shift_labels,
239
+ hidden_size=self.config.hidden_size,
240
+ **kwargs,
241
+ )
242
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
243
+
244
+ else:
245
+ logits = self.lm_head(kept_hidden_states)
246
+ if labels is not None or shift_labels is not None:
247
+ loss = self.loss_function(
248
+ logits=logits,
249
+ labels=labels,
250
+ shift_labels=shift_labels,
251
+ vocab_size=self.config.vocab_size,
252
+ **kwargs,
253
+ )
254
+
255
+ if not return_dict:
256
+ output = (logits,) + outputs[1:]
257
+ output = (loss,) + output if loss is not None else output
258
+ output = output + (token_accuracy,) if token_accuracy is not None else output
259
+ return output
260
+
261
+ # Return custom output class with token_accuracy field
262
+ return LigerCausalLMOutputWithPast(
263
+ loss=loss,
264
+ logits=logits,
265
+ past_key_values=outputs.past_key_values,
266
+ hidden_states=outputs.hidden_states,
267
+ attentions=outputs.attentions,
268
+ token_accuracy=token_accuracy,
269
+ )