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.

Apply the moved trainer kwargs to the config instead of dropping them (#8374)

Vineeth Sai Varikuntlaa4ac00b7bc5a
diff --git a/tests/test_warnings_issued_guard.py b/tests/test_warnings_issued_guard.py
index 255184b7376..7b3f5a3d24a 100644
--- a/tests/test_warnings_issued_guard.py
+++ b/tests/test_warnings_issued_guard.py
@@ -351,3 +351,125 @@ def test_every_trl_trainer_that_writes_it_goes_through_the_wrapper():
if __name__ == "__main__":
raise SystemExit(pytest.main([__file__, "-q"]))
+
+
+# ---- the kwargs the wrapper exists to move -------------------------------
+#
+# A real trl config, not a stand-in: `new_init` branches on
+# isinstance(TrainingArguments), so a plain dataclass takes the other branch and
+# the tests would pass against the bug.
+
+
+def _sft_config():
+ trl_module = pytest.importorskip("trl")
+ return trl_module.SFTConfig
+
+
+class _RecordingTrainer:
+ """trl.SFTTrainer's signature, enough of it to see what arrives."""
+
+ def __init__(
+ self,
+ model = None,
+ args = None,
+ train_dataset = None,
+ processing_class = None,
+ ):
+ self.args = args
+ self.train_dataset = train_dataset
+
+
+def _wrapped_recording():
+ config_class = _sft_config()
+ ns = _load(
+ "_ensure_warnings_issued", "_resolve_trainer_params", "_backwards_compatible_trainer"
+ )
+ if "trl" not in ns:
+ pytest.skip("trl not installed")
+
+ class T(_RecordingTrainer):
+ pass
+
+ T.__init__ = ns["_backwards_compatible_trainer"](T, config_class)
+ return T, config_class
+
+
+def test_config_kwargs_reach_the_config_the_caller_passed(tmp_path):
+ """Settings that used to be trainer kwargs have to end up on the config.
+ They were computed and then dropped whenever `args` was given."""
+ Trainer, config_class = _wrapped_recording()
+ config = config_class(output_dir = str(tmp_path), report_to = [])
+ assert config.packing is False and config.max_length != 2048
+
+ trainer = Trainer(
+ model = _Bare(),
+ args = config,
+ train_dataset = "DS",
+ packing = True,
+ max_length = 2048,
+ dataset_num_proc = 4,
+ )
+
+ assert trainer.args.packing is True
+ assert trainer.args.max_length == 2048
+ assert trainer.args.dataset_num_proc == 4
+
+
+def test_the_callers_own_config_object_is_the_one_used(tmp_path):
+ """Reinitialising re-triggers trl's mutually exclusive checks, so the values
+ have to be set rather than a new config built."""
+ Trainer, config_class = _wrapped_recording()
+ config = config_class(output_dir = str(tmp_path), report_to = [])
+
+ trainer = Trainer(model = _Bare(), args = config, packing = True)
+
+ assert trainer.args is config
+
+
+def test_untouched_config_values_keep_what_the_caller_set(tmp_path):
+ Trainer, config_class = _wrapped_recording()
+ config = config_class(output_dir = str(tmp_path), report_to = [], max_length = 777)
+
+ trainer = Trainer(model = _Bare(), args = config, packing = True)
+
+ assert trainer.args.max_length == 777
+
+
+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 = [])
+
+ trainer = Trainer(model = _Bare(), args = config, train_dataset = "DS", packing = True)
+
+ assert trainer.train_dataset == "DS"
+
+
+def test_auto_packing_wraps_inside_the_backwards_compatible_wrapper():
+ """Auto-packing reads `packing` off the config to block VLMs, custom collators
+ and the blocklist, so it has to wrap first and see the moved value. Wrapped
+ last it decides on the old one, and the block is undone right after."""
+ for node in ast.walk(ast.parse(SRC)):
+ if isinstance(node, ast.FunctionDef) and node.name == "_patch_trl_trainer":
+ body = ast.get_source_segment(SRC, node)
+ break
+ else:
+ raise AssertionError("_patch_trl_trainer not found")
+
+ assert body.index("_patch_sft_trainer_auto_packing(trl)") < body.index(
+ "_backwards_compatible_trainer(trl."
+ )
+
+
+def test_auto_packing_failure_still_leaves_the_wrapper_installed():
+ """Going first, a raise here would skip the wrapping loop and drop pre-0.13
+ compatibility, so the call has to be guarded."""
+ for node in ast.walk(ast.parse(SRC)):
+ if isinstance(node, ast.FunctionDef) and node.name == "_patch_trl_trainer":
+ guarded = any(
+ "_patch_sft_trainer_auto_packing" in ast.dump(stmt)
+ for stmt in node.body
+ if isinstance(stmt, ast.Try)
+ )
+ assert guarded, "_patch_sft_trainer_auto_packing must be wrapped in try/except"
+ return
+ raise AssertionError("_patch_trl_trainer not found")
diff --git a/unsloth/trainer.py b/unsloth/trainer.py
index 817b5802330..fe3d84ec2f9 100644
--- a/unsloth/trainer.py
+++ b/unsloth/trainer.py
@@ -766,7 +766,13 @@ def _backwards_compatible_trainer(trainer_class, config_class):
if not isinstance(training_args, TrainingArguments):
config = config_class(**config_dict)
else:
+ # Every trl config subclasses TrainingArguments, so this is the
+ # branch real calls take and config_dict was going nowhere. Set
+ # 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:
+ setattr(config, key, value)
# Reconstruct kwargs for Trainer
kwargs = trainer_kwargs
@@ -994,6 +1000,15 @@ def _patch_trl_trainer():
trl_configs = set(x[: -len("Config")] for x in trl_classes if x.endswith("Config"))
trl_classes = list(trl_trainers & trl_configs)
+ # Auto-packing wraps first so it lands INSIDE the backwards-compatible one: a
+ # moved `packing` kwarg must reach the config before packing is decided, else
+ # the block is undone right after. Guarded so a failure here still leaves the
+ # pre-0.13 compatibility wrappers installed.
+ try:
+ _patch_sft_trainer_auto_packing(trl)
+ except Exception as exc:
+ logger.warning(f"Unsloth: could not enable SFT auto-packing ({exc}).")
+
for x in trl_classes:
try:
exec(
@@ -1003,6 +1018,4 @@ def _patch_trl_trainer():
except:
continue
- _patch_sft_trainer_auto_packing(trl)
-
trl.__UNSLOTH_BACKWARDS_COMPATIBLE__ = True