liger-kernel-nightly 0.5.10.dev20250624183504__py3-none-any.whl → 0.6.4.dev20251121224847__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of liger-kernel-nightly might be problematic. Click here for more details.

Files changed (73) hide show
  1. liger_kernel/chunked_loss/__init__.py +1 -0
  2. liger_kernel/chunked_loss/cosine_similarity_loss.py +136 -0
  3. liger_kernel/chunked_loss/dpo_loss.py +54 -3
  4. liger_kernel/chunked_loss/functional.py +2 -0
  5. liger_kernel/chunked_loss/fused_linear_distillation.py +13 -2
  6. liger_kernel/chunked_loss/fused_linear_ppo.py +25 -5
  7. liger_kernel/chunked_loss/grpo_loss.py +46 -9
  8. liger_kernel/chunked_loss/jsd_loss.py +23 -7
  9. liger_kernel/ops/cross_entropy.py +118 -62
  10. liger_kernel/ops/fused_add_rms_norm.py +412 -0
  11. liger_kernel/ops/fused_linear_cross_entropy.py +113 -21
  12. liger_kernel/ops/geglu.py +1 -1
  13. liger_kernel/ops/grpo_loss.py +3 -1
  14. liger_kernel/ops/layer_norm.py +133 -79
  15. liger_kernel/ops/llama4_rope.py +225 -0
  16. liger_kernel/ops/poly_norm.py +386 -0
  17. liger_kernel/ops/rms_norm.py +2 -2
  18. liger_kernel/ops/rope.py +1 -1
  19. liger_kernel/ops/swiglu.py +1 -1
  20. liger_kernel/ops/tiled_mlp.py +136 -0
  21. liger_kernel/transformers/__init__.py +59 -0
  22. liger_kernel/transformers/cross_entropy.py +8 -3
  23. liger_kernel/transformers/experimental/__init__.py +5 -0
  24. liger_kernel/transformers/functional.py +38 -6
  25. liger_kernel/transformers/fused_add_rms_norm.py +39 -0
  26. liger_kernel/transformers/fused_linear_cross_entropy.py +16 -4
  27. liger_kernel/transformers/grpo_loss.py +56 -1
  28. liger_kernel/transformers/llama4_rope.py +93 -0
  29. liger_kernel/transformers/model/falcon_h1.py +122 -0
  30. liger_kernel/transformers/model/gemma.py +28 -8
  31. liger_kernel/transformers/model/gemma2.py +31 -8
  32. liger_kernel/transformers/model/gemma3.py +100 -110
  33. liger_kernel/transformers/model/glm4.py +18 -5
  34. liger_kernel/transformers/model/glm4v.py +163 -0
  35. liger_kernel/transformers/model/glm4v_moe.py +172 -0
  36. liger_kernel/transformers/model/hunyuan_v1.py +134 -0
  37. liger_kernel/transformers/model/internvl.py +157 -0
  38. liger_kernel/transformers/model/llama.py +26 -7
  39. liger_kernel/transformers/model/llama4.py +121 -0
  40. liger_kernel/transformers/model/llava.py +18 -6
  41. liger_kernel/transformers/model/loss_utils.py +34 -3
  42. liger_kernel/transformers/model/mistral.py +17 -10
  43. liger_kernel/transformers/model/mixtral.py +24 -9
  44. liger_kernel/transformers/model/mllama.py +18 -7
  45. liger_kernel/transformers/model/olmo2.py +18 -5
  46. liger_kernel/transformers/model/olmo3.py +142 -0
  47. liger_kernel/transformers/model/output_classes.py +147 -0
  48. liger_kernel/transformers/model/paligemma.py +41 -5
  49. liger_kernel/transformers/model/phi3.py +24 -159
  50. liger_kernel/transformers/model/qwen2.py +26 -4
  51. liger_kernel/transformers/model/qwen2_5_vl.py +21 -8
  52. liger_kernel/transformers/model/qwen2_vl.py +24 -7
  53. liger_kernel/transformers/model/qwen3.py +22 -6
  54. liger_kernel/transformers/model/qwen3_moe.py +27 -7
  55. liger_kernel/transformers/model/qwen3_next.py +146 -0
  56. liger_kernel/transformers/model/qwen3_vl.py +150 -0
  57. liger_kernel/transformers/model/qwen3_vl_moe.py +126 -0
  58. liger_kernel/transformers/model/smollm3.py +199 -0
  59. liger_kernel/transformers/model/smolvlm.py +158 -0
  60. liger_kernel/transformers/monkey_patch.py +1278 -116
  61. liger_kernel/transformers/multi_token_attention.py +1 -1
  62. liger_kernel/transformers/poly_norm.py +42 -0
  63. liger_kernel/transformers/rms_norm.py +7 -0
  64. liger_kernel/transformers/rope.py +43 -0
  65. liger_kernel/transformers/swiglu.py +17 -0
  66. liger_kernel/transformers/tiled_mlp.py +133 -0
  67. {liger_kernel_nightly-0.5.10.dev20250624183504.dist-info → liger_kernel_nightly-0.6.4.dev20251121224847.dist-info}/METADATA +29 -24
  68. liger_kernel_nightly-0.6.4.dev20251121224847.dist-info/RECORD +118 -0
  69. liger_kernel_nightly-0.5.10.dev20250624183504.dist-info/RECORD +0 -95
  70. {liger_kernel_nightly-0.5.10.dev20250624183504.dist-info → liger_kernel_nightly-0.6.4.dev20251121224847.dist-info}/LICENSE +0 -0
  71. {liger_kernel_nightly-0.5.10.dev20250624183504.dist-info → liger_kernel_nightly-0.6.4.dev20251121224847.dist-info}/NOTICE +0 -0
  72. {liger_kernel_nightly-0.5.10.dev20250624183504.dist-info → liger_kernel_nightly-0.6.4.dev20251121224847.dist-info}/WHEEL +0 -0
  73. {liger_kernel_nightly-0.5.10.dev20250624183504.dist-info → liger_kernel_nightly-0.6.4.dev20251121224847.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,122 @@
1
+ from typing import TYPE_CHECKING
2
+ from typing import Optional
3
+ from typing import Union
4
+
5
+ import torch
6
+
7
+ if TYPE_CHECKING:
8
+ from transformers.models.falcon_h1.modeling_falcon_h1 import FalconHybridMambaAttentionDynamicCache
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["FalconHybridMambaAttentionDynamicCache"] = 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
+ cache_position: Optional[torch.LongTensor] = None,
27
+ logits_to_keep: Union[int, torch.Tensor] = 0,
28
+ skip_logits: Optional[bool] = None,
29
+ return_dict: Optional[bool] = None,
30
+ **kwargs,
31
+ ) -> Union[tuple, LigerCausalLMOutputWithPast]:
32
+ r"""
33
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
34
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
35
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
36
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
37
+
38
+ Example:
39
+
40
+ ```python
41
+ >>> from transformers import AutoTokenizer, FalconH1ForCausalLM
42
+
43
+ >>> model = FalconH1ForCausalLM.from_pretrained("...")
44
+ >>> tokenizer = AutoTokenizer.from_pretrained("...")
45
+
46
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
47
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
48
+
49
+ >>> # Generate
50
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
51
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
52
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
53
+ ```"""
54
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
55
+ output_hidden_states = (
56
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
57
+ )
58
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
59
+
60
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
61
+ outputs = self.model(
62
+ input_ids=input_ids,
63
+ attention_mask=attention_mask,
64
+ position_ids=position_ids,
65
+ past_key_values=past_key_values,
66
+ inputs_embeds=inputs_embeds,
67
+ use_cache=use_cache,
68
+ output_attentions=output_attentions,
69
+ output_hidden_states=output_hidden_states,
70
+ cache_position=cache_position,
71
+ **kwargs,
72
+ )
73
+
74
+ hidden_states = outputs[0]
75
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
76
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
77
+ kept_hidden_states = hidden_states[:, slice_indices, :]
78
+
79
+ shift_labels = kwargs.pop("shift_labels", None)
80
+ logits = None
81
+ loss = None
82
+ token_accuracy = None
83
+
84
+ # if in training mode, don't materialize logits
85
+ if skip_logits and labels is None:
86
+ raise ValueError("skip_logits is True, but labels and shift_labels are None")
87
+
88
+ if skip_logits is None:
89
+ # By default, if in training mode, don't materialize logits
90
+ skip_logits = self.training and labels is not None
91
+
92
+ # Compute loss
93
+ if skip_logits:
94
+ result = LigerForCausalLMLoss(
95
+ hidden_states=kept_hidden_states,
96
+ lm_head_weight=self.lm_head.weight,
97
+ labels=labels,
98
+ shift_labels=shift_labels,
99
+ hidden_size=self.config.hidden_size,
100
+ **kwargs,
101
+ )
102
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
103
+ else:
104
+ logits = self.lm_head(kept_hidden_states)
105
+ if labels is not None or shift_labels is not None:
106
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
107
+
108
+ if not return_dict:
109
+ output = (logits,) + outputs[1:]
110
+ output = ((loss,) + output) if loss is not None else output
111
+ output = output + (token_accuracy,) if token_accuracy is not None else output
112
+ return output
113
+
114
+ # Return custom output class with token_accuracy field
115
+ return LigerCausalLMOutputWithPast(
116
+ loss=loss,
117
+ logits=logits,
118
+ past_key_values=outputs.past_key_values,
119
+ hidden_states=outputs.hidden_states,
120
+ attentions=outputs.attentions,
121
+ token_accuracy=token_accuracy,
122
+ )
@@ -12,6 +12,8 @@ from transformers.utils.deprecation import deprecate_kwarg
12
12
 
