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
Average GRPO gradients across DDP ranks, and keep MiniCPM3's pre-head scaling (#12193)
Daniel Han1c9bf9f72922
diff --git a/tests/_rl_source.py b/tests/_rl_source.pyindex 85a8a95c397..25501dfaa93 100644--- a/tests/_rl_source.py+++ b/tests/_rl_source.py@@ -32,6 +32,8 @@ WRAPPER_NAMES = ("_minimise_logits_kwarg","_drop_spare_hidden_states","_install_grpo_hidden_states_forward_wrapper",+ "_grpo_pre_head_hidden_divisor",+ "_grpo_hidden_states_reproduce_logits",)# present only once the per-call degradation fix has landed@@ -42,6 +44,8 @@ CONSTANT_NAMES = ("_UNSLOTH_GRPO_HIDDEN_STATES_WRAPPED_ATTR","_UNSLOTH_GRPO_HIDDEN_STATES_WARNING_ATTR","_UNSLOTH_GRPO_HIDDEN_STATES_DEGRADED_ATTR",+ "_UNSLOTH_GRPO_HIDDEN_STATES_UNSAFE_ATTR",+ "_UNSLOTH_GRPO_HIDDEN_STATES_VERIFIED_ATTR",)@@ -67,11 +71,27 @@ def load_rl_wrapper(names = WRAPPER_NAMES):if missing:raise AssertionError(f"missing module-level defs in {SOURCE_PATH}: {sorted(missing)}")+ import torch+namespace: dict = {"os": os,"collections": collections,"inspect": inspect,"logger": logging.getLogger("unsloth-repro"),+ "torch": torch,+ # rl.py imports these at module level; None skips the one-time head check, which needs zoo.+ "detect_logit_transforms": None,}+ replacements = SOURCE_PATH.with_name("rl_replacements.py")+ config_helpers = [+ node+ for node in ast.parse(replacements.read_text(encoding = "utf-8")).body+ if isinstance(node, ast.FunctionDef)+ and node.name in ("_unsloth_get_model_config", "_unsloth_text_configs")+ ]+ exec(+ compile(ast.Module(body = config_helpers, type_ignores = []), str(replacements), "exec"),+ namespace,+ )exec(compile(ast.Module(body = wanted, type_ignores = []), str(SOURCE_PATH), "exec"), namespace)return {name: namespace[name] for name in names}diff --git a/tests/python/_grpo_ddp_worker.py b/tests/python/_grpo_ddp_worker.pynew file mode 100644index 00000000000..a60c60cdc00--- /dev/null+++ b/tests/python/_grpo_ddp_worker.py@@ -0,0 +1,74 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""One gloo rank for test_grpo_ddp_gradient_sync.py. No unsloth import at module level: a spawned rank must set up the GPU-free harness first."""++from __future__ import annotations++import os+import runpy++MODES = ("bypass", "through_ddp", "no_sync")+++def run_rank(rank, port, queue):+ runpy.run_path(+ os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "conftest.py")+ )+ import torch+ import torch.distributed as dist+ import unsloth.models.rl as rl++ class LM(torch.nn.Module):+ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.body = torch.nn.Linear(6, 6)+ self.head = torch.nn.Linear(6, 11, bias = False)++ def forward(self, x):+ return self.head(self.body(x))++ class Trainer:+ """The generated GRPO trainer's loss runs the UNWRAPPED module (zoo's grpo_accumulated_loss)."""++ def __init__(self, through_ddp):+ self.through_ddp = through_ddp++ def training_step(self, model, inputs):+ forward = model if self.through_ddp else model.module+ loss = forward(inputs).logsumexp(-1).mean()+ loss.backward()+ return loss.detach()++ rl._wrap_grpo_ddp_gradient_sync(Trainer)+ os.environ.update(MASTER_ADDR = "127.0.0.1", MASTER_PORT = str(port))+ dist.init_process_group("gloo", rank = rank, world_size = 2)+ try:+ results = {}+ x = torch.randn(3, 4, 6, generator = torch.Generator().manual_seed(100 + rank))+ local = LM()+ local(x).logsumexp(-1).mean().backward()+ local_grads = torch.cat([p.grad.reshape(-1) for p in local.parameters()])+ gathered = [torch.zeros_like(local_grads) for _ in range(2)]+ dist.all_gather(gathered, local_grads)+ for mode in MODES:+ ddp = torch.nn.parallel.DistributedDataParallel(LM())+ trainer = Trainer(through_ddp = mode == "through_ddp")+ if mode == "no_sync":+ with ddp.no_sync():+ trainer.training_step(ddp, x)+ else:+ trainer.training_step(ddp, x)+ results[mode] = torch.cat(+ [p.grad.reshape(-1) for p in ddp.module.parameters()]+ ).tolist()+ # bucket_bytes=1: every gradient is larger than a bucket, so each one is reduced in place.+ ddp = torch.nn.parallel.DistributedDataParallel(LM())+ ddp.module(x).logsumexp(-1).mean().backward()+ rl._unsloth_average_gradients(ddp, bucket_bytes = 1)+ results["oversized"] = torch.cat(+ [p.grad.reshape(-1) for p in ddp.module.parameters()]+ ).tolist()+ queue.put((rank, results, torch.stack(gathered).mean(0).tolist(), local_grads.tolist()))+ finally:+ dist.destroy_process_group()diff --git a/tests/python/test_grpo_ddp_gradient_sync.py b/tests/python/test_grpo_ddp_gradient_sync.pynew file mode 100644index 00000000000..39ba1e2108c--- /dev/null+++ b/tests/python/test_grpo_ddp_gradient_sync.py@@ -0,0 +1,49 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""GRPO's gradient pass bypasses DDP.forward, so the trainer must average gradients itself, once, where DDP would."""++from __future__ import annotations++import os+import socket+import sys++import pytest+import torch++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # spawned ranks inherit sys.path+import _grpo_ddp_worker as worker # noqa: E402++pytestmark = pytest.mark.skipif(sys.platform == "win32", reason = "two gloo ranks over TCP localhost")+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def test_grpo_training_step_averages_gradients_like_ddp():+ import torch.multiprocessing as mp++ # spawn: fork is unsafe once autograd has run in this process.+ ctx = mp.get_context("spawn")+ queue = ctx.Queue()+ port = _free_port()+ procs = [ctx.Process(target = worker.run_rank, args = (rank, port, queue)) for rank in range(2)]+ for p in procs:+ p.start()+ results = [queue.get(timeout = 900) for _ in procs]+ for p in procs:+ p.join(120)+ assert p.exitcode == 0+ for _rank, grads, mean, local in results:+ mean, local = torch.tensor(mean), torch.tensor(local)+ torch.testing.assert_close(torch.tensor(grads["bypass"]), mean, rtol = 1e-6, atol = 1e-7)+ torch.testing.assert_close(torch.tensor(grads["oversized"]), mean, rtol = 1e-6, atol = 1e-7)+ torch.testing.assert_close(+ torch.tensor(grads["through_ddp"]), mean, rtol = 1e-6, atol = 1e-7+ ) # not averaged twice+ torch.testing.assert_close(+ torch.tensor(grads["no_sync"]), local+ ) # DDP does not reduce inside no_sync eitherdiff --git a/tests/python/test_grpo_hidden_states_pre_head.py b/tests/python/test_grpo_hidden_states_pre_head.pynew file mode 100644index 00000000000..44fae510c2e--- /dev/null+++ b/tests/python/test_grpo_hidden_states_pre_head.py@@ -0,0 +1,94 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""The GRPO hidden-state wrapper must hand back exactly what the output head consumes."""++from __future__ import annotations++import os+import types++import pytest+import torch++os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")+import unsloth.models.rl as rl+++def _hidden_then_head(model, input_ids):+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1"+ try:+ with torch.no_grad():+ out = model(input_ids = input_ids)+ finally:+ os.environ.pop("UNSLOTH_RETURN_HIDDEN_STATES", None)+ return out.logits+++def test_minicpm3_hidden_states_carry_the_pre_head_scaling():+ transformers = pytest.importorskip("transformers")+ if not hasattr(transformers, "MiniCPM3ForCausalLM"):+ pytest.skip("this transformers has no MiniCPM3ForCausalLM")+ config = transformers.MiniCPM3Config(+ vocab_size = 97,+ hidden_size = 32,+ intermediate_size = 64,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ num_key_value_heads = 4,+ q_lora_rank = 16,+ kv_lora_rank = 8,+ qk_nope_head_dim = 8,+ qk_rope_head_dim = 8,+ v_head_dim = 8,+ dim_model_base = 8,+ tie_word_embeddings = False,+ )+ torch.manual_seed(0)+ assert config.logits_scaling == 4.0+ model = transformers.MiniCPM3ForCausalLM(config).eval()+ input_ids = torch.randint(0, 97, (2, 9))+ with torch.no_grad():+ want = model(input_ids = input_ids).logits+ assert rl._install_grpo_hidden_states_forward_wrapper(model)+ hidden = _hidden_then_head(model, input_ids)+ assert hidden.shape[-1] == 32+ torch.testing.assert_close(model.lm_head(hidden), want, rtol = 1e-5, atol = 1e-5)+ assert getattr(model, rl._UNSLOTH_GRPO_HIDDEN_STATES_VERIFIED_ATTR) is True+++class _PreHeadScaledLM(torch.nn.Module):+ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.embed = torch.nn.Embedding(97, 16)+ self.lm_head = torch.nn.Linear(16, 97, bias = False)+ self.config = types.SimpleNamespace(model_type = "tiny_prehead")++ def get_output_embeddings(self):+ return self.lm_head++ def forward(+ self,+ input_ids,+ output_hidden_states = False,+ return_dict = True,+ logits_to_keep = 0,+ ):+ hidden = torch.tanh(self.embed(input_ids))+ logits = self.lm_head(+ (hidden * 3.0)[:, -logits_to_keep:, :] if logits_to_keep else hidden * 3.0+ )+ return types.SimpleNamespace(+ logits = logits, hidden_states = (hidden,) if output_hidden_states else None+ )+++def test_an_unknown_pre_head_transform_falls_back_to_real_logits():+ model = _PreHeadScaledLM()+ input_ids = torch.randint(0, 97, (2, 7))+ assert rl._install_grpo_hidden_states_forward_wrapper(model)+ first = _hidden_then_head(model, input_ids)+ assert first.shape[-1] == 97 # real logits, not hidden states+ assert getattr(model, rl._UNSLOTH_GRPO_HIDDEN_STATES_UNSAFE_ATTR) is True+ assert getattr(model, rl._UNSLOTH_GRPO_HIDDEN_STATES_DEGRADED_ATTR) is True+ assert _hidden_then_head(model, input_ids).shape[-1] == 97 # stickydiff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex 2bd2ba61270..7671f6d98e8 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -32,6 +32,8 @@ from unsloth_zoo.logging_utils import PatchRLStatisticsfrom unsloth_zoo.rl_replacements import RL_REPLACEMENTSfrom ..device_type import DEVICE_TYPEfrom .rl_replacements import (+ _unsloth_get_model_config,+ _unsloth_text_configs,RL_EXTRA_ARGS,RL_FUNCTIONS,RL_PRE_ITEMS,@@ -40,6 +42,11 @@ from .rl_replacements import (RL_ADDITIONAL_FUNCTIONS,)+try:+ from unsloth_zoo.device_map_planner import detect_logit_transforms+except Exception:+ detect_logit_transforms = None+torch_compile_options = {"epilogue_fusion": True,"max_autotune": False,@@ -1716,6 +1723,49 @@ def _replace_outputs_logits(outputs, hidden_states):raise TypeError(f"Unsupported output type for GRPO hidden-state fallback: {type(outputs)}")+# Sticky per model: its head input is not hidden_states[-1] in a way we can reproduce, so every call returns real logits.+_UNSLOTH_GRPO_HIDDEN_STATES_UNSAFE_ATTR = "_unsloth_grpo_hidden_states_unsafe"+_UNSLOTH_GRPO_HIDDEN_STATES_VERIFIED_ATTR = "_unsloth_grpo_hidden_states_verified"+++def _grpo_pre_head_hidden_divisor(model):+ """MiniCPM3 divides by ``logits_scaling`` before ``lm_head``; compiled forwards already include it, this wrapper does not."""+ for config in _unsloth_text_configs(getattr(model, "config", None)):+ if getattr(config, "model_type", None) == "minicpm3":+ scaling = getattr(config, "logits_scaling", None)+ return float(scaling) if scaling else None+ return None+++def _grpo_hidden_states_reproduce_logits(model, hidden_states, logits):+ """Does the head on our hidden states give the forward's own last-position logits? ``None`` when it cannot be checked."""+ get_output_embeddings = getattr(model, "get_output_embeddings", None)+ head = get_output_embeddings() if callable(get_output_embeddings) else None+ weight = getattr(head, "weight", None)+ if (+ detect_logit_transforms is None+ or not isinstance(weight, torch.Tensor)+ or weight.is_meta+ or not isinstance(logits, torch.Tensor)+ or logits.shape[-1] != weight.shape[0]+ or hidden_states.shape[-1] != weight.shape[-1]+ ):+ return None+ transforms = detect_logit_transforms(_unsloth_get_model_config(model))+ with torch.no_grad():+ got = head(hidden_states[..., -1:, :].to(weight.dtype)).float()+ if transforms["logit_scale_multiply"]:+ got = got * float(transforms["logit_scale_multiply"])+ if transforms["logit_scale_divide"]:+ got = got / float(transforms["logit_scale_divide"])+ if transforms["logit_softcapping"]:+ cap = float(transforms["logit_softcapping"])+ got = cap * torch.tanh(got / cap)+ want = logits[..., -1:, :].float().to(got.device)+ tolerance = 5e-2 * float(want.abs().max()) + 1e-3+ return bool(float((got - want).abs().max()) <= tolerance)++def _install_grpo_hidden_states_forward_wrapper(model):if model is None or getattr(model, _UNSLOTH_GRPO_HIDDEN_STATES_WRAPPED_ATTR, False):return False@@ -1730,12 +1780,16 @@ def _install_grpo_hidden_states_forward_wrapper(model):original_forward = target_model.forwardforward_signature = inspect.signature(original_forward)model_name = type(target_model).__name__+ # Once, not per forward: get_text_config() costs ~16 us and the config is fixed after load.+ divisor = _grpo_pre_head_hidden_divisor(target_model)def wrapped_forward(*args, **kwargs):# accelerate's extract_model_from_parallel(keep_fp32_wrapper = False), called every GRPO step, rebinds the forward as MethodType, so the module arrives as a leading positional argument; original_forward is already bound, so drop it.while len(args) != 0 and args[0] is target_model:args = args[1:]- if os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") != "1":+ if os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") != "1" or getattr(+ target_model, _UNSLOTH_GRPO_HIDDEN_STATES_UNSAFE_ATTR, False+ ):setattr(target_model, _UNSLOTH_GRPO_HIDDEN_STATES_DEGRADED_ATTR, True)return original_forward(*args, **kwargs)@@ -1797,6 +1851,23 @@ def _install_grpo_hidden_states_forward_wrapper(model):return original_forward(*args, **forward_kwargs)hidden_states = hidden_states[-1]+ if divisor is not None:+ hidden_states = hidden_states / divisor+ # Once per model: a head input we do not reproduce (another pre-head transform) would silently train a different objective.+ if getattr(target_model, _UNSLOTH_GRPO_HIDDEN_STATES_VERIFIED_ATTR, None) is None:+ verdict = _grpo_hidden_states_reproduce_logits(+ target_model, hidden_states, getattr(outputs, "logits", None)+ )+ if verdict is not None:+ setattr(target_model, _UNSLOTH_GRPO_HIDDEN_STATES_VERIFIED_ATTR, verdict)+ if verdict is False:+ setattr(target_model, _UNSLOTH_GRPO_HIDDEN_STATES_UNSAFE_ATTR, True)+ logger.warning(+ f"Unsloth: {model_name}'s head input is not its last hidden state; GRPO will use its full logits instead."+ )+ setattr(target_model, _UNSLOTH_GRPO_HIDDEN_STATES_DEGRADED_ATTR, True)+ del outputs, hidden_states+ return original_forward(*args, **kwargs)if num_logits_to_keep != 0:hidden_states = hidden_states[:, -num_logits_to_keep:, :]# Only the last layer is read, and accelerate's AlignDevicesHook.post_forward copies every tensor in the returned object to the input device, so keeping the rest costs a cross-device copy per layer as well as the memory.@@ -1836,6 +1907,97 @@ def _wrap_grpo_hidden_states_fallback(trainer_cls, attributes = ("model", "ref_mtrainer_cls.__init__ = wrapped_init+_UNSLOTH_DDP_GRAD_FORWARD_ATTR = "_unsloth_ddp_forward_with_grad"+++def _unsloth_find_ddp(model):+ seen = 0+ while model is not None and seen < 4:+ if isinstance(model, torch.nn.parallel.DistributedDataParallel):+ return model+ model = getattr(model, "_orig_mod", None)+ seen += 1+ return None+++def _unsloth_note_ddp_forward(module, args):+ if torch.is_grad_enabled():+ setattr(module, _UNSLOTH_DDP_GRAD_FORWARD_ATTR, True)+++def _unsloth_average_gradients(ddp, bucket_bytes = 64 << 20):+ """DDP reducer equivalent: average trainable grads; a grad on any rank is zero-filled elsewhere so ranks issue identical collectives."""+ import torch.distributed as dist++ group = ddp.process_group+ world_size = dist.get_world_size(group)+ params = [p for p in ddp.module.parameters() if p.requires_grad]+ if world_size <= 1 or len(params) == 0:+ return+ device = params[0].device+ present = torch.tensor([p.grad is not None for p in params], dtype = torch.uint8, device = device)+ dist.all_reduce(present, op = dist.ReduceOp.MAX, group = group)+ buckets = {}+ for p, has_grad in zip(params, present.tolist()):+ if not has_grad:+ continue+ if p.grad is None:+ p.grad = torch.zeros_like(p)+ buckets.setdefault((p.grad.device, p.grad.dtype), []).append(p.grad)+ for grads in buckets.values():+ start = 0+ while start < len(grads):+ stop, size = start, 0+ while stop < len(grads) and (+ stop == start+ or size + grads[stop].numel() * grads[stop].element_size() <= bucket_bytes+ ):+ size += grads[stop].numel() * grads[stop].element_size()+ stop += 1+ chunk = grads[start:stop]+ if len(chunk) == 1 and chunk[0].is_contiguous():+ # Reduce in place: a lone gradient can be far larger than the bucket (a full-vocab head).+ dist.all_reduce(chunk[0], group = group)+ chunk[0].div_(world_size)+ start = stop+ continue+ flat = torch.cat([g.reshape(-1) for g in chunk])+ dist.all_reduce(flat, group = group)+ flat.div_(world_size)+ offset = 0+ for g in chunk:+ g.copy_(flat[offset : offset + g.numel()].view_as(g))+ offset += g.numel()+ start = stop+++def _wrap_grpo_ddp_gradient_sync(trainer_cls):+ """zoo's grpo_accumulated_loss runs the unwrapped model, so DDP never all-reduces: average grads where DDP would have."""+ original_training_step = trainer_cls.training_step+ if getattr(original_training_step, "_unsloth_grpo_ddp_sync_wrapped", False):+ return++ def training_step(self, model, *args, **kwargs):+ ddp = _unsloth_find_ddp(model)+ if ddp is not None:+ if not getattr(ddp, "_unsloth_ddp_forward_hooked", False):+ ddp.register_forward_pre_hook(_unsloth_note_ddp_forward)+ ddp._unsloth_ddp_forward_hooked = True+ setattr(ddp, _UNSLOTH_DDP_GRAD_FORWARD_ATTR, False)+ loss = original_training_step(self, model, *args, **kwargs)+ # require_backward_grad_sync is False inside no_sync(): only the micro-step where DDP would reduce.+ if (+ ddp is not None+ and ddp.require_backward_grad_sync+ and not getattr(ddp, _UNSLOTH_DDP_GRAD_FORWARD_ATTR, False)+ ):+ _unsloth_average_gradients(ddp)+ return loss++ training_step._unsloth_grpo_ddp_sync_wrapped = True+ trainer_cls.training_step = training_step++def _backport_vision_dataset_gate(RLTrainer_source):"""Make TRL 0.22.x decide by DATASET, not by model, for SFT vision paths.@@ -3400,6 +3562,10 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):logger.info(f"Unsloth: Could not wrap GRPO hidden-state fallback for {RLTrainer_name}: {e}")+ try:+ _wrap_grpo_ddp_gradient_sync(getattr(created_module, f"Unsloth{RLTrainer_name}"))+ except Exception as e:+ logger.info(f"Unsloth: Could not wrap GRPO DDP gradient sync for {RLTrainer_name}: {e}")if trainer_file == "gkd_trainer" and "_unsloth_trl_compute_loss" in RLTrainer_source:try:_wrap_grpo_hidden_states_fallback(