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
[RL] make sync weights conditional (#4925)
Datta Nimmaturi883911826897
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex b2e6a45aa0c..7af2a7d1369 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -2594,6 +2594,7 @@ class FastLlamaModel:quant_state_dict, model_config, dtype, bnb_config)model.vllm_engine = llm+ llm.shared_weights = Truemodel.fast_generate = model.vllm_engine.generatemodel.fast_generate_batches = functools.partial(generate_batches, model.vllm_enginediff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex 9bf0d3e968b..359716fda48 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -2002,12 +2002,14 @@ def patch_functions(RLTrainer, trainer_file, RLTrainer_name, all_imports, import'GuidedDecodingParams(backend="outlines", regex=args.vllm_guided_decoding_regex) ''if getattr(args, "vllm_guided_decoding_regex", None) is not None else None,',)- # Replace with our vLLM engine+ # Replace with our vLLM engine when sharing weightssampling_params = (" " * 12- + "self.llm = model.vllm_engine; self._last_loaded_step = 0; "+ + "if getattr(getattr(model, 'vllm_engine', None), 'shared_weights', False): "+ + "self.llm = model.vllm_engine; self._last_loaded_step = 0\n"+ + " " * 12+ sampling_params- ) # Add spaces+ )# count the indentation of last line of sampling_params.splitted_sampling_params = sampling_params.split("\n")@@ -2040,14 +2042,27 @@ def patch_functions(RLTrainer, trainer_file, RLTrainer_name, all_imports, import)if trl_version >= Version("0.18.0"):- # Replace LLM init with already existing vLLM engine for colocate mode- vllm_llm_init_pattern = r"self\.llm\s*=\s*LLM\(.*?\)*\)\s*?\n(?!,)"- vllm_llm_replacement = "self.llm = model.vllm_engine\n"+ # Guard LLM init - use existing vLLM engine when sharing weights,+ # otherwise keep the original LLM() creation for sync/reload path+ vllm_llm_init_pattern = (+ r"(?P<indent>[ \t]*)self\.llm\s*=\s*LLM\(.*?\)*\)\s*?\n(?!,)"+ )++ def guard_llm_init(match):+ indent = match.group("indent")+ original = match.group(0)+ return (+ f"{indent}if getattr(getattr(model, 'vllm_engine', None), 'shared_weights', False):\n"+ f"{indent} self.llm = model.vllm_engine\n"+ f"{indent}else:\n"+ f"{indent} {original.lstrip()}"+ )+new_vllm_part = re.sub(vllm_llm_init_pattern,- vllm_llm_replacement,+ guard_llm_init,new_vllm_part,- flags = re.DOTALL, # Ensure . matches newlines [[5]]+ flags = re.DOTALL,)init = init.replace(vllm_part, new_vllm_part)@@ -2116,7 +2131,7 @@ def patch_functions(RLTrainer, trainer_file, RLTrainer_name, all_imports, importsource,)- # Replace self.llm.generate and self.llm.chat+ # Replace self.llm.generate and self.llm.chat with lora_request (only when sharing weights)if "CUDA_VISIBLE_DEVICES" in os.environ:lora_name = (trainer_file@@ -2129,7 +2144,9 @@ def patch_functions(RLTrainer, trainer_file, RLTrainer_name, all_imports, importr"(self\.llm\.(?:generate|chat)\([^\)]{1,})\)",r"\1, lora_request = self.model.load_lora('"+ lora_name- + r", load_tensors = True))",+ + r", load_tensors = True)"+ + r" if getattr(self.llm, 'shared_weights', False)"+ + r" else None)",source,)# All these are to fix multiple commas before lora_request (in case the original code ends with something like ",)")diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 9ddb5e94538..51d20f9ff76 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -613,39 +613,48 @@ def grpo_trainer__prepare_inputs(function_name, function):RL_FUNCTIONS["grpo_trainer"].append(grpo_trainer__prepare_inputs)-# Remove collective RPC of reload weights from generate-# trl added reload weights (potentially for quantized models), we don't need it for our use case (LoRA primarily)+# Guard reload_weights and sync_weights - skip when fast inference LoRA shares weights with vLLM# https://github.com/huggingface/trl/commit/7856d3b1f6518601732f489883b341bb6dd36434#diff-964e6fd373aa93037604064cb2b822d7f8e2735e33f791065acf2c4c3552d393R1168-R1169-def grpo_trainer__generate_single_turn(function_name, function):- if function_name != "_generate_single_turn":- return function-- # Remove the reload_weights collective RPC call from the generate function's source- # function = function.replace('self.llm.collective_rpc("reload_weights")', "")- # The regex below does the same thing but is more flexible and can handle single or double quotes- # This is for older versions.- function = re.sub(- r"self\.llm\.collective_rpc\(\s*(['\"])reload_weights\1\s*\)",- "",- function,+def _guard_vllm_sync_reload_for_shared_weights(function):+ # Guard reload_weights - only call when not sharing weights with vLLM+ reload_weights_pattern = re.compile(+ r"^(?P<indent>[ \t]*)self\.llm\.collective_rpc\(\s*(['\"])reload_weights\2\s*\)\s*$",+ re.MULTILINE,)- # Current TRL versions call vllm_generation.sync_weights() every step.- # When Unsloth fast inference LoRA is active, weights are already shared.+ def replace_reload_weights_line(match):+ indent = match.group("indent")+ return (+ f"{indent}if not getattr(self.llm, 'shared_weights', False):\n"+ f'{indent} self.llm.collective_rpc("reload_weights")\n'+ )++ function = reload_weights_pattern.sub(replace_reload_weights_line, function)++ # Guard sync_weights - skip when sharing weights with vLLMsync_weights_block = re.compile(r"(?P<indent>[ \t]*)with profiling_context\(self,\s*(['\"])sync_weights\2\s*\):\n"r"(?P=indent)[ \t]+self\.vllm_generation\.sync_weights\(\)\n",re.MULTILINE,)- def remove_sync_weights_block(match):+ def guard_sync_weights_block(match):indent = match.group("indent")return (- f"{indent}# Unsloth fast inference LoRA shares weights with vLLM already.\n"- f"{indent}# Skipping per-step vLLM sync_weights().\n"+ f"{indent}if not getattr(getattr(self.vllm_generation, 'llm', None), 'shared_weights', False):\n"+ f"{indent} with profiling_context(self, 'sync_weights'):\n"+ f"{indent} self.vllm_generation.sync_weights()\n")- function = sync_weights_block.sub(remove_sync_weights_block, function)+ function = sync_weights_block.sub(guard_sync_weights_block, function)+ return function+++def grpo_trainer__generate_single_turn(function_name, function):+ if function_name != "_generate_single_turn":+ return function++ function = _guard_vllm_sync_reload_for_shared_weights(function)# TRL 0.24.0-0.25.1 truncation regression fix#@@ -693,6 +702,16 @@ def grpo_trainer__generate_single_turn(function_name, function):RL_FUNCTIONS["grpo_trainer"].append(grpo_trainer__generate_single_turn)+def grpo_trainer__generate(function_name, function):+ if function_name != "_generate":+ return function++ return _guard_vllm_sync_reload_for_shared_weights(function)+++RL_FUNCTIONS["grpo_trainer"].append(grpo_trainer__generate)++# Fix incorrect special tokens handling and truncation in older TRL versionsdef grpo_trainer__generate_and_score_completions(function_name, function):if function_name != "_generate_and_score_completions":@@ -1970,7 +1989,7 @@ RL_METRICS_CHANGES["grpo_trainer"].append(grpo_trainer_metrics)def openenv_vllm_reload_weights():# This function patches the trl openenv generate_rollout_completions function to:- # 1. Remove the reload_weights call (unsloth handles weight reloading)+ # 1. Guard the reload_weights call (skip when sharing weights with vLLM)# 2. Fix wake_up call to be compatible with unsloth (remove tags to wake everything)## The issue: TRL's wake_up(tags=["kv_cache"]) only wakes kv_cache, leaving is_sleeping=True@@ -2027,8 +2046,20 @@ def openenv_vllm_reload_weights():src = textwrap.dedent(src)original_src = src- # Remove the reload_weights call - unsloth handles this differently- src = re.sub(r'.*\.collective_rpc\(\s*([\'"])reload_weights\1\s*\).*\n?', "", src)+ reload_weights_pattern = re.compile(+ r"^(?P<indent>[ \t]*)(?P<obj>\S+)\.collective_rpc\(\s*(['\"])reload_weights\3\s*\)\s*$",+ re.MULTILINE,+ )++ def replace_reload_weights(match):+ indent = match.group("indent")+ obj = match.group("obj")+ return (+ f"{indent}if not getattr({obj}, 'shared_weights', False):\n"+ f'{indent} {obj}.collective_rpc("reload_weights")\n'+ )++ src = reload_weights_pattern.sub(replace_reload_weights, src)# Change wake_up(tags=["kv_cache"]) to wake_up() - wake everything to set is_sleeping=False# This prevents double wake_up issues. Unsloth's allocator skips weights anyway.@@ -2118,7 +2149,9 @@ def vllm_generation_init_patch():f"{indent}if hasattr(model, 'vllm_engine'):\n"f"{indent} # Unsloth already inits vLLM in fast inference mode. Do not redo :)\n"f"{indent} self.llm = model.vllm_engine\n"- f"{indent} self.unsloth_fast_inference_lora = True\n"+ f"{indent} self.unsloth_fast_inference_lora = getattr(self.llm, 'shared_weights', False)\n"+ f"{indent} if getattr(self.llm, 'shared_weights', False) and hasattr(model, 'load_lora'):\n"+ f"{indent} self._unsloth_load_lora = model.load_lora\n"f"{indent}else:\n" + textwrap.indent(llm_block, indent + " "))@@ -2140,8 +2173,11 @@ def vllm_generation_init_patch():def replace_sync_weights(match):body = match.group("body")+ # Chain getattr so server mode (where self.llm is not set) does+ # not raise AttributeError before the default kicks in.guard = (- " if getattr(self, 'unsloth_fast_inference_lora', False):\n"+ " 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"" return\n\n")@@ -2162,7 +2198,12 @@ def vllm_generation_init_patch():def replace_reload_weights(match):indent = match.group("indent")- return f'{indent}pass # self.llm.collective_rpc("reload_weights")'+ # 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")'+ )patched_src, num_replacements = pattern.subn(replace_reload_weights, src, count = 1@@ -2171,25 +2212,39 @@ def vllm_generation_init_patch():raise RuntimeError("Unsloth: Warning - regex did not match, VLLMGeneration.generate patch may have failed")++ # Inject lora_request when sharing weights (vLLM needs the adapter)+ lora_generate_pattern = re.compile(+ r"(self\.llm\.generate\([^\)]+)\)",+ )++ 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_srctry:init_patched = patch_vllm_generation_method("_init_vllm",patch_init_vllm,- "self.unsloth_fast_inference_lora = True",+ "self.unsloth_fast_inference_lora = getattr(self.llm, 'shared_weights', False)","init_vllm",)sync_patched = patch_vllm_generation_method("sync_weights",patch_sync_weights,- "if getattr(self, 'unsloth_fast_inference_lora', False):",+ "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,- 'pass # self.llm.collective_rpc("reload_weights")',+ "if not (getattr(getattr(self, 'llm', None), 'shared_weights', False) or getattr(self, 'unsloth_fast_inference_lora', False)):","generate",)except RuntimeError as e:diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 73ef1db7e32..6c4842596f7 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -1079,6 +1079,7 @@ class FastBaseModel:is_vision_model = is_vlm,)model.vllm_engine = llm+ llm.shared_weights = Truemodel.fast_generate = model.vllm_engine.generatemodel.fast_generate_batches = functools.partial(generate_batches, model.vllm_engine