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.

GRPO: opt-in rollout logprobs as the old policy (UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD) (#14489)

Daniel Han9f303b390b52
diff --git a/tests/test_grpo_rollout_logps_as_old.py b/tests/test_grpo_rollout_logps_as_old.py
new file mode 100644
index 00000000000..6fbae512dbe
--- /dev/null
+++ b/tests/test_grpo_rollout_logps_as_old.py
@@ -0,0 +1,260 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Opt-in UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD=1: the rollout engine's logprobs are pi_old (verl
+rollout_correction bypass_mode, vime --use-rollout-logprobs), so the generation step skips the
+old-policy forward and marks the batch for unsloth_zoo's grpo_accumulated_loss.
+
+The decision runs once per generation batch, before TRL's old-logprob gate, and is the only place
+the env var is read: the loss acts on the per-row marker, so a toggle mid-run cannot split a batch
+between two policies."""
+
+from __future__ import annotations
+
+import ast
+import importlib.util
+import re
+import sys
+import textwrap
+import types
+import warnings
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+SOURCE = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "rl_replacements.py"
+
+
+def _decision():
+ tree = ast.parse(SOURCE.read_text(encoding = "utf-8"))
+ nodes = [
+ n
+ for n in tree.body
+ if isinstance(n, ast.FunctionDef) and n.name == "_unsloth_grpo_rollout_logps_as_old"
+ ]
+ assert len(nodes) == 1, "_unsloth_grpo_rollout_logps_as_old is missing"
+ ns = {"torch": torch}
+ exec(compile(ast.Module(nodes, []), str(SOURCE), "exec"), ns)
+ return ns["_unsloth_grpo_rollout_logps_as_old"]
+
+
+def _patched_generate_and_score():
+ spec = (
+ importlib.util.find_spec("trl.trainer.grpo_trainer")
+ if importlib.util.find_spec("trl")
+ else None
+ )
+ if spec is None or spec.origin is None:
+ pytest.skip("trl is not installed")
+ from unsloth.models.rl_replacements import grpo_trainer__generate_and_score_completions
+
+ module_source = Path(spec.origin).read_text(encoding = "utf-8")
+ node = next(
+ n
+ for n in ast.walk(ast.parse(module_source))
+ if isinstance(n, ast.FunctionDef) and n.name == "_generate_and_score_completions"
+ )
+ source = " " + ast.get_source_segment(module_source, node)
+ if "sampling_per_token_logps" not in source:
+ pytest.skip("this TRL has no rollout logprobs in _generate_and_score_completions")
+ return grpo_trainer__generate_and_score_completions("_generate_and_score_completions", source)
+
+
+def test_generation_skips_the_old_forward_and_marks_the_batch():
+ patched = _patched_generate_and_score()
+ ast.parse(textwrap.dedent(patched))
+ decision = patched.index("_unsloth_rollout_old = _unsloth_grpo_rollout_logps_as_old(")
+ skip = re.search(
+ r"\n([ \t]*)if _unsloth_rollout_old:\n\1 old_per_token_logps = None\n"
+ r"\1elif self\.args\.gradient_accumulation_steps % generate_every != 0",
+ patched,
+ )
+ assert skip is not None and skip.start() > decision
+ assert patched.index("self._get_per_token_logps_and_entropies(", skip.end()) > skip.end()
+ assert patched.index("sampling_per_token_logps", 0) < decision
+ marker = patched.index('output["unsloth_rollout_logps_as_old"] = torch.ones(')
+ assert marker > patched.index('output["old_per_token_logps"] = old_per_token_logps')
+
+
+def test_trl_gate_is_untouched_when_the_flag_is_off():
+ patched = _patched_generate_and_score()
+ match = re.search(
+ r"elif (self\.args\.gradient_accumulation_steps % generate_every != 0[^:]*):\n", patched
+ )
+ assert match is not None
+ if "or (" in match.group(1):
+ assert "self.use_vllm and self.vllm_importance_sampling_correction" in match.group(1)
+
+
+class _Zoo:
+ def __init__(self, monkeypatch, supported):
+ module = types.ModuleType("unsloth_zoo.rl_replacements")
+ if supported:
+ module.grpo_rollout_logps_as_old = lambda sampling, old = None: (sampling, None)
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.rl_replacements", module)
+
+
+def _trainer(loss_type = "dapo"):
+ return SimpleNamespace(args = SimpleNamespace(loss_type = loss_type))
+
+
+def _batch():
+ sampling = -torch.rand(3, 5, dtype = torch.float32)
+ mask = torch.tensor([[1, 1, 1, 0, 0], [1, 1, 1, 1, 1], [1, 0, 0, 0, 0]])
+ return sampling, mask
+
+
+def test_off_by_default(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD", raising = False)
+ _Zoo(monkeypatch, True)
+ trainer = _trainer()
+ sampling, mask = _batch()
+ assert _decision()(trainer, sampling, mask) is False
+ assert not hasattr(trainer, "_unsloth_rollout_logps_as_old_batches")
+ assert not hasattr(trainer, "_unsloth_rollout_logps_as_old_fallbacks")
+
+
+def test_engages_and_counts(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD", "1")
+ _Zoo(monkeypatch, True)
+ trainer = _trainer()
+ sampling, mask = _batch()
+ sampling[0, 4] = float("nan")
+ tool_mask = torch.ones_like(mask)
+ tool_mask[1, 2] = 0
+ sampling[1, 2] = float("nan")
+ decide = _decision()
+ assert decide(trainer, sampling, mask, tool_mask) is True
+ assert decide(trainer, sampling[2:], mask[2:]) is True
+ assert trainer._unsloth_rollout_logps_as_old_batches == 2
+
+
+ "case",
+ ["no_rollout_logps", "nan_on_a_loss_token", "vespo", "old_zoo", "no_loss_type"],
+)
+def test_falls_back_to_the_trainer_old_forward(monkeypatch, case):
+ monkeypatch.setenv("UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD", "1")
+ _Zoo(monkeypatch, case != "old_zoo")
+ trainer = _trainer("vespo" if case == "vespo" else "dapo")
+ if case == "no_loss_type":
+ trainer = SimpleNamespace(args = SimpleNamespace())
+ sampling, mask = _batch()
+ if case == "no_rollout_logps":
+ sampling = None
+ if case == "nan_on_a_loss_token":
+ sampling[1, 3] = float("nan")
+ decide = _decision()
+ with warnings.catch_warnings(record = True) as caught:
+ warnings.simplefilter("always")
+ assert decide(trainer, sampling, mask) is False
+ assert decide(trainer, sampling, mask) is False
+ assert trainer._unsloth_rollout_logps_as_old_fallbacks == 2
+ assert not hasattr(trainer, "_unsloth_rollout_logps_as_old_batches")
+ assert sum("UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD" in str(w.message) for w in caught) == 1
+
+
+def test_ranks_agree_on_the_fallback(monkeypatch):
+ # One rank with a non-finite rollout logprob must pull every rank onto the trainer's own pi_old:
+ # under FSDP / ZeRO-3 that forward is collective.
+ monkeypatch.setenv("UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD", "1")
+ _Zoo(monkeypatch, True)
+ sampling, mask = _batch()
+ other_rank_finite = {"value": 0}
+
+ class _Acc:
+ num_processes = 2
+
+ def gather(self, t):
+ return torch.cat([t, torch.tensor([other_rank_finite["value"]], dtype = t.dtype)])
+
+ trainer = SimpleNamespace(args = SimpleNamespace(loss_type = "dapo"), accelerator = _Acc())
+ decide = _decision()
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ assert decide(trainer, sampling, mask) is False
+ other_rank_finite["value"] = 1
+ assert decide(trainer, sampling, mask) is True
+ assert trainer._unsloth_rollout_logps_as_old_fallbacks == 1
+ assert trainer._unsloth_rollout_logps_as_old_batches == 1
+
+
+_FAKE_TRL = """
+ def _generate_and_score_completions(self, inputs):
+ sampling_per_token_logps = inputs["sampling"]
+ completion_mask = inputs["mask"]
+ completion_ids = inputs["ids"]
+ generate_every = self.args.steps_per_generation * self.num_iterations
+ with torch.no_grad():
+ if self.args.gradient_accumulation_steps % generate_every != 0 or (
+ self.use_vllm and self.vllm_importance_sampling_correction
+ ):
+ old_per_token_logps = self.score()
+ else:
+ old_per_token_logps = None
+ output = {"completion_ids": completion_ids}
+ if old_per_token_logps is not None:
+ output["old_per_token_logps"] = old_per_token_logps
+ return output
+"""
+
+
+def test_marked_batch_keeps_its_rollout_logprobs_on_older_trl():
+ # TRL 0.23.x only puts sampling_per_token_logps into the output with the IS correction on:
+ # a marked batch must carry them anyway, or the loss gets the marker without the tensor.
+ from unsloth.models.rl_replacements import grpo_trainer__generate_and_score_completions
+
+ patched = grpo_trainer__generate_and_score_completions(
+ "_generate_and_score_completions", _FAKE_TRL
+ )
+ ns = {
+ "torch": torch,
+ "_unsloth_grpo_rollout_logps_as_old": lambda *args: True,
+ "_unsloth_reject_grpo_image_list": lambda *args: None, # other rewrites' prologue
+ }
+ exec(textwrap.dedent(patched), ns)
+ sampling, mask = _batch()
+ calls = []
+ trainer = SimpleNamespace(
+ args = SimpleNamespace(steps_per_generation = 1, gradient_accumulation_steps = 1),
+ num_iterations = 2,
+ use_vllm = False,
+ vllm_importance_sampling_correction = False,
+ score = lambda: calls.append(1),
+ )
+ out = ns["_generate_and_score_completions"](
+ trainer, {"sampling": sampling, "mask": mask, "ids": torch.zeros(3, 5)}
+ )
+ assert not calls and "old_per_token_logps" not in out
+ assert out["unsloth_rollout_logps_as_old"].all()
+ assert out["sampling_per_token_logps"] is sampling
+
+
+def test_missing_rollout_logprobs_still_join_the_rank_reduction(monkeypatch):
+ # A None rank must still join the reduction, or the other ranks deadlock.
+ monkeypatch.setenv("UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD", "1")
+ _Zoo(monkeypatch, True)
+ sampling, mask = _batch()
+ gathered = []
+
+ class _Acc:
+ num_processes = 2
+
+ def __init__(self, other):
+ self.other = other
+
+ def gather(self, t):
+ gathered.append(int(t.item()))
+ return torch.cat([t, torch.tensor([self.other], dtype = t.dtype)])
+
+ decide = _decision()
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ no_logps = SimpleNamespace(args = SimpleNamespace(loss_type = "dapo"), accelerator = _Acc(1))
+ assert decide(no_logps, None, mask) is False
+ has_logps = SimpleNamespace(args = SimpleNamespace(loss_type = "dapo"), accelerator = _Acc(0))
+ assert decide(has_logps, sampling, mask) is False
+ assert gathered == [0, 1]
+ assert not hasattr(has_logps, "_unsloth_rollout_logps_as_old_batches")
diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py
index 058c7e15523..02b4920c583 100644
--- a/unsloth/models/rl_replacements.py
+++ b/unsloth/models/rl_replacements.py
@@ -2375,6 +2375,47 @@ def grpo_trainer__generate_and_score_completions(function_name, function):
"not be installed for this TRL version and are ignored.",
)
+ _old_logps_if = re.search(
+ r"\n([ \t]*)if self\.args\.gradient_accumulation_steps % generate_every != 0",
+ function,
+ )
+ _old_logps_output = (
+ " if old_per_token_logps is not None:\n"
+ ' output["old_per_token_logps"] = old_per_token_logps\n'
+ )
+ if (
+ _old_logps_if is not None
+ and function.count(_old_logps_output) == 1
+ and "sampling_per_token_logps" in function
+ ):
+ _indent = _old_logps_if.group(1)
+ function = (
+ function[: _old_logps_if.start()]
+ + f"\n{_indent}_unsloth_rollout_logps = locals().get('sampling_per_token_logps')\n"
+ + f"{_indent}_unsloth_rollout_old = _unsloth_grpo_rollout_logps_as_old(\n"
+ + f"{_indent} self, _unsloth_rollout_logps, completion_mask, locals().get('tool_mask'),\n"
+ + f"{_indent})\n"
+ + f"{_indent}if _unsloth_rollout_old:\n"
+ + f"{_indent} old_per_token_logps = None\n"
+ + f"{_indent}el"
+ + function[_old_logps_if.start() + 1 + len(_indent) :]
+ )
+ function = function.replace(
+ _old_logps_output,
+ _old_logps_output + " if _unsloth_rollout_old:\n"
+ ' output["unsloth_rollout_logps_as_old"] = torch.ones(\n'
+ " completion_ids.size(0), dtype = torch.bool, device = completion_ids.device\n"
+ " )\n"
+ # Older TRL (0.23.x) keeps the rollout logprobs only with the IS correction on.
+ ' output["sampling_per_token_logps"] = _unsloth_rollout_logps\n',
+ )
+ elif os.environ.get("UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD", "0") == "1":
+ _warn_once(
+ "grpo_rollout_logps_as_old",
+ "Unsloth: UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD could not be installed for this TRL "
+ "version and is ignored.",
+ )
+
return function
@@ -3578,6 +3619,75 @@ def grpo_update_SamplingParams(
return generation_kwargs
+def _unsloth_grpo_rollout_logps_as_old(
+ trainer,
+ sampling_per_token_logps,
+ completion_mask,
+ tool_mask = None,
+):
+ """UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD=1: use the rollout engine's logprobs (vLLM, or a
+ rollout_func) as pi_old and skip the old-policy forward, as verl rollout_correction
+ bypass_mode (loss_type ppo_clip) and vime --use-rollout-logprobs do. The PPO ratio is then
+ pi_theta / pi_rollout and its clip (plus the dual clip `delta`) is the correction, so no
+ vLLM importance weight is applied on top. True when this generation batch is marked."""
+ import os
+
+ if os.environ.get("UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD", "0") != "1":
+ return False
+
+ def _skip(reason):
+ trainer._unsloth_rollout_logps_as_old_fallbacks = (
+ getattr(trainer, "_unsloth_rollout_logps_as_old_fallbacks", 0) + 1
+ )
+ warned = getattr(trainer, "_unsloth_rollout_logps_as_old_warned", None)
+ if not isinstance(warned, set):
+ warned = set()
+ trainer._unsloth_rollout_logps_as_old_warned = warned
+ if reason not in warned:
+ warned.add(reason)
+ import warnings
+ warnings.warn(
+ f"Unsloth: UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD=1 is not applied to this batch: "
+ f"{reason}. The trainer scores pi_old itself instead.",
+ stacklevel = 2,
+ )
+ return False
+
+ reason = None
+ if sampling_per_token_logps is None:
+ reason = "there are no rollout logprobs (needs use_vllm=True or a rollout_func)"
+ elif getattr(trainer.args, "loss_type", None) == "vespo":
+ reason = "loss_type='vespo' weights by the vLLM importance ratio itself"
+ elif not hasattr(trainer.args, "loss_type"):
+ reason = "this TRL version predates loss_type"
+ else:
+ try:
+ from unsloth_zoo.rl_replacements import grpo_rollout_logps_as_old # noqa: F401
+ except Exception:
+ reason = "it needs a newer unsloth_zoo: pip install -U unsloth_zoo"
+ if reason is None:
+ loss_mask = completion_mask.to(torch.bool)
+ if tool_mask is not None:
+ loss_mask = loss_mask & tool_mask.to(device = loss_mask.device, dtype = torch.bool)
+ if not bool(torch.isfinite(sampling_per_token_logps[loss_mask]).all()):
+ reason = "some rollout logprobs on loss tokens are not finite"
+ accelerator = getattr(trainer, "accelerator", None)
+ if getattr(accelerator, "num_processes", 1) > 1:
+ # One reduction on every rank, before any of them returns: under FSDP / ZeRO-3 the
+ # old-policy forward a fallback runs is collective, so all ranks take the same branch.
+ eligible = torch.tensor(
+ [int(reason is None)], dtype = torch.int32, device = completion_mask.device
+ )
+ if not bool(accelerator.gather(eligible).min()) and reason is None:
+ reason = "another process cannot use its rollout logprobs for this batch"
+ if reason is not None:
+ return _skip(reason)
+ trainer._unsloth_rollout_logps_as_old_batches = (
+ getattr(trainer, "_unsloth_rollout_logps_as_old_batches", 0) + 1
+ )
+ return True
+
+
def _unsloth_grpo_sample_weight_mode():
import os
@@ -3716,6 +3826,7 @@ RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_accumulation
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_is_metric_values))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_is_sequence_level))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_sample_weight_mode))
+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_rollout_logps_as_old))
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))
@@ -3812,6 +3923,11 @@ def grpo_trainer_compute_loss(function_name, function):
num_items_in_batch = inputs.get("num_items_in_batch", None)
sampling_per_token_logps = inputs.get("sampling_per_token_logps", None)
tool_mask = inputs.get("tool_mask", None)
+ _rollout_logps_as_old = inputs.get("unsloth_rollout_logps_as_old", None) is not None
+ _loss_delta = getattr(self.args, "delta", None)
+ if _rollout_logps_as_old and _loss_delta is None:
+ # verl's dual-clip default (clip_ratio_c = 3.0).
+ _loss_delta = 3.0
current_gradient_accumulation_steps = _unsloth_grpo_accumulation_steps(self)
num_processes = self.accelerator.num_processes
@@ -3903,6 +4019,8 @@ def grpo_trainer_compute_loss(function_name, function):
device = completion_mask.device,
dtype = completion_mask.dtype,
)
+ if _rollout_logps_as_old:
+ old_logps, sampling_per_token_logps = sampling_per_token_logps, None
(
loss,
completion_length,
@@ -3927,7 +4045,7 @@ def grpo_trainer_compute_loss(function_name, function):
epsilon_low = self.epsilon_low,
epsilon_high = self.epsilon_high,
max_completion_length = self.args.max_completion_length,
- delta = self.args.delta,
+ delta = _loss_delta,
temperature = self.args.temperature,
max_left_pad = max_left_pad,
logit_softcapping = logit_softcapping,
@@ -4032,6 +4150,8 @@ def grpo_trainer_compute_loss(function_name, function):
_grpo_accumulated_loss_kwargs["sample_weight"] = _sample_weight
if tool_mask is not None:
_grpo_accumulated_loss_kwargs["tool_mask"] = tool_mask
+ if _rollout_logps_as_old:
+ _grpo_accumulated_loss_kwargs["rollout_logps_as_old"] = True
if hasattr(self.args, "loss_type"):
(
loss,
@@ -4055,7 +4175,7 @@ def grpo_trainer_compute_loss(function_name, function):
epsilon_low = self.epsilon_low,
epsilon_high = self.epsilon_high,
max_completion_length = self.args.max_completion_length,
- delta = self.args.delta,
+ delta = _loss_delta,
temperature = self.args.temperature,
max_left_pad = max_left_pad,
logit_softcapping = logit_softcapping,
@@ -4097,16 +4217,16 @@ def grpo_trainer_compute_loss(function_name, function):
self._metrics["completion_length"].append(completion_length.item())
self._metrics["kl"].append(mean_kl.item())
- if (
- self.use_vllm
- and delta is not None
- and getattr(self, "vllm_importance_sampling_correction", False)
+ if delta is not None and (
+ (self.use_vllm and getattr(self, "vllm_importance_sampling_correction", False))
+ or _rollout_logps_as_old
):
delta, flat_is_ratio = _unsloth_grpo_is_metric_values(
delta,
flat_is_ratio,
completion_mask,
- _unsloth_grpo_is_sequence_level(
+ (not _rollout_logps_as_old)
+ and _unsloth_grpo_is_sequence_level(
getattr(self.args, "vllm_importance_sampling_mode", None)
),
)