Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Keep Gemma embedding normalizer out of place for external inputs_embeds (#15308)

Daniel Han553c7e4f460c
diff --git a/tests/test_inputs_embeds_mask_gradients.py b/tests/test_inputs_embeds_mask_gradients.py
new file mode 100644
index 00000000000..490845d458a
--- /dev/null
+++ b/tests/test_inputs_embeds_mask_gradients.py
@@ -0,0 +1,150 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""External inputs_embeds from a trainable module must keep their graph through LlamaModel_fast_forward.
+
+With a frozen embedding table, the label-free (DPO) attention-mask branch and the Gemma normalizer
+used to detach a non-leaf inputs_embeds and scale it in place, so the projector that produced them
+got no gradient and the caller's tensor was overwritten.
+"""
+
+import math
+
+import pytest
+import torch
+import unsloth # noqa: F401
+
+from unsloth.models import llama as llama_module
+
+
+class _Captured(Exception):
+ pass
+
+
+class _CaptureHidden(torch.nn.Module):
+ def __init__(self, store):
+ super().__init__()
+ self.store = store
+
+ def extend_rope_embedding(self, hidden_states, *args, **kwargs):
+ self.store["hidden"] = hidden_states
+ raise _Captured
+
+
+def _model(model_type):
+ if model_type == "gemma":
+ from transformers import GemmaConfig as Config, GemmaModel as Model
+ else:
+ from transformers import LlamaConfig as Config, LlamaModel as Model
+ config = Config(
+ vocab_size = 64,
+ hidden_size = 16,
+ intermediate_size = 32,
+ num_hidden_layers = 1,
+ num_attention_heads = 2,
+ num_key_value_heads = 2,
+ head_dim = 8,
+ )
+ model = Model(config).train()
+ model.embed_tokens.weight.requires_grad_(False)
+ model.max_seq_length = 64
+ model._has_no_labels = True
+ return model
+
+
+def _forward(model, inputs_embeds, attention_mask):
+ store = {}
+ model.rotary_emb = _CaptureHidden(store)
+ with pytest.raises(_Captured):
+ llama_module.LlamaModel_fast_forward(
+ model,
+ inputs_embeds = inputs_embeds,
+ attention_mask = attention_mask,
+ use_cache = False,
+ )
+ return store["hidden"]
+
+
+def _scale(model):
+ if model.config.model_type.startswith("gemma") and not llama_module.embedding_applies_scale(
+ model.embed_tokens
+ ):
+ return math.sqrt(model.config.hidden_size)
+ return 1.0
+
+
[email protected]("model_type", ["llama", "gemma"])
+def test_projector_receives_gradient_through_masked_inputs_embeds(model_type):
+ torch.manual_seed(0)
+ model = _model(model_type)
+ projector = torch.nn.Linear(8, 16)
+ features = torch.randn(2, 5, 8)
+ attention_mask = torch.ones(2, 5, dtype = torch.long)
+ attention_mask[1, :2] = 0
+
+ inputs_embeds = projector(features)
+ original = inputs_embeds.detach().clone()
+ hidden = _forward(model, inputs_embeds, attention_mask)
+ weights = torch.randn_like(hidden)
+ (hidden * weights).sum().backward()
+
+ reference = torch.nn.Linear(8, 16)
+ reference.load_state_dict(projector.state_dict())
+ expected = reference(features) * _scale(model) * attention_mask.unsqueeze(-1)
+ (expected * weights).sum().backward()
+
+ assert projector.weight.grad is not None
+ assert torch.allclose(projector.weight.grad, reference.weight.grad, atol = 1e-5)
+ assert torch.allclose(hidden, expected, atol = 1e-5)
+ assert torch.equal(inputs_embeds.detach(), original)
+
+
+def test_float_mask_keeps_embedding_dtype():
+ model = _model("llama").to(torch.bfloat16)
+ inputs_embeds = torch.randn(2, 5, 16, dtype = torch.bfloat16)
+ attention_mask = torch.ones(2, 5, dtype = torch.float32)
+ attention_mask[0, :1] = 0
+ hidden = _forward(model, inputs_embeds, attention_mask)
+ assert hidden.dtype == torch.bfloat16
+ assert torch.equal(hidden[0, 0], torch.zeros(16, dtype = torch.bfloat16))
+
+
[email protected]("model_type", ["llama", "gemma"])
+def test_caller_leaf_inputs_embeds_get_gradient(model_type):
+ model = _model(model_type)
+ inputs_embeds = torch.randn(2, 5, 16, requires_grad = True)
+ original = inputs_embeds.detach().clone()
+ attention_mask = torch.ones(2, 5, dtype = torch.long)
+ attention_mask[0, :2] = 0
+ _forward(model, inputs_embeds, attention_mask).sum().backward()
+ expected = _scale(model) * attention_mask.unsqueeze(-1).expand(2, 5, 16).float()
+ assert torch.allclose(inputs_embeds.grad, expected)
+ assert torch.equal(inputs_embeds.detach(), original)
+
+
[email protected]("model_type", ["llama", "gemma"])
+def test_own_embedding_output_is_not_kept_for_backward(model_type):
+ import weakref
+
+ model = _model(model_type)
+ produced = []
+
+ def require_grad(module, args, output):
+ # What enable_input_require_grads does for frozen embeddings under LoRA.
+ output.requires_grad_(True)
+ produced.append(weakref.ref(output))
+
+ model.embed_tokens.register_forward_hook(require_grad)
+ store = {}
+ model.rotary_emb = _CaptureHidden(store)
+ with pytest.raises(_Captured):
+ llama_module.LlamaModel_fast_forward(
+ model,
+ input_ids = torch.randint(1, 64, (2, 5)),
+ attention_mask = torch.ones(2, 5, dtype = torch.long),
+ use_cache = False,
+ )
+ hidden = store["hidden"]
+ assert hidden.is_leaf and hidden.requires_grad
+ # Nothing beyond hidden itself may stay alive (base scaled it in place, so both are one tensor).
+ assert produced[0]() is None or produced[0]() is hidden
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index b4ac7ef2e40..8d82336f615 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -1290,6 +1290,14 @@ class Gemma2AttentionMaskConverter(AttentionMaskConverter):
)
+def _scale_inputs_embeds(inputs_embeds, factor, from_caller):
+ # A caller's or non-leaf tensor may carry a trainable graph: keep it, never write into it.
+ if from_caller or not inputs_embeds.is_leaf:
+ return inputs_embeds * factor
+ # Our own leaf has nothing upstream; detaching lets backward free it instead of holding it.
+ return (inputs_embeds.detach() * factor).requires_grad_(inputs_embeds.requires_grad)
+
+
# Ported from transformers models/llama/modeling_llama.py#L825
def LlamaModel_fast_forward(
self,
@@ -1392,6 +1400,7 @@ def LlamaModel_fast_forward(
if position_ids.shape[0] != batch_size:
position_ids = position_ids.repeat((batch_size, 1))
+ embeds_from_caller = inputs_embeds is not None
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
@@ -1409,20 +1418,7 @@ def LlamaModel_fast_forward(
if IS_GEMMA and not embedding_applies_scale(self.embed_tokens):
normalizer = torch.tensor(math_sqrt(self.config.hidden_size), dtype = inputs_embeds.dtype)
-
- if train_embed_tokens:
- # Careful: this must not be an inplace op.
- inputs_embeds = inputs_embeds * normalizer
- else:
- inputs_requires_grad = inputs_embeds.requires_grad
- if not inputs_embeds.is_leaf:
- inputs_embeds = inputs_embeds.detach()
- inputs_requires_grad = True
- elif inputs_requires_grad:
- inputs_embeds.requires_grad_(False)
- inputs_embeds *= normalizer
- if inputs_requires_grad:
- inputs_embeds.requires_grad_(True)
+ inputs_embeds = _scale_inputs_embeds(inputs_embeds, normalizer, embeds_from_caller)
# Fix up the attention mask by setting elements to 0, specifically for DPO.
if (
@@ -1435,8 +1431,9 @@ def LlamaModel_fast_forward(
):
# Careful: for inference the attention_mask is size (1, kv_seq_len) while input_embeds is (1, 1, 4096).
attention_mask = attention_mask[:, : self.max_seq_length] # Must resize!
- # Preserve the graph for external inputs_embeds without promoting their dtype.
- inputs_embeds = inputs_embeds * attention_mask.unsqueeze(-1).to(inputs_embeds.dtype)
+ # Cast so a float mask cannot promote bf16 embeddings to fp32.
+ embeds_mask = attention_mask.unsqueeze(-1).to(inputs_embeds.dtype)
+ inputs_embeds = _scale_inputs_embeds(inputs_embeds, embeds_mask, embeds_from_caller)
if attention_mask is None:
padding_mask = None