Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Keep checkpoint saves working, and portable, once a TRL config is patched (#8344)

Daniel Hanab0af1890629
diff --git a/tests/python/test_rl_config_pickling.py b/tests/python/test_rl_config_pickling.py
new file mode 100644
index 00000000000..ed4623aeef2
--- /dev/null
+++ b/tests/python/test_rl_config_pickling.py
@@ -0,0 +1,352 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Regression: `torch.save(trainer.args, ...)` must keep working once Unsloth has
+patched a TRL trainer, and the file it writes must stay readable without Unsloth.
+
+`Trainer._save_checkpoint` ends in `torch.save(self.args, os.path.join(output_dir,
+TRAINING_ARGS_NAME))`. Pickle stores a class as `__module__` + `__qualname__` and
+then refuses unless the object living at that path *is* the class. Patching a
+trainer rebinds `<X>Config` at the module the pristine class calls home, which
+breaks that identity for every instance of the pristine class, and the generated
+class used to answer to `Unsloth<X>Trainer.Unsloth<X>Config`, a module that only
+exists beside a compiled cache.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import pickle
+import subprocess
+import sys
+
+import pytest
+
+
+pytest.importorskip("trl")
+
+
[email protected](scope = "module")
+def patched():
+ import unsloth # noqa: F401
+ import trl.trainer.sft_config as config_module
+ return config_module.SFTConfig
+
+
+def _make(config_class, output_dir):
+ return config_class(
+ output_dir = str(output_dir),
+ bf16 = False,
+ fp16 = False,
+ use_cpu = True,
+ )
+
+
+def test_patched_config_answers_to_the_trl_name(patched):
+ # Without this the class pickles under a module that only ships inside a
+ # compiled cache, so the checkpoint cannot be read anywhere else.
+ assert patched.__module__ == "trl.trainer.sft_config"
+ assert patched.__qualname__ == "SFTConfig"
+
+ import trl.trainer.sft_config as config_module
+
+ assert getattr(config_module, "SFTConfig") is patched
+
+
+def test_pristine_config_instance_still_pickles(patched, tmp_path):
+ # An instance built before Unsloth patched TRL, or handed back by TRL's own
+ # TrainingArguments -> SFTConfig conversion, belongs to the pristine class.
+ pristine = patched.__mro__[1]
+ assert not pristine.__name__.startswith("Unsloth")
+
+ args = _make(pristine, tmp_path)
+ restored = pickle.loads(pickle.dumps(args))
+ assert restored.output_dir == args.output_dir
+
+
+def test_patched_config_instance_pickles(patched, tmp_path):
+ args = _make(patched, tmp_path)
+ restored = pickle.loads(pickle.dumps(args))
+ assert restored.output_dir == args.output_dir
+
+
[email protected]("use_pristine", [False, True])
+def test_torch_save_load_round_trip(patched, tmp_path, use_pristine):
+ torch = pytest.importorskip("torch")
+
+ config_class = patched.__mro__[1] if use_pristine else patched
+ args = _make(config_class, tmp_path)
+ path = tmp_path / f"training_args_{int(use_pristine)}.bin"
+ torch.save(args, path)
+
+ restored = torch.load(path, weights_only = False)
+ assert restored.output_dir == args.output_dir
+ assert restored.max_steps == args.max_steps
+
+
+def test_checkpoint_loads_without_unsloth(patched, tmp_path):
+ """The whole point of pickling under the TRL name: a checkpoint written here
+ has to open on a machine that only has transformers and TRL."""
+ torch = pytest.importorskip("torch")
+
+ path = tmp_path / "training_args.bin"
+ torch.save(_make(patched, tmp_path), path)
+
+ script = (
+ # Baseline FIRST, so this measures what the load drags in rather than what the
+ # interpreter already had. An editable install of unsloth puts its own import
+ # finder (__editable___unsloth_..._finder) into sys.modules at startup, which
+ # answers to a name test but says nothing about the checkpoint.
+ "import sys\n"
+ "preloaded = set(sys.modules)\n"
+ "import json, torch\n"
+ "obj = torch.load(sys.argv[1], weights_only = False)\n"
+ "leaked = sorted(\n"
+ " m for m in set(sys.modules) - preloaded\n"
+ " if 'unsloth' in m.lower() or m.startswith('Unsloth')\n"
+ ")\n"
+ "print(json.dumps({\n"
+ " 'cls': type(obj).__module__ + '.' + type(obj).__name__,\n"
+ " 'output_dir': obj.output_dir,\n"
+ " 'leaked': leaked,\n"
+ "}))\n"
+ )
+ env = dict(os.environ)
+ # A stock environment: no worktree on the path, no compiled cache beside it.
+ env.pop("PYTHONPATH", None)
+ env.pop("UNSLOTH_COMPILE_LOCATION", None)
+ process = subprocess.run(
+ [sys.executable, "-c", script, str(path)],
+ capture_output = True,
+ text = True,
+ env = env,
+ cwd = str(tmp_path),
+ )
+ assert process.returncode == 0, process.stderr[-3000:]
+
+ result = json.loads(process.stdout.strip().splitlines()[-1])
+ assert result["cls"] == "trl.trainer.sft_config.SFTConfig", result
+ assert result["output_dir"] == str(tmp_path)
+ assert result["leaked"] == [], result
+
+
+def test_training_arguments_conversion_keeps_unsloth_fields(patched, tmp_path):
+ """TRL converts a plain `TrainingArguments` with `args = SFTConfig(**dict_args)`.
+ That has to land on the Unsloth subclass, or the config reaches the trainer
+ without the fields the patched trainer reads (unslothai/unsloth#3931)."""
+ pytest.importorskip("transformers")
+ from transformers import TrainingArguments
+
+ import inspect
+
+ generated = sys.modules.get("UnslothSFTTrainer")
+ if generated is None:
+ pytest.skip("UnslothSFTTrainer compiled module not loaded")
+
+ source = inspect.getsource(generated._UnslothSFTTrainer.__init__)
+ if "dict_args" not in source:
+ pytest.skip("this TRL release does not convert TrainingArguments inline")
+ # The conversion must not name the bare TRL class: that global was imported
+ # before the patching and so still points at the pristine class.
+ assert "args = UnslothSFTConfig(**dict_args)" in source, source[:2000]
+
+ training_arguments = TrainingArguments(
+ output_dir = str(tmp_path),
+ bf16 = False,
+ fp16 = False,
+ use_cpu = True,
+ )
+ dict_args = training_arguments.to_dict()
+ dict_args["hub_token"] = training_arguments.hub_token
+ dict_args.pop("push_to_hub_token", None)
+
+ converted = generated.UnslothSFTConfig(**dict_args)
+ assert isinstance(converted, patched)
+ assert hasattr(converted, "unsloth_num_chunks")
+ assert pickle.loads(pickle.dumps(converted)).output_dir == str(tmp_path)
+
+
+def test_every_patched_config_pickles_portably(tmp_path):
+ """Sweep: no patched config may pickle under a compiled-cache module."""
+ import trl
+ import unsloth # noqa: F401
+
+ checked = 0
+ for name in sorted(x for x in dir(trl) if x.endswith("Config")):
+ config_class = getattr(trl, name)
+ if not isinstance(config_class, type):
+ continue
+ try:
+ args = config_class(output_dir = str(tmp_path))
+ except TypeError:
+ # Not a TrainingArguments-shaped config (ModelConfig and friends).
+ continue
+ pickle.dumps(args, protocol = 2)
+ assert not config_class.__module__.startswith("Unsloth"), (
+ f"{name} pickles under {config_class.__module__}, which does not exist "
+ "without a compiled cache"
+ )
+ checked += 1
+ assert checked > 0, "no TRL configs were exercised"
+
+
+def test_patched_config_still_subclasses_the_pristine_one(patched):
+ """The generated class is renamed onto TRL's name, which must not tempt a
+ later patching pass into making it its own base."""
+ base = patched.__mro__[1]
+ assert base is not patched
+ assert base.__name__ == "SFTConfig"
+ assert base.__module__.startswith("trl.")
+ assert "_unsloth_patched_rl_config" not in base.__dict__
+
+
+def test_reducer_registration_is_idempotent(patched, tmp_path):
+ """Patching can run more than once; it must not stack reducers or recurse."""
+ import copyreg
+
+ from unsloth.models.rl import _patch_trl_rl_trainers
+ import trl.trainer.sft_config as config_module
+
+ before = len(copyreg.dispatch_table)
+ for _ in range(3):
+ _patch_trl_rl_trainers("sft_trainer")
+
+ assert len(copyreg.dispatch_table) == before, "reducers stacked on re-patch"
+ assert config_module.SFTConfig is patched, "re-patching swapped the class"
+ # A self-referential reducer would recurse here rather than return.
+ assert pickle.loads(pickle.dumps(_make(patched, tmp_path))).output_dir == str(tmp_path)
+
+
+def test_a_displaced_sibling_wrapper_is_covered(patched, tmp_path):
+ """TRL's deprecation shims are siblings of the patched class, not its bases.
+
+ `trl.trainer.<x>_config.<X>Config` subclasses the real class in
+ `trl.experimental.<x>`, and the wrapper resolution generates the patched
+ class from that same parent -- so a subclass-only guard skips the shim even
+ though its module attribute has already been taken over, and any instance
+ captured before patching stays unpicklable.
+ """
+ import copyreg
+
+ from unsloth.models.rl import (
+ _UNSLOTH_CONFIG_PICKLE_TARGET,
+ _register_config_pickle_fallback,
+ )
+
+ experimental_parent = patched.__mro__[1]
+
+ class _Shim(experimental_parent):
+ pass
+
+ assert not issubclass(patched, _Shim), "not the sibling shape this test is about"
+
+ registered = copyreg.dispatch_table.get(_Shim)
+ try:
+ _register_config_pickle_fallback(_Shim, patched)
+ assert copyreg.dispatch_table.get(_Shim) is not None, "sibling shim left unregistered"
+ assert getattr(_Shim, _UNSLOTH_CONFIG_PICKLE_TARGET, None) is patched
+ restored = pickle.loads(pickle.dumps(_make(_Shim, tmp_path)))
+ assert restored.output_dir == str(tmp_path)
+ # Reduced through the patched class, so the file loads without Unsloth.
+ assert type(restored) is patched
+ finally:
+ copyreg.dispatch_table.pop(_Shim, None)
+ if registered is not None:
+ copyreg.dispatch_table[_Shim] = registered
+
+
+def test_an_unrelated_class_is_not_reduced_through_the_patched_one(patched):
+ """The widening stops at classes whose state the patched class can hold.
+
+ Rebuilding an unrelated class as this one would drop fields silently, which
+ is worse than the PicklingError it avoids.
+ """
+ import copyreg
+
+ from unsloth.models.rl import _register_config_pickle_fallback
+
+ class _Unrelated:
+ pass
+
+ _register_config_pickle_fallback(_Unrelated, patched)
+ assert _Unrelated not in copyreg.dispatch_table
+
+
+# ---------------------------------------------------------------------------
+# The reported ordering: a fresh interpreter that imports trl, builds a config,
+# and only then imports unsloth. The fixture above cannot reproduce it, because
+# by the time this module runs the session has already imported unsloth, so the
+# probe needs a subprocess of its own.
+# ---------------------------------------------------------------------------
+
+_PRISTINE_PROBE = r"""
+import json, os, pickle, sys, tempfile
+
+from trl import SFTConfig as pristine
+import trl.trainer.sft_config as config_module
+
+result = {"captured_pristine": config_module.SFTConfig is pristine}
+config = pristine(output_dir = "unused", bf16 = False, fp16 = False, use_cpu = True)
+
+import unsloth
+from unsloth import FastLanguageModel
+import torch
+
+result["rebound"] = config_module.SFTConfig is not pristine
+
+try:
+ pickle.dumps(config)
+ result["pickle"] = "ok"
+except Exception as error:
+ result["pickle"] = "%s: %s" % (type(error).__name__, error)
+
+try:
+ with tempfile.TemporaryDirectory() as folder:
+ path = os.path.join(folder, "training_args.bin")
+ torch.save(config, path)
+ restored = torch.load(path, weights_only = False)
+ assert restored.output_dir == "unused"
+ assert restored.per_device_train_batch_size == config.per_device_train_batch_size
+ result["torch_round_trip"] = "ok"
+except Exception as error:
+ result["torch_round_trip"] = "%s: %s" % (type(error).__name__, error)
+
+print("UNSLOTH_PROBE " + json.dumps(result))
+"""
+
+
[email protected](scope = "module")
+def pristine_probe(tmp_path_factory):
+ environment = dict(os.environ)
+ # Keep the generated module out of the shared cache directory.
+ environment["UNSLOTH_COMPILE_LOCATION"] = str(tmp_path_factory.mktemp("compiled_cache"))
+ finished = subprocess.run(
+ [sys.executable, "-c", _PRISTINE_PROBE],
+ capture_output = True,
+ text = True,
+ timeout = 1800,
+ env = environment,
+ )
+ marker = [line for line in finished.stdout.splitlines() if line.startswith("UNSLOTH_PROBE ")]
+ if not marker:
+ pytest.skip(
+ "could not run the trl-before-unsloth probe:\n"
+ f"{finished.stdout[-2000:]}\n{finished.stderr[-2000:]}"
+ )
+ payload = json.loads(marker[-1][len("UNSLOTH_PROBE ") :])
+ if not payload.get("captured_pristine"):
+ pytest.skip("trl was already patched before the probe captured the class")
+ if not payload.get("rebound"):
+ pytest.skip("this TRL/Unsloth pair does not rebind the config module")
+ return payload
+
+
+def test_config_captured_before_patching_still_pickles(pristine_probe):
+ """The reported regression, in the order it was reported."""
+ assert pristine_probe["pickle"] == "ok", pristine_probe["pickle"]
+
+
+def test_config_captured_before_patching_survives_torch_save(pristine_probe):
+ """Mirrors `Trainer._save`, which is where the crash surfaced."""
+ assert pristine_probe["torch_round_trip"] == "ok", pristine_probe["torch_round_trip"]
diff --git a/tests/version_compat/test_trl_loss_normalization_contract.py b/tests/version_compat/test_trl_loss_normalization_contract.py
index 7a4c8adb56e..4eed5d4d5d3 100644
--- a/tests/version_compat/test_trl_loss_normalization_contract.py
+++ b/tests/version_compat/test_trl_loss_normalization_contract.py
@@ -106,8 +106,14 @@ def _pristine_sft_config_cls():
"""TRL's own SFTConfig, not the generated subclass patching rebinds over it."""
import trl
+ # Go by the marker rather than the name: the generated subclass is renamed
+ # onto TRL's own name so that instances of it keep pickling, so `Unsloth`
+ # no longer appears in `__name__`. `__dict__` rather than `getattr`, so a
+ # user subclass of the generated class does not inherit its way past this.
cls = trl.SFTConfig
- return cls.__mro__[1] if cls.__name__.startswith("Unsloth") else cls
+ while "_unsloth_patched_rl_config" in cls.__dict__ or cls.__name__.startswith("Unsloth"):
+ cls = cls.__mro__[1]
+ return cls
def test_pristine_trl_sft_config_default_is_nll_too():
diff --git a/tests/version_compat/test_trl_padding_free_max_length.py b/tests/version_compat/test_trl_padding_free_max_length.py
index 6c1b190fb9b..5875f0009f2 100644
--- a/tests/version_compat/test_trl_padding_free_max_length.py
+++ b/tests/version_compat/test_trl_padding_free_max_length.py
@@ -524,8 +524,16 @@ def _pristine_sft_config_cls():
`max_seq_length` field no TRL from 0.22.2 to 1.9.2 declares. A caller who
imported SFTConfig before `import unsloth` still passes the pristine class.
"""
+ # Go by the marker rather than the name: the generated subclass is renamed
+ # onto TRL's own name so that instances of it keep pickling, so `Unsloth`
+ # no longer appears in `__name__`. `__dict__` rather than `getattr`, so a
+ # user subclass of the generated class does not inherit its way past this.
from trl import SFTConfig
- return SFTConfig.__bases__[0] if SFTConfig.__name__.startswith("Unsloth") else SFTConfig
+
+ cls = SFTConfig
+ while "_unsloth_patched_rl_config" in cls.__dict__ or cls.__name__.startswith("Unsloth"):
+ cls = cls.__bases__[0]
+ return cls
def test_pristine_trl_config_without_max_seq_length_still_truncates(tmp_path, trl_has_guard):
diff --git a/unsloth/models/rl.py b/unsloth/models/rl.py
index 6ed5d48b80b..dcacbf97cd8 100644
--- a/unsloth/models/rl.py
+++ b/unsloth/models/rl.py
@@ -19,6 +19,7 @@ __all__ = [
import torch
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union
+import copyreg
import importlib
import inspect
import os
@@ -559,6 +560,143 @@ pass
'''
+# Marks a config class generated by Unsloth. The generated class is renamed to
+# the TRL name it stands in for (see _patch_config_pickle_identity), so the
+# "already patched" checks cannot go by __name__ alone any more.
+_UNSLOTH_PATCHED_CONFIG_FLAG = "_unsloth_patched_rl_config"
+# Set on the PRISTINE config class, pointing at the Unsloth subclass that has
+# taken over its module attribute.
+_UNSLOTH_CONFIG_PICKLE_TARGET = "_unsloth_config_pickle_target"
+
+
+def _is_unsloth_patched_config(config_class):
+ return bool(
+ getattr(config_class, _UNSLOTH_PATCHED_CONFIG_FLAG, False)
+ or getattr(config_class, "__name__", "").startswith("Unsloth")
+ )
+
+
+def _reduce_pristine_rl_config(config):
+ """copyreg reducer for instances of a TRL config class Unsloth has replaced.
+
+ Anyone holding the pristine class - code that imported trl before unsloth, or
+ TRL's own `TrainingArguments` -> `<X>Config` conversion - owns instances whose
+ class no longer answers to its own module attribute, so pickle refuses them.
+ Reduce through `copyreg._reconstructor`, which is stdlib, and the Unsloth
+ subclass, which pickles under the pristine module and name, so the resulting
+ file loads as a plain `<X>Config` on a machine without unsloth.
+ """
+ target = getattr(type(config), _UNSLOTH_CONFIG_PICKLE_TARGET, None)
+ if target is None:
+ target = type(config)
+ getstate = getattr(config, "__getstate__", None)
+ state = getstate() if getstate is not None else config.__dict__
+ return (copyreg._reconstructor, (target, object, None), state)
+
+
+def _patch_config_pickle_identity(pristine_config, patched_config):
+ """Keep `torch.save(trainer.args, ...)` working once the config is patched.
+
+ `Trainer._save_checkpoint` ends in `torch.save(self.args, ...)`, and pickle
+ stores a class as `__module__` + `__qualname__`, then refuses unless the
+ object living at that path *is* the class. Patching a trainer rebinds
+ `<X>Config` at the module the pristine class calls home, which breaks that
+ identity for the pristine class, so every checkpoint save raises
+ `PicklingError`. Left alone the patched class is no better: it advertises
+ itself as `Unsloth<X>Trainer.Unsloth<X>Config`, a top level module that only
+ exists next to a compiled cache, so its `training_args.bin` cannot be read
+ back by a plain TRL install either.
+
+ Give the patched class the pristine module and name, so it pickles as
+ `trl.trainer.<x>_config.<X>Config` and reloads anywhere, and reduce pristine
+ instances through it.
+ """
+ if pristine_config is None or patched_config is None:
+ return
+ if pristine_config is patched_config:
+ return
+ home_module_name = getattr(pristine_config, "__module__", None)
+ qualname = getattr(pristine_config, "__qualname__", None) or getattr(
+ pristine_config, "__name__", None
+ )
+ # A nested or generated class has nothing stable to point pickle at.
+ if not home_module_name or not qualname or "." in qualname:
+ return
+ home_module = sys.modules.get(home_module_name)
+ if home_module is None:
+ try:
+ home_module = importlib.import_module(home_module_name)
+ except Exception:
+ return
+ # The rebinding above walks the trl.trainer.<x>_trainer -> <x>_config naming
+ # convention. The pristine class's own __module__ is what pickle consults,
+ # which is the same module for every stock TRL layout and the correct one for
+ # the trl.experimental wrappers the convention misses.
+ current = getattr(home_module, qualname, None)
+ if current is not pristine_config and current is not patched_config:
+ # Something else owns the name. Renaming the patched class now would
+ # only move the failure, so leave both classes as they are.
+ return
+ try:
+ setattr(home_module, qualname, patched_config)
+ patched_config.__module__ = home_module_name
+ patched_config.__qualname__ = qualname
+ patched_config.__name__ = qualname
+ setattr(patched_config, _UNSLOTH_PATCHED_CONFIG_FLAG, True)
+ except Exception as e:
+ logger.info(f"Unsloth: Could not repoint {qualname} for pickling: {e}")
+ return
+ _register_config_pickle_fallback(pristine_config, patched_config)
+
+
+def _config_reduction_is_safe(displaced_config, patched_config):
+ """Can instances of `displaced_config` be rebuilt as `patched_config`?
+
+ The straightforward yes is a subclass: the patched class carries every field
+ the displaced one declares.
+
+ A sibling also qualifies, and TRL produces one. The deprecation shims at
+ `trl.trainer.<x>_config.<X>Config` subclass the real class in
+ `trl.experimental.<x>`, and the wrapper resolution above generates the
+ patched class from that same parent rather than from the shim -- so the two
+ end up siblings, not subclass and base. The shim adds only a `__post_init__`
+ that warns, and every base it has is already in the patched class's MRO, so
+ the patched class still holds everything such an instance can carry.
+
+ Anything else is left alone: rebuilding an unrelated class as this one would
+ silently drop state, which is worse than the PicklingError it would avoid.
+ """
+ if issubclass(patched_config, displaced_config):
+ return True
+ # `object` alone is no relationship at all, so it does not count as shared.
+ bases = set(displaced_config.__mro__[1:]) - {object}
+ return bool(bases) and bases.issubset(set(patched_config.__mro__))
+
+
+def _register_config_pickle_fallback(displaced_config, patched_config):
+ """Route instances of a config class Unsloth displaced through the patched one.
+
+ Covers the pristine class, and any thin wrapper a TRL release leaves at a
+ module attribute the patching has taken over.
+ """
+ if displaced_config is None or displaced_config is patched_config:
+ return
+ if not isinstance(displaced_config, type):
+ return
+ if not _config_reduction_is_safe(displaced_config, patched_config):
+ return
+ if copyreg.dispatch_table.get(displaced_config) is _reduce_pristine_rl_config:
+ return
+ try:
+ setattr(displaced_config, _UNSLOTH_CONFIG_PICKLE_TARGET, patched_config)
+ copyreg.dispatch_table[displaced_config] = _reduce_pristine_rl_config
+ except Exception as e:
+ logger.info(
+ f"Unsloth: Could not make {getattr(displaced_config, '__name__', '?')} "
+ f"instances picklable: {e}"
+ )
+
+
def _wrap_grpo_generate_and_score(trainer_cls):
if not hasattr(trainer_cls, "_generate_and_score_completions"):
return
@@ -1912,7 +2050,7 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):
if RLTrainer.__name__.startswith("Unsloth"):
print(f"Unsloth: {RLTrainer.__name__} is already patched.")
return
- if RLConfig.__name__.startswith("Unsloth"):
+ if _is_unsloth_patched_config(RLConfig):
print(f"Unsloth: {RLConfig.__name__} is already patched.")
return
@@ -3428,6 +3566,20 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):
RLTrainer_source = RLTrainer_source[:_line_start] + RLTrainer_source[_block_end:]
break
+ # TRL turns a plain `TrainingArguments` into its own config with
+ # `args = <X>Config(**dict_args)`. That name resolves through the generated
+ # module's globals, which are imported from TRL before the config is patched
+ # below, so the conversion hands back a PRISTINE config: no unsloth fields on
+ # it (#3931 arrives this way too), and a class that no longer answers to its
+ # own module attribute, so the first checkpoint save cannot pickle it. Build
+ # the Unsloth subclass instead. Only the construction is rewritten - the
+ # `isinstance(args, <X>Config)` guard next to it still wants the pristine
+ # class, which the subclass satisfies.
+ RLTrainer_source = RLTrainer_source.replace(
+ f"args = {RLConfig_name}(**dict_args)",
+ f"args = Unsloth{RLConfig_name}(**dict_args)",
+ )
+
# Remove multiple doc strings
if __RLConfig_doc__ != "" and RLTrainer_source.count(__RLTrainer_doc__) == 2:
RLTrainer_source = RLTrainer_source.replace(__RLTrainer_doc__, "", 1)
@@ -3484,10 +3636,15 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):
locals(),
globals(),
)
+ _displaced_config = None
try:
config_module_name = trainer_file.replace("_trainer", "_config")
config_module = importlib.import_module(f"trl.trainer.{config_module_name}")
if hasattr(config_module, RLConfig_name):
+ # Remember what this attribute held: on the TRL releases that put a
+ # thin wrapper here it is a class of its own, and its instances need
+ # the same pickling fallback the pristine class gets.
+ _displaced_config = getattr(config_module, RLConfig_name)
setattr(
config_module,
RLConfig_name,
@@ -3495,11 +3652,15 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):
)
except Exception:
pass
+ _patched_config = getattr(created_module, f"Unsloth{RLConfig_name}", None)
+ _patch_config_pickle_identity(RLConfig, _patched_config)
+ if _patched_config is not None:
+ _register_config_pickle_fallback(_displaced_config, _patched_config)
if trainer_file == "sft_trainer":
try:
for _config_base in getattr(created_module, f"Unsloth{RLConfig_name}").__mro__[1:]:
- if not _config_base.__name__.startswith("Unsloth"):
+ if not _is_unsloth_patched_config(_config_base):
_pin_pristine_sft_loss_type(_config_base)
break
except Exception as e: