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
GRPO: latch autocast under vLLM only, zero-variance exclusion on TRL before 1.6 (#14123)
Daniel Han8e3fd9632040
diff --git a/tests/test_grpo_autocast_disabled.py b/tests/test_grpo_autocast_disabled.pyindex 4c6c8293c52..aea431d8236 100644--- a/tests/test_grpo_autocast_disabled.py+++ b/tests/test_grpo_autocast_disabled.py@@ -167,7 +167,8 @@ def test_the_flag_is_recorded_beside_the_dtype():lines = SRC.splitlines()dtype_at = [i for i, l in enumerate(lines) if "self._autocast_dtype = " in l]flag_at = [i for i, l in enumerate(lines) if "self._autocast_enabled = " in l]- assert len(dtype_at) == 2, dtype_at+ # the latch, its forced float32 override, and the unscored forced float32 no-autocast record+ assert len(dtype_at) == 3, dtype_atfor i in dtype_at:assert any(0 < j - i <= 8 for j in flag_at), (i, lines[i].strip())diff --git a/tests/test_grpo_efficient_autocast_latch.py b/tests/test_grpo_efficient_autocast_latch.pyindex 8be9aab0d3f..47ab379f601 100644--- a/tests/test_grpo_efficient_autocast_latch.py+++ b/tests/test_grpo_efficient_autocast_latch.py@@ -43,7 +43,9 @@ def _function(name, parent = None):def _namespace():ns = {"torch": torch, "os": os}+ exec(_function("_unsloth_grpo_autocast_forced_float32"), ns)exec(_function("_unsloth_grpo_autocast"), ns)+ exec(_function("_unsloth_grpo_autocast_unscored"), ns)exec(_function("_get_per_token_logps_and_entropies", "grpo_trainer__get_per_token_logps_and_entropies"@@ -59,6 +61,7 @@ def test_efficient_call_latches_this_trainers_precision(monkeypatch):trainer = types.SimpleNamespace(args = types.SimpleNamespace(mixed_precision = "bf16", bf16 = True, fp16 = False),model = None,+ use_vllm = True,)out = ns["_get_per_token_logps_and_entropies"](trainer, None, None, None, 4, compute_efficient = True@@ -71,7 +74,11 @@ def test_efficient_call_latches_this_trainers_precision(monkeypatch):def test_efficient_call_keeps_an_existing_latch(monkeypatch):ns = _namespace()trainer = types.SimpleNamespace(- args = None, model = None, _autocast_enabled = False, _autocast_dtype = torch.float16+ args = None,+ model = None,+ use_vllm = True,+ _autocast_enabled = False,+ _autocast_dtype = torch.float16,)ns["_get_per_token_logps_and_entropies"](trainer, None, None, None, 4, compute_efficient = True)assert trainer._autocast_enabled is False@@ -80,12 +87,106 @@ def test_efficient_call_keeps_an_existing_latch(monkeypatch):def test_legacy_logprob_replacement_latches_too(monkeypatch):ns = {"torch": torch, "os": os}+ exec(_function("_unsloth_grpo_autocast_forced_float32"), ns)exec(_function("_unsloth_grpo_autocast"), ns)+ exec(_function("_unsloth_grpo_autocast_unscored"), ns)exec(_function("_get_per_token_logps", "grpo_trainer__get_per_token_logps"), ns)monkeypatch.setenv("ACCELERATE_MIXED_PRECISION", "fp16")trainer = types.SimpleNamespace(args = types.SimpleNamespace(mixed_precision = "bf16", bf16 = True, fp16 = False),model = None,+ use_vllm = True,)assert ns["_get_per_token_logps"](trainer, None, None, None, 4) is Noneassert trainer._autocast_dtype is torch.bfloat16+++def _forced_float32_trainer(use_vllm):+ # What rl.py builds for a forced float32 model (Gemma3 on a T4, or dtype = torch.float16).+ return types.SimpleNamespace(+ args = types.SimpleNamespace(mixed_precision = "no", bf16 = False, fp16 = False),+ model = types.SimpleNamespace(_unsloth_forced_float32 = True),+ use_vllm = use_vllm,+ )+++def test_efficient_call_without_vllm_records_no_autocast_for_forced_float32(monkeypatch):+ # Without vLLM and with nothing scored, nothing latched before the efficient call did, and zoo then+ # trained a forced float32 model with no loss autocast. A latch here turns on float16 autocast.+ monkeypatch.setenv("ACCELERATE_MIXED_PRECISION", "no")+ monkeypatch.setenv("UNSLOTH_FORCE_FLOAT32", "1")+ ns = _namespace()+ trainer = _forced_float32_trainer(use_vllm = False)+ assert ns["_get_per_token_logps_and_entropies"](+ trainer, None, None, None, 4, compute_efficient = True+ ) == (None, None)+ assert trainer._autocast_enabled is False++ # Recorded on the trainer: a later model or trainer resetting the process-wide flags changes nothing.+ monkeypatch.setenv("ACCELERATE_MIXED_PRECISION", "fp16")+ monkeypatch.setenv("UNSLOTH_FORCE_FLOAT32", "0")+ ns["_get_per_token_logps_and_entropies"](trainer, None, None, None, 4, compute_efficient = True)+ assert trainer._autocast_enabled is False++ legacy = {"torch": torch, "os": os}+ exec(_function("_unsloth_grpo_autocast_forced_float32"), legacy)+ exec(_function("_unsloth_grpo_autocast"), legacy)+ exec(_function("_unsloth_grpo_autocast_unscored"), legacy)+ exec(_function("_get_per_token_logps", "grpo_trainer__get_per_token_logps"), legacy)+ trainer = _forced_float32_trainer(use_vllm = False)+ assert legacy["_get_per_token_logps"](trainer, None, None, None, 4) is None+ assert trainer._autocast_enabled is False+++def test_efficient_call_with_vllm_latches_forced_float32_as_the_old_forward_did(monkeypatch):+ # Under vLLM the old-policy forward always ran before the TRL gate came back and latched float16 autocast.+ monkeypatch.setenv("UNSLOTH_FORCE_FLOAT32", "1")+ ns = _namespace()+ trainer = _forced_float32_trainer(use_vllm = True)+ ns["_get_per_token_logps_and_entropies"](trainer, None, None, None, 4, compute_efficient = True)+ assert trainer._autocast_enabled is True+ assert trainer._autocast_dtype is torch.float16+ assert trainer._autocast_force_float32 is True+++def test_efficient_call_without_vllm_still_latches_an_ordinary_trainer(monkeypatch):+ # Only forced float32 models stay unlatched: an ordinary trainer keeps its own precision even when the+ # process-wide env (another trainer, or an explicit setting) says otherwise.+ monkeypatch.setenv("ACCELERATE_MIXED_PRECISION", "fp16")+ monkeypatch.delenv("UNSLOTH_FORCE_FLOAT32", raising = False)+ ns = _namespace()+ trainer = types.SimpleNamespace(+ args = types.SimpleNamespace(mixed_precision = "bf16", bf16 = True, fp16 = False),+ model = types.SimpleNamespace(_unsloth_forced_float32 = False),+ use_vllm = False,+ )+ ns["_get_per_token_logps_and_entropies"](trainer, None, None, None, 4, compute_efficient = True)+ assert trainer._autocast_enabled is True+ assert trainer._autocast_dtype is torch.bfloat16++ legacy = {"torch": torch, "os": os}+ exec(_function("_unsloth_grpo_autocast_forced_float32"), legacy)+ exec(_function("_unsloth_grpo_autocast"), legacy)+ exec(_function("_unsloth_grpo_autocast_unscored"), legacy)+ exec(_function("_get_per_token_logps", "grpo_trainer__get_per_token_logps"), legacy)+ trainer = types.SimpleNamespace(+ args = types.SimpleNamespace(mixed_precision = "bf16", bf16 = True, fp16 = False),+ model = None,+ use_vllm = False,+ )+ assert legacy["_get_per_token_logps"](trainer, None, None, None, 4) is None+ assert trainer._autocast_dtype is torch.bfloat16+++def test_efficient_call_without_vllm_keeps_bf16_for_a_forced_family_full_finetune(monkeypatch):+ # rl.py lets forced-family models full finetune in bf16 (args.mixed_precision = "bf16"): keep that latch.+ monkeypatch.setenv("UNSLOTH_FORCE_FLOAT32", "1")+ ns = _namespace()+ trainer = types.SimpleNamespace(+ args = types.SimpleNamespace(mixed_precision = "bf16", bf16 = True, fp16 = False),+ model = types.SimpleNamespace(_unsloth_forced_float32 = True),+ use_vllm = False,+ )+ ns["_get_per_token_logps_and_entropies"](trainer, None, None, None, 4, compute_efficient = True)+ assert trainer._autocast_enabled is True+ assert trainer._autocast_dtype is torch.bfloat16diff --git a/tests/test_grpo_reward_locals_cycle.py b/tests/test_grpo_reward_locals_cycle.pyindex 52640e69ab2..d2f96ce81f0 100644--- a/tests/test_grpo_reward_locals_cycle.py+++ b/tests/test_grpo_reward_locals_cycle.py@@ -8,6 +8,7 @@ the cyclic GC runs. The name must be gone before any later locals() call."""import astimport inspectimport textwrap+from pathlib import Pathimport pytest@@ -16,9 +17,15 @@ from unsloth.models.rl_replacements import grpo_trainer__generate_and_score_compdef _rewritten():trl_grpo = pytest.importorskip("trl.trainer.grpo_trainer")- source = textwrap.dedent(- inspect.getsource(trl_grpo.GRPOTrainer._generate_and_score_completions)+ # Read TRL's own file: importing unsloth swaps GRPOTrainer for the compiled, wrapped trainer, so+ # inspect.getsource on the class returns the wrapper and the rewrite would never anchor.+ text = Path(inspect.getsourcefile(trl_grpo)).read_text(encoding = "utf-8")+ node = next(+ n+ for n in ast.walk(ast.parse(text))+ if isinstance(n, ast.FunctionDef) and n.name == "_generate_and_score_completions")+ source = textwrap.dedent(ast.get_source_segment(text, node, padded = True))source = textwrap.indent(source, " ")out = grpo_trainer__generate_and_score_completions("_generate_and_score_completions", source)if "_unsloth_reward_locals = locals()" not in out:diff --git a/tests/test_grpo_sample_weight.py b/tests/test_grpo_sample_weight.pyindex b270ad31662..4bed8c9eef0 100644--- a/tests/test_grpo_sample_weight.py+++ b/tests/test_grpo_sample_weight.py@@ -34,9 +34,14 @@ def _load():nfor n in tree.bodyif isinstance(n, ast.FunctionDef)- and n.name in ("_unsloth_grpo_sample_weight_mode", "_unsloth_grpo_sample_weight")+ and n.name+ in (+ "_unsloth_grpo_sample_weight_mode",+ "_unsloth_grpo_sample_weight",+ "_unsloth_trl_masks_unscorable",+ )]- assert len(nodes) == 2+ assert len(nodes) in (2, 3)ns = {"torch": torch}exec(compile(ast.Module(nodes, []), str(SOURCE), "exec"), ns)return ns["_unsloth_grpo_sample_weight"]@@ -283,3 +288,16 @@ def test_group_with_one_scored_completion_is_kept(monkeypatch):trainer = _trainer("dapo", None)trainer.multi_objective_aggregation = aggregationassert _kept_groups(trainer, rpf, monkeypatch) == [True, True]+++def test_unscored_completion_counts_as_zero_on_trl_before_1_6(monkeypatch):+ # TRL < 1.6 sums an unscored completion's rewards to 0, so [None, 1, 1, 1] has std 0.5 and real+ # advantages; excluding the group would drop that signal. TRL >= 1.6 leaves it out: zero variance.+ import trl++ rpf = torch.tensor([[float("nan")] * 2, [1.0, 0.0], [1.0, 0.0], [1.0, 0.0]])+ trainer = _trainer("dapo", None)+ monkeypatch.setattr(trl, "__version__", "1.5.1")+ assert _kept_groups(trainer, rpf, monkeypatch) == [True]+ monkeypatch.setattr(trl, "__version__", "1.6.0")+ assert _kept_groups(trainer, rpf, monkeypatch) == [False]diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 140c101e12a..781f508002c 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -1152,6 +1152,14 @@ def sft_trainer_assistant_mask_fallback(function_name, function):RL_FUNCTIONS["sft_trainer"].append(sft_trainer_assistant_mask_fallback)+def _unsloth_grpo_autocast_forced_float32(self):+ # Stamped by from_pretrained: UNSLOTH_FORCE_FLOAT32 is process wide, so a model loaded after this trainer was built would answer for it here.+ forced = getattr(getattr(self, "model", None), "_unsloth_forced_float32", None)+ if forced is None:+ forced = os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1"+ return forced++def _unsloth_grpo_autocast(self):"""Decide the GRPO autocast once and latch it on the trainer. ACCELERATE_MIXED_PRECISION is process wide, so a trainer built later but run first would hand this trainer its precision; args belongs to this trainer."""if not hasattr(self, "_autocast_enabled"):@@ -1169,10 +1177,7 @@ def _unsloth_grpo_autocast(self):# "no" is a real value: full finetuning and an explicit float32 load both set it, and reading it as bfloat16 raises on a T4 or V100.self._autocast_enabled = precision != "no"self._autocast_force_float32 = False- # Stamped by from_pretrained: UNSLOTH_FORCE_FLOAT32 is process wide, so a model loaded after this trainer was built would answer for it here.- forced = getattr(getattr(self, "model", None), "_unsloth_forced_float32", None)- if forced is None:- forced = os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1"+ forced = _unsloth_grpo_autocast_forced_float32(self)if forced and precision != "bf16":# Gemma3 / gpt-oss set "no" but still want float16 autocast; a trainer already on bf16 keeps it, since float16 is what the forced list avoids.self._autocast_dtype = torch.float16@@ -1182,6 +1187,26 @@ def _unsloth_grpo_autocast(self):return self._autocast_enabled, self._autocast_dtype+def _unsloth_grpo_autocast_unscored(self):+ """Latch for a step that ran no scoring forward. Where the ordinary latch would force float16 autocast on a+ forced float32 model (Gemma3 on a T4) without vLLM, record no loss autocast instead: nothing latched there+ before the TRL old-logprob gate came back, so zoo trained it without autocast. A forced-family trainer on+ bf16 (full finetuning) keeps its bf16 latch. Recorded on the trainer rather than left to zoo's+ process-wide fallback, which a later model or trainer may have changed. Under vLLM the old-policy+ forward always ran and latched, so it latches as before."""+ fresh = not hasattr(self, "_autocast_enabled")+ latched = _unsloth_grpo_autocast(self)+ if (+ fresh+ and not getattr(self, "use_vllm", False)+ and getattr(self, "_autocast_force_float32", False)+ ):+ self._autocast_dtype = torch.float16+ self._autocast_enabled = False+ latched = (self._autocast_enabled, self._autocast_dtype)+ return latched++def _unsloth_grpo_autocast_kwargs(self, device_type = DEVICE_TYPE_TORCH):"""torch.amp.autocast kwargs for GRPO generation."""enabled, dtype = _unsloth_grpo_autocast(self)@@ -2426,8 +2451,8 @@ def grpo_trainer__get_per_token_logps(function_name, function):compute_efficient = False,):if True: # os.environ.get('UNSLOTH_USE_NEW_MODEL', '0') == '0':- # Older TRL calls this instead of _get_per_token_logps_and_entropies: latch here too.- _unsloth_grpo_autocast(self)+ # Older TRL calls this instead of _get_per_token_logps_and_entropies: latch here too (see below).+ _unsloth_grpo_autocast_unscored(self)return None # Unsloth efficient GRPO_unsloth_grpo_autocast(self)@@ -2472,7 +2497,7 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):# All Unsloth code in this function is licensed under AGPL3.if compute_efficient:# No scoring forward may run (vLLM, beta = 0): latch precision here, not from the shared env.- _unsloth_grpo_autocast(self)+ _unsloth_grpo_autocast_unscored(self)return None, Noneelse:_unsloth_grpo_autocast(self)@@ -3465,6 +3490,15 @@ def _unsloth_grpo_sample_weight_mode():return exclude, aggregation == "prompt"+def _unsloth_trl_masks_unscorable():+ try:+ import trl+ from packaging.version import Version+ return Version(trl.__version__) >= Version("1.6.0")+ except Exception:+ return True++def _unsloth_grpo_sample_weight(trainer, mode, rewards_per_func, completion_mask, tool_mask, process_slice):@@ -3511,7 +3545,10 @@ def _unsloth_grpo_sample_weight(rewards = (per_func.view_as(rewards_per_func) * weights).nansum(dim = 1)else:rewards = (rewards_per_func * weights).nansum(dim = 1)- rewards[torch.isnan(rewards_per_func).all(dim = 1)] = torch.nan+ if _unsloth_trl_masks_unscorable():+ # TRL >= 1.6 leaves a completion no reward function scored out of its group's statistics;+ # older TRL scores it 0 (nansum), so its group has variance and real advantages there.+ rewards[torch.isnan(rewards_per_func).all(dim = 1)] = torch.nanvariance = nan_variance(rewards.view(-1, num_generations), 1).squeeze(1)group_keep = torch.ones_like(variance, dtype = torch.bool)if exclude:@@ -3551,7 +3588,9 @@ grpo_compute_loss = RL_REPLACEMENTS["grpo_compute_loss"]grpo_compute_loss_slow = RL_REPLACEMENTS["grpo_compute_loss_slow"]UnslothEfficientGRPO = RL_REPLACEMENTS["UnslothEfficientGRPO"]grpo_accumulated_loss = RL_REPLACEMENTS["grpo_accumulated_loss"]+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast_forced_float32))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast))+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast_unscored))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))@@ -3564,6 +3603,7 @@ RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_fix_mm_token_typeRL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_accumulation_steps))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_is_metric_values))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_sample_weight_mode))+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_trl_masks_unscorable))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_sample_weight))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_vision_inputs))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_split_vision_by_sample))