13
13
  from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
14
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
15
17
 
16
18
 
17
19
  def lce_forward_deprecated(
@@ -27,6 +29,7 @@ def lce_forward_deprecated(
27
29
  output_hidden_states: Optional[bool] = None,
28
30
  return_dict: Optional[bool] = None,
29
31
  cache_position: Optional[torch.LongTensor] = None,
32
+ skip_logits: Optional[bool] = None,
30
33
  ) -> Union[Tuple, CausalLMOutputWithPast]:
31
34
  r"""
32
35
 
@@ -81,7 +84,14 @@ def lce_forward_deprecated(
81
84
  loss = None
82
85
  logits = None
83
86
 
84
- if self.training and (labels is not None):
87
+ if skip_logits and labels is None:
88
+ raise ValueError("skip_logits is True, but labels is None")
89
+
90
+ if skip_logits is None:
91
+ # By default, if in training mode, don't materialize logits
92
+ skip_logits = self.training and labels is not None
93
+
94
+ if skip_logits:
85
95
  shift_hidden_states = hidden_states[..., :-1, :].contiguous()
86
96
  shift_labels = labels[..., 1:].contiguous()
87
97
 
@@ -139,7 +149,7 @@ def lce_forward(
139
149
  logits_to_keep: Union[int, torch.Tensor] = 0,
140
150
  skip_logits: Optional[bool] = None,
141
151
  **kwargs,
142
- ) -> Union[Tuple, CausalLMOutputWithPast]:
152
+ ) -> Union[Tuple, LigerCausalLMOutputWithPast]:
143
153
  r"""
144
154
  Args:
145
155
  labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
@@ -201,6 +211,7 @@ def lce_forward(
201
211
  shift_labels = kwargs.pop("shift_labels", None)
202
212
  logits = None
203
213
  loss = None
214
+ token_accuracy = None
204
215
 
205
216
  if skip_logits and labels is None and shift_labels is None:
206
217
  raise ValueError("skip_logits is True, but labels and shift_labels are None")
@@ -209,8 +220,9 @@ def lce_forward(
209
220
  # By default, if in training mode, don't materialize logits
210
221
  skip_logits = self.training and (labels is not None or shift_labels is not None)
211
222
 
223
+ # Compute loss
212
224
  if skip_logits:
213
- loss = LigerForCausalLMLoss(
225
+ result = LigerForCausalLMLoss(
214
226
  hidden_states=kept_hidden_states,
215
227
  lm_head_weight=self.lm_head.weight,
216
228
  labels=labels,
@@ -218,24 +230,32 @@ def lce_forward(
218
230
  hidden_size=self.config.hidden_size,
219
231
  **kwargs,
220
232
  )
233
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
221
234
  else:
222
235
  logits = self.lm_head(kept_hidden_states)
223
- if labels is not None:
236
+ if labels is not None or shift_labels is not None:
224
237
  loss = self.loss_function(
225
238
  logits=logits,
226
239
  labels=labels,
240
+ shift_labels=shift_labels,
227
241
  vocab_size=self.config.vocab_size,
228
242
  **kwargs,
229
243
  )
230
244
 
231
245
  if not return_dict:
232
- output = (logits,) + outputs[1:]
233
- return (loss,) + output if loss is not None else output
234
-
235
- return CausalLMOutputWithPast(
246
+ output_tuple = (logits,) + outputs[1:]
247
+ if loss is not None:
248
+ output_tuple = (loss,) + output_tuple
249
+ if token_accuracy is not None:
250
+ output_tuple = output_tuple + (token_accuracy,)
251
+ return output_tuple
252
+
253
+ # Return custom output class with token_accuracy field
254
+ return LigerCausalLMOutputWithPast(
236
255
  loss=loss,
237
256
  logits=logits,
238
257
  past_key_values=outputs.past_key_values,
239
258
  hidden_states=outputs.hidden_states,
240
259
  attentions=outputs.attentions,
260
+ token_accuracy=token_accuracy,
241
261
  )
@@ -13,6 +13,8 @@ from transformers.utils.deprecation import deprecate_kwarg
13
13
 
14
14
  from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
15
15
  from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
16
+ from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
17
+ from liger_kernel.transformers.model.output_classes import LigerCausalLMOutputWithPast
16
18
 
17
19
  logger = logging.getLogger(__name__)
18
20
 
@@ -30,6 +32,7 @@ def lce_forward_deprecated(
30
32
  output_hidden_states: Optional[bool] = None,
31
33
  return_dict: Optional[bool] = None,
32
34
  cache_position: Optional[torch.LongTensor] = None,
35
+ skip_logits: Optional[bool] = None,
33
36
  **kwargs,
34
37
  ) -> Union[Tuple, CausalLMOutputWithPast]:
35
38
  r"""
@@ -85,7 +88,14 @@ def lce_forward_deprecated(
85
88
  loss = None
86
89
  logits = None
87
90
 
88
- if self.training and (labels is not None):
91
+ if skip_logits and labels is None:
92
+ raise ValueError("skip_logits is True, but labels is None")
93
+
94
+ if skip_logits is None:
95
+ # By default, if in training mode, don't materialize logits
96
+ skip_logits = self.training and labels is not None
97
+
98
+ if skip_logits:
89
99
  shift_hidden_states = hidden_states[..., :-1, :].contiguous()
90
100
  shift_labels = labels[..., 1:].contiguous()
91
101
 
@@ -150,7 +160,7 @@ def lce_forward(
150
160
  logits_to_keep: Union[int, torch.Tensor] = 0,
151
161
  skip_logits: Optional[bool] = None,
152
162
  **kwargs,
153
- ) -> Union[Tuple, CausalLMOutputWithPast]:
163
+ ) -> Union[Tuple, LigerCausalLMOutputWithPast]:
154
164
  r"""
155
165
  Args:
156
166
  labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
@@ -217,6 +227,7 @@ def lce_forward(
217
227
  shift_labels = kwargs.pop("shift_labels", None)
218
228
  logits = None
219
229
  loss = None
230
+ token_accuracy = None
220
231
 
221
232
  if skip_logits and labels is None and shift_labels is None:
222
233
  raise ValueError("skip_logits is True, but labels and shift_labels are None")
@@ -225,8 +236,9 @@ def lce_forward(
225
236
  # By default, if in training mode, don't materialize logits
226
237
  skip_logits = self.training and (labels is not None or shift_labels is not None)
227
238
 
239
+ # Compute loss
228
240
  if skip_logits:
229
- loss = LigerForCausalLMLoss(
241
+ result = LigerForCausalLMLoss(
230
242
  hidden_states=kept_hidden_states,
231
243
  lm_head_weight=self.lm_head.weight,
232
244
  labels=labels,
@@ -235,6 +247,7 @@ def lce_forward(
235
247
  final_logit_softcapping=self.config.final_logit_softcapping,
236
248
  **kwargs,
237
249
  )
250
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
238
251
 
239
252
  else:
240
253
  logits = self.lm_head(kept_hidden_states)
@@ -244,17 +257,27 @@ def lce_forward(
244
257
  logits = logits * self.config.final_logit_softcapping
245
258
 
246
259
  loss = None
247
- if labels is not None:
248
- loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
260
+ if labels is not None or shift_labels is not None:
261
+ loss = self.loss_function(
262
+ logits=logits,
263
+ labels=labels,
264
+ shift_labels=shift_labels,
265
+ vocab_size=self.vocab_size,
266
+ **kwargs,
267
+ )
249
268
 
250
269
  if not return_dict:
251
- output = (logits,) + outputs[1:]
252
- return (loss,) + output if loss is not None else output
270
+ output_tuple = (logits,) + outputs[1:]
271
+ output_tuple = (loss,) + output_tuple if loss is not None else output_tuple
272
+ output_tuple = output_tuple + (token_accuracy,) if token_accuracy is not None else output_tuple
273
+ return output_tuple
253
274
 
254
- return CausalLMOutputWithPast(
275
+ # Return custom output class with token_accuracy field
276
+ return LigerCausalLMOutputWithPast(
255
277
  loss=loss,
256
278
  logits=logits,
257
279
  past_key_values=outputs.past_key_values,
258
280
  hidden_states=outputs.hidden_states,
259
281
  attentions=outputs.attentions,
282
+ token_accuracy=token_accuracy,
260
283
  )
@@ -1,4 +1,3 @@
1
- from typing import List
2
1
  from typing import Optional
3
2
  from typing import Tuple
4
3
  from typing import Union
@@ -8,19 +7,17 @@ import torch.nn as nn
8
7
 
9
8
  from transformers.cache_utils import Cache
10
9
  from transformers.cache_utils import HybridCache
11
- from transformers.modeling_outputs import CausalLMOutputWithPast
12
- from transformers.models.gemma3.modeling_gemma3 import Gemma3CausalLMOutputWithPast
13
- from transformers.utils import is_torchdynamo_compiling
14
10
  from transformers.utils import logging
15
- from transformers.utils.deprecation import deprecate_kwarg
16
11
 
17
12
  from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
18
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 LigerCausalLMOutputWithPast
16
+ from liger_kernel.transformers.model.output_classes import LigerGemma3CausalLMOutputWithPast
19
17
 
20
18
  logger = logging.get_logger(__name__)
21
19
 
22
20
 
23
- @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
24
21
  def causal_forward(
25
22
  self,
26
23
  input_ids: torch.LongTensor = None,
@@ -37,7 +34,7 @@ def causal_forward(
37
34
  logits_to_keep: Union[int, torch.Tensor] = 0,
38
35
  skip_logits: Optional[bool] = None,
39
36
  **loss_kwargs,
40
- ) -> Union[Tuple, CausalLMOutputWithPast]:
37
+ ) -> Union[Tuple, LigerCausalLMOutputWithPast]:
41
38
  r"""
42
39
  labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
43
40
  Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
@@ -102,12 +99,14 @@ def causal_forward(
102
99
  shift_labels = loss_kwargs.pop("shift_labels", None)
103
100
  loss = None
104
101
  logits = None
102
+ token_accuracy = None
105
103
 
106
104
  if skip_logits is None:
107
105
  skip_logits = self.training and (labels is not None or shift_labels is not None)
108
106
 
107
+ # Compute loss
109
108
  if skip_logits:
110
- loss = LigerForCausalLMLoss(
109
+ result = LigerForCausalLMLoss(
111
110
  hidden_states=kept_hidden_states,
112
111
  lm_head_weight=self.lm_head.weight,
113
112
  labels=labels,
@@ -116,37 +115,46 @@ def causal_forward(
116
115
  final_logit_softcapping=self.config.final_logit_softcapping,
117
116
  **loss_kwargs,
118
117
  )
119
-
118
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
120
119
  else:
121
120
  logits = self.lm_head(kept_hidden_states)
122
121
  if self.config.final_logit_softcapping is not None:
123
122
  logits = logits / self.config.final_logit_softcapping
124
123
  logits = torch.tanh(logits)
125
124
  logits = logits * self.config.final_logit_softcapping
126
- if labels is not None:
127
- loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
125
+ if labels is not None or shift_labels is not None:
126
+ loss = self.loss_function(
127
+ logits=logits,
128
+ labels=labels,
129
+ shift_labels=shift_labels,
130
+ vocab_size=self.vocab_size,
131
+ **loss_kwargs,
132
+ )
128
133
 
129
134
  if not return_dict:
130
- output = (logits,) + outputs[1:]
131
- return (loss,) + output if loss is not None else output
135
+ output_tuple = (logits,) + outputs[1:]
136
+ output_tuple = (loss,) + output_tuple if loss is not None else output_tuple
137
+ output_tuple = output_tuple + (token_accuracy,) if token_accuracy is not None else output_tuple
138
+ return output_tuple
132
139
 
133
- return CausalLMOutputWithPast(
140
+ # Return custom output class with token_accuracy field
141
+ return LigerCausalLMOutputWithPast(
134
142
  loss=loss,
135
143
  logits=logits,
136
144
  past_key_values=outputs.past_key_values,
137
145
  hidden_states=outputs.hidden_states,
138
146
  attentions=outputs.attentions,
147
+ token_accuracy=token_accuracy,
139
148
  )
140
149
 
141
150
 
142
- @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
143
151
  def multimodal_forward(
144
152
  self,
145
153
  input_ids: torch.LongTensor = None,
146
154
  pixel_values: torch.FloatTensor = None,
147
155
  attention_mask: Optional[torch.Tensor] = None,
148
156
  position_ids: Optional[torch.LongTensor] = None,
149
- past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None,
157
+ past_key_values: Optional[Union[list[torch.FloatTensor], Cache]] = None,
150
158
  token_type_ids: Optional[torch.LongTensor] = None,
151
159
  cache_position: Optional[torch.LongTensor] = None,
152
160
  inputs_embeds: Optional[torch.FloatTensor] = None,
@@ -158,21 +166,12 @@ def multimodal_forward(
158
166
  logits_to_keep: Union[int, torch.Tensor] = 0,
159
167
  skip_logits: Optional[bool] = None,
160
168
  **lm_kwargs,
161
- ) -> Union[Tuple, Gemma3CausalLMOutputWithPast]:
169
+ ) -> Union[tuple, LigerGemma3CausalLMOutputWithPast]:
162
170
  r"""
163
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
164
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
165
- config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
166
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
167
-
168
- logits_to_keep (`int` or `torch.Tensor`, *optional*):
169
- If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
170
- `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
171
- token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
172
- If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
173
- This is useful when using packed tensor format (single dimension for batch and sequence length).
174
-
175
- Returns:
171
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
172
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
173
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
174
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
176
175
 
177
176
  Example:
178
177
 
@@ -181,23 +180,37 @@ def multimodal_forward(
181
180
  >>> import requests
182
181
  >>> from transformers import AutoProcessor, Gemma3ForConditionalGeneration
183
182
 
184
- >>> model = Gemma3ForConditionalGeneration.from_pretrained("google/Gemma3-test-224px-hf")
185
- >>> processor = AutoProcessor.from_pretrained("google/Gemma3-test-224px-hf")
186
-
187
- >>> prompt = "answer en Where is the cow standing?"
188
- >>> url = "https://huggingface.co/gv-hf/Gemma3-test-224px-hf/resolve/main/cow_beach_1.png"
189
- >>> image = Image.open(requests.get(url, stream=True).raw)
190
-
191
- >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
192
-
183
+ >>> model = Gemma3ForConditionalGeneration.from_pretrained("google/gemma-3-4b-it")
184
+ >>> processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it")
185
+
186
+ >>> messages = [
187
+ ... {
188
+ ... "role": "system",
189
+ ... "content": [
190
+ ... {"type": "text", "text": "You are a helpful assistant."}
191
+ ... ]
192
+ ... },
193
+ ... {
194
+ ... "role": "user", "content": [
195
+ ... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
196
+ ... {"type": "text", "text": "Where is the cat standing?"},
197
+ ... ]
198
+ ... },
199
+ ... ]
200
+
201
+ >>> inputs = processor.apply_chat_template(
202
+ ... messages,
203
+ ... tokenize=True,
204
+ ... return_dict=True,
205
+ ... return_tensors="pt",
206
+ ... add_generation_prompt=True
207
+ ... )
193
208
  >>> # Generate
194
- >>> generate_ids = model.generate(**inputs, max_length=30)
209
+ >>> generate_ids = model.generate(**inputs)
195
210
  >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
196
- "answer en Where is the cow standing?\nbeach"
197
- ```"""
198
-
199
- if (input_ids is None) ^ (inputs_embeds is not None):
200
- raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
211
+ "user\nYou are a helpful assistant.\n\n\n\n\n\nWhere is the cat standing?\nmodel\nBased on the image, the cat is standing in a snowy area, likely outdoors. It appears to"
212
+ ```
213
+ """
201
214
 
202
215
  output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
203
216
  output_hidden_states = (
@@ -205,79 +218,31 @@ def multimodal_forward(
205
218
  )
206
219
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
207
220
 
208
- is_training = token_type_ids is not None and labels is not None
209
-
210
- # Replace image id woth PAD if the image token if OOV, to avoid index-errors
211
- if input_ids is not None and self.config.image_token_index >= self.vocab_size:
212
- special_image_mask = input_ids == self.config.image_token_index
213
- llm_input_ids = input_ids.clone()
214
- llm_input_ids[special_image_mask] = 0
215
- else:
216
- llm_input_ids = input_ids
217
-
218
- if inputs_embeds is None:
219
- inputs_embeds = self.get_input_embeddings()(llm_input_ids)
220
-
221
- if cache_position is None:
222
- past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
223
- cache_position = torch.arange(
224
- past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
225
- )
226
-
227
- if position_ids is None:
228
- position_ids = cache_position.unsqueeze(0) + 1 # Gemma3 positions are 1-indexed
229
-
230
- # Merge text and images
231
- if pixel_values is not None:
232
- image_features = self.get_image_features(pixel_values)
233
-
234
- if input_ids is None:
235
- special_image_mask = inputs_embeds == self.get_input_embeddings()(
236
- torch.tensor(self.config.image_token_index, dtype=torch.long, device=inputs_embeds.device)
237
- )
238
- else:
239
- special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
240
- special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
241
-
242
- if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
243
- image_tokens_in_text = (special_image_mask).sum(dim=1).sum(dim=0)[0]
244
- raise ValueError(
245
- f"Number of images does not match number of special image tokens in the input text. "
246
- f"Got {image_tokens_in_text} image tokens in the text but {image_features.shape[0] * image_features.shape[1]} "
247
- "tokens from image embeddings."
248
- )
249
- image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
250
- inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
251
-
252
- # mask out pad-token-ids in labels for BC
253
- if labels is not None and self.pad_token_id in labels:
254
- logger.warning_once(
255
- "`labels` contains `pad_token_id` which will be masked with `config.ignore_index`. "
256
- "You have to mask out `pad_token_id` when preparing `labels`, this behavior will be removed in v.4.46.",
257
- )
258
- labels = torch.where(input_ids == self.pad_token_id, self.config.ignore_index, labels)
259
-
260
- causal_mask = self._update_causal_mask(
261
- attention_mask, token_type_ids, past_key_values, cache_position, inputs_embeds, is_training
262
- )
263
- outputs = self.language_model.model(
264
- attention_mask=causal_mask,
221
+ outputs = self.model(
222
+ input_ids=input_ids,
223
+ pixel_values=pixel_values,
224
+ token_type_ids=token_type_ids,
225
+ attention_mask=attention_mask,
265
226
  position_ids=position_ids,
266
227
  past_key_values=past_key_values,
267
228
  inputs_embeds=inputs_embeds,
268
229
  use_cache=use_cache,
230
+ labels=labels,
269
231
  output_attentions=output_attentions,
270
232
  output_hidden_states=output_hidden_states,
271
233
  return_dict=return_dict,
272
234
  cache_position=cache_position,
273
- logits_to_keep=logits_to_keep,
274
235
  **lm_kwargs,
275
236
  )
276
237
 
277
238
  hidden_states = outputs[0]
239
+
240
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
241
+ kept_hidden_states = hidden_states[:, slice_indices, :]
242
+
278
243
  loss = None
279
244
  logits = None
280
-
245
+ token_accuracy = None
281
246
  if skip_logits and labels is None:
282
247
  raise ValueError("skip_logits is True, but labels is None")
283
248
 
@@ -285,7 +250,7 @@ def multimodal_forward(
285
250
  skip_logits = self.training and (labels is not None)
286
251
 
287
252
  if skip_logits:
288
- shift_hidden_states = hidden_states[..., :-1, :]
253
+ shift_hidden_states = kept_hidden_states[..., :-1, :]
289
254
  shift_labels = labels[..., 1:]
290
255
 
291
256
  hidden_device = shift_hidden_states.device
@@ -304,9 +269,11 @@ def multimodal_forward(
304
269
  shift_labels = shift_labels.view(-1).to(hidden_device)
305
270
 
306
271
  lce = LigerFusedLinearCrossEntropyLoss()
307
- loss = lce(self.language_model.lm_head.weight, shift_hidden_states, shift_labels)
272
+ result = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
273
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
274
+
308
275
  else:
309
- logits = self.language_model.lm_head(hidden_states)
276
+ logits = self.lm_head(kept_hidden_states)
310
277
  if labels is not None:
311
278
  # Upcast to float if we need to compute the loss to avoid potential precision issues
312
279
  logits = logits.float()
@@ -327,15 +294,38 @@ def multimodal_forward(
327
294
  flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
328
295
  flat_labels = shift_labels.view(-1).to(shift_logits.device)
329
296
  loss = loss_fct(flat_logits, flat_labels)
297
+ elif shift_labels is not None:
298
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
299
+ logits = logits.float()
300
+ shift_logits = logits[..., :-1, :]
301
+ if attention_mask is not None:
302
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
303
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
304
+ shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
305
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
306
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
307
+ else:
308
+ shift_logits = shift_logits.contiguous()
309
+ shift_labels = shift_labels.contiguous()
310
+ # Flatten the tokens
311
+ loss_fct = nn.CrossEntropyLoss()
312
+
313
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
314
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
315
+ loss = loss_fct(flat_logits, flat_labels)
316
+
330
317
  if not return_dict:
331
318
  output = (logits,) + outputs[1:]
332
- return (loss,) + output if loss is not None else output
319
+ output = (loss,) + output if loss is not None else output
320
+ output = output + (token_accuracy,) if token_accuracy is not None else output
321
+ return output
333
322
 
334
- return Gemma3CausalLMOutputWithPast(
323
+ return LigerGemma3CausalLMOutputWithPast(
335
324
  loss=loss,
336
325
  logits=logits,
337
326
  past_key_values=outputs.past_key_values,
338
327
  hidden_states=outputs.hidden_states,
339
328
  attentions=outputs.attentions,
340
- image_hidden_states=image_features if pixel_values is not None else None,
329
+ image_hidden_states=outputs.image_hidden_states,
330
+ token_accuracy=token_accuracy,
341
331
  )