liger-kernel 0.5.4__py3-none-any.whl → 0.5.6__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 (44) hide show
  1. liger_kernel/chunked_loss/cpo_loss.py +51 -11
  2. liger_kernel/chunked_loss/dpo_loss.py +30 -4
  3. liger_kernel/chunked_loss/functional.py +2 -0
  4. liger_kernel/chunked_loss/fused_linear_distillation.py +20 -5
  5. liger_kernel/chunked_loss/fused_linear_ppo.py +331 -0
  6. liger_kernel/chunked_loss/fused_linear_preference.py +2 -2
  7. liger_kernel/chunked_loss/fused_linear_unpaired_preference.py +112 -17
  8. liger_kernel/chunked_loss/grpo_loss.py +137 -61
  9. liger_kernel/chunked_loss/jsd_loss.py +43 -13
  10. liger_kernel/chunked_loss/kto_loss.py +50 -12
  11. liger_kernel/chunked_loss/orpo_loss.py +37 -5
  12. liger_kernel/chunked_loss/simpo_loss.py +47 -11
  13. liger_kernel/ops/cross_entropy.py +7 -2
  14. liger_kernel/ops/dyt.py +225 -0
  15. liger_kernel/ops/fused_linear_jsd.py +2 -1
  16. liger_kernel/ops/jsd.py +30 -11
  17. liger_kernel/ops/kl_div.py +2 -2
  18. liger_kernel/transformers/__init__.py +4 -0
  19. liger_kernel/transformers/dyt.py +20 -0
  20. liger_kernel/transformers/functional.py +5 -0
  21. liger_kernel/transformers/model/gemma.py +8 -16
  22. liger_kernel/transformers/model/gemma2.py +7 -16
  23. liger_kernel/transformers/model/llama.py +8 -15
  24. liger_kernel/transformers/model/llava.py +369 -0
  25. liger_kernel/transformers/model/loss_utils.py +57 -0
  26. liger_kernel/transformers/model/mistral.py +9 -10
  27. liger_kernel/transformers/model/mixtral.py +8 -15
  28. liger_kernel/transformers/model/mllama.py +8 -15
  29. liger_kernel/transformers/model/olmo2.py +8 -16
  30. liger_kernel/transformers/model/paligemma.py +397 -0
  31. liger_kernel/transformers/model/phi3.py +8 -15
  32. liger_kernel/transformers/model/qwen2.py +8 -15
  33. liger_kernel/transformers/model/qwen2_5_vl.py +204 -0
  34. liger_kernel/transformers/model/qwen2_vl.py +9 -10
  35. liger_kernel/transformers/monkey_patch.py +286 -12
  36. liger_kernel/utils.py +1 -3
  37. {liger_kernel-0.5.4.dist-info → liger_kernel-0.5.6.dist-info}/METADATA +11 -7
  38. liger_kernel-0.5.6.dist-info/RECORD +80 -0
  39. {liger_kernel-0.5.4.dist-info → liger_kernel-0.5.6.dist-info}/WHEEL +1 -1
  40. liger_kernel/chunked_loss/fused_linear_rlhf.py +0 -213
  41. liger_kernel-0.5.4.dist-info/RECORD +0 -74
  42. {liger_kernel-0.5.4.dist-info → liger_kernel-0.5.6.dist-info/licenses}/LICENSE +0 -0
  43. {liger_kernel-0.5.4.dist-info → liger_kernel-0.5.6.dist-info/licenses}/NOTICE +0 -0
  44. {liger_kernel-0.5.4.dist-info → liger_kernel-0.5.6.dist-info}/top_level.txt +0 -0
@@ -185,9 +185,9 @@ class LigerKLDivLossFunction(torch.autograd.Function):
185
185
  Class implementing the forward and backward pass for the KL Divergence Loss using Triton, as defined by the following formula:
186
186
  ```python
187
187
  if log_target:
188
- loss = target * (target.log() - input)
189
- else:
190
188
  loss = target.exp() * (target - input)
189
+ else:
190
+ loss = target * (target.log() - input)
191
191
  ```,
192
192
  then the loss is reduced according to the `reduction` parameter.
193
193
  as defined in the PyTorch documentation: https://pytorch.org/docs/stable/generated/torch.nn.KLDivLoss.html
