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
Let TRL AsyncGRPOTrainer train Unsloth models; fix GRPO vision rewards for tool images and TRL 1.15 (#13205)
Daniel Han4c902beebc1b
diff --git a/tests/test_async_grpo_patch.py b/tests/test_async_grpo_patch.pynew file mode 100644index 00000000000..5524b06e200--- /dev/null+++ b/tests/test_async_grpo_patch.py@@ -0,0 +1,314 @@+# Unsloth Zoo - Utilities for Unsloth+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.+#+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published+# by the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.++"""CPU checks for patch_trl_async_grpo (loaded from rl.py source, TRL's async module replaced by a fake)."""++from __future__ import annotations++import ast+import functools+import importlib+import os+import sys+import types+import warnings++import pytest+import torch++REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))+RL_SOURCE_PATH = os.path.join(REPO_ROOT, "unsloth", "models", "rl.py")+NAMES = (+ "_without_instance_bound_methods",+ "_packed_seq_lengths_from_position_ids",+ "_is_unsloth_fast_backbone",+ "_unsloth_async_grpo_lm_head",+ "patch_trl_async_grpo",+)+++class _Logger:+ def info(self, *a, **k):+ pass+++def _load(fast_backbone_types = ()):+ src = open(RL_SOURCE_PATH, encoding = "utf-8").read()+ ns = {+ "copy": __import__("copy"),+ "types": types,+ "torch": torch,+ "functools": functools,+ "importlib": importlib,+ "warnings": warnings,+ "logger": _Logger(),+ }+ for node in ast.parse(src).body:+ if isinstance(node, ast.FunctionDef) and node.name in NAMES:+ exec(compile(ast.Module([node], []), RL_SOURCE_PATH, "exec"), ns)+ assert all(n in ns for n in NAMES)+ ns["_is_unsloth_fast_backbone"] = lambda b: isinstance(b, fast_backbone_types)+ return ns+++class FastBackbone(torch.nn.Module):+ pass+++class CausalLM(torch.nn.Module):+ def __init__(+ self,+ backbone,+ attn = "sdpa",+ ):+ super().__init__()+ self.model = backbone+ self.config = types.SimpleNamespace(+ _attn_implementation = attn, _name_or_path = "org/Tiny-Model"+ )++ @property+ def base_model(self):+ return self.model++ def forward(self, *a, **k):+ return k+++class Peft(torch.nn.Module):+ def __init__(self, inner):+ super().__init__()+ self.inner = inner++ @property+ def config(self): # PeftModel forwards attribute lookups to the wrapped model+ return self.inner.config++ def get_base_model(self):+ return self.inner+++def fake_trl(monkeypatch):+ calls = {"fused": [], "create": [], "init": []}+ mod = types.ModuleType("trl.experimental.async_grpo.async_grpo_trainer")++ def create_model_from_path(model_id, **kw):+ calls["create"].append(model_id)+ return CausalLM(torch.nn.Module(), attn = "kernels-community/flash-attn3")++ def add_fused_lm_head(model, **kw):+ calls["fused"].append(model)+ orig = model.forward++ def fused(+ *a,+ fused_lm_head = False,+ **k,+ ):+ return {"fused": fused_lm_head, **orig(*a, **k)}++ model.forward = fused++ class AsyncGRPOConfig:+ def __init__(self, output_dir):+ self.output_dir = output_dir++ class AsyncGRPOTrainer:+ def __init__(+ self,+ model,+ reward_funcs = None,+ args = None,+ **kw,+ ):+ calls["init"].append((model, args))+ mod.add_fused_lm_head(mod.create_model_from_path(model))++ mod.create_model_from_path = create_model_from_path+ mod.add_fused_lm_head = add_fused_lm_head+ mod.AsyncGRPOConfig = AsyncGRPOConfig+ mod.AsyncGRPOTrainer = AsyncGRPOTrainer+ for name in ("trl", "trl.experimental", "trl.experimental.async_grpo"):+ pkg = types.ModuleType(name)+ pkg.__path__ = []+ pkg.__spec__ = importlib.machinery.ModuleSpec(name, None, is_package = True)+ monkeypatch.setitem(sys.modules, name, pkg)+ mod.__spec__ = importlib.machinery.ModuleSpec(mod.__name__, None)+ monkeypatch.setitem(sys.modules, mod.__name__, mod)+ sys.modules["trl.experimental.async_grpo"].async_grpo_trainer = mod+ return mod, calls+++def test_packed_seq_lengths_from_position_ids():+ f = _load()["_packed_seq_lengths_from_position_ids"]+ pos = torch.tensor([[0, 1, 2, 0, 1, 0, 1, 2, 3]])+ assert f(pos).tolist() == [3, 2, 4]+ assert f(pos).dtype == torch.int32+ # A lone sequence still gets its length: it also lifts Unsloth's max_seq_length truncation for the row.+ assert f(torch.tensor([[0, 1, 2, 3]])).tolist() == [4]+ assert f(torch.tensor([[1, 2, 0, 1]])) is None # does not start at a sequence start+ assert f(torch.tensor([[0, 1], [0, 1]])) is None # padded batch, not one packed row+ assert f(None) is None+++def test_unsloth_model_passes_through_and_gets_boundaries(fake_trl):+ mod, calls = fake_trl+ ns = _load(fast_backbone_types = (FastBackbone,))+ ns["patch_trl_async_grpo"]()+ lm = CausalLM(FastBackbone())+ peft = Peft(lm)+ trainer = mod.AsyncGRPOTrainer(peft, None)+ # Fused head goes on the CausalLM under the PEFT wrapper.+ assert calls["create"] == []+ assert calls["fused"] == [lm]+ # Default args derived from the model name instead of crashing on model.split.+ assert calls["init"][0][1].output_dir == "Tiny-Model-AsyncGRPO"+ pos = torch.tensor([[0, 1, 0, 1, 2]])+ out = lm.forward(position_ids = pos, fused_lm_head = True)+ assert out["packed_seq_lengths"].tolist() == [2, 3]+ assert "packed_seq_lengths" not in lm.forward(position_ids = pos)+ mod.AsyncGRPOTrainer(Peft(CausalLM(FastBackbone())), None, None)+ assert calls["init"][1][1].output_dir == "Tiny-Model-AsyncGRPO"+ mod.AsyncGRPOTrainer("org/x", None, args = mod.AsyncGRPOConfig("o"))+ assert calls["create"] == ["org/x"]+++def test_non_unsloth_sdpa_model_is_refused(fake_trl):+ mod, _ = fake_trl+ ns = _load()+ ns["patch_trl_async_grpo"]()+ with pytest.raises(ValueError, match = "attend to each other"):+ mod.AsyncGRPOTrainer(+ CausalLM(torch.nn.Module(), attn = "sdpa"), None, args = mod.AsyncGRPOConfig("o")+ )+ # flash attention reads position_ids resets itself: left to TRL, no boundaries injected.+ lm = CausalLM(torch.nn.Module(), attn = "flash_attention_2")+ mod.AsyncGRPOTrainer(lm, None, args = mod.AsyncGRPOConfig("o"))+ assert "packed_seq_lengths" not in lm.forward(+ position_ids = torch.tensor([[0, 1, 0, 1]]), fused_lm_head = True+ )+++def test_patch_is_idempotent(fake_trl):+ mod, _ = fake_trl+ ns = _load()+ ns["patch_trl_async_grpo"]()+ first = (mod.create_model_from_path, mod.add_fused_lm_head, mod.AsyncGRPOTrainer.__init__)+ ns["patch_trl_async_grpo"]()+ assert (+ mod.create_model_from_path,+ mod.add_fused_lm_head,+ mod.AsyncGRPOTrainer.__init__,+ ) == first+++class Tok:+ def __init__(self):+ self.vocab = {"a": 1}++ def save_pretrained(self, d):+ return "plain"++ def encode(self, s):+ return [self.vocab[c] for c in s]+++def _unsloth_tokenizer_save_pretrained(self, d):+ return "patched"+++def _patch_like_unsloth(tok):+ tok.original_save_pretrained = tok.save_pretrained+ tok.save_pretrained = types.MethodType(_unsloth_tokenizer_save_pretrained, tok)+ return tok+++def test_rollout_worker_tokenizer_is_picklable():+ import pickle++ f = _load()["_without_instance_bound_methods"]+ plain = Tok()+ assert f(plain) is plain+ tok = _patch_like_unsloth(Tok())+ with pytest.raises((pickle.PicklingError, AttributeError, TypeError)):+ pickle.loads(pickle.dumps(tok))+ clean = f(tok)+ assert (+ clean is not tok and tok.save_pretrained(".") == "patched"+ ) # the trainer's tokenizer keeps Unsloth's saving+ back = pickle.loads(pickle.dumps(clean))+ assert back.encode("a") == [1] and back.save_pretrained(".") == "plain"+ proc = types.SimpleNamespace(tokenizer = _patch_like_unsloth(Tok()))+ clean_proc = f(proc)+ assert clean_proc is not proc and "save_pretrained" not in vars(clean_proc.tokenizer)+ assert "save_pretrained" in vars(proc.tokenizer)+++def test_rollout_worker_subclass_cleans_processing_class(fake_trl):+ mod, _ = fake_trl+ seen = {}++ class AsyncRolloutWorker:+ def __init__(+ self,+ processing_class = None,+ **kw,+ ):+ seen["pc"] = processing_class++ mod.AsyncRolloutWorker = AsyncRolloutWorker+ ns = _load()+ ns["patch_trl_async_grpo"]()+ tok = _patch_like_unsloth(Tok())+ w = mod.AsyncRolloutWorker(processing_class = tok)+ assert (+ isinstance(w, AsyncRolloutWorker)+ and mod.AsyncRolloutWorker.__name__ == "AsyncRolloutWorker"+ )+ assert seen["pc"] is not tok and "save_pretrained" not in vars(seen["pc"])+++def test_trl_113_chunked_head_gets_boundaries(fake_trl):+ # TRL 1.13 / 1.14 name the head patch_chunked_lm_head and always score through it.+ mod, calls = fake_trl+ chunked = mod.add_fused_lm_head+ del mod.add_fused_lm_head++ def patch_chunked_lm_head(model, **kw):+ orig = model.forward+ model.forward = lambda *a, **k: {"chunked": True, **orig(*a, **k)}++ mod.patch_chunked_lm_head = patch_chunked_lm_head++ class Trainer:+ def __init__(+ self,+ model,+ reward_funcs = None,+ args = None,+ **kw,+ ):+ mod.patch_chunked_lm_head(mod.create_model_from_path(model))++ mod.AsyncGRPOTrainer = Trainer+ ns = _load(fast_backbone_types = (FastBackbone,))+ ns["patch_trl_async_grpo"]()+ lm = CausalLM(FastBackbone())+ mod.AsyncGRPOTrainer(Peft(lm), None)+ out = lm.forward(position_ids = torch.tensor([[0, 1, 2, 0, 1]]))+ assert out["chunked"] and out["packed_seq_lengths"].tolist() == [3, 2]+ assert chunked is not mod.patch_chunked_lm_headdiff --git a/tests/test_grpo_vision_reward_inputs.py b/tests/test_grpo_vision_reward_inputs.pynew file mode 100644index 00000000000..614bdbcb001--- /dev/null+++ b/tests/test_grpo_vision_reward_inputs.py@@ -0,0 +1,87 @@+# Unsloth Zoo - Utilities for Unsloth+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.+#+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published+# by the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.++"""GRPO reward rewrite: TRL VLM tool-image branch (no prompts_text) and TRL 1.15 (no completions_text)."""++from __future__ import annotations++import ast+import os+import textwrap++REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))+SOURCE = os.path.join(REPO_ROOT, "unsloth", "models", "rl_replacements.py")+++def _replacement():+ tree = ast.parse(open(SOURCE, encoding = "utf-8").read())+ for node in ast.walk(tree):+ if (+ isinstance(node, ast.Assign)+ and any(isinstance(t, ast.Name) and t.id == "replacement_string" for t in node.targets)+ and isinstance(node.value, ast.Constant)+ and "_calculate_rewards(inputs, prompts_text" in node.value.value+ ):+ return node.value.value+ raise AssertionError("reward replacement not found")+++class _Proc:+ def batch_decode(+ self,+ ids,+ skip_special_tokens = True,+ ):+ return [f"decoded:{i}" for i in ids]+++class _Self:+ processing_class = _Proc()++ def _calculate_rewards(self, inputs, prompts, completions, completion_ids_list):+ return prompts, completions+++def _run(body_prefix):+ src = (+ "def f(self, inputs, prompts, completions, completion_ids, completion_ids_list, images):\n"+ + textwrap.indent(textwrap.dedent(body_prefix), " ")+ + textwrap.indent(textwrap.dedent(_replacement()), " ")+ + "\n return rewards_per_func\n"+ )+ ns = {}+ exec(src, ns)+ return ns["f"]+++def test_vision_prompts_get_text_trl_113():+ f = _run("prompts_text = ['p']\ncompletions_text = ['c']\n")+ assert f(_Self(), [], ["msgs"], ["cmsgs"], [1], [[1]], [["img"]]) == (["p"], ["c"])+++def test_vision_prompts_get_text_trl_115_without_completions_text():+ f = _run("prompts_text = ['p']\n")+ assert f(_Self(), [], ["msgs"], ["cmsgs"], [7], [[7]], [["img"]]) == (["p"], ["decoded:7"])+++def test_tool_image_branch_keeps_messages():+ f = _run("pass\n")+ assert f(_Self(), [], ["msgs"], ["cmsgs"], [7], [[7]], [["tool_img"]]) == (["msgs"], ["cmsgs"])+++def test_text_only_keeps_messages():+ f = _run("prompts_text = ['p']\n")+ assert f(_Self(), [], ["msgs"], ["cmsgs"], [7], [[7]], None) == (["msgs"], ["cmsgs"])diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex d6edf917415..90d185d823b 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -18,6 +18,7 @@ import torchfrom typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Unionimport copyimport copyreg+import typesimport functoolsimport importlibimport importlib.util@@ -4184,6 +4185,145 @@ def patch_trl_vllm_generation():return+def _packed_seq_lengths_from_position_ids(position_ids):+ # One padding-free row whose position_ids restart at 0 per sequence -> int32 lengths, else None.+ if position_ids is None or position_ids.dim() != 2 or position_ids.shape[0] != 1:+ return None+ pos = position_ids[0]+ starts = torch.nonzero(pos == 0, as_tuple = False).flatten()+ if starts.numel() == 0 or int(starts[0]) != 0:+ return None+ ends = torch.cat([starts[1:], starts.new_tensor([pos.numel()])])+ return (ends - starts).to(torch.int32)+++def _without_instance_bound_methods(obj):+ # Per-instance save_pretrained / push_to_hub wrappers cannot be unpickled in a spawned process.+ if obj is None or not hasattr(obj, "__dict__"):+ return obj+ bound = [+ k for k, v in vars(obj).items() if isinstance(v, types.MethodType) and v.__self__ is obj+ ]+ inner = getattr(obj, "tokenizer", None)+ clean_inner = (+ _without_instance_bound_methods(inner) if inner is not None and inner is not obj else inner+ )+ if not bound and clean_inner is inner:+ return obj+ clone = copy.copy(obj)+ for k in bound:+ clone.__dict__.pop(k, None)+ if clean_inner is not inner:+ clone.__dict__["tokenizer"] = clean_inner+ return clone+++def _is_unsloth_fast_backbone(backbone):+ from .llama import LlamaModel_fast_forward+ return getattr(type(backbone), "forward", None) is LlamaModel_fast_forward+++def _unsloth_async_grpo_lm_head(original, flag):+ # TRL >= 1.15 `add_fused_lm_head` (active when `flag` is passed), TRL 1.13-1.14 `patch_chunked_lm_head` (always).+ def patch_lm_head(model, *args, **kwargs):+ # The head replaces the CausalLM forward and calls its backbone, so it must sit under any PEFT wrapper.+ target = model.get_base_model() if hasattr(model, "get_base_model") else model+ original(target, *args, **kwargs)+ if not _is_unsloth_fast_backbone(getattr(target, "base_model", None)):+ attn = getattr(target.config, "_attn_implementation", None) or ""+ if "flash" not in str(attn):+ raise ValueError(+ "Unsloth: AsyncGRPOTrainer packs several sequences into one row and separates them only by "+ f"position_ids resets, which `{attn}` attention ignores, so sequences would attend to each other. "+ "Load the model with FastLanguageModel, or with a flash attention implementation."+ )+ return+ head_forward = target.forward++ @functools.wraps(head_forward)+ def forward(*f_args, **f_kwargs):+ # Unsloth's attention reads sequence boundaries from packed_seq_lengths, not position_ids resets.+ if (flag is None or f_kwargs.get(flag)) and f_kwargs.get("packed_seq_lengths") is None:+ lengths = _packed_seq_lengths_from_position_ids(f_kwargs.get("position_ids"))+ if lengths is not None:+ f_kwargs["packed_seq_lengths"] = lengths+ return head_forward(*f_args, **f_kwargs)++ target.forward = forward++ patch_lm_head._unsloth_async_grpo_patched = True+ return patch_lm_head+++def patch_trl_async_grpo():+ # Let TRL's AsyncGRPOTrainer take a loaded Unsloth model; keep packed rows from attending across sequences.+ if importlib.util.find_spec("trl.experimental") is None:+ return+ try:+ if importlib.util.find_spec("trl.experimental.async_grpo") is None:+ return+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ import trl.experimental.async_grpo.async_grpo_trainer as async_module+ except Exception as e:+ logger.info(f"Unsloth: Could not import trl.experimental.async_grpo: {e}")+ return+ heads = [+ (name, flag)+ for name, flag in (("add_fused_lm_head", "fused_lm_head"), ("patch_chunked_lm_head", None))+ if hasattr(async_module, name)+ ]+ if not heads or not all(+ hasattr(async_module, x) for x in ("create_model_from_path", "AsyncGRPOTrainer")+ ):+ return+ if getattr(getattr(async_module, heads[0][0]), "_unsloth_async_grpo_patched", False):+ return++ original_create = async_module.create_model_from_path++ @functools.wraps(original_create)+ def create_model_from_path(model_id, *args, **kwargs):+ if isinstance(model_id, torch.nn.Module):+ return model_id+ return original_create(model_id, *args, **kwargs)++ async_module.create_model_from_path = create_model_from_path+ for name, flag in heads:+ setattr(async_module, name, _unsloth_async_grpo_lm_head(getattr(async_module, name), flag))++ trainer_class = async_module.AsyncGRPOTrainer+ original_init = trainer_class.__init__++ @functools.wraps(original_init)+ def __init__(self, model, *args, **kwargs):+ config = args[1] if len(args) >= 2 else kwargs.get("args")+ if not isinstance(model, str) and config is None:+ name = getattr(getattr(model, "config", None), "_name_or_path", "") or "model"+ config = async_module.AsyncGRPOConfig(f"{name.split('/')[-1]}-AsyncGRPO")+ if len(args) >= 2:+ args = (args[0], config, *args[2:])+ else:+ kwargs["args"] = config+ original_init(self, model, *args, **kwargs)++ trainer_class.__init__ = __init__++ if hasattr(async_module, "AsyncRolloutWorker"):++ class AsyncRolloutWorker(async_module.AsyncRolloutWorker):+ # Its arguments are pickled into a spawned process, which only needs the tokenizer to tokenize.+ def __init__(self, *args, **kwargs):+ if "processing_class" in kwargs:+ kwargs["processing_class"] = _without_instance_bound_methods(+ kwargs["processing_class"]+ )+ super().__init__(*args, **kwargs)++ async_module.AsyncRolloutWorker = AsyncRolloutWorker+ return++def PatchFastRL(algorithm = None, FastLanguageModel = None):if FastLanguageModel is not None:PatchRL(FastLanguageModel)@@ -4201,5 +4341,9 @@ def PatchFastRL(algorithm = None, FastLanguageModel = None):patch_trl_rl_trainers()patch_trl_openenv()patch_trl_vllm_generation()+ try:+ patch_trl_async_grpo()+ except Exception as e:+ logger.info(f"Unsloth: Could not patch trl.experimental.async_grpo: {e}")if type(algorithm) is str and algorithm.islower():PatchRLStatistics(algorithm)diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 133a736bf47..aa57068e90a 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -1997,8 +1997,13 @@ def grpo_trainer__generate_and_score_completions(function_name, function):if trl_version >= Version("0.24.0"):string_to_find = " rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)"+ # TRL's VLM tool branch has no prompts_text; TRL 1.15 dropped completions_text, rebuilt as in 1.13.replacement_string = (- " if images is not None:\n"+ " _unsloth_reward_locals = locals()\n"+ " if images is not None and 'prompts_text' in _unsloth_reward_locals:\n"+ " completions_text = _unsloth_reward_locals.get('completions_text')\n"+ " if completions_text is None:\n"+ " completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)\n"" rewards_per_func = self._calculate_rewards(inputs, prompts_text, completions_text, completion_ids_list)\n"" else:\n"" rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)"