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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fix Gemma and Gemma2 embeddings scaled twice on transformers 5.4+ (#12116)
Daniel Han88d35ac2706e
diff --git a/tests/test_gemma_embed_scale.py b/tests/test_gemma_embed_scale.pynew file mode 100644index 00000000000..281efd99a7a--- /dev/null+++ b/tests/test_gemma_embed_scale.py@@ -0,0 +1,124 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Gemma / Gemma2 inputs are scaled by sqrt(hidden_size) exactly once, on every transformers version."""++import types++import pytest++import unsloth # noqa: F401 (must precede transformers)+from unsloth.models._utils import embedding_applies_scale+from real_accelerator import has_real_cuda++torch = pytest.importorskip("torch")+++class _Scaled(torch.nn.Embedding):+ def __init__(self):+ super().__init__(4, 2)+ self.register_buffer("embed_scale", torch.tensor(2.0), persistent = False)+++def test_embedding_applies_scale_detection():+ assert embedding_applies_scale(torch.nn.Embedding(4, 2)) is False+ assert embedding_applies_scale(_Scaled()) is True+ assert embedding_applies_scale(None) is False+ assert embedding_applies_scale(types.SimpleNamespace(base_layer = _Scaled())) is True+ assert embedding_applies_scale(types.SimpleNamespace(original_module = _Scaled())) is True+ assert (+ embedding_applies_scale(types.SimpleNamespace(base_layer = torch.nn.Embedding(4, 2))) is False+ )++[email protected]("arch", ["gemma", "gemma2"])+def test_detection_tracks_installed_transformers(arch):+ module = pytest.importorskip(f"transformers.models.{arch}.modeling_{arch}")+ config_cls = getattr(module, "GemmaConfig" if arch == "gemma" else "Gemma2Config", None)+ if config_cls is None:+ from transformers import GemmaConfig, Gemma2Config+ config_cls = GemmaConfig if arch == "gemma" else Gemma2Config+ config = config_cls(+ vocab_size = 32,+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 1,+ num_attention_heads = 2,+ num_key_value_heads = 1,+ head_dim = 8,+ )+ model = getattr(module, "GemmaModel" if arch == "gemma" else "Gemma2Model")(config)+ ids = torch.tensor([[1, 2, 3]])+ raw = torch.nn.functional.embedding(ids, model.embed_tokens.weight)+ scales_itself = not torch.equal(model.embed_tokens(ids), raw)+ assert embedding_applies_scale(model.embed_tokens) is scales_itself+++def _tiny_checkpoint(path, repo):+ # The hub tiny Gemma uses head_dim 2, which no xformers kernel takes; keep its config and tokenizer, widen heads.+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer++ config = AutoConfig.from_pretrained(repo)+ config.update(+ dict(+ hidden_size = 64,+ intermediate_size = 128,+ num_attention_heads = 2,+ num_key_value_heads = 1,+ head_dim = 32,+ )+ )+ torch.manual_seed(0)+ AutoModelForCausalLM.from_config(config).save_pretrained(path)+ AutoTokenizer.from_pretrained(repo).save_pretrained(path)+ return str(path)+++ not has_real_cuda(), reason = "loads tiny Gemma checkpoints through FastLanguageModel on CUDA"+)+ "repo, module_name",+ [+ ("trl-internal-testing/tiny-GemmaForCausalLM", "unsloth.models.gemma"),+ ("trl-internal-testing/tiny-Gemma2ForCausalLM", "unsloth.models.gemma2"),+ ],+)+def test_prefill_and_decode_scale_once(monkeypatch, tmp_path, repo, module_name):+ import importlib+ from unsloth import FastLanguageModel++ model, _ = FastLanguageModel.from_pretrained(+ _tiny_checkpoint(tmp_path, repo), max_seq_length = 64, load_in_4bit = False, dtype = torch.float32+ )+ FastLanguageModel.for_inference(model)+ hidden = model.config.hidden_size+ weight = model.get_input_embeddings().weight.detach()+ expected = lambda ids: torch.nn.functional.embedding(ids, weight) * torch.tensor(+ hidden**0.5, dtype = weight.dtype+ )++ prefill = {}++ def capture(mod, args, kwargs):+ prefill.setdefault("x", (args[0] if args else kwargs["hidden_states"]).detach())++ model.model.layers[0].register_forward_pre_hook(capture, with_kwargs = True)+ decode = []+ mod = importlib.import_module(module_name)+ original = mod.fast_rms_layernorm_inference_gemma+ # The first norm of each decode step sees the scaled embeddings (residual stream input).+ monkeypatch.setattr(+ mod,+ "fast_rms_layernorm_inference_gemma",+ lambda ln, x, *a, **k: (decode.append(x.detach().clone()), original(ln, x, *a, **k))[1],+ )+ ids = torch.tensor([[2, 10, 11, 12, 13]], device = "cuda")+ out = model.generate(+ input_ids = ids, attention_mask = torch.ones_like(ids), max_new_tokens = 2, do_sample = False+ )+ torch.testing.assert_close(prefill["x"], expected(ids), rtol = 1e-5, atol = 1e-5)+ assert decode, "decode path did not run"+ torch.testing.assert_close(+ decode[0], expected(out[:, ids.shape[1] : ids.shape[1] + 1]), rtol = 1e-5, atol = 1e-5+ )diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 17f48bd6d28..ff0c37d0bc1 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -3992,6 +3992,19 @@ def _accelerate_execution_device(module):return device+def embedding_applies_scale(embedding) -> bool:+ """True if the embedding applies sqrt(hidden_size) itself (Gemma / Gemma2 from transformers 5.4.0), through PEFT wrappers."""+ for _ in range(4):+ if embedding is None:+ return False+ if getattr(embedding, "embed_scale", None) is not None:+ return True+ embedding = getattr(embedding, "base_layer", None) or getattr(+ embedding, "original_module", None+ )+ return False++def per_layer_device(module, default = 0):"""Where this decoder layer lives, as (device, buffer_index); gemma, gemma2 and coherestill need the index, to subscript a per-device tuple. Probed, not version-gated: an olderdiff --git a/unsloth/models/gemma.py b/unsloth/models/gemma.pyindex ef3f2a8a80f..ad68d84a162 100644--- a/unsloth/models/gemma.py+++ b/unsloth/models/gemma.py@@ -12,7 +12,7 @@from .llama import *from .llama import _get_rope_thetafrom ._utils import __version__-from ._utils import move_to_device, per_layer_device+from ._utils import move_to_device, per_layer_device, embedding_applies_scalefrom unsloth_zoo.utils import _get_dtype, Versionfrom unsloth_zoo.hf_utils import dtype_from_configfrom ..utils.packing import (@@ -169,7 +169,8 @@ def GemmaModel_fast_forward_inference(hidden_states = self.model.embed_tokens(input_ids)hidden_states = hidden_states.to(_get_dtype(dtype_from_config(self.config)))# 3072**0.5 is 55.5000 in bfloat16 against 55.4256 in float32, and 2048**0.5 is 45.2500 against 45.2548.- hidden_states *= torch.tensor(math_sqrt(self.config.hidden_size), dtype = hidden_states.dtype)+ if not embedding_applies_scale(self.model.embed_tokens):+ hidden_states *= torch.tensor(math_sqrt(self.config.hidden_size), dtype = hidden_states.dtype)bsz, q_len, hd = hidden_states.shapeseq_len = past_key_values[0][0].shape[-2]diff --git a/unsloth/models/gemma2.py b/unsloth/models/gemma2.pyindex 916bb27f6ee..a9bd96821b2 100644--- a/unsloth/models/gemma2.py+++ b/unsloth/models/gemma2.py@@ -19,6 +19,7 @@ from ._utils import move_to_device, per_layer_device, DEVICE_TYPEfrom unsloth_zoo.utils import _get_dtype, Versionfrom unsloth_zoo.hf_utils import dtype_from_configfrom ..utils.packing import get_packed_info_from_kwargs+from ._utils import embedding_applies_scalefrom ..utils.attention_dispatch import (AttentionConfig,AttentionContext,@@ -529,7 +530,8 @@ def Gemma2Model_fast_forward_inference(hidden_states = self.model.embed_tokens(input_ids)hidden_states = hidden_states.to(_get_dtype(dtype_from_config(self.config)))# 3072**0.5 is 55.5000 in bfloat16 against 55.4256 in float32, and 2048**0.5 is 45.2500 against 45.2548.- hidden_states *= torch.tensor(math_sqrt(self.config.hidden_size), dtype = hidden_states.dtype)+ if not embedding_applies_scale(self.model.embed_tokens):+ hidden_states *= torch.tensor(math_sqrt(self.config.hidden_size), dtype = hidden_states.dtype)bsz, q_len, hd = hidden_states.shapeseq_len = past_key_values[0][0].shape[-2]diff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex 76af64068d7..ff83c94620a 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -23,6 +23,7 @@ from ._utils import apply_unsloth_gradient_checkpointingfrom ._utils import __version__, importlib_versionfrom ._utils import move_to_devicefrom ._utils import per_layer_device+from ._utils import embedding_applies_scalefrom ._utils import (_get_inference_mode_context_manager,_prepare_model_for_qat,@@ -970,7 +971,7 @@ def LlamaModel_fast_forward(train_embed_tokens = self.embed_tokens.weight.requires_grad- if IS_GEMMA:+ 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: