Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fix Online DPO crashing at start when use_vllm is on (#15598)
Nilay9686a630b4ba
diff --git a/tests/test_online_dpo_move_model_to_vllm_sync.py b/tests/test_online_dpo_move_model_to_vllm_sync.pynew file mode 100644index 00000000000..5a0386ccee1--- /dev/null+++ b/tests/test_online_dpo_move_model_to_vllm_sync.py@@ -0,0 +1,249 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++import textwrap+import types+from contextlib import nullcontext++import pytest+import torch+++# trl 1.15.0 experimental/online_dpo/online_dpo_trainer.py, FSDP branches dropped.+_TRL_SOURCES = {+ "_move_model_to_vllm": """+ def _move_model_to_vllm(self):+ if self.vllm_mode == "server" and self.accelerator.is_main_process:+ with self.vllm_client.weight_update():+ self._move_model_to_vllm_inner()+ else:+ self._move_model_to_vllm_inner()++ if self.vllm_mode == "server" and self.accelerator.is_main_process:+ self.vllm_client.reset_prefix_cache()+ elif self.vllm_mode == "colocate":+ self.llm.reset_prefix_cache()+""",+ "_move_model_to_vllm_inner": """+ def _move_model_to_vllm_inner(self):+ deepspeed_plugin = self.accelerator.state.deepspeed_plugin+ zero_stage_3 = deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3+ gather_if_zero3 = nullcontext++ if is_peft_model(self.model):+ with gather_if_zero3(list(self.model.parameters())):+ self.model.merge_adapter()+ for name, param in self.model.named_parameters():+ name = name.removeprefix("base_model.model.").replace(".base_layer", "")+ if self.model.prefix in name:+ continue+ if "original_module" in name:+ continue+ name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."])++ if self.vllm_mode == "server" and self.accelerator.is_main_process:+ self.vllm_client.update_named_param(name, param.data)+ elif self.vllm_mode == "colocate":+ llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model+ llm_model.load_weights([(name, param.data)])+ self.model.unmerge_adapter()+ else:+ for name, param in self.model.named_parameters():+ name = self._fix_param_name_to_vllm(name)+ with gather_if_zero3([param]):+ if self.vllm_mode == "server" and self.accelerator.is_main_process:+ self.vllm_client.update_named_param(name, param.data)+ elif self.vllm_mode == "colocate":+ llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model+ llm_model.load_weights([(name, param.data)])+""",+ # trl 0.22.2 trainer/online_dpo_trainer.py: the sync is inline, before generation.+ "_generate_vllm": """+ def _generate_vllm(self, model, prompts):+ # Load the latest weights+ llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model+ llm_model.load_weights(model.state_dict().items())+ return prompts+""",+}+++class _Recorder:+ def __init__(self):+ self.loaded = []+ self.tensors = {}+ self.resets = 0++ def load_weights(self, weights):+ for name, tensor in weights:+ self.loaded.append(name)+ self.tensors[name] = tensor.clone()++ def reset_prefix_cache(self):+ self.resets += 1+++class _Proj(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.proj = torch.nn.Linear(16, 16, dtype = torch.bfloat16)++ def forward(self, x):+ return self.proj(x)+++def _lora_model():+ from peft import LoraConfig, get_peft_model+ torch.manual_seed(0)+ return get_peft_model(+ _Proj(), LoraConfig(r = 4, lora_alpha = 8, target_modules = ["proj"], init_lora_weights = False)+ )+++def _patched_trainer_class():+ from unsloth.models.rl import _strip_vllm_weight_loads+ from unsloth.models.rl_replacements import RL_FUNCTIONS++ namespace = {+ "nullcontext": nullcontext,+ "is_peft_model": lambda model: hasattr(model, "peft_config"),+ }+ for function, source in _TRL_SOURCES.items():+ for edit in RL_FUNCTIONS["online_dpo_trainer"]:+ source = edit(function, source)+ source = _strip_vllm_weight_loads(function, source, "online_dpo_trainer")+ exec(textwrap.dedent(source), namespace)+ return type("Trainer", (), {name: namespace[name] for name in _TRL_SOURCES})+++def _trainer(model, shared_weights = False):+ rec = _Recorder()+ llm = types.SimpleNamespace(+ llm_engine = types.SimpleNamespace(+ model_executor = types.SimpleNamespace(+ driver_worker = types.SimpleNamespace(model_runner = types.SimpleNamespace(model = rec))+ )+ ),+ reset_prefix_cache = rec.reset_prefix_cache,+ )+ if shared_weights:+ llm.shared_weights = True+ trainer = _patched_trainer_class()()+ trainer.accelerator = types.SimpleNamespace(+ state = types.SimpleNamespace(deepspeed_plugin = None),+ is_main_process = True,+ unwrap_model = lambda m: getattr(m, "module", m),+ )+ trainer.model = model+ trainer.vllm_mode = "colocate"+ trainer.llm = llm+ trainer._fix_param_name_to_vllm = lambda name, extra_prefixes = None: name+ return trainer, rec+++class _NoAdapterModel(torch.nn.Linear):+ # transformers PeftAdapterMixin.active_adapters on a model with no adapter loaded+ def active_adapters(self):+ raise ValueError("No adapter loaded. Please load an adapter first.")+++def test_trl_colocated_vllm_receives_dense_weights():+ trainer, rec = _trainer(_NoAdapterModel(2, 2))+ trainer._move_model_to_vllm()+ assert rec.loaded == ["weight", "bias"]+ assert rec.resets == 1+++def test_trl_colocated_vllm_receives_lora_merged_out_of_place():+ model = _lora_model()+ layer = model.base_model.model.proj+ base = layer.base_layer.weight.detach().clone()+ expected = (+ base.float()+ + (layer.lora_B["default"].weight.float() @ layer.lora_A["default"].weight.float())+ * layer.scaling["default"]+ ).to(base.dtype)+ trainer, rec = _trainer(model)+ for _ in range(3):+ trainer._move_model_to_vllm()+ assert rec.loaded[:2] == ["proj.weight", "proj.bias"]+ assert torch.equal(rec.tensors["proj.weight"], expected)+ assert torch.equal(layer.base_layer.weight, base)+++def test_fast_inference_shared_weights_skips_sync():+ model = _lora_model()+ base = model.base_model.model.proj.base_layer.weight.detach().clone()+ trainer, rec = _trainer(model, shared_weights = True)+ assert trainer._move_model_to_vllm() is None+ assert trainer._generate_vllm(model, ["p"]) == ["p"]+ assert rec.loaded == [] and rec.resets == 0+ assert torch.equal(model.base_model.model.proj.base_layer.weight, base)+++def test_trl_022_inline_sync_reaches_trl_engine():+ dense = torch.nn.Linear(2, 2)+ trainer, rec = _trainer(dense)+ assert trainer._generate_vllm(dense, ["p"]) == ["p"]+ assert rec.loaded == ["weight", "bias"]+ assert rec.resets == 1++ # DDP passes the wrapped model; vLLM rejects the "module." prefix.+ trainer, rec = _trainer(dense)+ trainer._generate_vllm(types.SimpleNamespace(module = dense), ["p"])+ assert rec.loaded == ["weight", "bias"]++ trainer, rec = _trainer(dense)+ trainer._generate_vllm(+ types.SimpleNamespace(module = types.SimpleNamespace(_orig_mod = dense)), ["p"]+ )+ assert rec.loaded == ["weight", "bias"]++ trainer, rec = _trainer(dense)+ trainer.accelerator.state.deepspeed_plugin = types.SimpleNamespace(zero_stage = 3)+ with pytest.raises(RuntimeError, match = "sharded"):+ trainer._generate_vllm(dense, ["p"])+ assert rec.loaded == []++ model = _lora_model()+ base = model.base_model.model.proj.base_layer.weight.detach().clone()+ trainer, rec = _trainer(model)+ trainer._generate_vllm(model, ["p"])+ assert rec.loaded[:2] == ["proj.weight", "proj.bias"]+ assert not torch.equal(rec.tensors["proj.weight"], base)+ assert torch.equal(model.base_model.model.proj.base_layer.weight, base)+++# trl 1.15.0 experimental/online_dpo/online_dpo_trainer.py, generation trimmed.+_COLOCATE_SOURCE = """+ def _generate_vllm_colocate(self, prompts, images=None):+ if self.args.vllm_enable_sleep_mode:+ self.llm.wake_up(tags=["weights"])+ if self.state.global_step != self._last_loaded_step:+ self._move_model_to_vllm()+ self._last_loaded_step = self.state.global_step+ if self.args.vllm_enable_sleep_mode:+ self.llm.sleep(level=2)+ return prompts+"""+++def test_level2_sleep_reloads_weights_on_the_next_microbatch():+ from unsloth.models.rl_replacements import RL_FUNCTIONS++ source = _COLOCATE_SOURCE+ for edit in RL_FUNCTIONS["online_dpo_trainer"]:+ source = edit("_generate_vllm_colocate", source)+ namespace = {}+ exec(textwrap.dedent(source), namespace)+ syncs = []+ trainer = types.SimpleNamespace(+ args = types.SimpleNamespace(vllm_enable_sleep_mode = True),+ llm = types.SimpleNamespace(wake_up = lambda tags: None, sleep = lambda level: None),+ state = types.SimpleNamespace(global_step = 0),+ _last_loaded_step = -1,+ _move_model_to_vllm = lambda: syncs.append(1),+ )+ for _ in range(2):+ namespace["_generate_vllm_colocate"](trainer, ["p"])+ assert len(syncs) == 2diff --git a/tests/test_online_dpo_vllm_init.py b/tests/test_online_dpo_vllm_init.pynew file mode 100644index 00000000000..988249dc5da--- /dev/null+++ b/tests/test_online_dpo_vllm_init.py@@ -0,0 +1,137 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++import importlib.util+import os+import sys+import textwrap+import types+++# trl 1.15.0 experimental/online_dpo/online_dpo_trainer.py OnlineDPOTrainer.__init__, vLLM part only.+_TRL_SOURCE = """+class OnlineDPOTrainer:+ def __init__(self, model, args):+ self.args = args+ self.use_vllm = args.use_vllm+ self.vllm_mode = args.vllm_mode if args.use_vllm else None+ self.temperature = args.temperature+ if self.use_vllm:+ if not is_vllm_available():+ raise ImportError("vLLM is not available")++ if self.vllm_mode == "server":+ raise AssertionError("server mode")+ elif self.vllm_mode == "colocate":+ vllm_kwargs = {+ "model": model.name_or_path,+ "gpu_memory_utilization": self.args.vllm_gpu_memory_utilization,+ }+ os.environ["RANK"] = "0"+ ensure_master_addr_port()++ self.llm = LLM(**vllm_kwargs)+ if self.args.vllm_enable_sleep_mode:+ self.llm.sleep(level=2)+ else:+ raise ValueError(f"vllm_mode must be either 'server' or 'colocate', got '{self.vllm_mode}'.")+ self._last_loaded_step = -1 # tag to avoid useless loading during grad accumulation++ # Set up vLLM generation config+ generation_kwargs = {+ "n": 2, # 2 generations per prompt for Online DPO+ "temperature": self.temperature,+ "max_tokens": args.max_new_tokens,+ }+ if args.generation_kwargs is not None:+ generation_kwargs.update(args.generation_kwargs)+ self.generation_config = SamplingParams(**generation_kwargs)+ else:+ generation_kwargs = {"max_new_tokens": args.max_new_tokens}+ self.generation_config = GenerationConfig(**generation_kwargs)+"""+++class _LLM:+ def __init__(self, **kwargs):+ self.kwargs = kwargs+++def _patched_class(tmp_path):+ from unsloth.models.rl import patch_functions++ path = tmp_path / "online_dpo_trainer_source.py"+ path.write_text(textwrap.dedent(_TRL_SOURCE))+ spec = importlib.util.spec_from_file_location(path.stem, path)+ module = importlib.util.module_from_spec(spec)+ sys.modules[path.stem] = module+ spec.loader.exec_module(module)++ source = patch_functions(+ module.OnlineDPOTrainer, "online_dpo_trainer", "OnlineDPOTrainer", [], []+ )+ namespace = {+ "os": os,+ "LLM": _LLM,+ "SamplingParams": lambda **kwargs: kwargs,+ "vLLMSamplingParams": lambda **kwargs: types.SimpleNamespace(_set_kwargs = kwargs),+ "GenerationConfig": lambda **kwargs: kwargs,+ "is_vllm_available": lambda: True,+ "ensure_master_addr_port": lambda: None,+ }+ exec(source, namespace)+ return namespace["_UnslothOnlineDPOTrainer"]+++def _args():+ return types.SimpleNamespace(+ use_vllm = True,+ vllm_mode = "colocate",+ temperature = 0.9,+ max_new_tokens = 16,+ generation_kwargs = None,+ vllm_gpu_memory_utilization = 0.3,+ vllm_enable_sleep_mode = False,+ )+++def test_trl_owned_vllm_engine_is_built(tmp_path, monkeypatch):+ monkeypatch.delenv("RANK", raising = False)+ model = types.SimpleNamespace(name_or_path = "tiny-model")+ trainer = _patched_class(tmp_path)(model, _args())+ assert isinstance(trainer.llm, _LLM)+ assert trainer.llm.kwargs["model"] == "tiny-model"+ assert trainer.generation_config["n"] == 2+ assert trainer.generation_config["max_tokens"] == 16+ assert trainer._last_loaded_step == -1+++def test_fast_inference_reuses_the_shared_engine(tmp_path, monkeypatch):+ monkeypatch.delenv("RANK", raising = False)+ engine = types.SimpleNamespace(shared_weights = True)+ model = types.SimpleNamespace(name_or_path = "tiny-model", vllm_engine = engine)+ trainer = _patched_class(tmp_path)(model, _args())+ assert trainer.llm is engine+ assert trainer.generation_config["n"] == 2+ assert trainer._last_loaded_step == 0+++def test_fast_inference_never_routes_to_a_vllm_server(tmp_path, monkeypatch):+ monkeypatch.delenv("RANK", raising = False)+ engine = types.SimpleNamespace(shared_weights = True)+ model = types.SimpleNamespace(name_or_path = "tiny-model", vllm_engine = engine)+ args = _args()+ args.vllm_mode = "server"+ trainer = _patched_class(tmp_path)(model, args)+ assert trainer.vllm_mode == "colocate"+ assert trainer.llm is engine+++def test_vllm_sampling_params_override_trl_defaults(tmp_path, monkeypatch):+ monkeypatch.delenv("RANK", raising = False)+ model = types.SimpleNamespace(name_or_path = "tiny-model")+ args = _args()+ args.vllm_sampling_params = types.SimpleNamespace(_set_kwargs = {"temperature": 0.5})+ trainer = _patched_class(tmp_path)(model, args)+ assert trainer.generation_config["temperature"] == 0.5+ assert trainer.generation_config["n"] == 2diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex 6a914b7f89b..1c8ffb1cdfe 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -119,6 +119,14 @@ _GRPO_VLLM_SYNC_FUNCTIONS = frozenset("_sync_fsdp2_params_to_vllm",))+_ONLINE_DPO_VLLM_SYNC_FUNCTIONS = frozenset(+ (+ "_move_model_to_vllm",+ "_move_model_to_vllm_inner",+ "_sync_fsdp1_params_to_vllm",+ "_sync_fsdp2_params_to_vllm",+ )+)def _strip_vllm_weight_loads(function, source, trainer_file):@@ -126,6 +134,8 @@ def _strip_vllm_weight_loads(function, source, trainer_file):# and TRL's own vLLM (colocate or server) needs these lines to receive the trainer weights.if trainer_file == "grpo_trainer" and function in _GRPO_VLLM_SYNC_FUNCTIONS:return source+ if trainer_file == "online_dpo_trainer" and function in _ONLINE_DPO_VLLM_SYNC_FUNCTIONS:+ return sourcesource = re.sub(r"(\n[\s]{4,}).+?model_executor\.driver_worker.+?\n",r"\n\1pass\n",@@ -4174,6 +4184,9 @@ def patch_functions(RLTrainer, trainer_file, RLTrainer_name, all_imports, import+ "args.top_k = -1\n")+ # The shared engine is local: a vllm_server would never get the trained weights.+ if trainer_file == "online_dpo_trainer":+ vllm_setter += " " * 12 + "args.vllm_mode='colocate'\n"if "grpo" in trainer_file and trl_version >= Version("0.18.0"):vllm_setter += " " * 12 + "args.vllm_mode='colocate'\n"if trl_version >= Version("0.23.0"):@@ -4209,7 +4222,7 @@ def patch_functions(RLTrainer, trainer_file, RLTrainer_name, all_imports, import)if len(sampling_params) == 1:- sampling_params = sampling_params[0]+ sampling_params = original_sampling_params = sampling_params[0]sampling_params = sampling_params.replace("guided_decoding=guided_decoding,","guided_decoding="@@ -4232,19 +4245,24 @@ def patch_functions(RLTrainer, trainer_file, RLTrainer_name, all_imports, importlast_indentation = len(last_line) - len(last_line.lstrip())extra = "**getattr(getattr(args, 'vllm_sampling_params', vLLMSamplingParams()), '_set_kwargs', {})"+ # Merge, not two ** splats: a vllm_sampling_params key TRL also sets (top_p) is a TypeError.to_replace = (",\n"+ " " * last_prev_indentation+ + "), "+ extra- + ",\n"+ + "},\n"+ " " * last_indentation+ ")")+ sampling_params = sampling_params.replace(+ "SamplingParams(", "SamplingParams(**{**dict(", 1+ )sampling_params = to_replace.join(sampling_params.rsplit(")", 1))sampling_params = re.sub(r"[\,][\s]{0,}\,", ",", sampling_params)- new_vllm_part = (- f"\n{' ' * 8}if {args}.use_vllm:\n{sampling_params}\n{' ' * 8}else:\n"+ new_vllm_part = new_vllm_part.replace(+ " " * 12 + original_sampling_params, sampling_params, 1)if trl_version >= Version("0.18.0"):diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex f65aa00cdbc..fcc01276809 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -2928,7 +2928,11 @@ def _unsloth_vllm_active_adapters(model):configs = getattr(model, "peft_config", None) or {}active = getattr(model, "active_adapters", None)if callable(active):- active = active()+ try:+ active = active()+ except ValueError:+ # transformers' PeftAdapterMixin raises on a model with no adapter (full finetuning).+ active = Noneif isinstance(active, str):active = [active]return set(active) if active else set(configs)@@ -3373,6 +3377,85 @@ def grpo_trainer__move_model_to_vllm(function_name, function):RL_FUNCTIONS["grpo_trainer"].append(grpo_trainer__move_model_to_vllm)+def online_dpo_trainer__move_model_to_vllm(function_name, function):+ if function_name != "_move_model_to_vllm":+ return function+ function = grpo_trainer__move_model_to_vllm(function_name, function)+ return re.sub(+ r"^([ \t]+)return _unsloth_vllm_sync_peft_merged\(self\)\n",+ r"\1if self.vllm_mode == 'server' and self.accelerator.is_main_process and hasattr(self.vllm_client, 'weight_update'):\n"+ r"\1 with self.vllm_client.weight_update():\n"+ r"\1 return _unsloth_vllm_sync_peft_merged(self)\n"+ r"\1return _unsloth_vllm_sync_peft_merged(self)\n",+ function,+ count = 1,+ flags = re.MULTILINE,+ )+++RL_FUNCTIONS["online_dpo_trainer"].append(online_dpo_trainer__move_model_to_vllm)+++def _unsloth_vllm_load_state_dict(trainer, model):+ deepspeed_plugin = getattr(trainer.accelerator.state, "deepspeed_plugin", None)+ if getattr(trainer, "is_fsdp_enabled", False) or (+ deepspeed_plugin is not None and getattr(deepspeed_plugin, "zero_stage", 0) == 3+ ):+ raise RuntimeError(+ "Unsloth: Online DPO with use_vllm = True on TRL < 0.23 cannot sync sharded "+ "(FSDP / DeepSpeed ZeRO-3) weights into vLLM. Upgrade TRL to 0.23 or later."+ )+ model = trainer.accelerator.unwrap_model(model)+ model = getattr(model, "_orig_mod", model)+ trainer.llm.llm_engine.model_executor.driver_worker.model_runner.model.load_weights(+ model.state_dict().items()+ )+ trainer.llm.reset_prefix_cache()+++def online_dpo_trainer__generate_vllm(function_name, function):+ # TRL < 0.23 syncs inline here, which _strip_vllm_weight_loads would turn into pass.+ if function_name != "_generate_vllm":+ return function+ match = re.search(+ r"^(?P<indent>[ \t]+)llm_model = self\.llm\.llm_engine\.model_executor\.driver_worker\.model_runner\.model\n"+ r"(?P=indent)llm_model\.load_weights\(model\.state_dict\(\)\.items\(\)\)\n",+ function,+ re.MULTILINE,+ )+ if match is None:+ return function+ i = match.group("indent")+ sync = (+ f"{i}if not getattr(self.llm, 'shared_weights', False):\n"+ f"{i} from unsloth.models.rl_replacements import _unsloth_vllm_sync_kind_cached, _unsloth_vllm_sync_peft_merged, _unsloth_vllm_load_state_dict\n"+ f"{i} _unsloth_sync_kind = _unsloth_vllm_sync_kind_cached(self)\n"+ f"{i} if _unsloth_sync_kind == 'peft_merged':\n"+ f"{i} _unsloth_vllm_sync_peft_merged(self)\n"+ f"{i} elif _unsloth_sync_kind == 'trl':\n"+ f"{i} _unsloth_vllm_load_state_dict(self, model)\n"+ )+ return function[: match.start()] + sync + function[match.end() :]+++RL_FUNCTIONS["online_dpo_trainer"].append(online_dpo_trainer__generate_vllm)+++def online_dpo_trainer__generate_vllm_colocate(function_name, function):+ # Level-2 sleep discards the weights, but the next microbatch of the same step skips the sync.+ if function_name != "_generate_vllm_colocate":+ return function+ return re.sub(+ r"^([ \t]+)self\.llm\.sleep\(level=2\)\n",+ r"\1self.llm.sleep(level=2)\n\1self._last_loaded_step = -1\n",+ function,+ flags = re.MULTILINE,+ )+++RL_FUNCTIONS["online_dpo_trainer"].append(online_dpo_trainer__generate_vllm_colocate)++def grpo_trainer__get_per_token_logps(function_name, function):if function_name != "_get_per_token_logps":return function