diff --git a/src/transformers/loss/loss_utils.py b/src/transformers/loss/loss_utils.py index 92c0bd0637e5..7c272ab208c4 100644 --- a/src/transformers/loss/loss_utils.py +++ b/src/transformers/loss/loss_utils.py @@ -17,6 +17,7 @@ import torch.nn as nn from torch.nn import BCEWithLogitsLoss, MSELoss +from ..integrations import use_kernel_func_from_hub from .loss_d_fine import DFineForObjectDetectionLoss from .loss_deformable_detr import DeformableDetrForObjectDetectionLoss, DeformableDetrForSegmentationLoss from .loss_deimv2 import Deimv2ForObjectDetectionLoss @@ -46,6 +47,7 @@ def fixed_cross_entropy( return loss +@use_kernel_func_from_hub("ForCausalLMLoss") def ForCausalLMLoss( logits, labels, @@ -53,16 +55,22 @@ def ForCausalLMLoss( num_items_in_batch: torch.Tensor | None = None, ignore_index: int = -100, shift_labels: torch.Tensor | None = None, + hidden_states: torch.Tensor | None = None, + lm_head_weight: torch.Tensor | None = None, + lm_head_bias: torch.Tensor | None = None, **kwargs, ) -> torch.Tensor: - # Upcast to float if we need to compute the loss to avoid potential precision issues - logits = logits.float() - if shift_labels is None: # Shift so that tokens < n predict n labels = nn.functional.pad(labels, (0, 1), value=ignore_index) shift_labels = labels[..., 1:].contiguous() + if logits is None and hidden_states is not None and lm_head_weight is not None: + logits = nn.functional.linear(hidden_states, lm_head_weight, lm_head_bias) + + # Upcast to float if we need to compute the loss to avoid potential precision issues + logits = logits.float() + # Flatten the tokens logits = logits.view(-1, vocab_size) shift_labels = shift_labels.view(-1) diff --git a/src/transformers/models/gemma2/modeling_gemma2.py b/src/transformers/models/gemma2/modeling_gemma2.py index 20673571b2d2..0e1498635a02 100644 --- a/src/transformers/models/gemma2/modeling_gemma2.py +++ b/src/transformers/models/gemma2/modeling_gemma2.py @@ -28,7 +28,8 @@ from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...generation import GenerationMixin -from ...integrations import use_kernel_func_from_hub, use_kernelized_func +from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func +from ...loss.loss_utils import ForCausalLMLoss from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask from ...modeling_flash_attention_utils import FlashAttentionKwargs from ...modeling_layers import ( @@ -66,6 +67,7 @@ def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.eps}" +@use_kernel_forward_from_hub("GeGLUMLP") class Gemma2MLP(nn.Module): def __init__(self, config): super().__init__() @@ -473,6 +475,7 @@ def forward( ) +@use_kernelized_func(ForCausalLMLoss) @auto_docstring class Gemma2ForCausalLM(Gemma2PreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} @@ -533,15 +536,29 @@ def forward( hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep - logits = self.lm_head(hidden_states[:, slice_indices, :]) - if self.config.final_logit_softcapping is not None: + hidden_states = hidden_states[:, slice_indices, :] + + # We only compute logits during inference (no labels given) or when we do not use any kernel (materialization of logits needed) + logits = self.lm_head(hidden_states) if labels is None or not self.use_kernels else None + + if logits is not None and self.config.final_logit_softcapping is not None: logits = logits / self.config.final_logit_softcapping logits = torch.tanh(logits) logits = logits * self.config.final_logit_softcapping loss = None if labels is not None: - loss = self.loss_function(logits, labels, self.vocab_size, **kwargs) + loss = self.loss_function( + hidden_states=hidden_states, + lm_head_weight=self.lm_head.weight, + lm_head_bias=self.lm_head.bias, + logits=logits, + labels=labels, + vocab_size=self.config.vocab_size, + hidden_size=hidden_states.shape[-1], + final_logit_softcapping=self.config.final_logit_softcapping, + **kwargs, + ) return CausalLMOutputWithPast( loss=loss, diff --git a/src/transformers/models/llama/modeling_llama.py b/src/transformers/models/llama/modeling_llama.py index 9d659c7c6f08..dd3e2f546884 100644 --- a/src/transformers/models/llama/modeling_llama.py +++ b/src/transformers/models/llama/modeling_llama.py @@ -26,6 +26,7 @@ from ...cache_utils import Cache, DynamicCache from ...generation import GenerationMixin from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func +from ...loss.loss_utils import ForCausalLMLoss from ...masking_utils import create_causal_mask from ...modeling_layers import ( GenericForQuestionAnswering, @@ -168,6 +169,7 @@ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): return q_embed, k_embed +@use_kernel_forward_from_hub("SwiGLUMLP") class LlamaMLP(nn.Module): def __init__(self, config): super().__init__() @@ -425,6 +427,7 @@ def forward( ) +@use_kernelized_func(ForCausalLMLoss) @auto_docstring class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} @@ -484,11 +487,23 @@ def forward( hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep - logits = self.lm_head(hidden_states[:, slice_indices, :]) + hidden_states = hidden_states[:, slice_indices, :] + + # We only compute logits during inference (no labels given) or when we do not use any kernel (materialization of logits needed) + logits = self.lm_head(hidden_states) if labels is None or not self.use_kernels else None loss = None if labels is not None: - loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) + loss = self.loss_function( + hidden_states=hidden_states, + lm_head_weight=self.lm_head.weight, + lm_head_bias=self.lm_head.bias, + logits=logits, + labels=labels, + vocab_size=self.config.vocab_size, + hidden_size=hidden_states.shape[-1], + **kwargs, + ) return CausalLMOutputWithPast( loss=loss,