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.

Report a trainer kwarg that neither the trainer nor the config takes (#9944)

Vineeth Sai Varikuntla5d3accee836a
diff --git a/tests/test_rl_config_compat.py b/tests/test_rl_config_compat.py
index f2cc65fe40f..e6b4294e9c9 100644
--- a/tests/test_rl_config_compat.py
+++ b/tests/test_rl_config_compat.py
@@ -9,6 +9,7 @@ The module is loaded by file spec because `import unsloth.models.rl_config_compa
would run `unsloth/__init__.py` first and drag in torch, numpy and unsloth_zoo.
"""
+import ast
import dataclasses
import importlib.util
from pathlib import Path
@@ -31,6 +32,8 @@ def _load_module():
_MODULE = _load_module()
filter_config_init_kwargs = _MODULE.filter_config_init_kwargs
TRL_CONFIG_RENAMES = _MODULE.TRL_CONFIG_RENAMES
+TRANSFORMERS_CONFIG_RENAMES = _MODULE.TRANSFORMERS_CONFIG_RENAMES
+TRANSFORMERS_REMOVED_FIELD_ADVICE = _MODULE.TRANSFORMERS_REMOVED_FIELD_ADVICE
@dataclasses.dataclass
@@ -191,6 +194,238 @@ def test_rename_targets_are_real_fields_of_the_modern_config():
assert new in modern, new
+def test_the_transformers_tables_do_not_overlap_or_contradict_the_trl_ones():
+ """A name in both tables would resolve to whichever was consulted first."""
+ renames = set(TRANSFORMERS_CONFIG_RENAMES) | set(TRL_CONFIG_RENAMES)
+ advice = set(TRANSFORMERS_REMOVED_FIELD_ADVICE) | set(_MODULE.TRL_REMOVED_FIELD_ADVICE)
+ assert not (renames & advice), sorted(renames & advice)
+ assert not (set(TRANSFORMERS_CONFIG_RENAMES) & set(TRL_CONFIG_RENAMES))
+
+
+def test_a_field_the_installed_version_still_declares_is_never_migrated():
+ """The invariant that makes a table entry safe to write ahead of its removal.
+
+ The 28 arguments did not all go in 5.0.0: `group_by_length` survived to 5.1.0,
+ `warmup_ratio` and `logging_dir` to 5.14.1. An entry is consulted only after
+ the config rejects the name, so on a version that still has it the entry must
+ be inert. Asserted per entry, and per installed version, rather than assuming
+ one cutoff.
+ """
+ transformers = pytest.importorskip("transformers")
+ fields = {f.name for f in dataclasses.fields(transformers.TrainingArguments)}
+
+ for key in list(TRANSFORMERS_CONFIG_RENAMES) + list(TRANSFORMERS_REMOVED_FIELD_ADVICE):
+ if key in fields:
+ verdict, _ = _MODULE.classify_config_kwarg(transformers.TrainingArguments, key)
+ assert verdict == "accepted", f"{key} is still a field but classified {verdict}"
+
+
+def test_a_transformers_rename_target_exists_once_the_old_name_is_gone():
+ """A rename is only reachable after the old name goes, so that is when its
+ target has to be real. A typo there degrades the migration to a plain drop."""
+ transformers = pytest.importorskip("transformers")
+ fields = {f.name for f in dataclasses.fields(transformers.TrainingArguments)}
+
+ checked = 0
+ for old, new in TRANSFORMERS_CONFIG_RENAMES.items():
+ if old in fields:
+ continue
+ assert new in fields, f"{old} renames to {new}, which does not exist"
+ checked += 1
+ if not checked:
+ pytest.skip("this transformers still declares every renamed argument")
+
+
+def test_a_transformers_5_removal_is_carried_across_on_a_real_config():
+ """`warmup_ratio` is the one every notebook sets."""
+ transformers = pytest.importorskip("transformers")
+ fields = {f.name for f in dataclasses.fields(transformers.TrainingArguments)}
+ if "warmup_ratio" in fields:
+ pytest.skip("this transformers still declares warmup_ratio")
+
+ @dataclasses.dataclass
+ class ModernSFTConfig:
+ output_dir: str = "out"
+ warmup_steps: float = 0.0
+
+ messages = []
+ kept = filter_config_init_kwargs(
+ ModernSFTConfig,
+ {"output_dir": "out", "warmup_ratio": 0.1},
+ notify = messages.append,
+ )
+ assert kept == {"output_dir": "out", "warmup_steps": 0.1}
+ assert any("warmup_steps" in m for m in messages)
+
+
+def test_a_rename_survives_a_default_unsloth_overrode_on_the_generated_config():
+ """The bug this guards: `rl.py` mirrors the base parameter under its OWN
+ default (`warmup_steps = 0.1`, `per_device_train_batch_size = 4`), so
+ comparing against TRL's declared default reads Unsloth's injected value as
+ caller intent and silently trains at the injected number instead.
+ """
+
+ @dataclasses.dataclass
+ class ModernSFTConfig:
+ output_dir: str = "out"
+ warmup_steps: float = 0.0 # what TRL declares
+
+ class UnslothSFTConfig(ModernSFTConfig):
+ def __init__(
+ self,
+ output_dir = "out",
+ warmup_steps = 0.1,
+ **kwargs,
+ ):
+ pass # what rl.py generates: same field, different default
+
+ messages = []
+ kept = filter_config_init_kwargs(
+ ModernSFTConfig,
+ {"output_dir": "out", "warmup_steps": 0.1, "warmup_ratio": 0.03},
+ notify = messages.append,
+ mirrored_from = UnslothSFTConfig,
+ )
+ assert kept["warmup_steps"] == 0.03, "the caller's warmup_ratio was thrown away"
+ assert not any("ignored" in m for m in messages)
+
+
+def test_a_value_the_caller_really_set_still_beats_the_rename():
+ """The other half: `mirrored_from` must not turn every collision into a win."""
+
+ @dataclasses.dataclass
+ class ModernSFTConfig:
+ warmup_steps: float = 0.0
+
+ class UnslothSFTConfig(ModernSFTConfig):
+ def __init__(
+ self,
+ warmup_steps = 0.1,
+ **kwargs,
+ ):
+ pass
+
+ kept, messages = [], []
+ kept = filter_config_init_kwargs(
+ ModernSFTConfig,
+ {"warmup_steps": 0.25, "warmup_ratio": 0.03},
+ notify = messages.append,
+ mirrored_from = UnslothSFTConfig,
+ )
+ assert kept["warmup_steps"] == 0.25
+ assert any("ignored" in m for m in messages)
+
+
+def test_the_renames_rl_py_overrides_the_default_of_are_the_known_ones():
+ """The systemic check behind the `mirrored_from` fix.
+
+ A rename whose target `rl.py` also assigns a default is only correct because
+ the config path passes `mirrored_from`; without it the injected default reads
+ as caller intent and the rename is dropped. Three are in that position today.
+ A fourth appearing means someone added an `rl.py` default or a rename without
+ checking the interaction, so it should fail here rather than in training.
+ """
+ overridden = _rl_py_overridden_defaults()
+ # The entries the audit found, so a matcher that silently stops working fails.
+ assert {"warmup_steps", "per_device_train_batch_size", "include_num_input_tokens_seen"} <= (
+ overridden
+ ), sorted(overridden)
+
+ needing_mirror = {
+ old for old, new in TRANSFORMERS_CONFIG_RENAMES.items() if new in overridden
+ } | {old for old, new in TRL_CONFIG_RENAMES.items() if new in overridden}
+ assert needing_mirror == {
+ "warmup_ratio",
+ "per_gpu_train_batch_size",
+ "per_gpu_eval_batch_size",
+ }, sorted(needing_mirror)
+
+
+def test_setting_the_new_name_to_its_own_default_is_reported_as_ambiguous():
+ """The one case a value comparison cannot decide, so it is stated not hidden.
+
+ `UnslothSFTConfig(warmup_steps = 0.1, warmup_ratio = 0.03)` passes the new
+ name at exactly the default `rl.py` injects. Nothing in a mirrored parameter
+ records whether it was supplied, so the legacy value wins and the message has
+ to say so. Sentinel defaults would resolve it, at the cost of the signature
+ that `HfArgumentParser` and users read. The trainer path is unaffected: it
+ knows which names actually arrived.
+ """
+
+ @dataclasses.dataclass
+ class ModernSFTConfig:
+ warmup_steps: float = 0.0
+
+ class UnslothSFTConfig(ModernSFTConfig):
+ def __init__(self, warmup_steps = 0.1, **kwargs):
+ pass
+
+ messages = []
+ kept = filter_config_init_kwargs(
+ ModernSFTConfig,
+ {"warmup_steps": 0.1, "warmup_ratio": 0.03},
+ notify = messages.append,
+ mirrored_from = UnslothSFTConfig,
+ )
+ assert kept["warmup_steps"] == 0.03
+ assert "cannot be distinguished" in messages[0]
+ assert "drop `warmup_ratio`" in messages[0]
+
+ # No `mirrored_from` means no mirrored parameter, so no ambiguity to report.
+ messages = []
+ filter_config_init_kwargs(
+ ModernSFTConfig, {"warmup_ratio": 0.03}, notify = messages.append,
+ )
+ assert "cannot be distinguished" not in messages[0]
+
+
+def test_a_legacy_optional_forwarded_at_none_does_not_erase_the_target():
+ """`per_gpu_train_batch_size` really did default to `None` in transformers 4.x
+ (checked against 4.57.6), so a wrapper mirroring that signature forwards a
+ `None` nobody asked for. Writing it onto `per_device_train_batch_size` leaves
+ the trainer doing arithmetic on `None`."""
+
+ @dataclasses.dataclass
+ class ModernSFTConfig:
+ per_device_train_batch_size: int = 8
+
+ kept, messages = _collect(ModernSFTConfig, {"per_gpu_train_batch_size": None})
+ assert kept == {}, "an unset legacy alias must not be migrated"
+ assert messages == []
+
+ # A value that was actually chosen still migrates.
+ kept, _ = _collect(ModernSFTConfig, {"per_gpu_train_batch_size": 16})
+ assert kept == {"per_device_train_batch_size": 16}
+
+
+def test_none_still_migrates_when_the_target_itself_defaults_to_none():
+ """The guard is about losing information, not about `None` being special."""
+
+ @dataclasses.dataclass
+ class ModernSFTConfig:
+ hub_token: str = None
+
+ kept, _ = _collect(ModernSFTConfig, {"push_to_hub_token": None})
+ assert kept == {"hub_token": None}
+
+
+def test_an_alias_whose_target_is_read_during_post_init_is_not_a_rename():
+ """`use_cpu` is consumed by `__post_init__`, which resolves `device` (a
+ cached_property) and `_n_gpu` from it. Measured on transformers 5.16.1: after
+ `setattr(args, "use_cpu", True)` the device stays `cuda:0`, so routing
+ `no_cuda` through the trainer path would report a change that never happened.
+ """
+ assert "no_cuda" in TRANSFORMERS_REMOVED_FIELD_ADVICE
+ assert "no_cuda" not in TRANSFORMERS_CONFIG_RENAMES
+
+
+def test_a_rename_target_normalised_in_post_init_is_not_a_rename():
+ """`setattr` on an existing config skips `__post_init__`, so a field that
+ normalises its own value cannot be migrated by assignment."""
+ assert "include_tokens_per_second" in TRANSFORMERS_REMOVED_FIELD_ADVICE
+ assert "include_tokens_per_second" not in TRANSFORMERS_CONFIG_RENAMES
+
+
def test_a_default_factory_field_is_compared_not_crashed_on():
"""Reading a `default_factory` default must not raise while resolving a rename."""
@@ -211,11 +446,42 @@ def test_a_default_factory_field_is_compared_not_crashed_on():
RL_SOURCE = (REPO_ROOT / "unsloth" / "models" / "rl.py").read_text(encoding = "utf-8")
+def _rl_py_overridden_defaults():
+ """Config parameters whose default `rl.py` rewrites in the generated `__init__`.
+
+ Both spellings it uses: the `replacements = {...}` literals and the later
+ `replacements["warmup_steps"] = 0.1` version-conditional assignments.
+ """
+ names = set()
+ for node in ast.walk(ast.parse(RL_SOURCE)):
+ if not isinstance(node, ast.Assign):
+ continue
+ for target in node.targets:
+ if (
+ isinstance(target, ast.Name)
+ and target.id == "replacements"
+ and isinstance(node.value, ast.Dict)
+ ):
+ names.update(
+ k.value
+ for k in node.value.keys
+ if isinstance(k, ast.Constant) and isinstance(k.value, str)
+ )
+ elif (
+ isinstance(target, ast.Subscript)
+ and isinstance(target.value, ast.Name)
+ and target.value.id == "replacements"
+ and isinstance(target.slice, ast.Constant)
+ ):
+ names.add(target.slice.value)
+ return names
+
+
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))"
+ "{RLConfig_name}, _unsloth_config_arguments, mirrored_from = __class__))"
) 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
@@ -229,8 +495,11 @@ def test_the_generated_file_imports_the_filter_with_a_safe_fallback():
# 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
+ "def _unsloth_filter_config_init_kwargs(config_class, kwargs, **kw): return kwargs"
+ in RL_SOURCE
)
+ # ...and an older Unsloth, whose filter has no `mirrored_from`, must not see it.
+ assert '"mirrored_from" not in inspect.signature(' in RL_SOURCE
if __name__ == "__main__":
diff --git a/tests/test_warnings_issued_guard.py b/tests/test_warnings_issued_guard.py
index 7b3f5a3d24a..f0b9f4614d2 100644
--- a/tests/test_warnings_issued_guard.py
+++ b/tests/test_warnings_issued_guard.py
@@ -181,10 +181,16 @@ class _FakeTrainer:
def _wrapped():
ns = _load(
- "_ensure_warnings_issued", "_resolve_trainer_params", "_backwards_compatible_trainer"
+ "_ensure_warnings_issued",
+ "_resolve_trainer_params",
+ "_route_unknown_trainer_kwargs",
+ "_backwards_compatible_trainer",
)
if "trl" not in ns:
pytest.skip("trl not installed")
+ for name in ("classify_config_kwarg", "rename_source", "removal_source",
+ "rename_value_is_unset"):
+ ns[name] = getattr(_rl_config_compat(), name)
class T(_FakeTrainer):
pass
@@ -361,8 +367,11 @@ if __name__ == "__main__":
def _sft_config():
- trl_module = pytest.importorskip("trl")
- return trl_module.SFTConfig
+ pytest.importorskip("trl")
+ # Not `trl.SFTConfig`: on Apple Silicon `import unsloth` rebinds that name to
+ # the MLX training config. The defining module still holds the real one.
+ from trl.trainer.sft_config import SFTConfig
+ return SFTConfig
class _RecordingTrainer:
@@ -379,15 +388,33 @@ class _RecordingTrainer:
self.train_dataset = train_dataset
-def _wrapped_recording():
+def _rl_config_compat():
+ """Load by file spec: importing via the package drags in torch and unsloth_zoo."""
+ import importlib.util
+
+ path = ROOT / "unsloth" / "models" / "rl_config_compat.py"
+ spec = importlib.util.spec_from_file_location("_rl_config_compat_for_guard", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _wrapped_recording(trainer_base = None):
config_class = _sft_config()
ns = _load(
- "_ensure_warnings_issued", "_resolve_trainer_params", "_backwards_compatible_trainer"
+ "_ensure_warnings_issued",
+ "_resolve_trainer_params",
+ "_route_unknown_trainer_kwargs",
+ "_backwards_compatible_trainer",
)
if "trl" not in ns:
pytest.skip("trl not installed")
+ # The relative import in the routed function cannot work in a bare namespace.
+ for name in ("classify_config_kwarg", "rename_source", "removal_source",
+ "rename_value_is_unset"):
+ ns[name] = getattr(_rl_config_compat(), name)
- class T(_RecordingTrainer):
+ class T(trainer_base or _RecordingTrainer):
pass
T.__init__ = ns["_backwards_compatible_trainer"](T, config_class)
@@ -435,6 +462,121 @@ def test_untouched_config_values_keep_what_the_caller_set(tmp_path):
assert trainer.args.max_length == 777
+def test_a_kwarg_neither_side_takes_is_reported_not_swallowed(tmp_path):
+ """Not `max_seq_length` as the sentinel: the generated SFT config restores it."""
+ Trainer, config_class = _wrapped_recording()
+ config = config_class(output_dir = str(tmp_path), report_to = [])
+ unexpected = "definitely_not_a_trainer_or_config_kwarg"
+ assert unexpected not in {f.name for f in dataclasses.fields(config_class)}
+
+ with pytest.raises(TypeError, match = unexpected):
+ Trainer(model = _Bare(), args = config, **{unexpected: 2048})
+
+
+def test_a_field_trl_retired_is_reported_and_dropped_not_raised(tmp_path, capsys):
+ """Must warn, not raise: scripts pinned to an older TRL still pass these."""
+ Trainer, config_class = _wrapped_recording()
+ config = config_class(output_dir = str(tmp_path), report_to = [])
+ retired = "rpo_alpha" # DPOConfig, removed in TRL 0.29.0
+ assert retired not in {f.name for f in dataclasses.fields(config_class)}
+
+ trainer = Trainer(model = _Bare(), args = config, **{retired: 1.0})
+
+ assert trainer.args is config
+ assert not hasattr(config, retired)
+ assert retired in capsys.readouterr().out
+
+
+def test_a_field_trl_renamed_is_carried_across_to_the_new_name(tmp_path, capsys):
+ Trainer, config_class = _wrapped_recording()
+ fields = {f.name for f in dataclasses.fields(config_class)}
+ if "use_liger_kernel" not in fields or "use_liger_loss" in fields:
+ pytest.skip("installed trl does not show this rename on SFTConfig")
+ config = config_class(output_dir = str(tmp_path), report_to = [])
+
+ trainer = Trainer(model = _Bare(), args = config, use_liger_loss = True)
+
+ assert trainer.args.use_liger_kernel is True
+ assert "use_liger_kernel" in capsys.readouterr().out
+
+
+def test_the_explicitly_supplied_new_name_beats_the_renamed_old_one(tmp_path, capsys):
+ """Migrating over an explicit new name would silently train with the opposite
+ setting. Covers both branches: the caller's config, and the rebuilt one."""
+ Trainer, config_class = _wrapped_recording()
+ fields = {f.name for f in dataclasses.fields(config_class)}
+ if "use_liger_kernel" not in fields or "use_liger_loss" in fields:
+ pytest.skip("installed trl does not show this rename on SFTConfig")
+
+ config = config_class(output_dir = str(tmp_path), report_to = [])
+ trainer = Trainer(model = _Bare(), args = config, use_liger_loss = False, use_liger_kernel = True)
+ assert trainer.args.use_liger_kernel is True
+ assert "is ignored" in capsys.readouterr().out
+
+ Rebuilt, _ = _wrapped_recording()
+ rebuilt = Rebuilt(
+ model = _Bare(),
+ args = None,
+ output_dir = str(tmp_path),
+ report_to = [],
+ use_liger_loss = False,
+ use_liger_kernel = True,
+ )
+ assert rebuilt.args.use_liger_kernel is True
+
+
+def test_a_name_trl_never_had_still_raises(tmp_path):
+ """The retirement table must not become a way to swallow typos."""
+ Trainer, config_class = _wrapped_recording()
+ config = config_class(output_dir = str(tmp_path), report_to = [])
+
+ with pytest.raises(TypeError, match = "learnign_rate"):
+ Trainer(model = _Bare(), args = config, learnign_rate = 3e-4)
+
+
+def test_a_variadic_trainer_receives_a_name_the_table_does_not_know(tmp_path):
+ """A trainer declaring `**kwargs` opted into arbitrary names, so deliver."""
+
+ class _Variadic(_RecordingTrainer):
+ def __init__(
+ self,
+ model = None,
+ args = None,
+ train_dataset = None,
+ processing_class = None,
+ **kwargs,
+ ):
+ super().__init__(model, args, train_dataset, processing_class)
+ self.extra = dict(kwargs)
+
+ Trainer, config_class = _wrapped_recording(trainer_base = _Variadic)
+ config = config_class(output_dir = str(tmp_path), report_to = [])
+
+ trainer = Trainer(model = _Bare(), args = config, some_extension_kwarg = 5)
+
+ assert trainer.extra == {"some_extension_kwarg": 5}
+
+
+def test_a_trainer_whose_config_parameter_is_not_called_args_does_not_KeyError(tmp_path):
+ """`discard`, not `remove`: this used to raise KeyError."""
+
+ class _OddlyNamed:
+ def __init__(
+ self,
+ model = None,
+ config = None,
+ **kwargs,
+ ):
+ self.model, self.config, self.extra = model, config, dict(kwargs)
+
+ Trainer, config_class = _wrapped_recording(trainer_base = _OddlyNamed)
+ config = config_class(output_dir = str(tmp_path), report_to = [])
+
+ trainer = Trainer(model = _Bare(), args = config)
+
+ assert trainer.extra["args"] is config
+
+
def test_trainer_kwargs_still_go_to_the_trainer(tmp_path):
Trainer, config_class = _wrapped_recording()
config = config_class(output_dir = str(tmp_path), report_to = [])
diff --git a/unsloth/models/rl.py b/unsloth/models/rl.py
index b44eaa31b2b..65cb2621cd4 100644
--- a/unsloth/models/rl.py
+++ b/unsloth/models/rl.py
@@ -406,8 +406,14 @@ except Exception:
# 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
+ # A cache file generated here can be imported by an older Unsloth whose filter
+ # predates `mirrored_from`, so drop the argument rather than raise TypeError.
+ if "mirrored_from" not in inspect.signature(_unsloth_filter_config_init_kwargs).parameters:
+ _unsloth_filter_config_init_kwargs_old = _unsloth_filter_config_init_kwargs
+ def _unsloth_filter_config_init_kwargs(config_class, kwargs, **kw):
+ return _unsloth_filter_config_init_kwargs_old(config_class, kwargs)
except Exception:
- def _unsloth_filter_config_init_kwargs(config_class, kwargs): return kwargs
+ def _unsloth_filter_config_init_kwargs(config_class, kwargs, **kw): return kwargs
def prepare_for_training_mode(f):
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
@@ -521,7 +527,7 @@ class Unsloth{RLConfig_name}({RLConfig_name}):
# 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))
+ super().__init__(**_unsloth_filter_config_init_kwargs({RLConfig_name}, _unsloth_config_arguments, mirrored_from = __class__))
self.vllm_sampling_params = vllm_sampling_params
self.unsloth_num_chunks = unsloth_num_chunks
if unsloth_grpo_mini_batch is not None:
diff --git a/unsloth/models/rl_config_compat.py b/unsloth/models/rl_config_compat.py
index 2750657931e..f0c01367db8 100644
--- a/unsloth/models/rl_config_compat.py
+++ b/unsloth/models/rl_config_compat.py
@@ -35,7 +35,10 @@ import dataclasses
import inspect
__all__ = [
+ "classify_config_kwarg",
"filter_config_init_kwargs",
+ "TRANSFORMERS_CONFIG_RENAMES",
+ "TRANSFORMERS_REMOVED_FIELD_ADVICE",
"TRL_CONFIG_RENAMES",
"TRL_REMOVED_FIELD_ADVICE",
]
@@ -78,6 +81,54 @@ TRL_REMOVED_FIELD_ADVICE = {
}
+# Every trl config subclasses `transformers.TrainingArguments`, so transformers 5
+# removals land here too. From transformers' MIGRATION_GUIDE_V5.md, whose
+# `warmup_step` is a typo for `warmup_steps` (which does take a float).
+TRANSFORMERS_CONFIG_RENAMES = {
+ "warmup_ratio": "warmup_steps",
+ "push_to_hub_token": "hub_token",
+ "per_gpu_train_batch_size": "per_device_train_batch_size",
+ "per_gpu_eval_batch_size": "per_device_eval_batch_size",
+}
+
+
+# transformers 5 removals whose value cannot be carried across.
+TRANSFORMERS_REMOVED_FIELD_ADVICE = {
+ # Not a rename: `include_num_input_tokens_seen` is `str | bool` and normalises
+ # a bool to "no"/"all" in `__post_init__`, which the trainer's `setattr` path
+ # does not run, so a migrated `False` would read as truthy.
+ "include_tokens_per_second": ('set `include_num_input_tokens_seen = "all"` instead'),
+ # Also not a rename. `__post_init__` reads `device`, which is a cached_property,
+ # and settles `_n_gpu` with it, so assigning `use_cpu` afterwards is a no-op
+ # (measured: device stays cuda:0). Reporting it as forwarded would be a lie.
+ "no_cuda": "set `use_cpu = True` on the config you construct instead",
+ "group_by_length": 'set `train_sampling_strategy = "group_by_length"` instead',
+ "include_inputs_for_metrics": 'add "inputs" to the `include_for_metrics` list instead',
+ "tpu_metrics_debug": "use `debug` instead",
+ "push_to_hub_model_id": "set the full repository name in `hub_model_id` instead",
+ "push_to_hub_organization": "set the full repository name in `hub_model_id` instead",
+ "jit_mode_eval": "use `torch_compile` instead, torchscript is no longer recommended",
+ "torchdynamo": "use `torch_compile_backend` instead",
+ "fsdp_min_num_params": "use `fsdp_config` instead",
+ "fsdp_transformer_layer_cls_to_wrap": "use `fsdp_config` instead",
+ "fp16_backend": "transformers relies on torch.amp now, so this is no longer configurable",
+ "half_precision_backend": (
+ "transformers relies on torch.amp now, so this is no longer configurable"
+ ),
+ "fp16_opt_level": "the apex backend is gone, torch.amp is used instead",
+ "adafactor": 'pass `optim = "adafactor"` instead',
+ "save_safetensors": "safetensors is the only checkpoint format now",
+ "overwrite_output_dir": "use `resume_from_checkpoint` to control this instead",
+ "logging_dir": "set the TENSORBOARD_LOGGING_DIR environment variable instead",
+ "tpu_num_cores": "set the TPU_NUM_CORES environment variable instead",
+ "ray_scope": "set the RAY_SCOPE environment variable instead",
+ "use_mps_device": "mps is used automatically when it is detected",
+ "use_legacy_prediction_loop": "only `evaluation_loop` is used now",
+ "past_index": "this was only ever used by a few special architectures",
+ "mp_parameters": "this was a legacy SageMaker-only argument",
+}
+
+
# Memoised on the class object, which is module level and outlives the process.
_ACCEPTED_CACHE = {}
@@ -148,9 +199,41 @@ def _field_default(config_class, name):
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)
+def _init_default(config_class, name):
+ """The default `config_class.__init__` gives `name`, ignoring the field list.
+
+ `Unsloth<X>Config` inherits its dataclass fields but overrides some defaults
+ in its own `__init__` signature (`rl.py` sets `per_device_train_batch_size`
+ to 4, and `warmup_steps`/`warmup_ratio` to 0.1). Reading `dataclasses.fields`
+ there returns TRL's default instead of the one the caller actually got.
+ """
+ try:
+ parameter = inspect.signature(config_class.__init__).parameters.get(name)
+ except (TypeError, ValueError):
+ return _MISSING
+ if parameter is None or parameter.default is inspect.Parameter.empty:
+ return _MISSING
+ return parameter.default
+
+
+def _is_untouched(
+ config_class,
+ name,
+ value,
+ mirrored_from = None,
+):
+ """True if `value` is indistinguishable from `name`'s declared default.
+
+ `mirrored_from` is the class whose `__init__` supplied `value`, which is not
+ `config_class` when a generated config mirrors a base class parameter under a
+ different default. Comparing against the wrong one reads a default Unsloth
+ injected as a value the caller chose, and then refuses to apply the rename.
+ """
+ default = _MISSING
+ if mirrored_from is not None:
+ default = _init_default(mirrored_from, name)
+ if default is _MISSING:
+ default = _field_default(config_class, name)
if default is _MISSING:
return False
try:
@@ -159,20 +242,75 @@ def _is_untouched(config_class, name, value):
return default is value
+def rename_value_is_unset(config_class, renamed, value):
+ """True if `value` carries no information and must not overwrite `renamed`.
+
+ The legacy spellings are `Optional` and default to `None` (`per_gpu_*_batch_size`
+ in transformers 4.x), so a wrapper mirroring an old signature forwards `None`
+ for an argument nobody set. Writing that onto a target whose own default is a
+ number replaces a working value with one the trainer cannot do arithmetic on.
+ A target that defaults to `None` itself loses nothing, so it still migrates.
+ """
+ if value is not None:
+ return False
+ default = _field_default(config_class, renamed)
+ return default is not _MISSING and default is not None
+
+
def _default_notifier(message):
print(message)
+def rename_source(key):
+ """Which project renamed `key`, so the message names the right changelog."""
+ return "transformers" if key in TRANSFORMERS_CONFIG_RENAMES else "TRL"
+
+
+def removal_source(key):
+ """Which project retired `key`."""
+ return "transformers" if key in TRANSFORMERS_REMOVED_FIELD_ADVICE else "TRL"
+
+
+def classify_config_kwarg(config_class, key):
+ """Verdict on `key`: accepted / rename / retired / unknown, or opaque when the
+ config declares nothing to judge by. A trailing `**kwargs` is deliberately not
+ acceptance: the generated `Unsloth<X>Config.__init__` has one, so trusting it
+ would put every retired field back to being swallowed."""
+ accepted, takes_var_keyword = _accepted_parameters(config_class)
+ if key in accepted:
+ return "accepted", key
+ if takes_var_keyword and not accepted:
+ return "opaque", None
+
+ # trl first: it can retire a name transformers still has.
+ for renames in (TRL_CONFIG_RENAMES, TRANSFORMERS_CONFIG_RENAMES):
+ renamed = renames.get(key)
+ if renamed is not None and renamed in accepted:
+ return "rename", renamed
+
+ for table in (TRL_REMOVED_FIELD_ADVICE, TRANSFORMERS_REMOVED_FIELD_ADVICE):
+ advice = table.get(key)
+ if advice is not None:
+ return "retired", advice
+
+ return "unknown", None
+
+
def filter_config_init_kwargs(
config_class,
kwargs,
notify = None,
+ mirrored_from = 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).
+ Renames are applied where TRL or transformers 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).
+
+ `mirrored_from` is the generated config class whose `__init__` built `kwargs`.
+ It is what tells an untouched mirrored parameter apart from a real one, so
+ omitting it only costs a rename that loses to its own target's default.
"""
if not kwargs:
return kwargs
@@ -193,31 +331,49 @@ def filter_config_init_kwargs(
if key in accepted:
continue
- renamed = TRL_CONFIG_RENAMES.get(key)
- if renamed is not None and renamed in accepted:
+ verdict, detail = classify_config_kwarg(config_class, key)
+
+ if verdict == "rename":
+ renamed = detail
# 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):
+ who = rename_source(key)
+ if rename_value_is_unset(config_class, renamed, value):
+ continue
+ if existing is _MISSING or _is_untouched(
+ config_class, renamed, existing, mirrored_from = mirrored_from
+ ):
forwarded[renamed] = value
+ # A mirrored parameter carries no record of whether it was passed,
+ # so a caller who set it to exactly this default cannot be told
+ # apart from one who left it alone. Say which value won instead of
+ # letting the other disappear. The trainer path knows for certain
+ # which names arrived, so it never reaches this.
+ ambiguous = existing is not _MISSING and mirrored_from is not None
notify(
- f"Unsloth: TRL renamed `{key}` to `{renamed}`. Forwarding your "
+ f"Unsloth: {who} renamed `{key}` to `{renamed}`. Forwarding your "
f"value to `{renamed}` - update your code when convenient."
+ + (
+ f" If you also passed `{renamed}` as {existing!r}, that is its "
+ f"default here and cannot be distinguished from leaving it "
+ f"unset, so `{key}` was used; drop `{key}` to keep it."
+ if ambiguous else ""
+ )
)
else:
notify(
- f"Unsloth: `{key}` was renamed to `{renamed}` by TRL and this "
+ f"Unsloth: `{key}` was renamed to `{renamed}` by {who} 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:
+ if verdict == "retired":
notify(
- f"Unsloth: `{key}` is not supported by the installed TRL's "
- f"{config_name} and will be IGNORED - {advice}."
+ f"Unsloth: `{key}` is not supported by the installed "
+ f"{removal_source(key)}'s {config_name} and will be IGNORED - {detail}."
)
else:
notify(
diff --git a/unsloth/trainer.py b/unsloth/trainer.py
index fe3d84ec2f9..824c3e6b46e 100644
--- a/unsloth/trainer.py
+++ b/unsloth/trainer.py
@@ -711,6 +711,83 @@ def _ensure_warnings_issued(model):
pass
+def _route_unknown_trainer_kwargs(
+ config_class,
+ unknown,
+ notify = None,
+ already_supplied = None,
+):
+ """Split names neither side declares into `(to_config, to_trainer)` using
+ `rl_config_compat`'s rename/retire policy, which otherwise only runs when a
+ config is built; unrecognised names go back to the trainer call to raise there.
+
+ `already_supplied` uses presence, not a default comparison, because `kwargs`
+ holds only what the caller typed, so an explicit new name is never overwritten.
+ """
+ if not unknown:
+ return {}, {}
+
+ try:
+ from .models.rl_config_compat import (
+ classify_config_kwarg,
+ removal_source,
+ rename_source,
+ rename_value_is_unset,
+ )
+ except Exception:
+ # tests/ AST-load this function into a bare namespace with no package to
+ # import from, and supply the classifier through globals() instead.
+ classify_config_kwarg = globals().get("classify_config_kwarg")
+ rename_source = globals().get("rename_source", lambda key: "TRL")
+ removal_source = globals().get("removal_source", lambda key: "TRL")
+ rename_value_is_unset = globals().get(
+ "rename_value_is_unset", lambda cls, name, value: False
+ )
+ if classify_config_kwarg is None:
+ # Unreachable in a real install; keep the value on the trainer.
+ return {}, dict(unknown)
+
+ if notify is None:
+ notify = print
+ config_name = getattr(config_class, "__name__", str(config_class))
+
+ to_config, to_trainer = {}, {}
+ for key, value in unknown.items():
+ try:
+ verdict, detail = classify_config_kwarg(config_class, key)
+ except Exception:
+ verdict, detail = "unknown", None
+
+ if verdict == "accepted":
+ to_config[key] = value
+ elif verdict == "rename":
+ # A legacy Optional forwarded at its `None` default says nothing, so
+ # it must not replace a real value. Same rule as the config path.
+ if rename_value_is_unset(config_class, detail, value):
+ continue
+ if already_supplied and detail in already_supplied:
+ notify(
+ f"Unsloth: `{key}` was renamed to `{detail}` by {rename_source(key)} and "
+ f"this {config_name} accepts only the new name. You set both, so `{key}` "
+ f"is ignored and your `{detail}` is kept."
+ )
+ continue
+ to_config[detail] = value
+ notify(
+ f"Unsloth: {rename_source(key)} renamed `{key}` to `{detail}`. "
+ f"Forwarding your value to `{detail}` - update your code when convenient."
+ )
+ elif verdict == "retired":
+ notify(
+ f"Unsloth: `{key}` is not supported by the installed "
+ f"{removal_source(key)}'s {config_name} and will be IGNORED - {detail}."
+ )
+ else:
+ to_trainer[key] = value
+
+ return to_config, to_trainer
+
+
def _backwards_compatible_trainer(trainer_class, config_class):
original_init = trainer_class.__init__
@@ -725,8 +802,10 @@ def _backwards_compatible_trainer(trainer_class, config_class):
if ("args" in kwargs) and (Version(trl) >= Version("0.13.0.dev0")):
training_args = kwargs.pop("args", None)
- trainer_params.remove("self")
- trainer_params.remove("args")
+ # `discard`, not `remove`: a trainer naming its config something other
+ # than `args` would otherwise die with a bare KeyError here.
+ trainer_params.discard("self")
+ trainer_params.discard("args")
# Fields that should be passed to Config init
config_fields = {
@@ -749,6 +828,7 @@ def _backwards_compatible_trainer(trainer_class, config_class):
# Separate kwargs into trainer kwargs and config kwargs
trainer_kwargs = {}
additional_config_kwargs = {}
+ unknown_kwargs = {}
for key, value in kwargs.items():
if key in trainer_params:
@@ -756,7 +836,16 @@ def _backwards_compatible_trainer(trainer_class, config_class):
elif key in moved_params or key in config_fields:
additional_config_kwargs[key] = value
else:
- additional_config_kwargs[key] = value
+ # Filing this with the config kwargs dropped it in silence.
+ unknown_kwargs[key] = value
+
+ migrated, unroutable = _route_unknown_trainer_kwargs(
+ config_class,
+ unknown_kwargs,
+ already_supplied = set(additional_config_kwargs),
+ )
+ additional_config_kwargs.update(migrated)
+ trainer_kwargs.update(unroutable)
config_dict.update(additional_config_kwargs)
@@ -771,7 +860,8 @@ def _backwards_compatible_trainer(trainer_class, config_class):
# the moved values on the caller's config rather than rebuild it.
config = training_args
for key, value in additional_config_kwargs.items():
- if key in config_fields or key in moved_params:
+ # `migrated` keys are already known to be accepted here.
+ if key in config_fields or key in moved_params or key in migrated:
setattr(config, key, value)
# Reconstruct kwargs for Trainer