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
Absorb TRL config arguments retired between versions (#8330)
Daniel Han4ad6dc9c6c91
diff --git a/tests/test_rl_config_compat.py b/tests/test_rl_config_compat.pynew file mode 100644index 00000000000..4fe38fafd86--- /dev/null+++ b/tests/test_rl_config_compat.py@@ -0,0 +1,237 @@+"""Config arguments the installed TRL retired must not crash trainer construction.++The `**kwargs` catch-all in the generated `Unsloth<X>Config.__init__` used to be+splatted raw into `super().__init__()`, so a pinned notebook setting+`GRPOConfig.max_prompt_length` (removed in TRL 0.28.0) died with a `TypeError`+on upgrade. `filter_config_init_kwargs` is what absorbs that.++The module is loaded by file spec because `import unsloth.models.rl_config_compat`+would run `unsloth/__init__.py` first and drag in torch, numpy and unsloth_zoo.+"""++import dataclasses+import importlib.util+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[1]+MODULE_PATH = REPO_ROOT / "unsloth" / "models" / "rl_config_compat.py"+++def _load_module():+ spec = importlib.util.spec_from_file_location(+ "_unsloth_rl_config_compat_under_test", MODULE_PATH+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++_MODULE = _load_module()+filter_config_init_kwargs = _MODULE.filter_config_init_kwargs+TRL_CONFIG_RENAMES = _MODULE.TRL_CONFIG_RENAMES+++class ModernGRPOConfig:+ """TRL >= 0.28 `GRPOConfig`: no `max_prompt_length`, post-rename spellings."""++ output_dir: str = "out"+ max_completion_length: int = 256+ use_liger_kernel: bool = False+ vllm_structured_outputs_regex: str = None+ log_unique_prompts: bool = False+++class LegacyGRPOConfig:+ """TRL <= 0.27: the retired spellings are still real fields."""++ output_dir: str = "out"+ max_prompt_length: int = None+ use_liger_loss: bool = False+ vllm_guided_decoding_regex: str = None+ wandb_log_unique_prompts: bool = False+++def _collect(config_class, arguments):+ """Filter `arguments`, returning the survivors and the messages emitted."""+ messages = []+ kept = filter_config_init_kwargs(config_class, arguments, notify = messages.append)+ return kept, messages+++def test_a_retired_argument_is_dropped_rather_than_raising():+ """The bug: this exact call is what a pinned GRPO notebook makes."""+ kept, messages = _collect(ModernGRPOConfig, {"output_dir": "out", "max_prompt_length": 256})+ assert kept == {"output_dir": "out"}+ # Constructing with the survivors is the thing that used to raise.+ assert ModernGRPOConfig(**kept).output_dir == "out"+ assert any("max_prompt_length" in m for m in messages)+++def test_the_drop_is_announced_with_trls_own_advice():+ """A silent drop would change training semantics behind the user's back."""+ _, messages = _collect(ModernGRPOConfig, {"max_prompt_length": 256})+ assert len(messages) == 1+ assert "IGNORED" in messages[0]+ assert "filter overlong prompts" in messages[0]+++def test_every_documented_rename_is_carried_across():+ """TRL renamed these; dropping them would silently disable real features."""+ kept, _ = _collect(+ ModernGRPOConfig,+ {+ "use_liger_loss": True,+ "vllm_guided_decoding_regex": "abc",+ "wandb_log_unique_prompts": True,+ },+ )+ assert kept == {+ "use_liger_kernel": True,+ "vllm_structured_outputs_regex": "abc",+ "log_unique_prompts": True,+ }+ assert ModernGRPOConfig(**kept).use_liger_kernel is True+++def test_a_rename_overwrites_the_mirrored_default_not_a_real_value():+ """The generated __init__ always passes the new name, so the rename must win+ over the class default it carries when untouched..."""+ kept, _ = _collect(ModernGRPOConfig, {"use_liger_kernel": False, "use_liger_loss": True})+ assert kept["use_liger_kernel"] is True+++def test_an_explicitly_set_new_name_beats_the_old_one():+ """...but must not clobber a value the caller actually chose."""+ kept, messages = _collect(+ ModernGRPOConfig,+ {"vllm_structured_outputs_regex": "mine", "vllm_guided_decoding_regex": "old"},+ )+ assert kept["vllm_structured_outputs_regex"] == "mine"+ assert any("ignored" in m for m in messages)+++def test_the_two_pass_result_does_not_depend_on_ordering():+ """`**kwargs` lands last today, but nothing in the contract promises it."""+ forward = {"use_liger_kernel": False, "use_liger_loss": True}+ backward = {"use_liger_loss": True, "use_liger_kernel": False}+ assert _collect(ModernGRPOConfig, forward)[0] == _collect(ModernGRPOConfig, backward)[0]+++def test_an_older_trl_that_still_has_the_field_is_left_alone():+ """Forwards compatible is not enough; the pinned stacks must not change."""+ arguments = {+ "max_prompt_length": 256,+ "use_liger_loss": True,+ "vllm_guided_decoding_regex": "abc",+ "wandb_log_unique_prompts": True,+ }+ kept, messages = _collect(LegacyGRPOConfig, arguments)+ assert kept == arguments+ assert messages == []+++def test_a_field_retired_on_one_config_survives_on_another():+ """`max_completion_length` is gone from DPOConfig but current on GRPOConfig."""+ kept, messages = _collect(ModernGRPOConfig, {"max_completion_length": 64})+ assert kept == {"max_completion_length": 64}+ assert messages == []+++def test_an_unknown_argument_is_reported_by_name():+ """A typo stops being fatal, so the message has to carry the whole signal."""+ kept, messages = _collect(ModernGRPOConfig, {"learnign_rate": 3e-4})+ assert kept == {}+ assert len(messages) == 1+ assert "learnign_rate" in messages[0]+ assert "IGNORED" in messages[0]+++def test_a_config_taking_its_own_kwargs_is_never_filtered():+ """Nothing can be judged unacceptable if the base forwards it onwards."""++ class Permissive:+ def __init__(+ self,+ output_dir = "out",+ **kwargs,+ ):+ pass++ arguments = {"output_dir": "out", "anything_at_all": 1}+ kept, messages = _collect(Permissive, arguments)+ assert kept == arguments+ assert messages == []+++def test_an_unreadable_signature_forwards_everything_unchanged():+ """Guessing would be worse than the status quo, so it stands down."""++ arguments = {"whatever": 1}+ kept, messages = _collect(object(), arguments)+ assert kept == arguments+ assert messages == []+++def test_empty_kwargs_short_circuit():+ """The common path allocates nothing and says nothing."""+ messages = []+ assert filter_config_init_kwargs(ModernGRPOConfig, {}, notify = messages.append) == {}+ assert messages == []+++def test_rename_targets_are_real_fields_of_the_modern_config():+ """A typo in the rename table would silently degrade to a plain drop."""+ modern = {f.name for f in dataclasses.fields(ModernGRPOConfig)}+ for old, new in TRL_CONFIG_RENAMES.items():+ assert old not in modern, old+ assert new in modern, new+++def test_a_default_factory_field_is_compared_not_crashed_on():+ """Reading a `default_factory` default must not raise while resolving a rename."""++ @dataclasses.dataclass+ class WithFactory:+ include_for_metrics: list = dataclasses.field(default_factory = list)+ use_liger_kernel: bool = False++ kept, _ = _collect(WithFactory, {"include_for_metrics": [], "use_liger_loss": True})+ assert kept["use_liger_kernel"] is True+ assert kept["include_for_metrics"] == []+++# These two guard the wiring: reverting the rl.py template edit would leave+# every test above green. rl.py is read as text because importing it pulls in+# torch, trl and unsloth_zoo.++RL_SOURCE = (REPO_ROOT / "unsloth" / "models" / "rl.py").read_text()+++def test_the_generated_config_routes_super_through_the_filter():+ assert "_unsloth_config_arguments = dict({RLConfig_call_args}{RLConfig_kwargs})" in RL_SOURCE+ assert (+ "super().__init__(**_unsloth_filter_config_init_kwargs("+ "{RLConfig_name}, _unsloth_config_arguments))"+ ) in RL_SOURCE+ # The raw splat is what the fix removes; it must not come back.+ assert "super().__init__({RLConfig_call_args}{RLConfig_kwargs})" not in RL_SOURCE+++def test_the_generated_file_imports_the_filter_with_a_safe_fallback():+ assert (+ "from unsloth.models.rl_config_compat import filter_config_init_kwargs"+ " as _unsloth_filter_config_init_kwargs"+ ) in RL_SOURCE+ # An import failure must degrade to the historical passthrough, never to a+ # NameError inside a generated trainer.+ assert (+ "def _unsloth_filter_config_init_kwargs(config_class, kwargs): return kwargs" in RL_SOURCE+ )+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex ac405e4fcfd..6ed5d48b80b 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -396,6 +396,13 @@ try:from unsloth.models._utils import _unsloth_reset_stray_compile_cacheexcept Exception:def _unsloth_reset_stray_compile_cache(self): pass+# Drops/renames config arguments the installed TRL no longer accepts, so a+# script pinned to an older TRL keeps working after an upgrade. Falls back to+# the historical raw passthrough so this can never break trainer construction.+try:+ from unsloth.models.rl_config_compat import filter_config_init_kwargs as _unsloth_filter_config_init_kwargs+except Exception:+ def _unsloth_filter_config_init_kwargs(config_class, kwargs): return kwargsdef prepare_for_training_mode(f):@functools.wraps(f)def wrapper(self, *args, **kwargs):@@ -505,7 +512,11 @@ class Unsloth{RLConfig_name}({RLConfig_name}):**kwargs,):{RLConfig_extra_args}- super().__init__({RLConfig_call_args}{RLConfig_kwargs})+ # One dict so the filter sees the mirrored parameters AND `**kwargs`:+ # filtering kwargs alone would double-bind any argument TRL renamed,+ # since the new name is itself a mirrored parameter.+ _unsloth_config_arguments = dict({RLConfig_call_args}{RLConfig_kwargs})+ super().__init__(**_unsloth_filter_config_init_kwargs({RLConfig_name}, _unsloth_config_arguments))self.vllm_sampling_params = vllm_sampling_paramsself.unsloth_num_chunks = unsloth_num_chunksif unsloth_grpo_mini_batch is not None:diff --git a/unsloth/models/rl_config_compat.py b/unsloth/models/rl_config_compat.pynew file mode 100644index 00000000000..2750657931e--- /dev/null+++ b/unsloth/models/rl_config_compat.py@@ -0,0 +1,229 @@+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Forward only the config arguments the installed TRL still accepts.++The `Unsloth<X>Config.__init__` generated by `unsloth/models/rl.py` ends in a+`**kwargs` catch-all splatted into `super().__init__()`, so an argument TRL has+since retired crashes the base dataclass (`max_prompt_length` was removed from+`GRPOConfig` in 0.28.0, and fourteen `DPOConfig` fields in 0.29.0), breaking+pinned scripts that were correct when written. Stdlib only, so the generated+cache file can import it behind a try/except without pulling in torch.++Three outcomes per unrecognised argument: TRL documented a rename and the new+name exists, so the value is moved across; TRL removed the field, so it is+dropped and reported by name with TRL's advice; anything else is dropped with+a warning.++That last case means `GRPOConfig(learnign_rate = 3e-4)` now warns instead of+raising `TypeError`. The trade is accepted: a typo is still surfaced loudly,+whereas the crash it replaces hits correct code on a TRL upgrade and cannot be+fixed without editing library code.+"""++import dataclasses+import inspect++__all__ = [+ "filter_config_init_kwargs",+ "TRL_CONFIG_RENAMES",+ "TRL_REMOVED_FIELD_ADVICE",+]+++# Straight renames from TRL's own deprecation warnings. Only entries where the+# old value can be handed to the new name unchanged belong here, so anything+# needing a different value or setting goes in the advice table below.+TRL_CONFIG_RENAMES = {+ # Deprecated in TRL 0.26.0 (DPO) / 0.27.0 (GRPO), removed in 0.28.0.+ "use_liger_loss": "use_liger_kernel",+ # Deprecated in TRL 0.27.0, removed in 0.28.0.+ "vllm_guided_decoding_regex": "vllm_structured_outputs_regex",+ # Deprecated in TRL 0.26.0, removed in 0.27.0.+ "wandb_log_unique_prompts": "log_unique_prompts",+}+++# What TRL tells users to do instead, keyed on the retired argument name. Only+# consulted for arguments the installed config rejects, so an entry is harmless+# for a config that still accepts the field (`max_completion_length` is retired+# on `DPOConfig` but current on `GRPOConfig`).+TRL_REMOVED_FIELD_ADVICE = {+ # GRPOConfig, removed in TRL 0.28.0.+ "max_prompt_length": ("filter overlong prompts out of your dataset before training instead"),+ # DPOConfig, removed in TRL 0.29.0.+ "max_completion_length": "use `max_length` to cap total sample length instead",+ "base_model_attribute_name": "the base model is now retrieved via `get_decoder`",+ "force_use_ref_model": "no longer needed, pass `ref_model` and it is used automatically",+ "generate_during_eval": "use a `TrainerCallback` instead",+ "label_pad_token_id": "this value is no longer configurable",+ "model_adapter_name": "only the default adapter is supported now",+ "ref_adapter_name": "the trainer handles the reference adapter itself now",+ "ref_model_init_kwargs": ("build the reference model yourself and pass it as `ref_model`"),+ "reference_free": "use `CPOTrainer` for a reference-free objective",+ "rpo_alpha": ("add 'sft' to `loss_type` and set its weight in `loss_weights` instead"),+ "tools": "pass tools through the dataset instead",+ "use_logits_to_keep": "the DPO trainer no longer uses this setting",+ "padding_value": "this value is no longer configurable",+}+++# Memoised on the class object, which is module level and outlives the process.+_ACCEPTED_CACHE = {}+++def _accepted_parameters(config_class):+ """Names `config_class.__init__` accepts, and whether it takes `**kwargs`.++ A config with its own `**kwargs` may forward anywhere, so it is reported as+ accepting everything and the caller forwards unfiltered.+ """+ try:+ cached = _ACCEPTED_CACHE.get(config_class)+ except TypeError: # unhashable, so uncacheable; fall through and recompute+ cached = None+ if cached is not None:+ return cached++ names = set()+ takes_var_keyword = False+ try:+ parameters = inspect.signature(config_class.__init__).parameters+ except (TypeError, ValueError):+ parameters = None++ if parameters is not None:+ for name, parameter in parameters.items():+ if name == "self":+ continue+ if parameter.kind is inspect.Parameter.VAR_KEYWORD:+ takes_var_keyword = True+ elif parameter.kind is not inspect.Parameter.VAR_POSITIONAL:+ names.add(name)+ elif dataclasses.is_dataclass(config_class):+ # Unreadable `__init__`: the field list is the next best description.+ names = {f.name for f in dataclasses.fields(config_class) if f.init}+ else:+ # Nothing to go on. Forward everything rather than guess.+ takes_var_keyword = True++ result = (frozenset(names), takes_var_keyword)+ try:+ _ACCEPTED_CACHE[config_class] = result+ except TypeError: # unhashable class, vanishingly rare but not fatal+ pass+ return result+++_MISSING = object()+++def _field_default(config_class, name):+ """The declared default for `name`, or `_MISSING` if it cannot be read."""+ try:+ if dataclasses.is_dataclass(config_class):+ for field in dataclasses.fields(config_class):+ if field.name != name:+ continue+ if field.default is not dataclasses.MISSING:+ return field.default+ if field.default_factory is not dataclasses.MISSING:+ return field.default_factory()+ return _MISSING+ parameter = inspect.signature(config_class.__init__).parameters.get(name)+ if parameter is not None and parameter.default is not inspect.Parameter.empty:+ return parameter.default+ except Exception:+ pass+ return _MISSING+++def _is_untouched(config_class, name, value):+ """True if `value` is indistinguishable from `name`'s declared default."""+ default = _field_default(config_class, name)+ if default is _MISSING:+ return False+ try:+ return bool(default == value)+ except Exception:+ return default is value+++def _default_notifier(message):+ print(message)+++def filter_config_init_kwargs(+ config_class,+ kwargs,+ notify = None,+):+ """Return `kwargs` reduced to what `config_class.__init__` will accept.++ Renames are applied where TRL documented one; everything else the config+ rejects is dropped. Each decision is reported through `notify` (`print` by+ default, which shows up reliably in a notebook).+ """+ if not kwargs:+ return kwargs++ accepted, takes_var_keyword = _accepted_parameters(config_class)+ if takes_var_keyword:+ return kwargs++ if notify is None:+ notify = _default_notifier+ config_name = getattr(config_class, "__name__", str(config_class))++ # Two passes so the outcome does not depend on dict ordering: take what the+ # config accepts, then rename or drop the leftovers.+ forwarded = {key: value for key, value in kwargs.items() if key in accepted}++ for key, value in kwargs.items():+ if key in accepted:+ continue++ renamed = TRL_CONFIG_RENAMES.get(key)+ if renamed is not None and renamed in accepted:+ # The new name is a mirrored parameter, so it is already in the dict+ # carrying either the caller's value or the class default. Only+ # overwrite the default: an explicitly set new name wins.+ existing = kwargs.get(renamed, _MISSING)+ if existing is _MISSING or _is_untouched(config_class, renamed, existing):+ forwarded[renamed] = value+ notify(+ f"Unsloth: TRL renamed `{key}` to `{renamed}`. Forwarding your "+ f"value to `{renamed}` - update your code when convenient."+ )+ else:+ notify(+ f"Unsloth: `{key}` was renamed to `{renamed}` by TRL and this "+ f"{config_name} accepts only the new name. You set both, so "+ f"`{key}` is ignored and your `{renamed}` is kept."+ )+ continue++ advice = TRL_REMOVED_FIELD_ADVICE.get(key)+ if advice:+ notify(+ f"Unsloth: `{key}` is not supported by the installed TRL's "+ f"{config_name} and will be IGNORED - {advice}."+ )+ else:+ notify(+ f"Unsloth: `{key}` is not a valid {config_name} argument for the "+ f"installed TRL and will be IGNORED. Check the spelling, or your "+ f"TRL version if this argument used to work."+ )++ return forwarded