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.

Hand the LoRA to vLLM on TRL 1.x GRPO rollouts (#8701)

Daniel Hanc3230a749abe
diff --git a/tests/version_compat/test_trl_vllm_generation_lora_patch.py b/tests/version_compat/test_trl_vllm_generation_lora_patch.py
new file mode 100644
index 00000000000..0746e36ab4d
--- /dev/null
+++ b/tests/version_compat/test_trl_vllm_generation_lora_patch.py
@@ -0,0 +1,567 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team.
+"""Behavioural check on `vllm_generation_init_patch()` across TRL `generate` shapes.
+
+`fast_inference = True` GRPO hands its own vLLM engine to TRL's
+`VLLMGeneration`, and the adapter only reaches vLLM if `lora_request=` is
+passed on the rollout call. That injection used to be a source rewrite of
+TRL's `VLLMGeneration.generate`, anchored on a
+`self.llm.collective_rpc("reload_weights")` line. TRL 1.10.0 deleted that
+call (it invokes `self.sync_weights()` instead), so the anchor matched
+nothing and raised, the `lora_request` injection that ran after it in the
+same function never happened, and `_init_vllm` / `sync_weights` were already
+installed -- rollouts came from the BASE model, exit 0, finite losses, no
+warning a user would connect to it.
+
+So these tests are shape-driven, not version-driven: they build a synthetic
+`trl.generation.vllm_generation` module whose `_init_vllm` / `sync_weights`
+are TRL-shaped (those two are still source-patched) and whose `generate`
+reaches the engine the way a given TRL era reaches it, then run the real
+patch over it and watch what arrives at a fake engine. No vLLM, no GPU, no
+network, and no dependence on which TRL happens to be installed.
+"""
+
+from __future__ import annotations
+
+import importlib.machinery
+import importlib.util
+import linecache
+import os
+import sys
+import textwrap
+import types
+
+import pytest
+
+
+# Collection must stay cheap and safe where the runtime is absent (the
+# daily-fresh-fetch job collects tests/version_compat/ with only pytest).
+if importlib.util.find_spec("torch") is None:
+ pytest.skip("torch not installed; this test drives the real patch", allow_module_level = True)
+
+
+# --- TRL-shaped method sources ------------------------------------------------
+#
+# `_init_vllm` and `sync_weights` are still rewritten from source, so their text
+# has to carry the anchors the regexes look for: an `self.llm = LLM(...)` block
+# and a bare `def sync_weights(self):` line.
+
+_INIT_VLLM = """
+def _init_vllm(self, model):
+ if self.mode == "colocate":
+ self.llm = LLM(
+ model = model.name_or_path,
+ enable_sleep_mode = self.enable_sleep_mode,
+ )
+ else:
+ self.llm = None
+"""
+
+_SYNC_WEIGHTS = """
+def sync_weights(self):
+ if self._llm_weights_sleeping:
+ self.llm.wake_up()
+ self._llm_weights_sleeping = False
+ self.llm.collective_rpc("update_weights")
+"""
+
+# TRL >= 1.10.0: no `collective_rpc("reload_weights")` anywhere in `generate`.
+# This is the shape that silently dropped the adapter.
+_GENERATE_TRL_1_10 = """
+def generate(self, prompts, **kwargs):
+ self.sync_weights()
+ return self.llm.generate(prompts, sampling_params = self.sampling_params, use_tqdm = False)
+"""
+
+# TRL 0.22.2 era: reloads the checkpoint into the engine before sampling.
+_GENERATE_TRL_0_22 = """
+def generate(self, prompts, **kwargs):
+ if self.enable_sleep_mode:
+ self.llm.wake_up()
+ self.llm.collective_rpc("reload_weights")
+ return self.llm.generate(prompts, sampling_params = self.sampling_params, use_tqdm = False)
+"""
+
+# Conversational rollouts go through `LLM.chat`, which needs the same adapter.
+_GENERATE_CHAT = """
+def generate(self, prompts, **kwargs):
+ self.sync_weights()
+ return self.llm.chat(prompts, sampling_params = self.sampling_params)
+"""
+
+# Server mode: TRL talks to a remote vLLM over HTTP and `self.llm` is None.
+_GENERATE_SERVER = """
+def generate(self, prompts, **kwargs):
+ return self.client.generate(prompts)
+"""
+
+# A `sync_weights` the source patch cannot anchor on -- stands in for any future
+# TRL signature change, and is how we reach the all-or-nothing rollback branch.
+_SYNC_WEIGHTS_UNPATCHABLE = """
+def sync_weights(self, tags = None):
+ self.llm.collective_rpc("update_weights")
+"""
+
+
+class FakeEngine:
+ """Stand-in for the vLLM `LLM` object unsloth hands to TRL.
+
+ `shared_weights = True` is what marks an engine as unsloth's own, i.e. one
+ that already holds the live training weights and therefore needs the LoRA
+ passed explicitly on every call.
+ """
+
+ shared_weights = True
+
+ def __init__(
+ self,
+ log,
+ shared_weights = True,
+ ):
+ self.log = log
+ self.shared_weights = shared_weights
+ self.woken = 0
+
+ def generate(self, *args, **kwargs):
+ self.log.append(("generate", kwargs.get("lora_request", "ABSENT")))
+ return ["generated"]
+
+ def chat(self, *args, **kwargs):
+ self.log.append(("chat", kwargs.get("lora_request", "ABSENT")))
+ return ["chatted"]
+
+ def collective_rpc(self, method, *args, **kwargs):
+ self.log.append(("collective_rpc", method))
+ return "rpc_ran"
+
+ def wake_up(self, *args, **kwargs):
+ self.woken += 1
+ self.log.append(("wake_up", kwargs.get("tags", None)))
+
+
+def _rl_replacements():
+ from unsloth.models import rl_replacements
+ return rl_replacements
+
+
+def _build_fake_trl(
+ monkeypatch,
+ generate_src,
+ sync_src = _SYNC_WEIGHTS,
+ version = "1.10.0",
+):
+ """Install a synthetic `trl.generation.vllm_generation` and return its class.
+
+ Everything goes through `monkeypatch`, so sys.modules is exactly as it was
+ once the test ends no matter which order tests run in.
+ """
+ class_src = (
+ "class VLLMGeneration:\n"
+ + "\n".join(
+ textwrap.indent(textwrap.dedent(src), " ")
+ for src in (_INIT_VLLM, sync_src, generate_src)
+ )
+ + "\n"
+ )
+
+ # `inspect.getsource` is how the patch reads these methods back out.
+ filename = f"<fake_trl_{version}_vllm_generation>"
+ monkeypatch.setitem(
+ linecache.cache,
+ filename,
+ (len(class_src), None, [line + "\n" for line in class_src.splitlines()], filename),
+ )
+
+ vllm_generation = types.ModuleType("trl.generation.vllm_generation")
+ vllm_generation.__file__ = filename
+ vllm_generation.__spec__ = importlib.machinery.ModuleSpec(
+ name = "trl.generation.vllm_generation",
+ loader = None,
+ origin = filename,
+ )
+ # Referenced by the unpatched `_init_vllm` branch; never actually called here.
+ vllm_generation.LLM = FakeEngine
+ exec(compile(class_src, filename, "exec"), vllm_generation.__dict__)
+
+ generation = types.ModuleType("trl.generation")
+ generation.__spec__ = importlib.machinery.ModuleSpec(
+ name = "trl.generation",
+ loader = None,
+ origin = "<fake trl>",
+ )
+ generation.vllm_generation = vllm_generation
+
+ # A fake `trl` package too, so nothing here depends on a real TRL install:
+ # the patch gates on `importlib.util.find_spec("trl")`, which resolves out of
+ # sys.modules when the name is already there.
+ trl = types.ModuleType("trl")
+ trl.__spec__ = importlib.machinery.ModuleSpec(name = "trl", loader = None, origin = "<fake trl>")
+ trl.__spec__.submodule_search_locations = []
+ trl.__path__ = []
+ trl.__version__ = version
+ trl.generation = generation
+
+ monkeypatch.setitem(sys.modules, "trl", trl)
+ monkeypatch.setitem(sys.modules, "trl.generation", generation)
+ monkeypatch.setitem(sys.modules, "trl.generation.vllm_generation", vllm_generation)
+ monkeypatch.setattr(
+ _rl_replacements(),
+ "importlib_version",
+ lambda name: version if name == "trl" else "0",
+ )
+ return vllm_generation.VLLMGeneration
+
+
+def _make_generation(
+ cls,
+ log,
+ shared_weights = True,
+ with_lora = True,
+ sleeping = True,
+):
+ """A `VLLMGeneration` instance shaped the way unsloth's `_init_vllm` leaves it."""
+ self = cls.__new__(cls)
+ self.llm = FakeEngine(log, shared_weights = shared_weights)
+ self.mode = "colocate"
+ self.enable_sleep_mode = True
+ self._llm_weights_sleeping = sleeping
+ self.sampling_params = {"n": 1}
+ if with_lora:
+ self.unsloth_fast_inference_lora = True
+ self._unsloth_load_lora = lambda name, load_tensors = False: f"LORA[{name}|{load_tensors}]"
+ return self
+
+
+def _lora_requests(log, kind = "generate"):
+ return [entry[1] for entry in log if entry[0] == kind]
+
+
+def _lora_name():
+ """The adapter directory the patch derives, device suffix and all.
+
+ Recomputed rather than hardcoded: the suffix depends on CUDA_VISIBLE_DEVICES,
+ which is set on any CI runner that has a GPU and unset on the ones that do not.
+ """
+ name = "vllm_gen_lora"
+ if "CUDA_VISIBLE_DEVICES" in os.environ:
+ name += "_" + os.environ.get("CUDA_VISIBLE_DEVICES", "0").replace(",", "")
+ return name
+
+
+def test_lora_reaches_engine_without_reload_weights_anchor(monkeypatch):
+ """TRL >= 1.10.0 `generate`: no reload_weights line, adapter still passed.
+
+ This is the reported bug. Before the fix the anchor regex matched nothing,
+ raised, and took the `lora_request` injection down with it, so vLLM sampled
+ the base model.
+ """
+ cls = _build_fake_trl(monkeypatch, _GENERATE_TRL_1_10)
+ _rl_replacements().vllm_generation_init_patch()
+
+ log = []
+ self = _make_generation(cls, log)
+ assert cls.generate(self, ["hello"]) == ["generated"]
+
+ requests = _lora_requests(log)
+ assert requests, f"engine.generate was never called: {log}"
+ assert all(isinstance(r, str) and r.startswith("LORA[vllm_gen_lora") for r in requests), (
+ f"vLLM was asked to sample without the adapter -> rollouts come from the "
+ f"BASE model. lora_request values: {requests}"
+ )
+ assert all(
+ "|True" in r for r in requests
+ ), f"the adapter tensors were not loaded (load_tensors=True): {requests}"
+
+
+def test_trl_0_22_shape_keeps_working(monkeypatch):
+ """The older `generate`, with the reload_weights call, must not regress."""
+ cls = _build_fake_trl(monkeypatch, _GENERATE_TRL_0_22, version = "0.28.0")
+ _rl_replacements().vllm_generation_init_patch()
+
+ log = []
+ self = _make_generation(cls, log)
+ assert cls.generate(self, ["hello"]) == ["generated"]
+
+ requests = _lora_requests(log)
+ assert requests and all(
+ str(r).startswith("LORA[vllm_gen_lora") for r in requests
+ ), f"adapter missing on the 0.22.2-era shape: {log}"
+ # The shared engine already holds the live training weights, so a
+ # reload_weights would drag the original checkpoint back off disk.
+ assert (
+ ("collective_rpc", "reload_weights") not in log
+ ), f"reload_weights reached the shared engine and clobbered the trained weights: {log}"
+
+
+def test_chat_rollouts_get_the_adapter_too(monkeypatch):
+ """Conversational rollouts go through `LLM.chat`, same adapter requirement."""
+ cls = _build_fake_trl(monkeypatch, _GENERATE_CHAT)
+ _rl_replacements().vllm_generation_init_patch()
+
+ log = []
+ self = _make_generation(cls, log)
+ assert cls.generate(self, [[{"role": "user", "content": "hi"}]]) == ["chatted"]
+
+ requests = _lora_requests(log, kind = "chat")
+ assert requests and all(
+ str(r).startswith("LORA[vllm_gen_lora") for r in requests
+ ), f"adapter missing on llm.chat: {log}"
+
+
+def test_engine_is_restored_after_the_call(monkeypatch):
+ """The override lasts one `generate` call and no longer.
+
+ The same engine object backs `model.fast_generate`, so a leaked override
+ would silently attach the training adapter to unrelated user generations.
+ """
+ cls = _build_fake_trl(monkeypatch, _GENERATE_TRL_1_10)
+ _rl_replacements().vllm_generation_init_patch()
+
+ log = []
+ self = _make_generation(cls, log)
+ cls.generate(self, ["hello"])
+
+ for name in ("generate", "chat", "collective_rpc"):
+ assert name not in self.llm.__dict__, f"{name} override outlived the call"
+
+ log.clear()
+ self.llm.generate(["direct call, e.g. model.fast_generate"])
+ assert _lora_requests(log) == [
+ "ABSENT"
+ ], f"a direct engine call picked up an injected lora_request: {log}"
+
+
+def test_pre_existing_instance_attribute_is_put_back(monkeypatch):
+ """Restoring must not delete an override the engine already carried."""
+ cls = _build_fake_trl(monkeypatch, _GENERATE_TRL_1_10)
+ _rl_replacements().vllm_generation_init_patch()
+
+ log = []
+ self = _make_generation(cls, log)
+
+ def sentinel(*args, **kwargs):
+ log.append(("generate", kwargs.get("lora_request", "ABSENT")))
+ return ["generated"]
+
+ self.llm.generate = sentinel
+ cls.generate(self, ["hello"])
+
+ assert (
+ self.llm.__dict__.get("generate", None) is sentinel
+ ), "the engine's own generate was deleted instead of restored"
+ assert all(str(r).startswith("LORA[") for r in _lora_requests(log)), log
+
+
+def test_engine_trl_created_itself_is_left_alone(monkeypatch):
+ """No shared weights and no unsloth LoRA -> upstream behaviour, untouched."""
+ cls = _build_fake_trl(monkeypatch, _GENERATE_TRL_0_22, version = "0.28.0")
+ _rl_replacements().vllm_generation_init_patch()
+
+ log = []
+ self = _make_generation(cls, log, shared_weights = False, with_lora = False)
+ assert cls.generate(self, ["hello"]) == ["generated"]
+
+ assert _lora_requests(log) == [
+ "ABSENT"
+ ], f"unsloth injected an adapter into an engine TRL owns: {log}"
+ assert ("collective_rpc", "reload_weights") in log, (
+ f"TRL's own reload_weights was suppressed on an engine unsloth does not "
+ f"share weights with: {log}"
+ )
+
+
+def test_server_mode_falls_through(monkeypatch):
+ """Server mode has no `self.llm` at all; the wrapper must just delegate."""
+ cls = _build_fake_trl(monkeypatch, _GENERATE_SERVER)
+ _rl_replacements().vllm_generation_init_patch()
+
+ log = []
+ self = cls.__new__(cls)
+ self.llm = None
+ self.mode = "server"
+ self.client = types.SimpleNamespace(
+ generate = lambda prompts, **kwargs: log.append(("client", prompts)) or ["served"],
+ )
+ assert cls.generate(self, ["hello"]) == ["served"]
+ assert log == [("client", ["hello"])]
+
+
+def test_sleeping_engine_is_woken_before_sync_weights_returns(monkeypatch):
+ """TRL >= 1.x only wakes the engine inside `sync_weights`.
+
+ The shared-weights guard returns early from that method, so without an
+ explicit wake-up the next rollout runs against a sleeping engine.
+ """
+ cls = _build_fake_trl(monkeypatch, _GENERATE_TRL_1_10)
+ _rl_replacements().vllm_generation_init_patch()
+
+ log = []
+ self = _make_generation(cls, log, sleeping = True)
+ cls.generate(self, ["hello"])
+
+ assert self.llm.woken == 1, f"engine was never woken: {log}"
+ assert self._llm_weights_sleeping is False
+ # ...and the sleep flag means it is woken once, not once per rollout.
+ cls.generate(self, ["again"])
+ assert self.llm.woken == 1, f"engine woken again while already awake: {log}"
+
+
+def test_failed_patch_rolls_all_three_methods_back(monkeypatch):
+ """Half-patched is worse than unpatched, so it must be unreachable.
+
+ `_init_vllm` + `sync_weights` without the adapter injection means no weight
+ sync AND no LoRA, which is exactly the silent base-model sampling this fix
+ exists to stop.
+ """
+ cls = _build_fake_trl(monkeypatch, _GENERATE_TRL_1_10, sync_src = _SYNC_WEIGHTS_UNPATCHABLE)
+ originals = {name: getattr(cls, name) for name in ("_init_vllm", "sync_weights", "generate")}
+
+ _rl_replacements().vllm_generation_init_patch()
+
+ for name, original in originals.items():
+ assert getattr(cls, name) is original, (
+ f"{name} stayed patched after a sibling patch failed; VLLMGeneration "
+ f"is now half-patched"
+ )
+
+
+def test_patching_twice_does_not_double_wrap(monkeypatch):
+ """`vllm_generation_init_patch` runs once per RL trainer patch, so it repeats."""
+ cls = _build_fake_trl(monkeypatch, _GENERATE_TRL_1_10)
+ rl_replacements = _rl_replacements()
+
+ rl_replacements.vllm_generation_init_patch()
+ after_first = {name: getattr(cls, name) for name in ("_init_vllm", "sync_weights", "generate")}
+ rl_replacements.vllm_generation_init_patch()
+
+ for name, method in after_first.items():
+ assert getattr(cls, name) is method, f"{name} was re-patched on the second call"
+
+ # One layer of wrapping, and it unwraps to TRL's own function so that
+ # `inspect.getsource` / `inspect.signature` still report TRL's `generate`.
+ wrapped = getattr(cls.generate, "__wrapped__", None)
+ assert wrapped is not None, "the wrapper did not set __wrapped__"
+ assert getattr(wrapped, "__wrapped__", None) is None, "generate was wrapped twice"
+
+ log = []
+ self = _make_generation(cls, log)
+ cls.generate(self, ["hello"])
+ assert len(_lora_requests(log)) == 1, f"generate reached the engine twice: {log}"
+
+
+# --- vLLM signature fidelity --------------------------------------------------
+#
+# The tests above use an engine whose methods take `*args, **kwargs`, so they say
+# nothing about how the injection behaves against vLLM's ACTUAL parameter lists.
+# Those differ between the two entry points, and that difference matters:
+#
+# LLM.generate(self, prompts, sampling_params = None, *, use_tqdm, lora_request, ...)
+# LLM.chat(self, messages, sampling_params = None, use_tqdm = True, lora_request = None, ...)
+#
+# `lora_request` is KEYWORD-ONLY on `generate` in every vLLM release from 0.11.0 to
+# 0.27.1, so nothing can reach it positionally there. On `chat` it is an ordinary
+# positional parameter, and its index has already moved once (`tokenization_kwargs`
+# was inserted in 0.18.0). A caller that fills it positionally and an injector that
+# then adds it as a keyword is `TypeError: got multiple values for argument`.
+
+
+class VLLMSignatureEngine(FakeEngine):
+ """`FakeEngine` with vLLM 0.27.1's real parameter lists on both entry points."""
+
+ def generate(
+ self,
+ prompts,
+ sampling_params = None,
+ *,
+ use_tqdm = True,
+ lora_request = None,
+ priority = None,
+ tokenization_kwargs = None,
+ mm_processor_kwargs = None,
+ ):
+ self.log.append(("generate", lora_request if lora_request is not None else "ABSENT"))
+ return ["generated"]
+
+ def chat(
+ self,
+ messages,
+ sampling_params = None,
+ use_tqdm = True,
+ lora_request = None,
+ chat_template = None,
+ chat_template_content_format = "auto",
+ add_generation_prompt = True,
+ continue_final_message = False,
+ tools = None,
+ chat_template_kwargs = None,
+ tokenization_kwargs = None,
+ mm_processor_kwargs = None,
+ ):
+ self.log.append(("chat", lora_request if lora_request is not None else "ABSENT"))
+ return ["chatted"]
+
+
+# TRL reaching `chat` with `lora_request` as the fourth POSITIONAL argument.
+_GENERATE_CHAT_POSITIONAL = """
+def generate(self, prompts, **kwargs):
+ self.sync_weights()
+ return self.llm.chat(prompts, self.sampling_params, False, self.caller_lora)
+"""
+
+
+def test_the_adapter_still_reaches_a_signature_accurate_engine(monkeypatch):
+ """`generate`'s keyword-only `lora_request` accepts the injected keyword."""
+ cls = _build_fake_trl(monkeypatch, _GENERATE_TRL_1_10)
+ _rl_replacements().vllm_generation_init_patch()
+
+ log = []
+ self = _make_generation(cls, log)
+ self.llm = VLLMSignatureEngine(log)
+
+ assert cls.generate(self, ["hello"]) == ["generated"]
+ assert _lora_requests(log) == ["LORA[%s|True]" % _lora_name()], log
+
+
+def test_a_positionally_supplied_adapter_is_not_injected_over(monkeypatch):
+ """The caller already filled `lora_request`; a keyword on top is a TypeError.
+
+ Not hypothetical arithmetic: `chat` takes `lora_request` positionally in every
+ vLLM release checked, so this is reachable from any TRL that spells the call
+ that way. Before the signature check the wrapper raised here.
+ """
+ cls = _build_fake_trl(monkeypatch, _GENERATE_CHAT_POSITIONAL)
+ _rl_replacements().vllm_generation_init_patch()
+
+ log = []
+ self = _make_generation(cls, log)
+ self.llm = VLLMSignatureEngine(log)
+ self.caller_lora = "CALLER_LORA"
+
+ assert cls.generate(self, [[{"role": "user", "content": "hi"}]]) == ["chatted"]
+ # The caller's own adapter, untouched, and exactly one call.
+ assert _lora_requests(log, kind = "chat") == ["CALLER_LORA"], log
+
+
+def test_an_explicit_none_adapter_is_overridden(monkeypatch):
+ """`lora_request = None` by keyword means base-model rollouts, which is the bug.
+
+ A shared-weights engine holds the BASE weights, so honouring the None is how
+ the adapter goes missing in the first place. Only a non-None value from the
+ caller is treated as a choice worth keeping.
+ """
+ cls = _build_fake_trl(
+ monkeypatch,
+ """
+def generate(self, prompts, **kwargs):
+ self.sync_weights()
+ return self.llm.generate(prompts, sampling_params = self.sampling_params, lora_request = None)
+""",
+ )
+ _rl_replacements().vllm_generation_init_patch()
+
+ log = []
+ self = _make_generation(cls, log)
+ self.llm = VLLMSignatureEngine(log)
+
+ assert cls.generate(self, ["hello"]) == ["generated"]
+ assert _lora_requests(log) == ["LORA[%s|True]" % _lora_name()], log
diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py
index a2c87b1a45c..7a9fa4ca249 100644
--- a/unsloth/models/rl_replacements.py
+++ b/unsloth/models/rl_replacements.py
@@ -3329,7 +3329,16 @@ def vllm_generation_init_patch():
guard = (
" if getattr(getattr(self, 'llm', None), 'shared_weights', False) or "
"getattr(self, 'unsloth_fast_inference_lora', False):\n"
- " # Unsloth fast inference LoRA shares weights with vLLM already.\n"
+ " # Unsloth fast inference LoRA shares weights with vLLM already,\n"
+ " # so there is nothing to push. But TRL >= 1.x only wakes the\n"
+ " # engine from sleep mode inside this method, and generate()\n"
+ " # delegates that wake-up to it, so still do it here or the next\n"
+ " # generate runs against a sleeping engine. Unsloth's allocator\n"
+ " # skips weights, so wake everything rather than a tag subset.\n"
+ " if getattr(self, '_llm_weights_sleeping', False) and "
+ "getattr(self, 'llm', None) is not None:\n"
+ " self.llm.wake_up()\n"
+ " self._llm_weights_sleeping = False\n"
" return\n\n"
)
return match.group("def_line") + guard + body
@@ -3341,42 +3350,153 @@ def vllm_generation_init_patch():
)
return patched_src
- def patch_generate(src):
- pattern = re.compile(
- r"^(?P<indent>[ \t]*)self\.llm\.collective_rpc\(\s*(['\"])reload_weights\2\s*\)\s*$",
- re.MULTILINE,
- )
-
- def replace_reload_weights(match):
- indent = match.group("indent")
- # Chain getattr so server mode (no self.llm) is safe here too.
- return (
- f"{indent}if not (getattr(getattr(self, 'llm', None), 'shared_weights', False) or "
- f"getattr(self, 'unsloth_fast_inference_lora', False)):\n"
- f'{indent} self.llm.collective_rpc("reload_weights")'
- )
+ # `generate` is deliberately NOT source-patched.
+ #
+ # It used to be, with two regexes: one anchored on a
+ # `self.llm.collective_rpc("reload_weights")` line, and one injecting
+ # `lora_request=...` into `self.llm.generate(...)`. Both anchors live inside a TRL
+ # method body, and both have already drifted:
+ # * TRL >= 1.x deleted the `collective_rpc("reload_weights")` call from `generate`
+ # entirely and calls `self.sync_weights()` instead
+ # (https://github.com/vllm-project/vllm/issues/29341). The old anchor matched 0
+ # times, raised, and - because the lora injection ran *after* it in the same
+ # function - the adapter stopped being passed to vLLM at all. Since `_init_vllm`
+ # and `sync_weights` had already been installed by then, weights were no longer
+ # synced into vLLM either, so GRPO rollouts were silently sampled from the BASE
+ # model with no error raised.
+ # * `(self\.llm\.generate\([^\)]+)\)` is not paren-balanced, so it also mis-edits any
+ # call whose arguments contain nested parentheses or span several lines.
+ #
+ # So intercept on the vLLM engine instead of on TRL's method body. `self.llm` is the
+ # vLLM `LLM` object in colocate mode in every TRL release that has `VLLMGeneration`,
+ # and `LLM.generate` / `LLM.chat` / `LLM.collective_rpc` are public, stable vLLM APIs.
+ # Checked against every vLLM release from 0.11.0 to 0.27.1: all three exist on `LLM` at
+ # each one, `generate` and `chat` both take `lora_request`, `LLM` has no `__slots__` and
+ # no `__setattr__`/`__getattr__` hook (so the instance override below always takes), and
+ # nothing here is decorated. TRL's method body is free to move around;
+ # whatever shape it takes, it has to reach the engine through those calls. The
+ # override is scoped to the dynamic extent of one `VLLMGeneration.generate` call and
+ # is undone in a `finally`, so `model.fast_generate` and any other user of the same
+ # engine are unaffected.
+ _UNSLOTH_GENERATE_WRAPPED = "_unsloth_vllm_generation_lora_wrapped"
+
+ # Mirror the per-device naming in rl.py so two ranks on one node do not race on the
+ # same adapter directory.
+ lora_name = "vllm_gen_lora"
+ if "CUDA_VISIBLE_DEVICES" in os.environ:
+ lora_name += "_" + os.environ.get("CUDA_VISIBLE_DEVICES", "0").replace(",", "")
+
+ def install_generate_wrapper():
+ original_generate = getattr(vllm_generation.VLLMGeneration, "generate", None)
+ if original_generate is None:
+ logger.info("Unsloth: Could not find VLLMGeneration.generate")
+ return False
+ if getattr(original_generate, _UNSLOTH_GENERATE_WRAPPED, False):
+ return True
- patched_src, num_replacements = pattern.subn(replace_reload_weights, src, count = 1)
- if num_replacements == 0:
- raise RuntimeError(
- "Unsloth: Warning - regex did not match, VLLMGeneration.generate patch may have failed"
+ def generate(self, *args, **kwargs):
+ llm = getattr(self, "llm", None)
+ sharing = getattr(llm, "shared_weights", False) or getattr(
+ self, "unsloth_fast_inference_lora", False
)
+ if llm is None or not sharing:
+ # Server mode, or a vLLM engine TRL created itself -> upstream behaviour.
+ return original_generate(self, *args, **kwargs)
+
+ load_lora = getattr(self, "_unsloth_load_lora", None)
+ saved = []
+
+ def override(name, make_replacement):
+ bound = getattr(llm, name, None)
+ if bound is None:
+ return
+ had_own = name in getattr(llm, "__dict__", {})
+ try:
+ setattr(llm, name, make_replacement(bound))
+ except (AttributeError, TypeError):
+ return
+ saved.append((name, had_own, bound))
+
+ def caller_already_bound_lora(bound, args, kwargs):
+ """Has the caller's own argument list already filled `lora_request`?
+
+ A keyword `lora_request` that is not None is the caller's choice, so leave
+ it. A keyword `lora_request = None` is not: on a shared-weights engine that
+ means base-model rollouts, which is the bug this whole wrapper exists to
+ fix, so it gets overwritten.
+
+ The positional case is the one that has to be checked rather than assumed.
+ `lora_request` is keyword-only on `LLM.generate` in every vLLM release from
+ 0.11.0 to 0.27.1, but on `LLM.chat` it is an ordinary positional-or-keyword
+ parameter, and its index there has already moved once (`tokenization_kwargs`
+ landed in 0.18.0). A caller that passed it positionally has supplied it, and
+ adding a keyword on top would be `TypeError: got multiple values`, not a
+ missing adapter. Bind the real signature instead of counting arguments so a
+ future reshuffle cannot reintroduce that.
+ """
+ if kwargs.get("lora_request", None) is not None:
+ return True
+ try:
+ positional = inspect.signature(bound).bind_partial(*args).arguments
+ except (TypeError, ValueError):
+ # Unintrospectable callable (C extension, odd wrapper): the keyword
+ # check above is all we have, and injecting is the safe default.
+ return False
+ return "lora_request" in positional
+
+ def wrap_generation_call(bound):
+ def unsloth_generation_call(*args, **kwargs):
+ # vLLM needs the adapter handed to it explicitly: the shared engine
+ # holds the BASE weights, and sync_weights is a no-op when sharing.
+ if load_lora is not None and not caller_already_bound_lora(bound, args, kwargs):
+ kwargs["lora_request"] = load_lora(lora_name, load_tensors = True)
+ return bound(*args, **kwargs)
+
+ return unsloth_generation_call
+
+ def wrap_collective_rpc(bound):
+ def unsloth_collective_rpc(method, *args, **kwargs):
+ # The engine already shares the live training weights, so
+ # reload_weights would pull the ORIGINAL checkpoint back off disk.
+ if method == "reload_weights":
+ return None
+ return bound(method, *args, **kwargs)
+
+ return unsloth_collective_rpc
+
+ override("generate", wrap_generation_call)
+ override("chat", wrap_generation_call)
+ override("collective_rpc", wrap_collective_rpc)
+ try:
+ return original_generate(self, *args, **kwargs)
+ finally:
+ for name, had_own, bound in reversed(saved):
+ try:
+ if had_own:
+ setattr(llm, name, bound)
+ else:
+ delattr(llm, name)
+ except AttributeError:
+ pass
- # Inject lora_request when sharing weights (vLLM needs the adapter)
- lora_generate_pattern = re.compile(
- r"(self\.llm\.generate\([^\)]+)\)",
+ generate.__name__ = getattr(original_generate, "__name__", "generate")
+ generate.__qualname__ = getattr(
+ original_generate, "__qualname__", "VLLMGeneration.generate"
)
+ generate.__doc__ = getattr(original_generate, "__doc__", None)
+ # inspect.getsource / inspect.signature unwrap this, so drift detectors and any
+ # other source-reading patch still see TRL's own `generate`.
+ generate.__wrapped__ = original_generate
+ setattr(generate, _UNSLOTH_GENERATE_WRAPPED, True)
+ vllm_generation.VLLMGeneration.generate = generate
+ return True
- def inject_lora_request(match):
- return (
- f"{match.group(1)}, lora_request="
- f"self._unsloth_load_lora('vllm_gen_lora', load_tensors=True) "
- f"if hasattr(self, '_unsloth_load_lora') else None)"
- )
-
- patched_src = lora_generate_pattern.sub(inject_lora_request, patched_src)
- return patched_src
-
+ # Snapshot before patching: a HALF-patched VLLMGeneration is worse than an unpatched
+ # one. `_init_vllm` + `sync_weights` without the generate-side adapter injection means
+ # no weight sync AND no LoRA, i.e. rollouts from the base model with no error. If any
+ # one of the three fails, put all three back.
+ method_names = ("_init_vllm", "sync_weights", "generate")
+ originals = {name: getattr(vllm_generation.VLLMGeneration, name, None) for name in method_names}
try:
init_patched = patch_vllm_generation_method(
"_init_vllm",
@@ -3390,13 +3510,11 @@ def vllm_generation_init_patch():
"if getattr(getattr(self, 'llm', None), 'shared_weights', False) or getattr(self, 'unsloth_fast_inference_lora', False):",
"sync_weights",
)
- generate_patched = patch_vllm_generation_method(
- "generate",
- patch_generate,
- "if not (getattr(getattr(self, 'llm', None), 'shared_weights', False) or getattr(self, 'unsloth_fast_inference_lora', False)):",
- "generate",
- )
+ generate_patched = install_generate_wrapper()
except RuntimeError as e:
+ for name, original in originals.items():
+ if original is not None:
+ setattr(vllm_generation.VLLMGeneration, name, original)
logger.warning(str(e))
return