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.

Apply the logit scale on the fused cross entropy path (#11277)

Vineeth Sai Varikuntla917af389473e
diff --git a/tests/python/test_grpo_ddp_model_config.py b/tests/python/test_grpo_ddp_model_config.py
index 64367c74ced..4078029b2f2 100644
--- a/tests/python/test_grpo_ddp_model_config.py
+++ b/tests/python/test_grpo_ddp_model_config.py
@@ -20,11 +20,16 @@ def test_grpo_logit_scaling_uses_model_config_helper():
assert "logit_softcapping = _unsloth_get_final_logit_softcapping(model)" in src
assert "if config is None:" in src.split("def _unsloth_get_final_logit_softcapping")[1]
# Logit scale/divide read through the unwrapped config, not bare model.config.
- assert 'getattr(model_config, "logit_scale", 0)' in src
- assert 'getattr(model_config, "logits_scaling", 0)' in src
+ # Whitespace-insensitive: the formatter wraps one of the two calls and not the other.
+ flat = "".join(src.split())
+ assert (
+ flat.count("=_unsloth_resolve_logit_scales(model_config)") == 2
+ ), "both fallback arms must resolve the scales from the unwrapped config"
+ assert "_unsloth_resolve_logit_scales(model)" not in flat
assert src.count("model_config = _unsloth_get_model_config(model)") >= 2
# Helper source is injected into the compiled GRPO trainer.
assert "inspect.getsource(_unsloth_get_model_config)" in src
+ assert "inspect.getsource(_unsloth_resolve_logit_scales)" in src
# No direct model.config access remains in the RL logit path.
assert "model.config" not in src
diff --git a/tests/python/test_grpo_logit_transform_fallback.py b/tests/python/test_grpo_logit_transform_fallback.py
new file mode 100644
index 00000000000..36002865ebc
--- /dev/null
+++ b/tests/python/test_grpo_logit_transform_fallback.py
@@ -0,0 +1,167 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team.
+"""The GRPO fallback must answer the same as ``detect_logit_transforms``.
+
+The fallback is inlined into two GRPO bodies by ``inspect.getsource``, so it cannot be
+imported: lift each ``else:`` arm out with ast and run it. A wrong factor here does not
+raise, it shifts every log-prob and with it the importance ratio.
+"""
+
+from __future__ import annotations
+
+import ast
+import inspect
+from pathlib import Path
+
+import pytest
+
+import unsloth.models.rl_replacements as rl
+
+
+SOURCE = Path(inspect.getfile(rl)).read_text(encoding = "utf-8")
+GUARD = "detect_logit_transforms is not None"
+
+
+def _fallback_blocks():
+ """Every `else:` arm of an `if detect_logit_transforms is not None:` in the file."""
+ tree = ast.parse(SOURCE)
+ blocks = {}
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.If) or not node.orelse:
+ continue
+ if ast.unparse(node.test).strip() != GUARD:
+ continue
+ enclosing = next(
+ fn.name
+ for fn in ast.walk(tree)
+ if isinstance(fn, ast.FunctionDef)
+ and fn.lineno <= node.lineno <= (fn.end_lineno or node.lineno)
+ )
+ blocks[f"{enclosing}:{node.lineno}"] = ast.Module(body = node.orelse, type_ignores = [])
+ return blocks
+
+
+BLOCKS = _fallback_blocks()
+
+
+def test_both_grpo_call_sites_were_found():
+ """A rename would otherwise make this whole file silently vacuous."""
+ assert len(BLOCKS) == 2, f"expected two fallback arms, found {sorted(BLOCKS)}"
+
+
+class _Cfg:
+ def __init__(self, **fields):
+ for key, value in fields.items():
+ setattr(self, key, value)
+
+
+class _Model:
+ def __init__(self, config):
+ self.config = config
+
+
+def _run(block, config):
+ namespace = {
+ "model_config": config,
+ # The real readers, not stubs: a stub would pass while the shipped fallback drops
+ # a field. The soft-cap one takes a model, so hand it one carrying this config.
+ "model": _Model(config),
+ "_unsloth_get_final_logit_softcapping": rl._unsloth_get_final_logit_softcapping,
+ "_unsloth_resolve_logit_scales": rl._unsloth_resolve_logit_scales,
+ }
+ exec(compile(block, "<fallback>", "exec"), namespace)
+ return (
+ namespace["logit_softcapping"],
+ namespace["logit_scale_multiply"],
+ namespace["logit_scale_divide"],
+ )
+
+
+_CASES = [
+ (
+ "granite",
+ _Cfg(model_type = "granite", logits_scaling = 8.0),
+ (0, 0, 8.0),
+ "modeling_granite.py divides by logits_scaling",
+ ),
+ (
+ "cohere",
+ _Cfg(model_type = "cohere", logit_scale = 0.0625),
+ (0, 0.0625, 0),
+ "modeling_cohere.py multiplies by logit_scale",
+ ),
+ (
+ "falcon_h1",
+ _Cfg(model_type = "falcon_h1", lm_head_multiplier = 0.01953125),
+ (0, 0.01953125, 0),
+ "the scale is spelled lm_head_multiplier, and was dropped entirely",
+ ),
+ (
+ "hyperclovax",
+ _Cfg(model_type = "hyperclovax", logits_scaling = 8.0),
+ (0, 8.0, 0),
+ "MuP multiplies by logits_scaling, unlike Granite which divides",
+ ),
+ (
+ "minicpm3",
+ _Cfg(model_type = "minicpm3", logits_scaling = 8.0),
+ (0, 0, 0),
+ "logits_scaling scales the hidden states before the head, not the logits",
+ ),
+ (
+ "llama",
+ _Cfg(model_type = "llama"),
+ (0, 0, 0),
+ "no transform, and no attribute to read either",
+ ),
+ (
+ "muse_glimmer",
+ _Cfg(model_type = "muse_glimmer", output_multiplier = 2.0, final_logit_softcapping = 30.0),
+ (30.0, 2.0, 0),
+ "output_multiplier multiplies, and this family soft caps as well",
+ ),
+ (
+ "recurrentgemma",
+ _Cfg(model_type = "recurrentgemma", logits_soft_cap = 30.0),
+ (30.0, 0, 0),
+ "the soft cap is spelled logits_soft_cap here",
+ ),
+ (
+ "xlstm",
+ _Cfg(model_type = "xlstm", output_logit_soft_cap = 30.0),
+ (30.0, 0, 0),
+ "the soft cap is spelled output_logit_soft_cap here",
+ ),
+ (
+ "null fields",
+ _Cfg(model_type = None, logit_scale = None, logits_scaling = None),
+ (0, 0, 0),
+ "None must read as off rather than reach the loss",
+ ),
+]
+
+
[email protected]("site", sorted(BLOCKS))
[email protected]("name, config, expected, why", _CASES)
+def test_fallback_matches_the_planner(site, name, config, expected, why):
+ assert _run(BLOCKS[site], config) == expected, f"{site}: {why}"
+
+
[email protected]("name, config, expected, why", _CASES)
+def test_fallback_agrees_with_detect_logit_transforms(name, config, expected, why):
+ """The two arms must not disagree, or the answer depends on the zoo version."""
+ detect = pytest.importorskip(
+ "unsloth_zoo.device_map_planner",
+ reason = "unsloth_zoo without the planner",
+ ).__dict__.get("detect_logit_transforms")
+ if detect is None:
+ pytest.skip("installed unsloth_zoo predates detect_logit_transforms")
+ transforms = detect(config)
+ planner = (
+ transforms["logit_softcapping"],
+ transforms["logit_scale_multiply"],
+ transforms["logit_scale_divide"],
+ )
+ if planner != expected:
+ pytest.skip(f"installed unsloth_zoo predates {name} coverage")
+ assert _run(BLOCKS[sorted(BLOCKS)[0]], config) == planner, why
diff --git a/tests/test_fused_ce_logit_scale.py b/tests/test_fused_ce_logit_scale.py
new file mode 100644
index 00000000000..fc00825171e
--- /dev/null
+++ b/tests/test_fused_ce_logit_scale.py
@@ -0,0 +1,364 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Every loss branch must apply the logit transforms the reference implementation does.
+
+Cohere multiplies by logit_scale, Granite divides by logits_scaling; dropping either
+optimizes a different loss. Pure torch, so it runs on CPU.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import torch
+import torch.nn.functional as F
+from transformers import (
+ CohereConfig,
+ Gemma2Config,
+ GraniteConfig,
+ MistralConfig,
+)
+
+try:
+ from transformers import FalconH1Config
+except ImportError:
+ # Absent before transformers 4.53, and the declared floor is 4.51.3. A module-scope
+ # import would cost the whole file, not just the Falcon-H1 cases.
+ FalconH1Config = None
+from transformers.modeling_outputs import BaseModelOutputWithPast
+
+import pytest
+
+import unsloth.models.llama as llama_module
+import unsloth.models.mistral as mistral_module
+from unsloth.models.llama import (
+ apply_logit_transforms,
+ CausalLM_fast_forward,
+ resolve_logit_transforms,
+)
+from unsloth.models.mistral import MistralForCausalLM_fast_forward
+
+
+VOCAB_SIZE = 8
+HIDDEN_SIZE = 4
+BSZ = 2
+Q_LEN = 4
+LABELS = torch.tensor([[0, 1, 2, 3], [4, 5, 6, 7]])
+
+
+def _hidden_states():
+ """Deterministic without a seed, so the expected value survives a PRNG change."""
+ values = torch.arange(BSZ * Q_LEN * HIDDEN_SIZE, dtype = torch.float32)
+ return ((values % 7) - 3.0).reshape(BSZ, Q_LEN, HIDDEN_SIZE)
+
+
+def _lm_head_weight():
+ values = torch.arange(VOCAB_SIZE * HIDDEN_SIZE, dtype = torch.float32)
+ return ((values % 5) - 2.0).reshape(VOCAB_SIZE, HIDDEN_SIZE)
+
+
+class _FakeModel:
+ """Stands in for the decoder stack: the branch under test only reads outputs[0]."""
+
+ def __init__(self, hidden_states):
+ self.hidden_states = hidden_states
+
+ def __call__(self, **kwargs):
+ return BaseModelOutputWithPast(
+ last_hidden_state = self.hidden_states,
+ past_key_values = None,
+ hidden_states = None,
+ attentions = None,
+ )
+
+
+class _FakeCausalLM:
+ # mistral.py reads self.training before either loss branch; without this the tests
+ # pass or error depending on which attention backend a previous test selected.
+ training = False
+
+ def __init__(self, config):
+ self.config = config
+ self.model = _FakeModel(_hidden_states())
+ self.lm_head = torch.nn.Linear(HIDDEN_SIZE, VOCAB_SIZE, bias = False)
+ with torch.no_grad():
+ self.lm_head.weight.copy_(_lm_head_weight())
+
+
+def _fused_loss(
+ config,
+ monkeypatch,
+ forward = None,
+):
+ monkeypatch.delenv("UNSLOTH_RETURN_LOGITS", raising = False)
+ monkeypatch.delenv("UNSLOTH_RETURN_HIDDEN_STATES", raising = False)
+ extra = {}
+ if forward is None:
+ forward = CausalLM_fast_forward(None)
+ else:
+ # mistral.py reads input_ids.shape before it reaches the decoder stack.
+ extra["input_ids"] = torch.zeros(BSZ, Q_LEN, dtype = torch.long)
+ output = forward(_FakeCausalLM(config), labels = LABELS.clone(), return_dict = True, **extra)
+ return output.loss.item()
+
+
+def _reference_loss(scale, softcapping = 0.0):
+ """Transformers' own order: scale the logits, soft cap, shift, then cross entropy.
+
+ Computed in float64 so the expected value is the arithmetic, not the float32 path.
+ """
+ logits = F.linear(_hidden_states().double(), _lm_head_weight().double())
+ logits = logits * scale
+ if softcapping:
+ logits = softcapping * torch.tanh(logits / softcapping)
+ shifted = torch.empty_like(LABELS)
+ shifted[..., :-1] = LABELS[..., 1:]
+ shifted[..., -1] = -100
+ loss = F.cross_entropy(logits.reshape(-1, VOCAB_SIZE), shifted.reshape(-1))
+ return loss.item()
+
+
+def _config(cls, **kwargs):
+ """Deferred: transformers validates strictly and per release, so eager construction
+ turns one unconstructable class into a collection error for the whole file."""
+
+ def build():
+ if cls is None:
+ pytest.skip("this transformers predates the model this case needs")
+ try:
+ return cls(
+ hidden_size = HIDDEN_SIZE,
+ intermediate_size = 2 * HIDDEN_SIZE,
+ num_hidden_layers = 1,
+ num_attention_heads = 2,
+ vocab_size = VOCAB_SIZE,
+ **kwargs,
+ )
+ except Exception as error:
+ pytest.skip(f"{cls.__name__} does not accept this shape here: {error}")
+
+ build.cls = cls
+ return build
+
+
+ "config,scale",
+ [
+ # Cohere / Command-R / Aya multiply, Granite 3 divides.
+ (_config(CohereConfig, logit_scale = 0.0625), 0.0625),
+ (_config(GraniteConfig, logits_scaling = 4.0), 1.0 / 4.0),
+ ],
+ ids = ["cohere", "granite"],
+)
+def test_fused_ce_applies_the_configured_logit_scale(config, scale, monkeypatch):
+ config = config()
+ unscaled = _reference_loss(1.0) # 7.898634, what the fused branch returns unfixed
+ expected = _reference_loss(scale)
+ assert abs(expected - unscaled) > 1.0, "the fixture no longer separates the two losses"
+
+ # float32 accumulation over 8 logits, so well inside the default float32 tolerance.
+ assert _fused_loss(config, monkeypatch) == pytest.approx(expected, rel = 1e-6), (
+ f"fused CE dropped {config.model_type}'s logit scale: it returns the unscaled "
+ f"{unscaled:.6f} instead of {expected:.6f}"
+ )
+
+
+def test_fused_ce_applies_falcon_h1_multiplier_once(monkeypatch):
+ """The multiplier is folded into the hidden states, so it must not scale the logits too."""
+ config = _config(FalconH1Config, lm_head_multiplier = 3.0)()
+ assert _fused_loss(config, monkeypatch) == pytest.approx(_reference_loss(3.0), rel = 1e-6)
+
+
+def test_mistral_fused_ce_reads_the_transforms_the_same_way(monkeypatch):
+ """No shipped Mistral config carries a scale, so one is injected: the point is that
+ the call site forwards what the config holds, not that Mistral needs it."""
+ plain = _config(MistralConfig)()
+ assert _fused_loss(plain, monkeypatch, MistralForCausalLM_fast_forward) == pytest.approx(
+ _reference_loss(1.0),
+ rel = 1e-6,
+ ), "plain Mistral carries no transform and must be unaffected"
+
+ scaled = _config(MistralConfig)()
+ scaled.logit_scale = 0.0625
+ assert _fused_loss(scaled, monkeypatch, MistralForCausalLM_fast_forward) == pytest.approx(
+ _reference_loss(0.0625),
+ rel = 1e-6,
+ ), "mistral.py's fused branch dropped the configured logit scale"
+
+
+ "config,expected",
+ [
+ (_config(CohereConfig, logit_scale = 0.0625), (0, 0.0625, 0)),
+ (_config(GraniteConfig, logits_scaling = 4.0), (0, 0, 4.0)),
+ # The exact model_type test the fallback used to do missed the MoE spellings.
+ (_config(GraniteConfig, logits_scaling = 4.0, model_type = "granitemoe"), (0, 0, 4.0)),
+ (_config(FalconH1Config, lm_head_multiplier = 3.0), (0, 3.0, 0)),
+ ],
+ ids = ["cohere", "granite", "granitemoe", "falcon_h1"],
+)
+def test_transforms_resolve_without_unsloth_zoo(config, expected, monkeypatch):
+ config = config()
+ """The fallback arm runs whenever unsloth_zoo predates detect_logit_transforms."""
+ monkeypatch.setattr(llama_module, "detect_logit_transforms", None)
+ # Both arms agree on these configs, so without this the coverage could evaporate
+ # silently if the patch stopped reaching the code under test.
+ assert llama_module.detect_logit_transforms is None
+ assert resolve_logit_transforms(config) == pytest.approx(expected)
+
+
+ "model_type,fields",
+ [
+ ("cohere", {"logit_scale": 0.0625}),
+ ("granite", {"logits_scaling": 8.0}),
+ ("granitemoehybrid", {"logits_scaling": 8.0}),
+ ("falcon_h1", {"lm_head_multiplier": 3.0}),
+ # logits_scaling multiplies here (MuP), the opposite of Granite.
+ ("hyperclovax", {"logits_scaling": 4.0}),
+ # logits_scaling scales the hidden states, so it is not a logit transform.
+ ("minicpm3", {"logits_scaling": 4.0}),
+ ("gemma2", {"final_logit_softcapping": 30.0}),
+ # The softcap spellings only the planner's table knows.
+ ("recurrentgemma", {"logits_soft_cap": 30.0}),
+ ("xlstm", {"output_logit_soft_cap": 30.0}),
+ ("muse_glimmer", {"output_multiplier": 2.0, "final_logit_softcapping": 30.0}),
+ ],
+)
+def test_both_resolver_arms_agree(model_type, fields, monkeypatch):
+ """An old unsloth_zoo must not train a different loss than a new one.
+
+ The fallback arm is only reached when the installed unsloth_zoo predates
+ detect_logit_transforms, which is exactly when nobody would notice it disagreeing.
+ """
+
+ def build():
+ config = MistralConfig(
+ hidden_size = HIDDEN_SIZE,
+ intermediate_size = 2 * HIDDEN_SIZE,
+ num_hidden_layers = 1,
+ num_attention_heads = 2,
+ vocab_size = VOCAB_SIZE,
+ )
+ config.model_type = model_type
+ for name, value in fields.items():
+ setattr(config, name, value)
+ return config
+
+ planner = llama_module.detect_logit_transforms
+ if planner is None:
+ pytest.skip("this unsloth_zoo predates detect_logit_transforms")
+ with_planner = resolve_logit_transforms(build())
+
+ monkeypatch.setattr(llama_module, "detect_logit_transforms", None)
+ without_planner = resolve_logit_transforms(build())
+
+ assert without_planner == pytest.approx(with_planner), (
+ f"the two arms disagree on {model_type}: the planner says {with_planner}, "
+ f"the fallback says {without_planner}"
+ )
+
+
+ "model_type,field",
+ [
+ ("cohere", "logit_scale"),
+ ("granite", "logits_scaling"),
+ ("falcon_h1", "lm_head_multiplier"),
+ ("gemma2", "final_logit_softcapping"),
+ ],
+)
+def test_a_none_valued_field_resolves_to_zero(model_type, field, monkeypatch):
+ """None must read as "off". A namespace, not a config: transformers 5 rejects None at
+ construction, but a checkpoint carrying one still loads into an older config."""
+ monkeypatch.setattr(llama_module, "detect_logit_transforms", None)
+ config = SimpleNamespace(model_type = model_type, **{field: None})
+ assert resolve_logit_transforms(config) == (0, 0, 0)
+
+
+def test_a_none_model_type_does_not_raise(monkeypatch):
+ """Remote-code configs do set model_type to None, and `in`-style reads must survive it."""
+ monkeypatch.setattr(llama_module, "detect_logit_transforms", None)
+ config = _config(CohereConfig, logit_scale = 0.0625)()
+ config.model_type = None
+ assert resolve_logit_transforms(config) == (0, 0.0625, 0)
+
+
+def _inference_logits(model, forward):
+ extra = {"input_ids": torch.zeros(BSZ, Q_LEN, dtype = torch.long)} if forward else {}
+ forward = forward or CausalLM_fast_forward(None)
+ return forward(model, labels = None, return_dict = True, **extra).logits
+
+
+_SCALE_CASES = [
+ (_config(CohereConfig, logit_scale = 0.0625), 0.0625, 0.0),
+ # Granite exercises the divisor fold, which the fused branch never takes.
+ (_config(GraniteConfig, logits_scaling = 4.0), 1.0 / 4.0, 0.0),
+ (_config(Gemma2Config, final_logit_softcapping = 4.0), 1.0, 4.0),
+]
+_SCALE_IDS = ["cohere", "granite", "gemma2_softcap"]
+
+
+ "forward", [None, MistralForCausalLM_fast_forward], ids = ["llama", "mistral"]
+)
[email protected]("config,scale,softcapping", _SCALE_CASES, ids = _SCALE_IDS)
+def test_inference_logits_carry_the_same_transforms(config, scale, softcapping, forward):
+ config = config()
+ """The labels-free branch returns the logits, so they must arrive already transformed."""
+ expected = F.linear(_hidden_states(), _lm_head_weight()) * scale
+ if softcapping:
+ expected = softcapping * torch.tanh(expected / softcapping)
+ model = _FakeCausalLM(config)
+ assert torch.allclose(_inference_logits(model, forward), expected, atol = 1e-5)
+ # Applied in place, so a second call on the SAME model must not compound them.
+ assert torch.allclose(_inference_logits(model, forward), expected, atol = 1e-5)
+
+
+ "module,forward",
+ [(llama_module, None), (mistral_module, MistralForCausalLM_fast_forward)],
+ ids = ["llama", "mistral"],
+)
[email protected]("config,scale,softcapping", _SCALE_CASES, ids = _SCALE_IDS)
+def test_materialized_branch_is_handed_the_same_transforms(
+ config, scale, softcapping, module, forward, monkeypatch
+):
+ """The eager branch needs Triton, so assert on what it hands the kernel. Each module
+ has its own binding via `from .llama import *`, so the spy goes on the call site's."""
+ config = config()
+ calls = []
+
+ def spy(**kwargs):
+ calls.append(kwargs)
+ return torch.zeros((), requires_grad = True)
+
+ monkeypatch.setattr(module, "fast_cross_entropy_loss", spy)
+ monkeypatch.setenv("UNSLOTH_RETURN_LOGITS", "1")
+ extra = {"input_ids": torch.zeros(BSZ, Q_LEN, dtype = torch.long)} if forward else {}
+ (forward or CausalLM_fast_forward(None))(
+ _FakeCausalLM(config),
+ labels = LABELS.clone(),
+ return_dict = True,
+ **extra,
+ )
+
+ assert len(calls) == 1, "the eager branch did not run"
+ assert calls[0]["logit_scaling"] == pytest.approx(scale if scale != 1.0 else 0)
+ assert calls[0]["logit_softcapping"] == pytest.approx(softcapping)
+
+
+def test_transforms_are_applied_scale_first_then_soft_cap():
+ """tanh does not commute with scaling, and no shipped family does both, so nothing
+ above separates the two orders."""
+ logits = F.linear(_hidden_states(), _lm_head_weight())
+ scale, softcapping = 0.0625, 4.0
+ scale_first = softcapping * torch.tanh((logits * scale) / softcapping)
+ cap_first = softcapping * torch.tanh(logits / softcapping) * scale
+ assert not torch.allclose(scale_first, cap_first), "the fixture no longer separates the orders"
+ assert torch.allclose(
+ apply_logit_transforms(logits.clone(), softcapping, scale),
+ scale_first,
+ atol = 1e-6,
+ )
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 462e7af45fa..94f2cfa177a 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -1340,6 +1340,83 @@ def _LlamaModel_fast_forward_inference(
LlamaModel_fast_forward_inference = _LlamaModel_fast_forward_inference()
+# Copy of unsloth_zoo.device_map_planner's tables, for zoos predating detect_logit_transforms.
+_FALLBACK_TRANSFORM_FIELDS = (
+ ("logit_softcapping", ("final_logit_softcapping", "logits_soft_cap", "output_logit_soft_cap")),
+ ("logit_scale_multiply", ("logit_scale", "lm_head_multiplier", "output_multiplier")),
+ ("logit_scale_divide", ("logits_scaling",)),
+)
+_FALLBACK_TRANSFORM_BUCKETS = tuple(bucket for bucket, _ in _FALLBACK_TRANSFORM_FIELDS)
+# `logits_scaling` is not one knob: Granite divides by it, HyperCLOVA X multiplies (MuP),
+# and MiniCPM3 scales the hidden states before the head, so it is not a logit transform.
+_FALLBACK_BUCKET_OVERRIDES = {
+ ("logits_scaling", "hyperclovax"): "logit_scale_multiply",
+ ("logits_scaling", "minicpm3"): None,
+}
+
+
+def resolve_logit_transforms(config):
+ """What the loss must do to the logits, as (softcapping, multiply, divide).
+
+ Every loss branch reads it from here so they cannot drift apart. 0 means off, so an
+ absent field must read as 0 and not as 1.
+ """
+ if detect_logit_transforms is not None:
+ transforms = detect_logit_transforms(config)
+ return (
+ transforms["logit_softcapping"],
+ transforms["logit_scale_multiply"],
+ transforms["logit_scale_divide"],
+ )
+ # Same table as detect_logit_transforms: the zoo version must not pick the loss.
+ found = dict.fromkeys(_FALLBACK_TRANSFORM_BUCKETS, 0)
+ model_type = getattr(config, "model_type", "") or ""
+ for bucket, names in _FALLBACK_TRANSFORM_FIELDS:
+ for name in names:
+ target = _FALLBACK_BUCKET_OVERRIDES.get((name, model_type), bucket)
+ if target is None or found[target]:
+ continue
+ # Nullable: a None reaches the kernel and raises instead of reading as "off".
+ value = getattr(config, name, 0) or 0
+ if value:
+ found[target] = value
+ break
+ return (
+ found["logit_softcapping"],
+ found["logit_scale_multiply"],
+ found["logit_scale_divide"],
+ )
+
+
+def resolve_logit_scaling(config):
+ """The single factor fast_cross_entropy_loss takes, with the divisor folded in."""
+ logit_softcapping, logit_scale_multiply, logit_scale_divide = resolve_logit_transforms(config)
+ logit_scaling = logit_scale_multiply
+ if logit_scale_divide:
+ logit_scaling = (logit_scaling or 1.0) / logit_scale_divide
+ return logit_softcapping, logit_scaling
+
+
+def apply_logit_transforms(logits, logit_softcapping, logit_scaling):
+ """Scale, then soft cap, the order the kernels and the reference both use. Only for
+ branches that return the logits; the loss paths let the kernel apply them."""
+ if logit_scaling != 0:
+ if logits.requires_grad:
+ logits = logit_scaling * logits
+ else:
+ logits *= logit_scaling
+ if logit_softcapping != 0:
+ if logits.requires_grad:
+ logits = (1.0 / logit_softcapping) * logits
+ logits = torch.tanh(logits)
+ logits = logit_softcapping * logits
+ else:
+ logits *= 1.0 / logit_softcapping
+ logits.tanh_()
+ logits *= logit_softcapping
+ return logits
+
+
def CausalLM_fast_forward(fast_forward_inference):
def _CausalLM_fast_forward(
self,
@@ -1402,8 +1479,6 @@ def CausalLM_fast_forward(fast_forward_inference):
lm_head = self.lm_head.weight
lm_head_device = lm_head.device
- logit_softcapping = getattr(self.config, "final_logit_softcapping", 0)
- logit_scaling = getattr(self.config, "logit_scale", 0)
dtype = lm_head.dtype
# Skip int max() if either is a tensor (HF selective-decode form).
if isinstance(num_logits_to_keep, torch.Tensor) or isinstance(logits_to_keep, torch.Tensor):
@@ -1444,8 +1519,16 @@ def CausalLM_fast_forward(fast_forward_inference):
if n_items is None:
n_items = kwargs.get("n_items", None)
- if self.config.model_type == "falcon_h1":
- hidden_states = hidden_states * self.config.lm_head_multiplier
+ # Without these the fused branch optimizes a different loss than the branch below.
+ logit_softcapping, logit_scale_multiply, logit_scale_divide = (
+ resolve_logit_transforms(self.config)
+ )
+
+ if self.config.model_type == "falcon_h1" and logit_scale_multiply:
+ # Via the resolver, so a nullable lm_head_multiplier reads as "off".
+ hidden_states = hidden_states * logit_scale_multiply
+ # Now folded into the hidden states, so the kernel must not scale again.
+ logit_scale_multiply = 0
# Packed-boundary guard on raw labels (the fused kernel shifts internally). This branch RETURNS,
# so mask_packed_sequence_boundaries() below is dead on packed paths: it needs
@@ -1470,6 +1553,8 @@ def CausalLM_fast_forward(fast_forward_inference):
target_gb = None,
torch_compile = True,
logit_softcapping = logit_softcapping,
+ logit_scale_multiply = logit_scale_multiply,
+ logit_scale_divide = logit_scale_divide,
)
if not return_dict:
# Fused CE never materializes logits; use EMPTY_LOGITS like the return_dict branch below (#2068).
@@ -1489,22 +1574,8 @@ def CausalLM_fast_forward(fast_forward_inference):
logits = logits.to(_get_dtype(dtype_from_config(self.config)))
loss = None
- # Which field carries the scale is per family (cohere logit_scale, granite logits_scaling,
- # falcon_h1 lm_head_multiplier). The planner sizes the head's card from the same answer, so a
- # new family is taught once, not twice.
- if detect_logit_transforms is not None:
- _transforms = detect_logit_transforms(self.config)
- logit_softcapping = _transforms["logit_softcapping"]
- logit_scaling = _transforms["logit_scale_multiply"]
- if not logit_scaling and _transforms["logit_scale_divide"]:
- logit_scaling = 1 / _transforms["logit_scale_divide"]
- else:
- logit_softcapping = getattr(self.config, "final_logit_softcapping", 0)
- logit_scaling = getattr(self.config, "logit_scale", 0)
- if self.config.model_type == "granite":
- logit_scaling = 1 / getattr(self.config, "logits_scaling", 1)
- elif self.config.model_type == "falcon_h1":
- logit_scaling = self.config.lm_head_multiplier
+ # Same answer the fused branch above reads, so the two branches cannot drift apart.
+ logit_softcapping, logit_scaling = resolve_logit_scaling(self.config)
if labels is not None:
shift_logits = logits
@@ -1526,20 +1597,7 @@ def CausalLM_fast_forward(fast_forward_inference):
n_items = n_items,
)
else:
- if logit_scaling != 0:
- if logits.requires_grad:
- logits = logit_scaling * logits
- else:
- logits *= logit_scaling
- if logit_softcapping != 0:
- if logits.requires_grad:
- logits = (1.0 / logit_softcapping) * logits
- logits = torch.tanh(logits)
- logits = logit_softcapping * logits
- else:
- logits *= 1.0 / logit_softcapping
- logits.tanh_()
- logits *= logit_softcapping
+ logits = apply_logit_transforms(logits, logit_softcapping, logit_scaling)
if not return_dict:
output = (logits,) + outputs[1:]
diff --git a/unsloth/models/mistral.py b/unsloth/models/mistral.py
index 3db12fe3043..fbc67823dbc 100644
--- a/unsloth/models/mistral.py
+++ b/unsloth/models/mistral.py
@@ -33,6 +33,9 @@ from .llama import (
LlamaLinearScalingRotaryEmbedding,
original_apply_qkv,
original_apply_o,
+ apply_logit_transforms,
+ resolve_logit_scaling,
+ resolve_logit_transforms,
)
from transformers.models.mistral.modeling_mistral import (
MistralAttention,
@@ -327,7 +330,10 @@ def MistralForCausalLM_fast_forward(
n_items = kwargs.get("num_items_in_batch", None)
if n_items is None:
n_items = kwargs.get("n_items", None)
- logit_softcapping = getattr(self.config, "final_logit_softcapping", 0)
+ # Same source as llama.py's fused branch.
+ logit_softcapping, logit_scale_multiply, logit_scale_divide = resolve_logit_transforms(
+ self.config
+ )
# Packed-boundary guard, see llama.py. This branch returns, so mask_packed_sequence_boundaries()
# below is never reached.
@@ -348,6 +354,8 @@ def MistralForCausalLM_fast_forward(
target_gb = None,
torch_compile = True,
logit_softcapping = logit_softcapping,
+ logit_scale_multiply = logit_scale_multiply,
+ logit_scale_divide = logit_scale_divide,
)
if not return_dict:
# Fused CE never materializes logits; use EMPTY_LOGITS like the return_dict branch below (#2068).
@@ -367,6 +375,9 @@ def MistralForCausalLM_fast_forward(
logits = logits.to(_get_dtype(dtype_from_config(self.config)))
loss = None
+ # Same answer the fused branch above reads, so the two branches cannot drift apart.
+ logit_softcapping, logit_scaling = resolve_logit_scaling(self.config)
+
if labels is not None:
shift_logits = logits
shift_labels = torch.empty_like(labels)
@@ -382,8 +393,13 @@ def MistralForCausalLM_fast_forward(
loss = fast_cross_entropy_loss(
logits = shift_logits,
labels = shift_labels,
+ logit_softcapping = logit_softcapping,
+ logit_scaling = logit_scaling,
n_items = n_items,
)
+ else:
+ # Inference returns the logits, so they carry the transforms themselves.
+ logits = apply_logit_transforms(logits, logit_softcapping, logit_scaling)
if not return_dict:
output = (logits,) + outputs[1:]
diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py
index a5dc834a8ff..3893796d581 100644
--- a/unsloth/models/rl_replacements.py
+++ b/unsloth/models/rl_replacements.py
@@ -1991,12 +1991,9 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):
logit_scale_divide = _transforms["logit_scale_divide"]
else:
logit_softcapping = _unsloth_get_final_logit_softcapping(model)
- logit_scale_multiply = getattr(model_config, "logit_scale", 0)
- if logit_scale_multiply is None:
- logit_scale_multiply = 0
- logit_scale_divide = getattr(model_config, "logits_scaling", 0)
- if logit_scale_divide is None:
- logit_scale_divide = 0
+ logit_scale_multiply, logit_scale_divide = _unsloth_resolve_logit_scales(
+ model_config
+ )
zipped_inputs = zip(
input_ids_chunks,
@@ -2565,24 +2562,64 @@ def _unsloth_get_model_config(model):
return config
+def _unsloth_text_configs(config):
+ """``config`` and its text sub-config, the two places a transform can live: Gemma-4-style configs keep it on ``config.text_config``, T5Gemma-style ones only reach it via ``config.get_text_config()``."""
+ if config is None:
+ return []
+ holders = [config]
+ text_cfg = getattr(config, "text_config", None)
+ if text_cfg is None:
+ get_text_config = getattr(config, "get_text_config", None)
+ if callable(get_text_config):
+ try:
+ text_cfg = get_text_config()
+ except (TypeError, ValueError):
+ text_cfg = None
+ if text_cfg is not None and text_cfg is not config:
+ holders.append(text_cfg)
+ return holders
+
+
def _unsloth_get_final_logit_softcapping(model):
- """final_logit_softcapping for a model config, falling back to the nested text sub-config for composite models: Gemma-4-style configs keep it on ``config.text_config``, T5Gemma-style ones only reach it via ``config.get_text_config()``. Returns 0 if unset."""
+ """The soft cap the loss applies, under any of its three spellings: ``final_logit_softcapping`` (Gemma), ``logits_soft_cap`` (RecurrentGemma), ``output_logit_soft_cap`` (xLSTM). Returns 0 if unset."""
config = _unsloth_get_model_config(model)
if config is None:
return 0
- softcap = getattr(config, "final_logit_softcapping", None)
- if softcap is None:
- text_cfg = getattr(config, "text_config", None)
- if text_cfg is None:
- get_text_config = getattr(config, "get_text_config", None)
- if callable(get_text_config):
- try:
- text_cfg = get_text_config()
- except (TypeError, ValueError):
- text_cfg = None
- if text_cfg is not None and text_cfg is not config:
- softcap = getattr(text_cfg, "final_logit_softcapping", None)
- return 0 if softcap is None else softcap
+ for holder in _unsloth_text_configs(config):
+ for name in ("final_logit_softcapping", "logits_soft_cap", "output_logit_soft_cap"):
+ softcap = getattr(holder, name, None)
+ if softcap:
+ return softcap
+ return 0
+
+
+def _unsloth_resolve_logit_scales(model_config):
+ """``(multiply, divide)`` for the logits, read with the same field table and per-family overrides ``detect_logit_transforms`` uses.
+
+ Only reached when the installed unsloth_zoo predates that helper. Must stay in step with ``resolve_logit_transforms`` in unsloth/models/llama.py: if the forward applies a transform GRPO does not, the policy log-probabilities come from different logits than the ones generated, which silently shifts every importance ratio.
+ """
+ # ``logits_scaling`` is not one knob: Granite divides, HyperCLOVA X multiplies (MuP),
+ # MiniCPM3 scales the hidden states so it is not a logit transform.
+ overrides = {
+ ("logits_scaling", "hyperclovax"): "multiply",
+ ("logits_scaling", "minicpm3"): None,
+ }
+ found = {"multiply": 0, "divide": 0}
+ for holder in _unsloth_text_configs(model_config):
+ model_type = getattr(holder, "model_type", "") or ""
+ for bucket, names in (
+ ("multiply", ("logit_scale", "lm_head_multiplier", "output_multiplier")),
+ ("divide", ("logits_scaling",)),
+ ):
+ for name in names:
+ target = overrides.get((name, model_type), bucket)
+ if target is None or found[target]:
+ continue
+ value = getattr(holder, name, 0) or 0
+ if value:
+ found[target] = value
+ break
+ return found["multiply"], found["divide"]
def _unsloth_grpo_returns_hidden_states(model, tensor, lm_head):
@@ -2702,7 +2739,9 @@ grpo_update_SamplingParams = RL_REPLACEMENTS["grpo_update_SamplingParams"]
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast_kwargs))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_model_config))
+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_text_configs))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_final_logit_softcapping))
+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_resolve_logit_scales))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_returns_hidden_states))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_hidden_states_signal))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_mm_token_id))
@@ -2856,12 +2895,7 @@ def grpo_trainer_compute_loss(function_name, function):
logit_scale_divide = _transforms["logit_scale_divide"]
else:
logit_softcapping = _unsloth_get_final_logit_softcapping(model) # Gemma
- logit_scale_multiply = getattr(model_config, "logit_scale", 0) # Cohere
- if logit_scale_multiply is None:
- logit_scale_multiply = 0
- logit_scale_divide = getattr(model_config, "logits_scaling", 0) # Granite
- if logit_scale_divide is None:
- logit_scale_divide = 0
+ logit_scale_multiply, logit_scale_divide = _unsloth_resolve_logit_scales(model_config)
max_left_pad = inputs.get("max_left_pad", 0)
if per_token_logps is not None: