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
Add resilience to TRL internal API reclassification (#4111)
Daniel Han00fe9a40c069
diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex 181e9479df2..fbb32b2c504 100755--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -94,7 +94,40 @@ def vLLMSamplingParams(**kwargs):def PatchRL(FastLanguageModel):- from trl.models.utils import unwrap_model_for_generation+ try:+ from trl.models.utils import unwrap_model_for_generation+ except ImportError:+ try:+ from trl.models import unwrap_model_for_generation+ except ImportError:+ # Local fallback -- TRL removed or moved this symbol+ from contextlib import contextmanager as _cm++ @_cm+ def unwrap_model_for_generation(+ model, accelerator, gather_deepspeed3_params = True+ ):+ unwrapped_model = accelerator.unwrap_model(model)+ is_gc = getattr(unwrapped_model, "is_gradient_checkpointing", False)+ if is_gc:+ unwrapped_model.gradient_checkpointing_disable()+ if (+ getattr(accelerator, "state", None) is not None+ and getattr(accelerator.state, "deepspeed_plugin", None) is not None+ and accelerator.state.deepspeed_plugin.zero_stage == 3+ ):+ if not gather_deepspeed3_params:+ yield accelerator.unwrap_model(model)+ else:+ import deepspeed++ with deepspeed.zero.GatheredParameters(model.parameters()):+ yield accelerator.unwrap_model(model)+ else:+ yield unwrapped_model+ if is_gc:+ unwrapped_model.gradient_checkpointing_enable()+from contextlib import contextmanager@contextmanager@@ -253,9 +286,12 @@ create_completion_attention_mask = RL_REPLACEMENTS["create_completion_attention_left_pack_padding = RL_REPLACEMENTS["left_pack_padding"]align_logprobs_with_mask = RL_REPLACEMENTS["align_logprobs_with_mask"]autotune_batch_and_chunks = RL_REPLACEMENTS["grpo_autotune_batch_and_chunks"]+sanitize_logprob = RL_REPLACEMENTS["sanitize_logprob"]RLTrainer_replacement = '''import os+import math+import loggingfrom typing import *from dataclasses import dataclass, fieldfrom packaging.version import Version@@ -324,6 +360,7 @@ torch_compile_options = {{{left_pack_padding_code}{align_logprobs_with_mask_code}{autotune_batch_and_chunks_code}+{sanitize_logprob_code}{RL_pre}@@ -1228,6 +1265,7 @@ def _patch_trl_rl_trainers(trainer_file = "grpo_trainer"):left_pack_padding_code = inspect.getsource(left_pack_padding)align_logprobs_with_mask_code = inspect.getsource(align_logprobs_with_mask)autotune_batch_and_chunks_code = inspect.getsource(autotune_batch_and_chunks)+ sanitize_logprob_code = inspect.getsource(sanitize_logprob)# Get final source codeRLTrainer_source = RLTrainer_replacement.format(RLTrainer_name = RLTrainer_name,@@ -1256,6 +1294,7 @@ def _patch_trl_rl_trainers(trainer_file = "grpo_trainer"):autotune_batch_and_chunks_code = autotune_batch_and_chunks_code,left_pack_padding_code = left_pack_padding_code,align_logprobs_with_mask_code = align_logprobs_with_mask_code,+ sanitize_logprob_code = sanitize_logprob_code,)if RLTrainer_name == "GRPOTrainer":diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 27f00f10f39..b3a55440f92 100755--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -355,8 +355,9 @@ def grpo_trainer__generate_and_score_completions(function_name, function):re.DOTALL | re.MULTILINE,)+ # sanitize_logprob is injected as a module-level function via RLTrainer_replacement+ # template in rl.py (from RL_REPLACEMENTS), so just reference it directly here.replacement_text = (- r"\1from trl.scripts.vllm_serve import sanitize_logprob\n"r"\1all_logprobs = [\n"r"\1 [sanitize_logprob(next(iter(logprob.values()))) for logprob in output.logprobs]\n"r"\1 for outputs in all_outputs\n"diff --git a/unsloth/tokenizer_utils.py b/unsloth/tokenizer_utils.pyindex 1c107bd84f9..c445879df7d 100644--- a/unsloth/tokenizer_utils.py+++ b/unsloth/tokenizer_utils.py@@ -1007,7 +1007,14 @@ def patch_sft_trainer_tokenizer():function = function.replace(replacer, check_text + replacer)x = [x for x in all_imports if x in function]- exec(f"from trl.trainer.sft_trainer import ({','.join(x)})", locals())+ try:+ exec(f"from trl.trainer.sft_trainer import ({','.join(x)})", locals())+ except ImportError:+ for _item in x:+ try:+ exec(f"from trl.trainer.sft_trainer import {_item}", locals())+ except ImportError:+ passexec(function, locals(), globals())exec(f"trl.trainer.sft_trainer.SFTTrainer.{function_name} = {function_name}",