@@ -1,5 +1,6 @@
1
1
  from liger_kernel.transformers.auto_model import AutoLigerKernelForCausalLM # noqa: F401
2
2
  from liger_kernel.transformers.cross_entropy import LigerCrossEntropyLoss # noqa: F401
3
+ from liger_kernel.transformers.dyt import LigerDyT # noqa: F401
3
4
  from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss # noqa: F401
4
5
  from liger_kernel.transformers.fused_linear_jsd import LigerFusedLinearJSD # noqa: F401
5
6
  from liger_kernel.transformers.geglu import LigerGEGLUMLP # noqa: F401
@@ -11,12 +12,15 @@ from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_gemma
11
12
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_gemma2 # noqa: F401
12
13
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_granite # noqa: F401
13
14
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_llama # noqa: F401
15
+ from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_llava # noqa: F401
14
16
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mistral # noqa: F401
15
17
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mixtral # noqa: F401
16
18
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mllama # noqa: F401
17
19
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_olmo2 # noqa: F401
20
+ from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_paligemma # noqa: F401
18
21
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_phi3 # noqa: F401
19
22
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2 # noqa: F401
23
+ from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2_5_vl # noqa: F401
20
24
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2_vl # noqa: F401
21
25
  from liger_kernel.transformers.rms_norm import LigerRMSNorm # noqa: F401
22
26
  from liger_kernel.transformers.rope import liger_rotary_pos_emb # noqa: F401
@@ -0,0 +1,20 @@
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from liger_kernel.ops.dyt import LigerDyTFunction
5
+
6
+
7
+ class LigerDyT(nn.Module):
8
+ def __init__(self, hidden_size, init_alpha=0.5):
9
+ super().__init__()
10
+ self.hidden_size = hidden_size
11
+ self.init_alpha = init_alpha
12
+ self.alpha = nn.Parameter(torch.ones(1) * init_alpha)
13
+ self.gamma = nn.Parameter(torch.ones(hidden_size))
14
+ self.beta = nn.Parameter(torch.zeros(hidden_size))
15
+
16
+ def forward(self, x):
17
+ return LigerDyTFunction.apply(x, self.alpha, self.gamma, self.beta)
18
+
19
+ def extra_repr(self):
20
+ return f"{self.hidden_size}, init_alpha={self.init_alpha}"
@@ -1,6 +1,7 @@
1
1
  from typing import Optional
2
2
 
3
3
  from liger_kernel.ops.cross_entropy import LigerCrossEntropyFunction
4
+ from liger_kernel.ops.dyt import LigerDyTFunction
4
5
  from liger_kernel.ops.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyFunction
5
6
  from liger_kernel.ops.fused_linear_jsd import LigerFusedLinearJSDFunction
6
7
  from liger_kernel.ops.geglu import LigerGELUMulFunction
