Skip to content
14 changes: 11 additions & 3 deletions src/transformers/loss/loss_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -46,23 +47,30 @@ def fixed_cross_entropy(
return loss


@use_kernel_func_from_hub("ForCausalLMLoss")
def ForCausalLMLoss(
logits,
labels,
vocab_size: int,
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)
Expand Down
25 changes: 21 additions & 4 deletions src/transformers/models/gemma2/modeling_gemma2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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__()
Expand Down Expand Up @@ -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"}
Expand Down Expand Up @@ -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,
Expand Down
19 changes: 17 additions & 2 deletions src/transformers/models/llama/modeling_llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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__()
Expand Down Expand Up @@ -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"}
Expand Down Expand Up @@ -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,
Expand Down
Loading