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 TRL PPOTrainer under Unsloth: rollout crash, sampling filters and left padding (#13108)
Daniel Haneac50baf1650
diff --git a/tests/test_ppo_trainer_patches.py b/tests/test_ppo_trainer_patches.pyindex fda142f7c82..77b1f70ff7b 100644--- a/tests/test_ppo_trainer_patches.py+++ b/tests/test_ppo_trainer_patches.py@@ -12,6 +12,9 @@ The rl.py helpers are lifted out with ``ast`` so those checks run without ``impofrom __future__ import annotationsimport ast+import copy+import functools+import inspectimport sysfrom contextlib import contextmanagerfrom pathlib import Path@@ -135,7 +138,11 @@ def _unsloth_unwrap(calls):"contextmanager": contextmanager,"unwrap_model_for_generation": _trl_unwrap,"FastLanguageModel": fast,+ "copy": copy,+ "inspect": inspect,}+ _lift("_generate_accepts_use_model_defaults", namespace)+ _lift("_caller_sampling_only", namespace)return _lift("unsloth_unwrap_model_for_generation", namespace, parent = "PatchRL")@@ -201,3 +208,150 @@ def test_rope_extension_ignores_a_refilled_inv_freq(garbage):torch.testing.assert_close(cos, ref_cos, rtol = 0, atol = 0)torch.testing.assert_close(sin, ref_sin, rtol = 0, atol = 0)torch.testing.assert_close(rope.inv_freq, reference.inv_freq, rtol = 0, atol = 0)+++def _rollout_helpers():+ namespace = {"copy": copy, "functools": functools, "inspect": inspect}+ for name in (+ "_generate_accepts_use_model_defaults",+ "_caller_sampling_only",+ "_ppo_padding_mask_modules",+ "_wrap_ppo_train",+ ):+ _lift(name, namespace)+ return namespace+++NS = _rollout_helpers()+++class _Generator:+ def __init__(self, generation_config):+ self.generation_config = generation_config+++def test_ppo_rollouts_keep_caller_sampling():+ transformers = pytest.importorskip("transformers")+ model_config = transformers.GenerationConfig(+ top_p = 0.8, top_k = 20, temperature = 0.7, min_p = 0.05, eos_token_id = 5, pad_token_id = 7+ )+ trl_config = transformers.GenerationConfig(+ max_new_tokens = 8, temperature = 0.7, top_k = 0, top_p = 1.0, do_sample = True+ )+ kwargs = {"input_ids": "ids", "generation_config": trl_config}+ out = NS["_caller_sampling_only"](_Generator(model_config), kwargs)+ if not NS["_generate_accepts_use_model_defaults"]():+ # transformers 5 only fills fields left unset, and TRL sets its sampling fields explicitly.+ assert out is kwargs+ return+ assert out["use_model_defaults"] is False and out["input_ids"] == "ids"+ passed = out["generation_config"]+ assert (passed.top_p, passed.top_k, passed.min_p) == (1.0, 0, None)+ # Stopping still follows the model (TRL writes its stop token there).+ assert (passed.eos_token_id, passed.pad_token_id) == (5, 7)+ assert trl_config.eos_token_id is None and model_config.top_p == 0.8+++def test_ppo_rollouts_respect_explicit_use_model_defaults():+ transformers = pytest.importorskip("transformers")+ kwargs = {"generation_config": transformers.GenerationConfig(), "use_model_defaults": True}+ assert (+ NS["_caller_sampling_only"](_Generator(transformers.GenerationConfig()), kwargs) is kwargs+ )+ assert NS["_caller_sampling_only"](_Generator(None), {"max_new_tokens": 4}) == {+ "max_new_tokens": 4+ }+++def test_ppo_train_wrapped_once_and_mask_cleared_on_error():+ base = _Module(base = True)++ class _Trainer:+ policy_model = _Module(base)++ def train(self):+ assert base._unsloth_keep_padding_mask is True+ raise RuntimeError("oom")++ NS["_wrap_ppo_train"](_Trainer)+ first = _Trainer.train+ NS["_wrap_ppo_train"](_Trainer)+ assert _Trainer.train is first+ with pytest.raises(RuntimeError):+ _Trainer().train()+ assert base._unsloth_keep_padding_mask is False+++def test_rollout_logits_freed_after_scoring():+ ppo = pytest.importorskip("trl.trainer.ppo_trainer")+ if not hasattr(ppo, "PPOTrainer"):+ pytest.skip("TRL without trl.trainer.ppo_trainer.PPOTrainer")+ path = RL_PY.with_name("rl_replacements.py")+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ node = next(+ n+ for n in tree.body+ if isinstance(n, ast.FunctionDef) and n.name == "ppo_trainer_free_rollout_logits"+ )+ namespace = {}+ exec(compile(ast.Module(body = [node], type_ignores = []), str(path), "exec"), namespace)+ edit = namespace["ppo_trainer_free_rollout_logits"]++ source = inspect.getsource(ppo.PPOTrainer.train)+ patched = edit("train", source)+ assert "unwrapped_model, logitss)" in patched+ # Nothing past the rollout reads them.+ tail = patched.split("unwrapped_model, logitss)", 1)[1]+ assert "logitss" not in tail+ assert edit("generate_completions", source) == source+++class _Module:+ def __init__(+ self,+ *children,+ base = False,+ ):+ self.children = children+ if base:+ self.embed_tokens = object()++ def modules(self):+ yield self+ for child in self.children:+ yield from child.modules()+++def test_ppo_training_keeps_padding_masks_then_restores():+ transformers = pytest.importorskip("transformers")+ policy_base, value_base, other_base = _Module(base = True), _Module(base = True), _Module(base = True)+ seen = {}++ class _Trainer:+ def __init__(self):+ self.policy_model = _Module(_Module(policy_base))+ self.policy_model.generation_config = transformers.GenerationConfig()+ self.value_model = _Module(value_base)+ self.ref_model = None+ self.reward_model = _Module(other_base)++ def train(self):+ seen["policy"] = policy_base._unsloth_keep_padding_mask+ seen["value"] = value_base._unsloth_keep_padding_mask+ seen["reward"] = getattr(other_base, "_unsloth_keep_padding_mask", None)++ NS["_wrap_ppo_train"](_Trainer)+ _Trainer().train()+ # The reward model runs in eval mode, which already keeps the mask.+ assert seen == {"policy": True, "value": True, "reward": None}+ assert policy_base._unsloth_keep_padding_mask is False+ assert value_base._unsloth_keep_padding_mask is False+++def test_llama_training_forward_mask_is_opt_in():+ # Every other trainer keeps today's behaviour: training mode drops the mask unless the flag is set.+ source = (RL_PY.parent / "llama.py").read_text(encoding = "utf-8")+ assert (+ 'elif self.training and not getattr(self, "_unsloth_keep_padding_mask", False):\n'+ " attention_mask = None\n"+ ) in sourcediff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex 4005d7400bc..e00d6ebfe97 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -1126,7 +1126,7 @@ def LlamaModel_fast_forward(if attention_mask is None:padding_mask = None- elif self.training:+ elif self.training and not getattr(self, "_unsloth_keep_padding_mask", False):attention_mask = Nonepadding_mask = Noneelse:diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex 34bea619d8c..b8d4d750e26 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -16,7 +16,9 @@ __all__ = [import torchfrom typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union+import copyimport copyreg+import functoolsimport importlibimport importlib.utilimport collections@@ -152,6 +154,32 @@ def _patch_resume_from_checkpoint_memory(trainer_class):trainer_class.train = _unsloth_train_with_resume_guard+def _generate_accepts_use_model_defaults():+ try:+ from transformers.generation.utils import GenerationMixin+ return "use_model_defaults" in inspect.signature(GenerationMixin.generate).parameters+ except Exception:+ return False+++def _caller_sampling_only(model, kwargs):+ # transformers 4.50-4.x refills TRL's default-valued fields from the model (Qwen3: top_p 0.8),+ # skewing rollout logprobs vs training; keep TRL's sampling, take only token ids (TRL's eos) from the model.+ generation_config = kwargs.get("generation_config", None)+ if (+ generation_config is None+ or "use_model_defaults" in kwargs+ or not _generate_accepts_use_model_defaults()+ ):+ return kwargs+ generation_config = copy.deepcopy(generation_config)+ model_config = getattr(model, "generation_config", None)+ for key in ("bos_token_id", "eos_token_id", "pad_token_id", "decoder_start_token_id"):+ if getattr(generation_config, key, None) is None:+ setattr(generation_config, key, getattr(model_config, key, None))+ return {**kwargs, "generation_config": generation_config, "use_model_defaults": False}++def PatchRL(FastLanguageModel):try:from trl.models.utils import unwrap_model_for_generation@@ -213,6 +241,8 @@ def PatchRL(FastLanguageModel):original_generate = generating_model.generatedef generate_with_clone(*args, **kwargs):+ if generating_model is not unwrapped_model:+ kwargs = _caller_sampling_only(generating_model, kwargs)out = original_generate(*args, **kwargs)if isinstance(out, torch.Tensor):return out.clone()@@ -335,6 +365,10 @@ def PatchRL(FastLanguageModel):setattr(current_trainer, unwrap, unsloth_unwrap_model_for_generation)except:continue+ # TRL >= 0.29 keeps PPO only under trl.experimental, which the trl.trainer walk above never sees.+ ppo_module = _import_trl_experimental_trainers().get("ppo")+ if ppo_module is not None and hasattr(ppo_module, unwrap):+ setattr(ppo_module, unwrap, unsloth_unwrap_model_for_generation)Trainer.prediction_step = unsloth_prediction_step@@ -747,6 +781,42 @@ def _wrap_full_eval_keeps_trainable_dtype(trainer_cls):setattr(trainer_cls, loop_name, _make(original, loop_name))+def _ppo_padding_mask_modules(trainer):+ # Unsloth's training forward drops the attention mask (it assumes right padding), but PPO+ # left-pads every query, so policy and value forwards would attend to the pads.+ seen = set()+ for name in ("policy_model", "value_model", "ref_model"):+ model = getattr(trainer, name, None)+ if model is None or not hasattr(model, "modules"):+ continue+ for module in model.modules():+ if hasattr(module, "embed_tokens") and id(module) not in seen:+ seen.add(id(module))+ yield module+++def _wrap_ppo_train(trainer_cls):+ if not hasattr(trainer_cls, "train"):+ return+ original = trainer_cls.train+ if getattr(original, "_unsloth_ppo_train_wrapped", False):+ return++ def wrapped(self, *args, **kwargs):+ masked = list(_ppo_padding_mask_modules(self))+ for module in masked:+ module._unsloth_keep_padding_mask = True+ try:+ return original(self, *args, **kwargs)+ finally:+ for module in masked:+ module._unsloth_keep_padding_mask = False++ functools.update_wrapper(wrapped, original)+ wrapped._unsloth_ppo_train_wrapped = True+ trainer_cls.train = wrapped++def _wrap_grpo_generate_and_score(trainer_cls):if not hasattr(trainer_cls, "_generate_and_score_completions"):return@@ -3617,6 +3687,11 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):_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 == "ppo_trainer":+ try:+ _wrap_ppo_train(getattr(created_module, f"Unsloth{RLTrainer_name}"))+ except Exception as e:+ logger.info(f"Unsloth: Could not wrap PPO rollouts for {RLTrainer_name}: {e}")if trainer_file == "gkd_trainer" and "_unsloth_trl_compute_loss" in RLTrainer_source:try:_wrap_grpo_hidden_states_fallback(diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex f4fbc849253..afb69b4bf6b 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -173,6 +173,19 @@ def gkd_trainer_mask_prompt(function_name, function):RL_FUNCTIONS["gkd_trainer"].append(gkd_trainer_mask_prompt)+def ppo_trainer_free_rollout_logits(function_name, function):+ # TRL keeps the float32 (batch, response_length, vocab) generation logits alive through every PPO+ # epoch, though only the logprobs taken from them are read: 1.2 GB on a T4 for 8 x 256 Qwen3 tokens.+ if function_name != "train" or "logitss" not in function:+ return function+ old = "del (logprob, ref_logprob, full_value, value, score, unwrapped_model)"+ new = "del (logprob, ref_logprob, full_value, value, score, unwrapped_model, logitss)"+ return function.replace(old, new, 1)+++RL_FUNCTIONS["ppo_trainer"].append(ppo_trainer_free_rollout_logits)++def dpo_trainer_fix_columns(call_args, extra_args):if "model" in call_args and "train_dataset" in call_args:fix_dpo = (