@@ -192,3 +193,7 @@ def liger_rope(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
192
193
 
193
194
  def liger_swiglu(a, b):
194
195
  return LigerSiLUMulFunction.apply(a, b)
196
+
197
+
198
+ def liger_dyt(x, alpha, gamma, beta):
199
+ return LigerDyTFunction.apply(x, alpha, gamma, beta)
@@ -14,6 +14,7 @@ from transformers.utils import add_start_docstrings_to_model_forward
14
14
  from transformers.utils import replace_return_docstrings
15
15
 
16
16
  from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
17
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
17
18
 
18
19
 
19
20
  @add_start_docstrings_to_model_forward(GEMMA_INPUTS_DOCSTRING)
@@ -200,22 +201,13 @@ def lce_forward(
200
201
  loss = None
201
202
  # if in training mode, don't materialize logits
202
203
  if self.training and (labels is not None):
203
- # We do the same thing as ForCausalLMLoss but using Liger FLCE
204
-
205
- shift_hidden_states = hidden_states[..., :-1, :].contiguous()
206
- shift_labels = labels[..., 1:].contiguous()
207
-
208
- # flatten tokens
209
- shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
210
- shift_labels = shift_labels.view(-1)
211
-
212
- reduction = "sum" if "num_items_in_batch" in loss_kwargs else "mean"
213
- lce = LigerFusedLinearCrossEntropyLoss(reduction=reduction)
214
-
215
- loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
216
- if reduction == "sum":
217
- loss /= loss_kwargs["num_items_in_batch"]
218
-
204
+ loss = LigerForCausalLMLoss(
205
+ hidden_states=hidden_states,
206
+ lm_head_weight=self.lm_head.weight,
207
+ labels=labels,
208
+ hidden_size=self.config.hidden_size,
209
+ **loss_kwargs,
210
+ )
219
211
  else: # if in inference mode materialize logits
220
212
  logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
221
213
  if labels is not None:
@@ -15,6 +15,7 @@ from transformers.utils import add_start_docstrings_to_model_forward
15
15
  from transformers.utils import replace_return_docstrings
16
16
 
17
17
  from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
18
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
18
19
 
19
20
  logger = logging.getLogger(__name__)
20
21
 
@@ -212,25 +213,15 @@ def lce_forward(
212
213
  loss = None
213
214
  # if in training mode, don't materialize logits
214
215
  if self.training and (labels is not None):
215
- # We do the same thing as ForCausalLMLoss but using Liger FLCE
216
-
217
- shift_hidden_states = hidden_states[..., :-1, :].contiguous()
218
- shift_labels = labels[..., 1:].contiguous()
219
-
220
- # flatten tokens
221
- shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
222
- shift_labels = shift_labels.view(-1)
223
-
224
- reduction = "sum" if "num_items_in_batch" in loss_kwargs else "mean"
225
- lce = LigerFusedLinearCrossEntropyLoss(
216
+ loss = LigerForCausalLMLoss(
217
+ hidden_states=hidden_states,
218
+ lm_head_weight=self.lm_head.weight,
219
+ labels=labels,
220
+ hidden_size=self.config.hidden_size,
226
221
  softcap=self.config.final_logit_softcapping,
227
- reduction=reduction,
222
+ **loss_kwargs,
228
223
  )
229
224
 
230
- loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
231
- if reduction == "sum":
232
- loss /= loss_kwargs["num_items_in_batch"]
233
-
234
225
  else: # if in inference mode materialize logits
235
226
  logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
236
227
  if self.config.final_logit_softcapping is not None:
@@ -15,6 +15,7 @@ from transformers.utils import add_start_docstrings_to_model_forward
15
15
  from transformers.utils import replace_return_docstrings
16
16
 
17
17
  from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
18
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
18
19
 
19
20
  if TYPE_CHECKING:
20
21
  from transformers.cache_utils import Cache
@@ -212,21 +213,13 @@ def lce_forward(
212
213
  loss = None
213
214
  # if in training mode, don't materialize logits
214
215
  if self.training and (labels is not None):
215
- # We do the same thing as ForCausalLMLoss but using Liger FLCE
216
-
217
- shift_hidden_states = hidden_states[..., :-1, :].contiguous()
218
- shift_labels = labels[..., 1:].contiguous()
219
-
220
- # flatten tokens
221
- shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
222
- shift_labels = shift_labels.view(-1)
223
-
224
- reduction = "sum" if "num_items_in_batch" in loss_kwargs else "mean"
225
- lce = LigerFusedLinearCrossEntropyLoss(reduction=reduction)
226
-
227
- loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
228
- if reduction == "sum":
229
- loss /= loss_kwargs["num_items_in_batch"]
216
+ loss = LigerForCausalLMLoss(
217
+ hidden_states=hidden_states,
218
+ lm_head_weight=self.lm_head.weight,
219
+ labels=labels,
220
+ hidden_size=self.config.hidden_size,
221
+ **loss_kwargs,
222
+ )
230
223
 
231
224
  else: # if in inference mode materialize logits
232
225
  logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
@@ -0,0 +1,369 @@
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.models.llava.modeling_llava import _CONFIG_FOR_DOC
9
+ from transformers.models.llava.modeling_llava import LLAVA_INPUTS_DOCSTRING
10
+ from transformers.models.llava.modeling_llava import LlavaCausalLMOutputWithPast
11
+ from transformers.utils import add_start_docstrings_to_model_forward
12
+ from transformers.utils import is_torchdynamo_compiling
13
+ from transformers.utils import replace_return_docstrings
14
+ from transformers.utils.deprecation import deprecate_kwarg
15
+
16
+ from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
17
+
18
+
19
+ @add_start_docstrings_to_model_forward(LLAVA_INPUTS_DOCSTRING)
20
+ @replace_return_docstrings(output_type=LlavaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
21
+ def lce_forward_deprecated(
22
+ self,
23
+ input_ids: torch.LongTensor = None,
24
+ pixel_values: torch.FloatTensor = None,
25
+ attention_mask: Optional[torch.Tensor] = None,
26
+ position_ids: Optional[torch.LongTensor] = None,
27
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
28
+ inputs_embeds: Optional[torch.FloatTensor] = None,
29
+ vision_feature_layer: Optional[int] = None,
30
+ vision_feature_select_strategy: Optional[str] = None,
31
+ labels: Optional[torch.LongTensor] = None,
32
+ use_cache: Optional[bool] = None,
33
+ output_attentions: Optional[bool] = None,
34
+ output_hidden_states: Optional[bool] = None,
35
+ return_dict: Optional[bool] = None,
36
+ ) -> Union[Tuple, LlavaCausalLMOutputWithPast]:
37
+ r"""
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
+ num_logits_to_keep (`int`, *optional*):
45
+ Calculate logits for the last `num_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
+
49
+
50
+ Returns:
51
+
52
+ Example:
53
+
54
+ ```python
55
+ >>> from PIL import Image
56
+ >>> import requests
57
+ >>> from transformers import AutoProcessor, LlavaForConditionalGeneration
58
+
59
+ >>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
60
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
61
+
62
+ >>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
63
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
64
+ >>> image = Image.open(requests.get(url, stream=True).raw)
65
+
66
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
67
+
68
+ >>> # Generate
69
+ >>> generate_ids = model.generate(**inputs, max_new_tokens=15)
70
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
71
+ "USER: \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
72
+ ```"""
73
+
74
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
75
+ output_hidden_states = (
76
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
77
+ )
78
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
79
+ vision_feature_layer = (
80
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
81
+ )
82
+ vision_feature_select_strategy = (
83
+ vision_feature_select_strategy
84
+ if vision_feature_select_strategy is not None
85
+ else self.config.vision_feature_select_strategy
86
+ )
87
+
88
+ if (input_ids is None) ^ (inputs_embeds is not None):
89
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
90
+
91
+ if pixel_values is not None and inputs_embeds is not None:
92
+ raise ValueError(
93
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
94
+ )
95
+
96
+ if inputs_embeds is None:
97
+ # 1. Extra the input embeddings
98
+ inputs_embeds = self.get_input_embeddings()(input_ids)
99
+
100
+ # 2. Merge text and images
101
+ if pixel_values is not None and input_ids.shape[1] != 1:
102
+ image_outputs = self.vision_tower(pixel_values, output_hidden_states=True)
103
+ # this is not memory efficient at all (output_hidden_states=True) will save all the hidden stated.
104
+ selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
105
+
106
+ if vision_feature_select_strategy == "default":
107
+ selected_image_feature = selected_image_feature[:, 1:]
108
+ elif vision_feature_select_strategy == "full":
109
+ selected_image_feature = selected_image_feature
110
+ else:
111
+ raise ValueError(f"Unexpected select feature strategy: {self.config.vision_feature_select_strategy}")
112
+
113
+ image_features = self.multi_modal_projector(selected_image_feature)
114
+ inputs_embeds = inputs_embeds.to(image_features.dtype)
115
+ inputs_embeds, attention_mask, labels, position_ids = self._merge_input_ids_with_image_features(
116
+ image_features, inputs_embeds, input_ids, attention_mask, labels
117
+ )
118
+
119
+ # In case input_ids.shape[1] == 1 & pixel_values==None & past_key_values != None, we are in the case of
120
+ # generation with cache
121
+ elif past_key_values is not None and pixel_values is not None and input_ids.shape[1] == 1:
122
+ # Retrieve the first layer to inspect the logits and mask out the hidden states
123
+ # that are set to 0
124
+ first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]
125
+
126
+ # Sum all dimensions of head_dim (-2) to avoid random errors such as: https://github.com/huggingface/transformers/pull/28032#issuecomment-1863691941
127
+ batch_index, non_attended_tokens = torch.where(first_layer_past_key_value.float().sum(-2) == 0)
128
+
129
+ # Get the target length
130
+ target_length = input_ids.shape[1]
131
+ past_length = first_layer_past_key_value.shape[-1]
132
+
133
+ extended_attention_mask = torch.ones(
134
+ (attention_mask.shape[0], past_length),
135
+ dtype=attention_mask.dtype,
136
+ device=attention_mask.device,
137
+ )
138
+
139
+ # Filter out only the tokens that can be un-attended, this can happen
140
+ # if one uses Llava + Fused modules where the cache on the
141
+ # first iteration is already big enough, or if one passes custom cache
142
+ valid_indices = non_attended_tokens < extended_attention_mask.size(-1)
143
+ new_batch_index = batch_index[valid_indices]
144
+ new_non_attended_tokens = non_attended_tokens[valid_indices]
145
+
146
+ # Zero-out the places where we don't need to attend
147
+ extended_attention_mask[new_batch_index, new_non_attended_tokens] = 0
148
+
149
+ attention_mask = torch.cat((extended_attention_mask, attention_mask[:, -target_length:]), dim=1)
150
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
151
+
152
+ # TODO: @raushan retain only the new behavior after v4.47
153
+ elif image_features is not None:
154
+ n_image_tokens = (input_ids == self.config.image_token_index).sum().item()
155
+ n_image_features = image_features.shape[0] * image_features.shape[1]
156
+
157
+ if n_image_tokens != n_image_features:
158
+ raise ValueError(
159
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
160
+ )
161
+ special_image_mask = (
162
+ (input_ids == self.config.image_token_index).unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
163
+ )
164
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
165
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
166
+
167
+ outputs = self.language_model.model(
168
+ attention_mask=attention_mask,
169
+ position_ids=position_ids,
170
+ past_key_values=past_key_values,
171
+ inputs_embeds=inputs_embeds,
172
+ use_cache=use_cache,
173
+ output_attentions=output_attentions,
174
+ output_hidden_states=output_hidden_states,
175
+ return_dict=return_dict,
176
+ )
177
+ hidden_states = outputs[0]
178
+
179
+ loss = None
180
+ logits = None
181
+
182
+ if self.training and (labels is not None):
183
+ # Shift so that tokens < n predict n
184
+ if attention_mask is not None:
185
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
186
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
187
+ shift_attention_mask = attention_mask[:, -(hidden_states.shape[1] - 1) :].to(hidden_states.device)
188
+ shift_hidden_states = hidden_states[..., :-1, :][
189
+ shift_attention_mask.to(hidden_states.device) != 0
190
+ ].contiguous()
191
+ shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
192
+ else:
193
+ shift_hidden_states = hidden_states[..., :-1, :].contiguous()
194
+ shift_labels = labels[..., 1:].contiguous()
195
+
196
+ lce = LigerFusedLinearCrossEntropyLoss()
197
+ loss = lce(self.language_model.lm_head.weight, shift_hidden_states, shift_labels)
198
+
199
+ if not return_dict:
200
+ # NOTE: This part has not been tested.
201
+ output = outputs[1:]
202
+ return (loss,) + output if loss is not None else output
203
+
204
+ return LlavaCausalLMOutputWithPast(
205
+ loss=loss,
206
+ logits=logits,
207
+ past_key_values=outputs.past_key_values,
208
+ hidden_states=outputs.hidden_states,
209
+ attentions=outputs.attentions,
210
+ )
211
+
212
+
213
+ @add_start_docstrings_to_model_forward(LLAVA_INPUTS_DOCSTRING)
214
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
215
+ @replace_return_docstrings(output_type=LlavaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
216
+ def lce_forward(
217
+ self,
218
+ input_ids: torch.LongTensor = None,
219
+ pixel_values: torch.FloatTensor = None,
220
+ attention_mask: Optional[torch.Tensor] = None,
221
+ position_ids: Optional[torch.LongTensor] = None,
222
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
223
+ inputs_embeds: Optional[torch.FloatTensor] = None,
224
+ vision_feature_layer: Optional[int] = None,
225
+ vision_feature_select_strategy: Optional[str] = None,
226
+ labels: Optional[torch.LongTensor] = None,
227
+ use_cache: Optional[bool] = None,
228
+ output_attentions: Optional[bool] = None,
229
+ output_hidden_states: Optional[bool] = None,
230
+ return_dict: Optional[bool] = None,
231
+ cache_position: Optional[torch.LongTensor] = None,
232
+ logits_to_keep: Union[int, torch.Tensor] = 0,
233
+ image_sizes: torch.Tensor = None,
234
+ **lm_kwargs,
235
+ ) -> Union[Tuple, LlavaCausalLMOutputWithPast]:
236
+ r"""
237
+ Args:
238
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
239
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
240
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
241
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
242
+
243
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
244
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
245
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
246
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
247
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
248
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
249
+
250
+
251
+ Returns:
252
+
253
+ Example:
254
+
255
+ ```python
256
+ >>> from PIL import Image
257
+ >>> import requests
258
+ >>> from transformers import AutoProcessor, LlavaForConditionalGeneration
259
+
260
+ >>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
261
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
262
+
263
+ >>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
264
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
265
+ >>> image = Image.open(requests.get(url, stream=True).raw)
266
+
267
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
268
+
269
+ >>> # Generate
270
+ >>> generate_ids = model.generate(**inputs, max_new_tokens=15)
271
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
272
+ "USER: \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
273
+ ```"""
274
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
275
+ output_hidden_states = (
276
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
277
+ )
278
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
279
+ vision_feature_layer = (
280
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
281
+ )
282
+ vision_feature_select_strategy = (
283
+ vision_feature_select_strategy
284
+ if vision_feature_select_strategy is not None
285
+ else self.config.vision_feature_select_strategy
286
+ )
287
+
288
+ if (input_ids is None) ^ (inputs_embeds is not None):
289
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
290
+
291
+ if pixel_values is not None and inputs_embeds is not None:
292
+ raise ValueError(
293
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
294
+ )
295
+
296
+ if inputs_embeds is None:
297
+ inputs_embeds = self.get_input_embeddings()(input_ids)
298
+
299
+ if pixel_values is not None:
300
+ image_features = self.get_image_features(
301
+ pixel_values=pixel_values,
302
+ vision_feature_layer=vision_feature_layer,
303
+ vision_feature_select_strategy=vision_feature_select_strategy,
304
+ image_sizes=image_sizes,
305
+ )
306
+
307
+ special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
308
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
309
+ if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
310
+ n_image_tokens = (input_ids == self.config.image_token_index).sum()
311
+ n_image_features = image_features.shape[0] * image_features.shape[1]
312
+ raise ValueError(
313
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
314
+ )
315
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
316
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
317
+
318
+ outputs = self.language_model.model(
319
+ attention_mask=attention_mask,
320
+ position_ids=position_ids,
321
+ past_key_values=past_key_values,
322
+ inputs_embeds=inputs_embeds,
323
+ use_cache=use_cache,
324
+ output_attentions=output_attentions,
325
+ output_hidden_states=output_hidden_states,
326
+ return_dict=return_dict,
327
+ cache_position=cache_position,
328
+ logits_to_keep=logits_to_keep,
329
+ **lm_kwargs,
330
+ )
331
+ hidden_states = outputs[0]
332
+
333
+ loss = None
334
+ logits = None
335
+
336
+ if self.training and (labels is not None):
337
+ # Shift so that tokens < n predict n
338
+ if attention_mask is not None:
339
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
340
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
341
+ shift_attention_mask = attention_mask[:, -(hidden_states.shape[1] - 1) :].to(hidden_states.device)
342
+ shift_hidden_states = hidden_states[..., :-1, :][
343
+ shift_attention_mask.to(hidden_states.device) != 0
344
+ ].contiguous()
345
+ shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
346
+ else:
347
+ shift_hidden_states = hidden_states[..., :-1, :].contiguous()
348
+ shift_labels = labels[..., 1:].contiguous()
349
+
350
+ lce = LigerFusedLinearCrossEntropyLoss()
351
+ loss = lce(
352
+ self.language_model.lm_head.weight,
353
+ shift_hidden_states.view(-1, shift_hidden_states.size(-1)),
354
+ shift_labels.view(-1).to(shift_hidden_states.device),
355
+ )
356
+
357
+ if not return_dict:
358
+ # NOTE: This part has not been tested.
359
+ output = outputs[1:]
360
+ return (loss,) + output if loss is not None else output
361
+
362
+ return LlavaCausalLMOutputWithPast(
363
+ loss=loss,
364
+ logits=logits,
365
+ past_key_values=outputs.past_key_values,
366
+ hidden_states=outputs.hidden_states,
367
+ attentions=outputs.attentions,
368
+ image_hidden_states=image_features if pixel_values is not None else None,
369
+ )
@@ -0,0 +1,57 @@
1
+ import torch.nn as nn
2
+
3
+ import liger_kernel.transformers.functional as F
4
+
5
+
6
+ def fixed_fused_linear_cross_entropy(
7
+ hidden_states,
8
+ lm_head_weight,
9
+ target,
10
+ num_items_in_batch: int = None,
11
+ ignore_index: int = -100,
12
+ **kwargs,
13
+ ):
14
+ reduction = "sum" if num_items_in_batch is not None else "mean"
15
+ loss = F.liger_fused_linear_cross_entropy(
16
+ hidden_states,
17
+ lm_head_weight,
18
+ target,
19
+ reduction=reduction,
20
+ ignore_index=ignore_index,
21
+ **kwargs,
22
+ )
23
+ if reduction == "sum":
24
+ loss = loss / num_items_in_batch
25
+
26
+ return loss
27
+
28
+
29
+ def LigerForCausalLMLoss(
30
+ hidden_states,
31
+ lm_head_weight,
32
+ labels,
33
+ hidden_size: int,
34
+ num_items_in_batch: int = None,
35
+ ignore_index: int = -100,
36
+ **kwargs,
37
+ ):
38
+ # Skip upcast since intermediate values for the loss are all fp32 in kernel
39
+ labels = labels.to(hidden_states.device)
40
+ # Shift so that token < n predict n
41
+ labels = nn.functional.pad(labels, (0, 1), value=ignore_index)
42
+ shift_labels = labels[..., 1:].contiguous()
43
+
44
+ # Flatten the tokens
45
+ hidden_states = hidden_states.view(-1, hidden_size)
46
+ shift_labels = shift_labels.view(-1)
47
+ # Enable model parallelism
48
+ shift_labels = shift_labels.to(hidden_states.device)
49
+ loss = fixed_fused_linear_cross_entropy(
50
+ hidden_states,
51
+ lm_head_weight,
52
+ shift_labels,
53
+ num_items_in_batch,
54
+ ignore_index,
55
+ **kwargs,
56
+ )
57
+ return loss
@@ -13,7 +13,7 @@ from transformers.models.mistral.modeling_mistral import MISTRAL_INPUTS_DOCSTRIN
13
13
  from transformers.utils import add_start_docstrings_to_model_forward
14
14
  from transformers.utils import replace_return_docstrings
15
15
 
16
- from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
16
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
17
17
 
18
18
 
19
19
  @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
@@ -31,6 +31,7 @@ def lce_forward(
31
31
  output_hidden_states: Optional[bool] = None,
32
32
  return_dict: Optional[bool] = None,
33
33
  cache_position: Optional[torch.LongTensor] = None,
34
+ **loss_kwargs,
34
35
  ) -> Union[Tuple, CausalLMOutputWithPast]:
35
36
  r"""
36
37
  Copy paste Mistral's forward but replace torch cross entropy with liger fused linear cross entropy
@@ -87,15 +88,13 @@ def lce_forward(
87
88
  logits = None
88
89
 
89
90
  if self.training and (labels is not None):
90
- shift_hidden_states = hidden_states[..., :-1, :].contiguous()
91
- shift_labels = labels[..., 1:].contiguous()
92
-
93
- # flatten tokens
94
- shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
95
- shift_labels = shift_labels.view(-1)
96
-
97
- lce = LigerFusedLinearCrossEntropyLoss()
98
- loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
91
+ loss = LigerForCausalLMLoss(
92
+ hidden_states=hidden_states,
93
+ lm_head_weight=self.lm_head.weight,
94
+ labels=labels,
95
+ hidden_size=self.config.hidden_size,
96
+ **loss_kwargs,
97
+ )
99
98
 
100
99
  else:
101
100
  logits = self.lm_head(hidden_states)