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(grpo): use the evaluated model's output head for log-probs (#11877)
cherry77-cloudc0f0c190e620
diff --git a/tests/test_grpo_ref_model_output_head.py b/tests/test_grpo_ref_model_output_head.pynew file mode 100644index 00000000000..f5e3a29c918--- /dev/null+++ b/tests/test_grpo_ref_model_output_head.py@@ -0,0 +1,44 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Full fine-tuning with beta > 0 scores a separate ref_model: its log-probs need its own head, not the policy's."""++import ast+import textwrap+from pathlib import Path+from types import SimpleNamespace++import pytest++torch = pytest.importorskip("torch")++_SOURCE_PATH = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "rl_replacements.py"+++def _lm_head_assignment():+ source = _SOURCE_PATH.read_text(encoding = "utf-8")+ (function,) = [+ node+ for node in ast.walk(ast.parse(source))+ if isinstance(node, ast.FunctionDef) and node.name == "_get_per_token_logps_and_entropies"+ ]+ (assign,) = [+ node+ for node in ast.walk(function)+ if isinstance(node, ast.Assign)+ and any(isinstance(t, ast.Name) and t.id == "lm_head" for t in node.targets)+ ]+ return compile(textwrap.dedent(ast.get_source_segment(source, assign)), "<lm_head>", "exec")+++def _causal_lm(seed):+ torch.manual_seed(seed)+ head = torch.nn.Linear(8, 16, bias = False)+ return SimpleNamespace(get_output_embeddings = lambda: head)+++def test_reference_model_scored_with_its_own_head():+ policy, ref = _causal_lm(0), _causal_lm(1)+ namespace = {"self": SimpleNamespace(model = policy), "unwrapped_model": ref}+ exec(_lm_head_assignment(), namespace)+ assert namespace["lm_head"] is ref.get_output_embeddings().weightdiff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 69591cfb7f1..eab687c9463 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -1927,7 +1927,7 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):unwrapped_model = self.accelerator.unwrap_model(model, keep_fp32_wrapper = False)- lm_head = self.model.get_output_embeddings().weight+ lm_head = unwrapped_model.get_output_embeddings().weight# Size on the dtype the forward actually runs in: with autocast off that is the model's own dtype.forward_dtype = (