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
AsyncGRPOTrainer with fast_inference: train and generate on one GPU with shared weights (#13292)
Daniel Hane1d635460177
diff --git a/tests/test_async_grpo_fast_inference.py b/tests/test_async_grpo_fast_inference.pynew file mode 100644index 00000000000..b24f1fe21d5--- /dev/null+++ b/tests/test_async_grpo_fast_inference.py@@ -0,0 +1,421 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""In-process vLLM server for TRL AsyncGRPOTrainer with fast_inference=True, against a fake engine (CPU)."""++import importlib.util+import json+import sys+import threading+import time+import types+import urllib.error+import urllib.request+from pathlib import Path++import pytest++_MODULE = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "_async_grpo_vllm.py"+_spec = importlib.util.spec_from_file_location("_async_grpo_vllm", _MODULE)+server_module = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(server_module)+++class _Sampling:+ def __init__(self, **kwargs):+ self.kwargs = kwargs+++class _Lora:+ def __init__(self, path, lora_request_id):+ self.lora_path = path+ self.lora_int_id = lora_request_id+++class _FakeEngine:+ def __init__(self):+ lora_config = types.SimpleNamespace(max_lora_rank = 64)+ model_config = types.SimpleNamespace(max_model_len = 2048, dtype = "torch.bfloat16")+ scheduler_config = types.SimpleNamespace(max_num_seqs = 64)+ self.vllm_config = types.SimpleNamespace(+ model_config = model_config, lora_config = lora_config, scheduler_config = scheduler_config+ )+ self.requests = {}+ self.added_loras = []+ self.removed_loras = []+ self.aborted = []+ self.sleeping = False+ self.hold = threading.Event()+ self.hold.set()++ def add_request(+ self,+ request_id,+ prompt,+ params,+ lora_request = None,+ ):+ self.requests[request_id] = (prompt["prompt_token_ids"], params, lora_request)++ def step(self):+ self.hold.wait()+ outputs = []+ for request_id, (prompt, params, lora) in list(self.requests.items()):+ del self.requests[request_id]+ tokens = [prompt[-1] + 1, prompt[-1] + 2]+ completion = types.SimpleNamespace(+ token_ids = tokens,+ logprobs = [+ {t: types.SimpleNamespace(logprob = -0.5 * (i + 1))} for i, t in enumerate(tokens)+ ],+ finish_reason = "stop",+ )+ output = types.SimpleNamespace(+ request_id = request_id, finished = True, outputs = [completion]+ )+ output.params, output.lora = params, lora+ outputs.append(output)+ time.sleep(0.01)+ return outputs++ def abort_request(self, ids):+ self.aborted.extend(ids)+ for request_id in ids:+ self.requests.pop(request_id, None)++ def add_lora(self, lora):+ self.added_loras.append(lora.lora_int_id)++ def remove_lora(self, lora_id):+ self.removed_loras.append(lora_id)++ def is_sleeping(self):+ return self.sleeping+++class _FakeLLM:+ def __init__(self):+ self.llm_engine = _FakeEngine()+ self.woken = 0++ def get_default_sampling_params(self):+ return types.SimpleNamespace(+ temperature = 0.6, top_p = 0.95, top_k = 20, min_p = 0.0, repetition_penalty = 1.0+ )++ def wake_up(self):+ self.woken += 1+ self.llm_engine.sleeping = False+++def _model(llm):+ model = types.SimpleNamespace(+ vllm_engine = llm, config = types.SimpleNamespace(_name_or_path = "org/tiny")+ )+ model.load_lora = lambda path, lora_request_id = None: _Lora(path, lora_request_id)+ return model+++def served():+ llm = _FakeLLM()+ server = server_module.UnslothAsyncVLLMServer(_model(llm), sampling_params = _Sampling)+ yield server, llm+ server.stop()+++def _get(server, path):+ with urllib.request.urlopen(server.url + path, timeout = 10) as response:+ return response.status, json.loads(response.read())+++def _post(+ server,+ path,+ payload = None,+ timeout = 10,+):+ request = urllib.request.Request(+ server.url + path,+ data = json.dumps(payload or {}).encode(),+ headers = {"Content-Type": "application/json"},+ )+ with urllib.request.urlopen(request, timeout = timeout) as response:+ return response.status, json.loads(response.read())+++def _complete(+ server,+ prompt,+ model = "org/tiny",+ **extra,+):+ payload = {+ "model": model,+ "prompt": prompt,+ "max_tokens": 8,+ "temperature": 1.0,+ "top_p": 1.0,+ "top_k": None,+ "repetition_penalty": 1.0,+ "n": 1,+ "return_token_ids": True,+ "logprobs": 0,+ "seed": 7,+ **extra,+ }+ return _post(server, "/v1/completions", payload)[1]+++def test_introspection_endpoints_match_what_trl_reads(served):+ server, _ = served+ assert _get(server, "/health")[0] == 200+ assert _get(server, "/v1/models")[1]["data"][0]["max_model_len"] == 2048+ info = _get(server, "/server_info?config_format=json")[1]["vllm_config"]+ assert info["model_config"]["dtype"] == "torch.bfloat16"+ assert info["lora_config"]["max_lora_rank"] == 64+ assert info["lora_config"]["max_loras"] >= 10+ assert info["parallel_config"]["data_parallel_size"] == 1+ assert _get(server, "/get_world_size")[1]["world_size"] == 1+++def test_completion_returns_token_ids_and_sampled_logprobs(served):+ server, llm = served+ choice = _complete(server, [5, 6, 7])["choices"][0]+ assert choice["token_ids"] == [8, 9]+ assert choice["logprobs"]["token_logprobs"] == [-0.5, -1.0]+++def test_unset_fields_take_the_generation_config_defaults_and_set_fields_win(served):+ server, llm = served+ seen = {}+ original = llm.llm_engine.add_request++ def spy(+ request_id,+ prompt,+ params,+ lora_request = None,+ ):+ seen.update(params.kwargs)+ return original(request_id, prompt, params, lora_request)++ llm.llm_engine.add_request = spy+ _complete(server, [1])+ assert seen["top_k"] == 20 and seen["temperature"] == 1.0 and seen["seed"] == 7+ assert seen["logprobs"] == 0 and seen["n"] == 1 and seen["max_tokens"] == 8+++def test_concurrent_requests_all_complete(served):+ server, _ = served+ results = [None] * 32++ def worker(i):+ results[i] = _complete(server, [i])["choices"][0]["token_ids"]++ threads = [threading.Thread(target = worker, args = (i,)) for i in range(32)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(10)+ assert results == [[i + 1, i + 2] for i in range(32)]+++def test_pause_holds_new_requests_until_resume(served):+ server, _ = served+ _post(server, "/pause")+ box = {}+ thread = threading.Thread(target = lambda: box.update(out = _complete(server, [3])))+ thread.start()+ thread.join(0.5)+ assert thread.is_alive() and "out" not in box+ _post(server, "/resume")+ thread.join(10)+ assert box["out"]["choices"][0]["token_ids"] == [4, 5]+++def test_adapters_load_eagerly_serve_newest_and_unload_after_drain(served):+ server, llm = served+ engine = llm.llm_engine+ _post(server, "/v1/load_lora_adapter", {"lora_name": "trl-policy-v1", "lora_path": "/tmp/v1"})+ first = engine.added_loras[-1]+ seen = []+ original = engine.add_request+ engine.add_request = lambda rid, p, params, lora_request = None: (+ seen.append(lora_request),+ original(rid, p, params, lora_request),+ )[1]+ _complete(server, [1], model = "trl-policy-v1")+ assert seen[-1].lora_int_id == first+ _post(server, "/v1/load_lora_adapter", {"lora_name": "trl-policy-v2", "lora_path": "/tmp/v2"})+ second = engine.added_loras[-1]+ assert second != first+ # A request still naming v1 is served by the newest adapter.+ _complete(server, [1], model = "trl-policy-v1")+ assert seen[-1].lora_int_id == second++ _post(server, "/v1/unload_lora_adapter", {"lora_name": "trl-policy-v1"})+ assert first in engine.removed_loras+ _post(server, "/v1/unload_lora_adapter", {"lora_name": "missing"})+++def test_a_second_server_on_one_engine_gets_new_lora_ids():+ llm = _FakeLLM()+ engine = llm.llm_engine+ model = _model(llm)+ first = server_module.UnslothAsyncVLLMServer(model, sampling_params = _Sampling)+ _post(first, "/v1/load_lora_adapter", {"lora_name": "trl-policy-v1", "lora_path": "/tmp/v1"})+ first.stop()+ # The stopped server leaves nothing registered in the shared engine.+ assert engine.removed_loras == engine.added_loras+ second = server_module.UnslothAsyncVLLMServer(model, sampling_params = _Sampling)+ try:+ _post(+ second, "/v1/load_lora_adapter", {"lora_name": "trl-policy-v1", "lora_path": "/tmp/v1"}+ )+ finally:+ second.stop()+ assert len(set(engine.added_loras)) == 2+++def test_unload_of_an_adapter_in_use_waits_for_its_requests(served):+ server, llm = served+ engine = llm.llm_engine+ _post(server, "/v1/load_lora_adapter", {"lora_name": "a-v1", "lora_path": "/tmp/v1"})+ lora_id = engine.added_loras[-1]+ engine.hold.clear()+ box = {}+ thread = threading.Thread(target = lambda: box.update(out = _complete(server, [9], model = "a-v1")))+ thread.start()+ deadline = time.time() + 5+ while not engine.requests and time.time() < deadline:+ time.sleep(0.01)+ # The engine thread is blocked in step(); queue the unload behind it, then release.+ unload = threading.Thread(+ target = lambda: _post(server, "/v1/unload_lora_adapter", {"lora_name": "a-v1"})+ )+ unload.start()+ time.sleep(0.1)+ assert lora_id not in engine.removed_loras+ engine.hold.set()+ thread.join(10)+ unload.join(10)+ assert box["out"]["choices"][0]["token_ids"] == [10, 11]+ assert lora_id in engine.removed_loras+++def test_bad_prompts_and_engine_errors_are_http_errors(served):+ server, llm = served+ with pytest.raises(urllib.error.HTTPError) as error:+ _post(server, "/v1/completions", {"model": "x", "prompt": "text", "max_tokens": 4})+ assert error.value.code == 400++ def boom(*args, **kwargs):+ raise ValueError("prompt too long")++ llm.llm_engine.add_request = boom+ with pytest.raises(urllib.error.HTTPError) as error:+ _complete(server, [1])+ assert error.value.code == 400 and b"prompt too long" in error.value.read()+++def test_abort_all_fails_in_flight_requests_and_the_server_keeps_serving(served):+ server, llm = served+ llm.llm_engine.hold.clear()+ box = {}++ def run():+ try:+ box["out"] = _complete(server, [1])+ except urllib.error.HTTPError as error:+ box["code"] = error.code++ thread = threading.Thread(target = run)+ thread.start()+ deadline = time.time() + 5+ while not llm.llm_engine.requests and time.time() < deadline:+ time.sleep(0.01)+ # abort_all is a command: it runs once the blocked step returns.+ aborter = threading.Thread(target = server.abort_all)+ aborter.start()+ llm.llm_engine.hold.set()+ aborter.join(10)+ thread.join(10)+ assert "out" in box or box.get("code") == 400+ assert _complete(server, [4])["choices"][0]["token_ids"] == [5, 6]+++def test_abort_all_also_fails_requests_still_queued(served):+ server, llm = served+ _post(server, "/pause")+ box = {}++ def run():+ try:+ box["out"] = _complete(server, [7])+ except urllib.error.HTTPError as error:+ box["code"] = error.code++ thread = threading.Thread(target = run)+ thread.start()+ deadline = time.time() + 5+ while not server.engine.pending and time.time() < deadline:+ time.sleep(0.01)+ server.abort_all()+ thread.join(10)+ assert box == {"code": 400}+ _post(server, "/resume")+ assert not llm.llm_engine.requests+ assert _complete(server, [4])["choices"][0]["token_ids"] == [5, 6]+++def test_sleeping_engine_is_woken_once(monkeypatch):+ llm = _FakeLLM()+ llm.llm_engine.sleeping = True+ server = server_module.UnslothAsyncVLLMServer(_model(llm), sampling_params = _Sampling)+ try:+ assert llm.woken == 1+ finally:+ server.stop()+++def test_stop_is_idempotent_and_frees_the_port():+ llm = _FakeLLM()+ server = server_module.UnslothAsyncVLLMServer(_model(llm), sampling_params = _Sampling)+ url = server.url+ server.stop()+ server.stop()+ with pytest.raises(OSError):+ urllib.request.urlopen(url + "/health", timeout = 2)+++def test_model_without_load_lora_is_refused():+ llm = _FakeLLM()+ model = types.SimpleNamespace(vllm_engine = llm, config = types.SimpleNamespace(_name_or_path = "x"))+ with pytest.raises(ValueError, match = "get_peft_model"):+ server_module.UnslothAsyncVLLMServer(model, sampling_params = _Sampling)+++def test_trl_vllm_client_reads_this_server():+ pytest.importorskip("requests")+ try:+ from accelerate.state import PartialState+ from trl.experimental.async_grpo.vllm_client import VLLMClient+ except Exception:+ pytest.skip("TRL AsyncGRPO not installed")+ PartialState() # TRL logs through accelerate's logger+ llm = _FakeLLM()+ server = server_module.UnslothAsyncVLLMServer(_model(llm), sampling_params = _Sampling)+ try:+ client = VLLMClient(server.url, server_timeout = 10)+ client.wait_for_server_ready(poll_interval_s = 0.1)+ assert client.get_max_model_len() == 2048+ assert client.get_dtype() == "torch.bfloat16"+ assert client.get_world_size() == 1+ client.pause()+ client.load_lora_adapter("trl-policy-v1", "/tmp/v1")+ client.resume()+ client.unload_lora_adapter("trl-policy-v1")+ assert llm.llm_engine.added_loras and llm.llm_engine.removed_loras+ finally:+ server.stop()diff --git a/tests/test_async_grpo_packed_rows.py b/tests/test_async_grpo_packed_rows.pynew file mode 100644index 00000000000..2209a3aa76a--- /dev/null+++ b/tests/test_async_grpo_packed_rows.py@@ -0,0 +1,165 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""AsyncGRPO packed rows on compiled / vision backbones: enabled only where a packed sequence cannot see the+previous one (CPU, tiny random transformers models)."""++from __future__ import annotations++import ast+import functools+import importlib+import os+import types+from importlib.metadata import version as importlib_version++import pytest+import torch+from packaging.version import Version++transformers = pytest.importorskip("transformers")++RL_SOURCE_PATH = os.path.join(os.path.dirname(__file__), os.pardir, "unsloth", "models", "rl.py")+NAMES = (+ "_packed_seq_lengths_from_position_ids",+ "_text_prepended_position_ids",+ "_packing_honored",+ "_unsloth_async_grpo_lm_head",+)+++def _load():+ src = open(RL_SOURCE_PATH, encoding = "utf-8").read()+ ns = {+ "torch": torch,+ "functools": functools,+ "importlib": importlib,+ "Version": Version,+ "importlib_version": importlib_version,+ }+ 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)+ ns["_is_unsloth_fast_backbone"] = lambda backbone: False+ return ns+++def _tiny_llama():+ from transformers import LlamaConfig, LlamaForCausalLM++ torch.manual_seed(0)+ config = LlamaConfig(+ vocab_size = 128,+ hidden_size = 64,+ intermediate_size = 128,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ attn_implementation = "sdpa",+ )+ return LlamaForCausalLM(config).eval()+++def _tiny_qwen2_5_vl():+ try:+ from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration+ except ImportError:+ pytest.skip("transformers without Qwen2.5-VL")+ torch.manual_seed(0)+ config = Qwen2_5_VLConfig(+ text_config = dict(+ vocab_size = 160,+ hidden_size = 64,+ intermediate_size = 128,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ rope_scaling = {"type": "mrope", "mrope_section": [2, 3, 3]},+ ),+ vision_config = dict(+ depth = 1, hidden_size = 32, intermediate_size = 64, num_heads = 2, out_hidden_size = 64+ ),+ attn_implementation = "sdpa",+ )+ return Qwen2_5_VLForConditionalGeneration(config).eval()+++class _Leaky(torch.nn.Module):+ # Every token sees every earlier token of the row, whatever the position_ids say.+ def __init__(self):+ super().__init__()+ self.embed = torch.nn.Embedding(128, 16)+ self.config = types.SimpleNamespace(vocab_size = 128, get_text_config = lambda: self.config)++ def forward(+ self,+ input_ids,+ position_ids = None,+ use_cache = False,+ ):+ h = self.embed(input_ids).cumsum(1)+ return types.SimpleNamespace(last_hidden_state = h)+++class _LeakyLM(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.backbone = _Leaky()+ self.config = self.backbone.config++ @property+ def base_model(self):+ return self.backbone++ def forward(self, *a, **k):+ return k+++def _fake_fused_head(model, **kwargs):+ original = model.forward++ def forward(+ *a,+ fused_lm_head = False,+ **k,+ ):+ return {"fused": fused_lm_head, **k} if fused_lm_head else original(*a, **k)++ model.forward = forward+++def test_compiled_backbone_that_honors_packing_is_enabled_unchanged():+ ns = _load()+ model = _tiny_llama()+ assert ns["_packing_honored"](model.base_model)+ ns["_unsloth_async_grpo_lm_head"](_fake_fused_head, "fused_lm_head")(model)+ pos = torch.tensor([[0, 1, 2, 0, 1]])+ out = model.forward(position_ids = pos, fused_lm_head = True)+ assert out["position_ids"] is pos and "packed_seq_lengths" not in out+++def test_mrope_vlm_gets_text_prepended_position_ids():+ ns = _load()+ model = _tiny_qwen2_5_vl()+ # Plain 2D ids reach no packed mask (sequences attend to each other); the text-prepended form does.+ assert not ns["_packing_honored"](model.base_model)+ assert ns["_packing_honored"](model.base_model, ns["_text_prepended_position_ids"])+ ns["_unsloth_async_grpo_lm_head"](_fake_fused_head, "fused_lm_head")(model)+ pos = torch.tensor([[0, 1, 2, 0, 1]])+ out = model.forward(position_ids = pos, fused_lm_head = True)+ assert out["position_ids"].shape == (4, 1, 5)+ assert torch.equal(out["position_ids"][0], pos)+++def test_backbone_that_leaks_across_sequences_is_refused():+ ns = _load()+ with pytest.raises(ValueError, match = "attend to each other"):+ ns["_unsloth_async_grpo_lm_head"](_fake_fused_head, "fused_lm_head")(_LeakyLM())+++def test_self_test_restores_training_mode():+ ns = _load()+ model = _tiny_llama().train()+ model.model.layers[0].eval()+ ns["_packing_honored"](model.base_model)+ assert model.training and model.model.training and not model.model.layers[0].trainingdiff --git a/tests/test_async_grpo_patch.py b/tests/test_async_grpo_patch.pyindex 5524b06e200..61cd69ec8ac 100644--- a/tests/test_async_grpo_patch.py+++ b/tests/test_async_grpo_patch.py@@ -36,6 +36,17 @@ NAMES = ("_packed_seq_lengths_from_position_ids","_is_unsloth_fast_backbone","_unsloth_async_grpo_lm_head",+ "_fast_inference_engine",+ "_async_grpo_uses_fast_inference",+ "_dataset_has_images",+ "_start_async_grpo_vllm_server",+ "_check_async_grpo_fast_inference",+ "_text_prepended_position_ids",+ "_packing_honored",+ "_align_vlm_text_config",+ "_hold_peft_requires_grad",+ "_allow_moe_parameter_lora",+ "_check_async_grpo_adapter_servable","patch_trl_async_grpo",)@@ -54,7 +65,10 @@ def _load(fast_backbone_types = ()):"functools": functools,"importlib": importlib,"warnings": warnings,+ "weakref": __import__("weakref"),"logger": _Logger(),+ "Version": __import__("packaging.version", fromlist = ["Version"]).Version,+ "importlib_version": __import__("importlib.metadata", fromlist = ["version"]).version,}for node in ast.parse(src).body:if isinstance(node, ast.FunctionDef) and node.name in NAMES:@@ -183,6 +197,8 @@ def test_unsloth_model_passes_through_and_gets_boundaries(fake_trl):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"+ # TRL-built models (from a string id) have real backbones that pass the packing self-test.+ ns["_packing_honored"] = lambda backbone, transform = None: Truemod.AsyncGRPOTrainer("org/x", None, args = mod.AsyncGRPOConfig("o"))assert calls["create"] == ["org/x"]@@ -195,7 +211,21 @@ def test_non_unsloth_sdpa_model_is_refused(fake_trl):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.++ # Flash attention honors position_ids resets; TRL builds these models on CPU, where the self-test cannot run.+ def unrunnable(backbone, transform = None):+ raise NotImplementedError("flash varlen kernel on the CPU backend")++ ns["_packing_honored"] = unrunnable+ for attn in ("flash_attention_2", "kernels-community/flash-attn3"):+ lm = CausalLM(torch.nn.Module(), attn = attn)+ mod.AsyncGRPOTrainer(lm, None, args = mod.AsyncGRPOConfig("o"))+ # A self-test that cannot run refuses, like one that fails.+ with pytest.raises(ValueError, match = "keeps them apart failed"):+ mod.AsyncGRPOTrainer(+ CausalLM(torch.nn.Module(), attn = "sdpa"), None, args = mod.AsyncGRPOConfig("o")+ )+ ns["_packing_honored"] = lambda backbone, transform = None: Truelm = CausalLM(torch.nn.Module(), attn = "flash_attention_2")mod.AsyncGRPOTrainer(lm, None, args = mod.AsyncGRPOConfig("o"))assert "packed_seq_lengths" not in lm.forward(@@ -312,3 +342,320 @@ def test_trl_113_chunked_head_gets_boundaries(fake_trl):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_head+++class _FakeServer:+ started = []++ def __init__(self, model):+ self.url = "http://127.0.0.1:1"+ self.max_num_seqs = 96+ self.stopped = 0+ self.aborted = 0+ _FakeServer.started.append(self)++ def stop(self):+ self.stopped += 1++ def abort_all(self):+ self.aborted += 1+++def _fast_inference_peft(lm):+ peft = Peft(lm)+ peft.peft_config = {"default": object()}+ peft.vllm_engine = object()+ peft.load_lora = lambda *a, **k: None+ peft.lora = torch.nn.Parameter(torch.zeros(2))+ peft.frozen = torch.nn.Parameter(torch.zeros(2), requires_grad = False)+ return peft+++def fast_inference_trl(fake_trl):+ mod, calls = fake_trl+ mod.select_adapter_sync = lambda *a, **k: True++ class AsyncGRPOConfig:+ def __init__(+ self,+ output_dir,+ vllm_server_base_url = "http://localhost:8000",+ max_inflight_tasks = -1,+ ):+ self.output_dir = output_dir+ self.vllm_server_base_url = vllm_server_base_url+ self.max_inflight_tasks = max_inflight_tasks++ class AsyncGRPOTrainer:+ lora_sync = True++ def __init__(+ self,+ model,+ reward_funcs = None,+ args = None,+ train_dataset = None,+ **kw,+ ):+ calls["init"].append((model, args))+ self.url_seen = args.vllm_server_base_url+ # What TRL does for a VLM: unfreeze the text model.+ model.frozen.requires_grad_(True)+ self._lora_sync = AsyncGRPOTrainer.lora_sync++ def train(self):+ return "trained"++ mod.AsyncGRPOConfig = AsyncGRPOConfig+ mod.AsyncGRPOTrainer = AsyncGRPOTrainer+ mod._calls = calls+ _FakeServer.started = []+ ns = _load(fast_backbone_types = (FastBackbone,))+ ns["_start_async_grpo_vllm_server"] = _FakeServer+ ns["patch_trl_async_grpo"]()+ return mod, ns+++def calls_args(mod):+ return mod._calls["init"][-1][1]+++def test_fast_inference_model_gets_the_in_process_server(fast_inference_trl):+ mod, _ = fast_inference_trl+ peft = _fast_inference_peft(CausalLM(FastBackbone()))+ trainer = mod.AsyncGRPOTrainer(+ peft, None, args = mod.AsyncGRPOConfig("o"), train_dataset = [{"prompt": "hi"}]+ )+ (server,) = _FakeServer.started+ assert trainer.url_seen == server.url+ assert calls_args(mod).max_inflight_tasks == 96+ mod.AsyncGRPOTrainer(+ _fast_inference_peft(CausalLM(FastBackbone())),+ None,+ args = mod.AsyncGRPOConfig("o", max_inflight_tasks = 8),+ )+ assert calls_args(mod).max_inflight_tasks == 8+ assert not peft.frozen.requires_grad and peft.lora.requires_grad+ assert trainer.train() == "trained" and server.aborted == 1+++def test_explicit_server_url_keeps_the_external_server(fast_inference_trl):+ mod, _ = fast_inference_trl+ peft = _fast_inference_peft(CausalLM(FastBackbone()))+ cfg = mod.AsyncGRPOConfig("o", vllm_server_base_url = "http://gpu-box:8000")+ trainer = mod.AsyncGRPOTrainer(peft, None, args = cfg)+ assert _FakeServer.started == [] and trainer.url_seen == "http://gpu-box:8000"+++def test_fast_inference_refusals(fast_inference_trl):+ mod, _ = fast_inference_trl+ lm = CausalLM(FastBackbone())+ lm.vllm_engine = object()+ with pytest.raises(ValueError, match = "get_peft_model"):+ mod.AsyncGRPOTrainer(lm, None, args = mod.AsyncGRPOConfig("o"))+ images = [+ {+ "prompt": [+ {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "?"}]}+ ]+ }+ ]+ with pytest.raises(ValueError, match = "image prompts"):+ mod.AsyncGRPOTrainer(+ _fast_inference_peft(CausalLM(FastBackbone())),+ None,+ args = mod.AsyncGRPOConfig("o"),+ train_dataset = images,+ )+ mod.AsyncGRPOTrainer.lora_sync = False+ with pytest.raises(ValueError, match = "plain LoRA adapter"):+ mod.AsyncGRPOTrainer(+ _fast_inference_peft(CausalLM(FastBackbone())), None, args = mod.AsyncGRPOConfig("o")+ )+ assert _FakeServer.started[-1].stopped == 1+ assert _FakeServer.started == [_FakeServer.started[0]] or len(_FakeServer.started) == 1+ del mod.select_adapter_sync+ with pytest.raises(ValueError, match = "TRL >= 1.14"):+ mod.AsyncGRPOTrainer(+ _fast_inference_peft(CausalLM(FastBackbone())), None, args = mod.AsyncGRPOConfig("o")+ )+++def _vlm(copy_text_config):+ from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration++ config = Qwen2_5_VLConfig(+ text_config = dict(+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 1,+ num_attention_heads = 2,+ num_key_value_heads = 1,+ vocab_size = 128,+ rope_scaling = {"type": "mrope", "mrope_section": [1, 1, 2]},+ ),+ vision_config = dict(+ depth = 1, hidden_size = 16, intermediate_size = 32, num_heads = 2, out_hidden_size = 16+ ),+ )+ model = Qwen2_5_VLForConditionalGeneration(config)+ language_model = model.model.language_model+ if copy_text_config:+ # Unsloth's loaders hand each level its own config copy.+ language_model.config = __import__("copy").deepcopy(language_model.config)+ return model, model.config, language_model+++def test_vlm_text_config_answers_with_the_language_model_config_during_init():+ ns = _load()+ model, top, language_model = _vlm(copy_text_config = True)+ original = top.get_text_config()+ assert language_model.config is not original+ restore = ns["_align_vlm_text_config"](model)+ assert model.config.get_text_config() is language_model.config+ restore()+ assert model.config.get_text_config() is original+ assert "get_text_config" not in vars(top)+++def test_vlm_text_config_left_alone_when_identity_already_holds():+ ns = _load()+ model, top, language_model = _vlm(copy_text_config = False)+ restore = ns["_align_vlm_text_config"](model)+ assert "get_text_config" not in vars(top)+ assert model.config.get_text_config() is language_model.config+ restore()+++def test_peft_requires_grad_calls_are_held_during_init():+ ns = _load()+ model, _, language_model = _vlm(copy_text_config = True)+ model.peft_config = {"default": object()}+ model.requires_grad_(False)+ for p in model.lm_head.parameters():+ p.requires_grad_(False)+ restore = ns["_hold_peft_requires_grad"](model)+ # What TRL's VLM branch does: unfreeze the text model and LM head.+ model.requires_grad_(False)+ language_model.requires_grad_(True)+ model.get_output_embeddings().requires_grad_(True)+ assert not any(p.requires_grad for p in model.parameters())+ restore()+ assert all("requires_grad_" not in vars(m) for m in model.modules())+ language_model.requires_grad_(True)+ assert all(p.requires_grad for p in language_model.parameters())+++def test_non_peft_requires_grad_is_untouched():+ ns = _load()+ model, _, language_model = _vlm(copy_text_config = True)+ restore = ns["_hold_peft_requires_grad"](model)+ model.requires_grad_(False)+ language_model.requires_grad_(True)+ assert all(p.requires_grad for p in language_model.parameters())+ restore()+++def test_moe_parameter_lora_passes_validation_only_while_held():+ ns = _load()+ peft_config = types.SimpleNamespace(target_parameters = ["mlp.experts.gate_up_proj"])+ model = types.SimpleNamespace(peft_config = {"default": peft_config})+ seen = []++ def validate(peft_model):+ seen.append(peft_config.target_parameters)+ if peft_config.target_parameters:+ raise ValueError("target_parameters")+ return peft_config++ module = types.SimpleNamespace(validate_lora_for_vllm_sync = validate)+ restore = ns["_allow_moe_parameter_lora"](module, model)+ assert module.validate_lora_for_vllm_sync(model) is peft_config+ assert seen == [None]+ assert peft_config.target_parameters == ["mlp.experts.gate_up_proj"]+ restore()+ assert module.validate_lora_for_vllm_sync is validate+++def test_unservable_adapter_fails_at_construction(fast_inference_trl):+ mod, _ = fast_inference_trl+ peft = _fast_inference_peft(CausalLM(FastBackbone()))+ seen = []++ def load_lora(directory, load_tensors = False):+ seen.append(+ (os.path.exists(directory), os.path.isdir(os.path.dirname(directory)), load_tensors)+ )+ raise NotImplementedError("cannot serve this LoRA on MoE expert weights")++ peft.load_lora = load_lora+ with pytest.raises(NotImplementedError, match = "MoE expert"):+ mod.AsyncGRPOTrainer(+ peft, None, args = mod.AsyncGRPOConfig("o"), train_dataset = [{"prompt": "hi"}]+ )+ assert seen == [(False, True, True)]+ assert _FakeServer.started == []+ assert mod._calls["init"] == []+++def test_a_reused_config_keeps_its_own_server_url(fast_inference_trl):+ mod, _ = fast_inference_trl+ config = mod.AsyncGRPOConfig("o")+ trainer = mod.AsyncGRPOTrainer(+ _fast_inference_peft(CausalLM(FastBackbone())),+ None,+ args = config,+ train_dataset = [{"prompt": "hi"}],+ )+ assert trainer.url_seen == _FakeServer.started[0].url+ assert config.vllm_server_base_url == "http://localhost:8000"+ mod.AsyncGRPOTrainer.lora_sync = False+ try:+ config = mod.AsyncGRPOConfig("o")+ with pytest.raises(ValueError, match = "plain LoRA adapter"):+ mod.AsyncGRPOTrainer(+ _fast_inference_peft(CausalLM(FastBackbone())),+ None,+ args = config,+ train_dataset = [{"prompt": "hi"}],+ )+ finally:+ mod.AsyncGRPOTrainer.lora_sync = True+ assert (config.vllm_server_base_url, config.max_inflight_tasks) == ("http://localhost:8000", -1)+ assert _FakeServer.started[1].stopped == 1+++def test_servable_check_reads_only_a_lone_default_adapter():+ ns = _load()+ calls = []+ model = types.SimpleNamespace(+ peft_config = {"policy": object()}, load_lora = lambda *a, **k: calls.append(a)+ )+ ns["_check_async_grpo_adapter_servable"](model)+ model.peft_config = {"default": object(), "other": object()}+ ns["_check_async_grpo_adapter_servable"](model)+ assert calls == []+ model.peft_config = {"default": object()}+ ns["_check_async_grpo_adapter_servable"](model)+ assert len(calls) == 1+++def test_image_check_does_not_consume_an_iterable_dataset():+ ns = _load()++ class OneShot:+ def __init__(self):+ self.rows = iter([{"prompt": "a"}, {"prompt": "b"}])++ def __iter__(self):+ return self++ def __next__(self):+ return next(self.rows)++ data = OneShot()+ assert ns["_dataset_has_images"](data) is False+ assert next(data) == {"prompt": "a"}+ assert ns["_dataset_has_images"]([{"image": object()}]) is True+ assert ns["_dataset_has_images"]([{"prompt": "hi"}]) is Falsediff --git a/tests/test_trl_tool_chat_templates.py b/tests/test_trl_tool_chat_templates.pyindex a5e7f06537d..dfc331fe270 100644--- a/tests/test_trl_tool_chat_templates.py+++ b/tests/test_trl_tool_chat_templates.py@@ -12,6 +12,7 @@ other outcome of TRL unchanged.from __future__ import annotationsimport copy+import pickleimport importlib.utilimport pathlibimport sys@@ -206,3 +207,64 @@ def test_typed_tool_arguments_pick_the_right_training_family(patched):edited = "{#- Chat template fixes by Unsloth #}\n" + getattr(trl_utils, name)found = [n for n, _ in module._matching_families(trl_utils, tokenizer, edited, "conversation")]assert found == [name]+++def _child_accepts(processing_class, originals):+ # What AsyncGRPO's rollout worker does without Unsloth: skip TRL's match only when a parser is already set.+ processing_class = pickle.loads(pickle.dumps(processing_class))+ if all(getattr(processing_class, name, None) is None for name in ("response_template", "response_schema")):+ originals["add_response_schema"](processing_class)+ return processing_class+++def test_rollout_copy_carries_the_resolved_parser(patched):+ module, originals = patched+ tokenizer = _tokenizer(UNSLOTH_QWEN3)+ for uses_tools in (True, False):+ handed = module.with_response_parser(tokenizer, uses_tools)+ assert handed is not tokenizer and _parser(tokenizer) == (None, None)+ reference = originals["add_response_schema"](_tokenizer(trl_utils.qwen3_chat_template))+ assert _parser(_child_accepts(handed, originals)) == _parser(reference)+ assert handed.chat_template == UNSLOTH_QWEN3+++def test_rollout_copy_without_tools_needs_no_family(patched):+ module, originals = patched+ tokenizer = _tokenizer(PLAIN)+ assert module.with_response_parser(tokenizer, True) is tokenizer+ with pytest.raises(ValueError, match = "Unrecognized chat template"):+ _child_accepts(tokenizer, originals)+ handed = module.with_response_parser(tokenizer, False)+ child = _child_accepts(handed, originals)+ assert child.chat_template == PLAIN+ assert _parser(tokenizer) == (None, None)+ if not hasattr(child, "parse_response"):+ return # transformers 4.x: TRL's worker cannot parse any completion, Unsloth or not+ # The worker parses every completion, tools or not.+ prompt = child.apply_chat_template(+ [{"role": "user", "content": "hi"}], add_generation_prompt = True, return_dict = False+ )+ ids = child("The answer is 12.", add_special_tokens = False)["input_ids"]+ assert trl_utils.parse_response(child, ids, prefix = prompt) == {+ "role": "assistant",+ "content": "The answer is 12.",+ }+++def test_rollout_processor_gets_its_tokenizers_parser(patched):+ module, originals = patched++ from transformers import ProcessorMixin++ class Processor(ProcessorMixin):+ attributes = ["tokenizer"]++ tokenizer = _tokenizer(UNSLOTH_QWEN3)+ trl_utils.add_response_schema(tokenizer)+ # A tokenizer that already carries a parser (Gemma 4 repos ship one), inside a processor that does not.+ processor = Processor.__new__(Processor)+ processor.tokenizer = tokenizer+ processor.chat_template = UNSLOTH_QWEN3+ handed = module.with_response_parser(processor, True)+ assert handed is not processor and _parser(handed) == _parser(tokenizer)+ assert _parser(processor) == (None, None)diff --git a/unsloth/models/_async_grpo_vllm.py b/unsloth/models/_async_grpo_vllm.pynew file mode 100644index 00000000000..eb671f78c3c--- /dev/null+++ b/unsloth/models/_async_grpo_vllm.py@@ -0,0 +1,431 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++# TRL's AsyncGRPOTrainer generates through a vLLM server over HTTP. With fast_inference=True the model already owns+# an in-process vLLM engine sharing its base weights, so serve that engine on localhost instead: the rollout process+# is unchanged, no weights are copied, and only the LoRA adapter moves on each sync.++__all__ = [+ "UnslothAsyncVLLMServer",+]++import itertools+import json+import logging+import threading+import time+import uuid+from concurrent.futures import Future+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from urllib.parse import urlparse++logger = logging.getLogger(__name__)++# Adapter ids of their own, so they never collide with the ids Unsloth's GRPOTrainer hands out.+_LORA_ID_BASE = 1_000_000+# Process-wide: one engine outlives each trainer's server, and vLLM ignores a re-added id it already holds.+_LORA_IDS = itertools.count(_LORA_ID_BASE)+# Every request is served by the newest adapter (see `_lora_for`), so any number of named versions is servable.+_SERVABLE_LORAS = 1 << 20+_BATCH_WAIT_S = 0.0005+++def _sampled_logprob(logprobs, position, token_id):+ entry = logprobs[position]+ value = entry[token_id] if token_id in entry else next(iter(entry.values()))+ return float(getattr(value, "logprob", value))+++class _Engine:+ """Owns the vLLM engine on one thread; every engine call happens there."""++ def __init__(+ self,+ llm,+ load_lora,+ sampling_params = None,+ ):+ if sampling_params is None:+ from vllm import SamplingParams as sampling_params+ self.sampling_params = sampling_params+ self.llm = llm+ self.engine = llm.llm_engine+ self.load_lora = load_lora+ self.defaults = llm.get_default_sampling_params()+ self.cv = threading.Condition()+ self.pending = []+ self.commands = []+ self.active = {}+ self.paused = False+ self.stopping = False+ self.loras = {}+ self.newest = None+ self.lora_holds = {}+ self.aborted = None+ self.stats = {"requests": 0, "tokens": 0, "steps": 0, "step_s": 0.0, "max_batch": 0}+ self.thread = threading.Thread(+ target = self._run, name = "unsloth-async-grpo-vllm", daemon = True+ )+ self.thread.start()++ # Called from HTTP threads.+ def submit(self, prompt_ids, params, model):+ future = Future()+ with self.cv:+ if self.stopping:+ raise RuntimeError("Unsloth: the in-process vLLM server is stopped.")+ self.pending.append((prompt_ids, params, model, future))+ self.cv.notify()+ return future++ def call(self, fn):+ future = Future()+ with self.cv:+ if self.stopping:+ raise RuntimeError("Unsloth: the in-process vLLM server is stopped.")+ self.commands.append((fn, future))+ self.cv.notify()+ return future.result()++ def stop(self):+ with self.cv:+ self.stopping = True+ self.cv.notify()+ if threading.current_thread() is not self.thread:+ self.thread.join(timeout = 60)++ # Engine thread only.+ def _run(self):+ while True:+ with self.cv:+ while not (+ self.stopping+ or self.commands+ or (not self.paused and (self.pending or self.active))+ ):+ self.cv.wait()+ if self.stopping:+ break+ commands, self.commands = self.commands, []+ pending = []+ if not self.paused:+ pending, self.pending = self.pending, []+ for fn, future in commands:+ try:+ future.set_result(fn())+ except BaseException as error:+ future.set_exception(error)+ if self.aborted is not None:+ # Requests taken from the queue alongside an abort never reach the engine.+ for item in pending:+ item[-1].set_exception(self.aborted)+ pending, self.aborted = [], None+ for item in pending:+ self._admit(*item)+ if self.paused or not self.active:+ continue+ started = time.perf_counter()+ batch = len(self.active)+ try:+ outputs = self.engine.step()+ except BaseException as error:+ self._fail_active(error)+ continue+ with self.cv:+ # Releases the GIL so the HTTP thread can hand over requests that arrived during the step.+ if not (self.pending or self.commands or self.stopping):+ self.cv.wait(_BATCH_WAIT_S)+ stats = self.stats+ stats["steps"] += 1+ stats["step_s"] += time.perf_counter() - started+ stats["max_batch"] = max(stats["max_batch"], batch)+ for output in outputs:+ if output.finished and output.request_id in self.active:+ future, lora_id = self.active.pop(output.request_id)+ self._release(lora_id)+ stats["requests"] += 1+ stats["tokens"] += len(output.outputs[0].token_ids)+ future.set_result(output)+ self._fail_active(RuntimeError("Unsloth: the in-process vLLM server stopped."))+ with self.cv:+ pending, self.pending = self.pending, []+ for item in pending:+ item[-1].set_exception(RuntimeError("Unsloth: the in-process vLLM server stopped."))+ for name in list(self.loras):+ self.remove_adapter(name)++ def _admit(self, prompt_ids, params, model, future):+ request_id = uuid.uuid4().hex+ lora = self._lora_for(model)+ try:+ sampling = self.sampling_params(**{**self._default_kwargs(), **params})+ self.engine.add_request(+ request_id, {"prompt_token_ids": prompt_ids}, sampling, lora_request = lora+ )+ except BaseException as error:+ future.set_exception(error)+ return+ lora_id = lora.lora_int_id if lora is not None else None+ if lora_id is not None:+ self.hold_lora(lora_id)+ self.active[request_id] = (future, lora_id)++ def _default_kwargs(self):+ # The generation config's sampling defaults, as `vllm serve` applies them to fields a request leaves unset.+ names = ("temperature", "top_p", "top_k", "min_p", "repetition_penalty")+ return {+ name: getattr(self.defaults, name) for name in names if hasattr(self.defaults, name)+ }++ def _lora_for(self, model):+ # Serving the newest adapter keeps one adapter active (Unsloth engines hold max_loras=1) and is never staler+ # than the version the rollout named; the sampled logprobs are the serving policy's own.+ if self.newest is None:+ return None+ return self.loras[self.newest]++ def hold_lora(self, lora_id):+ self.lora_holds.setdefault(lora_id, [False, 0])[1] += 1++ def _release(self, lora_id):+ if lora_id is None or lora_id not in self.lora_holds:+ return+ state = self.lora_holds[lora_id]+ state[1] -= 1+ self._maybe_remove(lora_id)++ def _maybe_remove(self, lora_id):+ state = self.lora_holds.get(lora_id)+ if state is None or not state[0] or state[1] > 0:+ return+ del self.lora_holds[lora_id]+ try:+ self.engine.remove_lora(lora_id)+ except Exception as error:+ logger.info(f"Unsloth: could not remove LoRA {lora_id} from vLLM: {error}")++ def _fail_active(self, error):+ active, self.active = self.active, {}+ if active:+ try:+ self.engine.abort_request(list(active))+ except Exception:+ pass+ for future, lora_id in active.values():+ if not future.done():+ future.set_exception(error)+ if lora_id is not None and lora_id in self.lora_holds:+ self.lora_holds[lora_id][1] -= 1+ self._maybe_remove(lora_id)++ # Commands (run on the engine thread through `call`).+ def add_adapter(self, name, path):+ lora_id = next(_LORA_IDS)+ lora = self.load_lora(path, lora_request_id = lora_id)+ # Load now, while the trainer waits on this sync, not lazily on the first request.+ self.engine.add_lora(lora)+ self.loras[name] = lora+ self.newest = name+ self.lora_holds.setdefault(lora.lora_int_id, [False, 0])+ return lora.lora_int_id++ def remove_adapter(self, name):+ lora = self.loras.pop(name, None)+ if lora is None:+ return False+ if self.newest == name:+ self.newest = next(reversed(self.loras), None)+ state = self.lora_holds.setdefault(lora.lora_int_id, [False, 0])+ state[0] = True+ self._maybe_remove(lora.lora_int_id)+ return True++ def set_paused(self, paused):+ self.paused = paused+ return True++ def abort_all(self):+ error = RuntimeError("Unsloth: generation aborted when training ended.")+ with self.cv:+ pending, self.pending = self.pending, []+ for item in pending:+ item[-1].set_exception(error)+ self.aborted = error+ self._fail_active(error)+ return True+++class _Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"+ server_version = "UnslothAsyncVLLM"++ def log_message(self, *args):+ pass++ def _send(self, code, payload):+ body = json.dumps(payload).encode()+ try:+ self.send_response(code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError):+ # The rollout process exits with requests in flight when training ends.+ self.close_connection = True++ def do_GET(self):+ self._send(*self.server.owner.get(urlparse(self.path).path))++ def do_POST(self):+ owner = self.server.owner+ length = int(self.headers.get("Content-Length") or 0)+ try:+ body = json.loads(self.rfile.read(length) or b"{}") if length else {}+ except ValueError as error:+ return self._send(400, {"error": f"bad JSON: {error}"})+ path = urlparse(self.path).path+ if path == "/v1/completions":+ try:+ return self._send(200, owner.finish(owner.start(body).result()))+ except Exception as error:+ return self._send(400, {"error": f"{type(error).__name__}: {error}"})+ self._send(*owner.post(path, body))+++class UnslothAsyncVLLMServer:+ """Serves `model.vllm_engine` to TRL's AsyncGRPOTrainer on 127.0.0.1."""++ def __init__(+ self,+ model,+ model_name = None,+ sampling_params = None,+ ):+ llm = model.vllm_engine+ self.vllm_config = llm.llm_engine.vllm_config+ self.max_model_len = self.vllm_config.model_config.max_model_len+ self.max_num_seqs = self.vllm_config.scheduler_config.max_num_seqs+ self.model_name = model_name or getattr(+ getattr(model, "config", None), "_name_or_path", "model"+ )+ load_lora = getattr(model, "load_lora", None)+ if load_lora is None:+ raise ValueError(+ "Unsloth: AsyncGRPOTrainer with fast_inference=True needs a LoRA model from get_peft_model."+ )+ _keep_awake(llm)+ self.engine = _Engine(llm, load_lora, sampling_params)+ self.stopped = False+ self.url = f"http://127.0.0.1:{self._serve()}"++ def _serve(self):+ httpd = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)+ httpd.daemon_threads = True+ httpd.owner = self+ self._thread = threading.Thread(+ target = httpd.serve_forever, name = "unsloth-async-grpo-http", daemon = True+ )+ self._thread.start()++ def shutdown():+ httpd.shutdown()+ httpd.server_close()++ self._shutdown = shutdown+ return httpd.server_address[1]++ def server_info(self):+ lora_config = self.vllm_config.lora_config+ return {+ "model_config": {"dtype": str(self.vllm_config.model_config.dtype)},+ "lora_config": None+ if lora_config is None+ else {+ "max_lora_rank": lora_config.max_lora_rank,+ "max_loras": _SERVABLE_LORAS,+ },+ "parallel_config": {"data_parallel_size": 1},+ }++ def get(self, path):+ if path == "/health":+ return 200, {"status": "ok"}+ if path == "/v1/models":+ model = {"id": self.model_name, "object": "model", "max_model_len": self.max_model_len}+ return 200, {"object": "list", "data": [model]}+ if path == "/server_info":+ return 200, {"vllm_config": self.server_info()}+ if path == "/get_world_size":+ return 200, {"world_size": 1}+ return 404, {"error": f"unknown path {path}"}++ def post(self, path, body):+ engine = self.engine+ commands = {+ "/v1/load_lora_adapter": lambda: engine.add_adapter(+ body["lora_name"], body["lora_path"]+ ),+ "/v1/unload_lora_adapter": lambda: engine.remove_adapter(body.get("lora_name")),+ "/pause": lambda: engine.set_paused(True),+ "/resume": lambda: engine.set_paused(False),+ }+ if path not in commands:+ return 404, {"error": f"unknown path {path}"}+ try:+ engine.call(commands[path])+ except Exception as error:+ return 400, {"error": f"{type(error).__name__}: {error}"}+ return 200, {"status": "ok"}++ def start(self, body):+ prompt = body["prompt"]+ if not (isinstance(prompt, list) and all(isinstance(x, int) for x in prompt)):+ raise ValueError("Unsloth: the in-process vLLM server takes token-id prompts only.")+ params = {"n": 1, "max_tokens": body.get("max_tokens"), "detokenize": False}+ for name in ("temperature", "top_p", "top_k", "min_p", "repetition_penalty", "seed"):+ if body.get(name) is not None:+ params[name] = body[name]+ if body.get("logprobs") is not None:+ params["logprobs"] = int(body["logprobs"])+ return self.engine.submit(prompt, params, body.get("model"))++ @staticmethod+ def finish(output):+ completion = output.outputs[0]+ token_ids = list(completion.token_ids)+ logprobs = None+ if completion.logprobs is not None:+ logprobs = {+ "token_logprobs": [+ _sampled_logprob(completion.logprobs, i, t) for i, t in enumerate(token_ids)+ ]+ }+ choice = {+ "index": 0,+ "text": "",+ "token_ids": token_ids,+ "finish_reason": completion.finish_reason,+ "logprobs": logprobs,+ }+ return {"id": output.request_id, "object": "text_completion", "choices": [choice]}++ def abort_all(self):+ if not self.stopped:+ self.engine.call(self.engine.abort_all)++ def stop(self):+ if self.stopped:+ return+ self.stopped = True+ self.engine.stop()+ self._shutdown()+++def _keep_awake(llm):+ # Async generation overlaps training, so a standby (sleep mode) engine has to stay awake for the whole run.+ try:+ if llm.llm_engine.is_sleeping():+ llm.wake_up()+ except Exception as error:+ logger.info(f"Unsloth: could not check vLLM sleep state: {error}")diff --git a/unsloth/models/_trl_tool_templates.py b/unsloth/models/_trl_tool_templates.pyindex d29a305438a..7d5c3c4f51a 100644--- a/unsloth/models/_trl_tool_templates.py+++ b/unsloth/models/_trl_tool_templates.py@@ -7,6 +7,8 @@__all__ = ["patch_trl_tool_chat_templates",+ "with_trl_known_chat_template",+ "with_response_parser",]import copy@@ -299,6 +301,47 @@ def _wrap_get_training_chat_template(original, trl_module):return get_training_chat_template+def with_trl_known_chat_template(processing_class):+ """A copy whose chat_template is the TRL-known one rendering conversations and tool calls identically, for+ processes that run TRL without Unsloth (AsyncGRPO's rollout worker). Returns the input when TRL already knows the+ template or no single family matches."""+ try:+ import trl.chat_template_utils as trl_module+ except Exception:+ return processing_class+ template = _template_of(processing_class)+ if template is None:+ return processing_class+ original = getattr(+ trl_module.add_response_schema, "__wrapped__", trl_module.add_response_schema+ )+ tokenizer = _tokenizer_of(processing_class)+ try:+ original(_template_copy(tokenizer, template))+ return processing_class+ except Exception:+ pass+ conversation = {+ name for name, _ in _matching_families(trl_module, tokenizer, template, "conversation")+ }+ found = {}+ for name, known in _matching_families(trl_module, tokenizer, template, "completion"):+ if name in conversation and _parser_for(original, tokenizer, known) is not None:+ found.setdefault(known, name)+ if len(found) != 1:+ return processing_class+ ((known, name),) = found.items()+ clone = copy.copy(processing_class)+ clone.chat_template = known+ if clone is not tokenizer and getattr(clone, "tokenizer", None) is tokenizer:+ clone.tokenizer = copy.copy(tokenizer)+ clone.tokenizer.chat_template = known+ logger.info(+ f"Unsloth: the rollout process uses TRL's `{name}`, which renders this chat template identically."+ )+ return clone++def _rebind(name, original, replacement):# TRL trainers import these by name, so rebind every module still holding the original.for module in list(sys.modules.values()):@@ -329,3 +372,49 @@ def patch_trl_tool_chat_templates():_rebind(name, original, wrap(original, trl_module))patched = Truereturn patched+++_PLAIN_RESPONSE_SCHEMA = {+ "type": "object",+ "properties": {"role": {"const": "assistant"}, "content": {"type": "string"}},+ "x-regex": r"^(?P<content>[\s\S]*)$",+}+++def with_response_parser(processing_class, uses_tools):+ """A copy carrying the tool-call parser resolved here, for processes that run TRL without Unsloth: AsyncGRPO's+ rollout worker calls add_response_schema on every run, tools or not, and skips it only when a parser is set."""+ try:+ import trl.chat_template_utils as trl_module+ except Exception:+ return processing_class++ def has_parser(holder):+ return any(getattr(holder, attribute, None) is not None for attribute in _PARSER_ATTRIBUTES)++ if has_parser(processing_class):+ return processing_class+ tokenizer = _tokenizer_of(processing_class)+ clone = copy.copy(processing_class)+ clone_tokenizer = clone+ if processing_class is not tokenizer:+ clone.tokenizer = clone_tokenizer = copy.copy(tokenizer)+ try:+ if not has_parser(clone_tokenizer):+ trl_module.add_response_schema(clone)+ except ValueError:+ if uses_tools:+ return processing_class+ # Without tools a completion is plain assistant text. The new-style parser falls back to decoding it; the+ # legacy one needs a schema mapping the whole text to content.+ if getattr(trl_module, "_SUPPORTS_RESPONSE_TEMPLATE", False):+ clone_tokenizer.response_template = {}+ else:+ clone_tokenizer.response_schema = _PLAIN_RESPONSE_SCHEMA+ # The worker checks the processor itself, while add_response_schema sets the inner tokenizer.+ if clone is not clone_tokenizer:+ for attribute in _PARSER_ATTRIBUTES:+ value = getattr(clone_tokenizer, attribute, None)+ if value is not None:+ setattr(clone, attribute, value)+ return clonediff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex 4643c88b30f..b50c877b438 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -28,6 +28,7 @@ import osimport reimport sysimport warnings+import weakreffrom contextlib import contextmanagerfrom unsloth_zoo.compiler import create_new_functionfrom unsloth_zoo.log import logger@@ -4259,30 +4260,124 @@ def _is_unsloth_fast_backbone(backbone):return getattr(type(backbone), "forward", None) is LlamaModel_fast_forward+def _text_prepended_position_ids(position_ids):+ # Multimodal-RoPE text models (Qwen2.5-VL) build the packed mask only from [4, B, T] ids whose first plane is+ # the text positions; text-only rows use the same positions on every plane.+ if position_ids is None or position_ids.dim() != 2:+ return position_ids+ return position_ids[None].expand(4, *position_ids.shape)++[email protected]_grad()+def _packing_honored(backbone, position_transform = None):+ # Runs the backbone the way the fused head does: a second packed sequence must match itself run alone far more+ # closely than when it can see the first one. Numeric, so it covers every attention and mixer implementation.+ params = next(backbone.parameters(), None)+ if params is None:+ return False+ device = params.device+ config = getattr(backbone, "config", None)+ text_config = config.get_text_config() if hasattr(config, "get_text_config") else config+ vocab = int(getattr(text_config, "vocab_size", 0) or 0)+ if vocab < 20:+ return False+ generator = torch.Generator().manual_seed(3407)+ first, second = 24, 20+ ids = torch.randint(10, min(vocab, 32000), (1, first + second), generator = generator).to(device)+ transform = position_transform or (lambda p: p)+ dtype = getattr(config, "torch_dtype", None) or params.dtype+ if dtype not in (torch.float16, torch.bfloat16):+ dtype = torch.bfloat16 if params.dtype == torch.float32 else params.dtype+ training = [(module, module.training) for module in backbone.modules()]+ # Training mode, as in the trainer: some models (gpt-oss) take a different attention path when training.+ # Dropout off so the comparison is deterministic.+ backbone.train()+ for module in backbone.modules():+ if isinstance(module, torch.nn.modules.dropout._DropoutNd):+ module.training = False++ def hidden(input_ids, position_ids):+ with torch.autocast(device.type, dtype = dtype, enabled = device.type in ("cuda", "xpu")):+ out = backbone(+ input_ids = input_ids, position_ids = transform(position_ids), use_cache = False+ )+ return out.last_hidden_state.float()++ try:+ arange = lambda n: torch.arange(n, device = device)[None]+ packed = hidden(ids, torch.cat([arange(first), arange(second)], dim = 1))[0, first:]+ alone = hidden(ids[:, first:], arange(second))[0]+ crossed = hidden(ids, arange(first + second))[0, first:]+ finally:+ for module, mode in training:+ module.training = mode+ leak = (packed - alone).abs().mean()+ control = (crossed - alone).abs().mean()+ return bool(torch.isfinite(leak)) and bool(control > 0) and bool(leak <= 0.2 * control)++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 modeloriginal(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):+ head_forward = target.forward+ if _is_unsloth_fast_backbone(getattr(target, "base_model", None)):+ # Unsloth's attention reads sequence boundaries from packed_seq_lengths, not position_ids resets.+ def packed_kwargs(f_kwargs):+ if 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+ else:+ # Compiled / vision / MoE backbones: transformers builds the packed mask from position_ids resets.+ # Use the first position_ids form this backbone honors, else refuse.+ config = target.config+ is_vlm = getattr(config, "get_text_config", lambda: config)() is not config+ # Same backbone TRL's fused head calls.+ backbone = (+ getattr(target, "model", None)+ if (is_vlm and Version(importlib_version("transformers")) < Version("5.0.0"))+ else getattr(target, "base_model", None)+ )+ transforms = [None, _text_prepended_position_ids] if is_vlm else [None]+ attn = str(getattr(config, "_attn_implementation", None) or "")+ if "flash" in attn and not is_vlm:+ # Varlen flash attention reads sequence boundaries from position_ids, as TRL expects; TRL builds+ # these models on CPU, where the kernel cannot run the self-test.+ return+ try:+ transform = next(+ (+ t+ for t in transforms+ if backbone is not None and _packing_honored(backbone, t)+ ),+ False,+ )+ except Exception as error:+ raise ValueError(+ "Unsloth: AsyncGRPOTrainer packs several sequences into one row, and checking that "+ f"`{type(backbone).__name__}` keeps them apart failed ({type(error).__name__}: {error}). Load "+ "the model with a flash attention implementation, or train it with GRPOTrainer instead."+ ) from error+ if transform is False: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."+ "Unsloth: AsyncGRPOTrainer packs several sequences into one row, separated only by "+ f"position_ids resets, and `{type(backbone).__name__}` lets them attend to each other. Load "+ "the model with a flash attention implementation, or train it with GRPOTrainer instead.")- return- head_forward = target.forward+ if transform is None:+ return++ def packed_kwargs(f_kwargs):+ f_kwargs["position_ids"] = transform(f_kwargs.get("position_ids"))@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+ if flag is None or f_kwargs.get(flag):+ packed_kwargs(f_kwargs)return head_forward(*f_args, **f_kwargs)target.forward = forward@@ -4291,6 +4386,182 @@ def _unsloth_async_grpo_lm_head(original, flag):return patch_lm_head+def _fast_inference_engine(model):+ for candidate in (model, getattr(model, "get_base_model", lambda: None)()):+ engine = getattr(candidate, "vllm_engine", None)+ if engine is not None:+ return engine+ return None+++def _async_grpo_uses_fast_inference(model, config, kwargs):+ if isinstance(model, str) or _fast_inference_engine(model) is None:+ return False+ if kwargs.get("weight_transfer") is not None or kwargs.get("rollout_worker") is not None:+ return False+ url = getattr(config, "vllm_server_base_url", None)+ if url not in (None, "http://localhost:8000"):+ logger.info(+ f"Unsloth: AsyncGRPOTrainer uses the vLLM server at {url}, not the model's fast_inference engine."+ )+ return False+ return True+++def _dataset_has_images(dataset):+ # Index, never iterate: a stateful iterable dataset would lose its first row.+ try:+ row = dataset[0] if hasattr(dataset, "__getitem__") and len(dataset) > 0 else None+ except Exception:+ return False+ if not isinstance(row, dict):+ return False+ if any(row.get(key) is not None for key in ("image", "images")):+ return True+ prompt = row.get("prompt")+ if isinstance(prompt, list):+ for message in prompt:+ content = message.get("content") if isinstance(message, dict) else None+ if isinstance(content, list) and any(+ isinstance(part, dict) and part.get("type") in ("image", "image_url")+ for part in content+ ):+ return True+ return False+++def _start_async_grpo_vllm_server(model):+ from ._async_grpo_vllm import UnslothAsyncVLLMServer+ return UnslothAsyncVLLMServer(model)+++def _check_async_grpo_fast_inference(async_module, model, train_dataset):+ if not hasattr(async_module, "select_adapter_sync"):+ raise ValueError(+ "Unsloth: AsyncGRPOTrainer with fast_inference=True syncs a LoRA adapter, which needs TRL >= 1.14. "+ "Upgrade TRL, or load with fast_inference=False and run a separate vLLM server."+ )+ if not hasattr(model, "peft_config") or getattr(model, "load_lora", None) is None:+ raise ValueError(+ "Unsloth: with fast_inference=True, vLLM generates from the same base weights the trainer holds, so "+ "AsyncGRPOTrainer can only train a LoRA adapter on top of them. Call FastLanguageModel.get_peft_model "+ "(or FastVisionModel.get_peft_model) first; for full fine-tuning load with fast_inference=False and "+ "run a separate vLLM server."+ )+ if _dataset_has_images(train_dataset):+ raise ValueError(+ "Unsloth: TRL's AsyncGRPOTrainer sends token ids only to vLLM, so image prompts are not supported. "+ "Use GRPOTrainer for image prompts."+ )+++def _align_vlm_text_config(model):+ # TRL finds a VLM's text model by `module.config is model.config.get_text_config()`; Unsloth's loaders keep+ # separate config copies per level, so answer with the language model's own config while TRL's init runs.+ from transformers import PreTrainedModel++ config = getattr(model, "config", None)+ if config is None or not hasattr(config, "get_text_config"):+ return lambda: None+ text_config = config.get_text_config()+ if text_config is config:+ return lambda: None+ modules = [+ m+ for m in model.modules()+ if isinstance(m, PreTrainedModel) and getattr(m, "config", None) is not config+ ]+ if any(m.config is text_config for m in modules):+ return lambda: None+ matches = {id(m.config): m.config for m in modules if isinstance(m.config, type(text_config))}+ if len(matches) != 1:+ return lambda: None+ (target,) = matches.values()+ had = "get_text_config" in vars(config)+ previous = vars(config).get("get_text_config")+ config.get_text_config = lambda *args, **kwargs: target++ def restore():+ if had:+ config.get_text_config = previous+ else:+ vars(config).pop("get_text_config", None)++ return restore+++def _hold_peft_requires_grad(model):+ # TRL's VLM branch calls requires_grad_ on the model, its text model and LM head: under LoRA that would train+ # the base (and raises on 4-bit weights), so make those calls no-ops while TRL's init runs.+ from transformers import PreTrainedModel++ if not hasattr(model, "peft_config"):+ return lambda: None+ targets = {id(model): model}+ for module in model.modules():+ if isinstance(module, PreTrainedModel):+ targets[id(module)] = module+ try:+ head = model.get_output_embeddings()+ if isinstance(head, torch.nn.Module):+ targets[id(head)] = head+ except Exception:+ pass+ held = [m for m in targets.values() if "requires_grad_" not in vars(m)]+ for module in held:+ module.requires_grad_ = functools.partial(lambda m, *args, **kwargs: m, module)++ def restore():+ for module in held:+ vars(module).pop("requires_grad_", None)++ return restore+++def _allow_moe_parameter_lora(async_module, model):+ # TRL refuses target_parameters (fused-MoE LoRA) because a stock vLLM server needs is_3d_lora_weight declared;+ # the in-process server loads adapters through Unsloth's load_lora, which remaps and validates MoE LoRA itself.+ original = getattr(async_module, "validate_lora_for_vllm_sync", None)+ peft_configs = getattr(model, "peft_config", None)+ if original is None or not isinstance(peft_configs, dict):+ return lambda: None++ @functools.wraps(original)+ def validate_lora_for_vllm_sync(peft_model):+ saved = {+ name: config.target_parameters+ for name, config in peft_configs.items()+ if getattr(config, "target_parameters", None)+ }+ for name in saved:+ peft_configs[name].target_parameters = None+ try:+ return original(peft_model)+ finally:+ for name, value in saved.items():+ peft_configs[name].target_parameters = value++ async_module.validate_lora_for_vllm_sync = validate_lora_for_vllm_sync++ def restore():+ async_module.validate_lora_for_vllm_sync = original++ return restore+++def _check_async_grpo_adapter_servable(model):+ # Raise vLLM's refusals (e.g. LoRA on MoE experts) at construction instead of at the first weight sync.+ import os+ import tempfile++ # load_lora reads the "default" adapter; TRL syncs the active one, so other layouts are left to the sync.+ if set(getattr(model, "peft_config", None) or ()) != {"default"}:+ return+ with tempfile.TemporaryDirectory() as directory:+ # A path that does not exist yet: older load_lora writes the adapter config only into a new directory.+ model.load_lora(os.path.join(directory, "adapter"), load_tensors = True)++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:@@ -4330,6 +4601,7 @@ def patch_trl_async_grpo():trainer_class = async_module.AsyncGRPOTraineroriginal_init = trainer_class.__init__+ original_train = getattr(trainer_class, "train", None)@functools.wraps(original_init)def __init__(self, model, *args, **kwargs):@@ -4341,9 +4613,75 @@ def patch_trl_async_grpo():args = (args[0], config, *args[2:])else:kwargs["args"] = config- original_init(self, model, *args, **kwargs)+ server = None+ if _async_grpo_uses_fast_inference(model, config, kwargs):+ train_dataset = args[2] if len(args) >= 3 else kwargs.get("train_dataset")+ _check_async_grpo_fast_inference(async_module, model, train_dataset)+ _check_async_grpo_adapter_servable(model)+ server = _start_async_grpo_vllm_server(model)+ saved_config = (config.vllm_server_base_url, config.max_inflight_tasks)+ config.vllm_server_base_url = server.url+ if getattr(config, "max_inflight_tasks", 0) < 0:+ # TRL's default counts rows, not rollouts, so token-budget packing would leave the engine+ # nearly idle; let the engine batch as many as it can schedule.+ config.max_inflight_tasks = server.max_num_seqs+ # TRL unfreezes a VLM's whole text model and LM head; under LoRA that is full fine-tuning of the base (and,+ # with fast_inference, of the weights vLLM serves from), so keep the adapter-only trainable set.+ trainable = (+ {id(p) for p in model.parameters() if p.requires_grad}+ if isinstance(model, torch.nn.Module) and hasattr(model, "peft_config")+ else None+ )+ is_module = isinstance(model, torch.nn.Module)+ restore_text_config = _align_vlm_text_config(model) if is_module else (lambda: None)+ restore_requires_grad = _hold_peft_requires_grad(model) if is_module else (lambda: None)+ restore_validate = (+ _allow_moe_parameter_lora(async_module, model) if server is not None else (lambda: None)+ )+ try:+ try:+ original_init(self, model, *args, **kwargs)+ finally:+ if server is not None:+ # TRL read the URL during init; a reused config must not point at this trainer's server.+ config.vllm_server_base_url = saved_config[0]+ restore_validate()+ restore_requires_grad()+ restore_text_config()+ if trainable is not None:+ for p in model.parameters():+ if p.requires_grad and id(p) not in trainable:+ p.requires_grad_(False)+ if server is not None:+ if not getattr(self, "_lora_sync", False):+ raise ValueError(+ "Unsloth: with fast_inference=True, vLLM and the trainer share the base weights, so "+ "AsyncGRPOTrainer can only sync a plain LoRA adapter. Drop modules_to_save, DoRA and "+ "bias training, or load with fast_inference=False and run a separate vLLM server."+ )+ except BaseException:+ if server is not None:+ server.stop()+ config.max_inflight_tasks = saved_config[1]+ raise+ if server is not None:+ self._unsloth_vllm_server = server+ weakref.finalize(self, server.stop)trainer_class.__init__ = __init__+ if original_train is not None:++ @functools.wraps(original_train)+ def train(self, *args, **kwargs):+ try:+ return original_train(self, *args, **kwargs)+ finally:+ server = getattr(self, "_unsloth_vllm_server", None)+ if server is not None:+ # The rollout process is gone; drop the requests it left in flight.+ server.abort_all()++ trainer_class.train = trainif hasattr(async_module, "AsyncRolloutWorker"):@@ -4351,9 +4689,23 @@ def patch_trl_async_grpo():# 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"]- )+ processing_class = _without_instance_bound_methods(kwargs["processing_class"])+ # That process imports TRL without Unsloth, so it matches chat templates by exact string.+ try:+ from ._trl_tool_templates import (+ with_response_parser,+ with_trl_known_chat_template,+ )+ processing_class = with_trl_known_chat_template(processing_class)+ processing_class = with_response_parser(+ processing_class,+ bool(kwargs.get("tools") or kwargs.get("environment_factory")),+ )+ except Exception as e:+ logger.info(+ f"Unsloth: Could not map the chat template for the rollout process: {e}"+ )+ kwargs["processing_class"] = processing_classsuper().__init__(*args, **kwargs)async_module.AsyncRolloutWorker = AsyncRolloutWorker