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.

Validate unsloth train flags the way the config file is validated (#11780)

Abhishek B R57365a4f352e
diff --git a/unsloth_cli/commands/train.py b/unsloth_cli/commands/train.py
index 224c9ef6a2a..67106f60c7a 100644
--- a/unsloth_cli/commands/train.py
+++ b/unsloth_cli/commands/train.py
@@ -102,15 +102,14 @@ def train(
config_overrides: dict = None,
):
"""Launch training using the existing Unsloth training backend."""
+ config_overrides = config_overrides or {}
try:
cfg = load_config(config)
+ cfg.apply_overrides(**config_overrides)
except (FileNotFoundError, ConfigError) as e:
typer.echo(f"Error: {e}", err = True)
raise typer.Exit(code = 2)
- config_overrides = config_overrides or {}
- cfg.apply_overrides(**config_overrides)
-
# CLI/env tokens take precedence; guard against unresolved typer.Option.
from typer.models import OptionInfo
diff --git a/unsloth_cli/config.py b/unsloth_cli/config.py
index 66c3748de99..fe025928ba6 100644
--- a/unsloth_cli/config.py
+++ b/unsloth_cli/config.py
@@ -5,19 +5,26 @@ from pathlib import Path
from typing import Literal, Optional, List
import yaml
-from pydantic import BaseModel, ConfigDict, Field, ValidationError
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
+
+
+def _lower_str(value):
+ return value.strip().lower() if isinstance(value, str) else value
class DataConfig(BaseModel):
- model_config = ConfigDict(extra = "forbid")
+ model_config = ConfigDict(extra = "forbid", validate_assignment = True)
dataset: Optional[str] = None
local_dataset: Optional[List[str]] = None
- format_type: Literal["auto", "alpaca", "chatml", "sharegpt"] = "auto"
+ # raw and conversational are handled by format_and_template_dataset (raw = continued pretraining).
+ format_type: Literal["auto", "alpaca", "chatml", "sharegpt", "conversational", "raw"] = "auto"
+
+ _normalize_format_type = field_validator("format_type", mode = "before")(_lower_str)
class TrainingConfig(BaseModel):
- model_config = ConfigDict(extra = "forbid")
+ model_config = ConfigDict(extra = "forbid", validate_assignment = True)
training_type: Literal["lora", "full"] = "lora"
max_seq_length: int = 2048
@@ -36,9 +43,26 @@ class TrainingConfig(BaseModel):
train_on_completions: bool = False
gradient_checkpointing: Literal["unsloth", "true", "none"] = "unsloth"
+ _normalize_training_type = field_validator("training_type", mode = "before")(_lower_str)
+
+ @field_validator("gradient_checkpointing", mode = "before")
+ @classmethod
+ def _normalize_gradient_checkpointing(cls, value):
+ # Same spellings the trainer's normalize_gradient_checkpointing accepts, incl. YAML booleans.
+ if isinstance(value, bool):
+ return "true" if value else "none"
+ text = _lower_str(value)
+ if text == "":
+ return "unsloth"
+ if text in ("1", "yes"):
+ return "true"
+ if text in ("false", "0", "no", "off"):
+ return "none"
+ return text
+
class LoraConfig(BaseModel):
- model_config = ConfigDict(extra = "forbid")
+ model_config = ConfigDict(extra = "forbid", validate_assignment = True)
lora_r: int = 64
lora_alpha: int = 16
@@ -55,7 +79,7 @@ class LoraConfig(BaseModel):
class LoggingConfig(BaseModel):
- model_config = ConfigDict(extra = "forbid")
+ model_config = ConfigDict(extra = "forbid", validate_assignment = True)
enable_wandb: bool = False
wandb_project: str = "unsloth-training"
@@ -66,7 +90,7 @@ class LoggingConfig(BaseModel):
class Config(BaseModel):
- model_config = ConfigDict(extra = "forbid")
+ model_config = ConfigDict(extra = "forbid", validate_assignment = True)
model: Optional[str] = None
data: DataConfig = Field(default_factory = DataConfig)
@@ -76,16 +100,24 @@ class Config(BaseModel):
def apply_overrides(self, **kwargs):
"""Apply CLI overrides by matching arg names to config fields."""
+ errors = []
for key, value in kwargs.items():
if value is None:
continue
- if hasattr(self, key):
- setattr(self, key, value)
- else:
- for section in (self.data, self.training, self.lora, self.logging):
- if hasattr(section, key):
- setattr(section, key, value)
- break
+ try:
+ if hasattr(self, key):
+ setattr(self, key, value)
+ else:
+ for section in (self.data, self.training, self.lora, self.logging):
+ if hasattr(section, key):
+ setattr(section, key, value)
+ break
+ except ValidationError as error:
+ flag = "--" + key.replace("_", "-")
+ for err in error.errors():
+ errors.append(f" - {flag}: {err.get('msg', 'invalid value')}")
+ if errors:
+ raise ConfigError("\n".join(["Invalid command line options:", *errors]))
def model_kwargs(self, use_lora: bool, is_vision: bool) -> dict:
"""Return kwargs for trainer.prepare_model_for_training()."""
diff --git a/unsloth_cli/tests/test_train_cli_override_validation.py b/unsloth_cli/tests/test_train_cli_override_validation.py
new file mode 100644
index 00000000000..6dd31639051
--- /dev/null
+++ b/unsloth_cli/tests/test_train_cli_override_validation.py
@@ -0,0 +1,130 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`unsloth train` flags must be validated like the same keys in a config file."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+import typer
+from typer.testing import CliRunner
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+if str(_REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(_REPO_ROOT))
+
+from unsloth_cli.config import Config, ConfigError # noqa: E402
+
+
+def _train_app():
+ from unsloth_cli.commands.train import train
+
+ app = typer.Typer()
+ app.command()(train)
+ return app
+
+
+def _dry_run(*args: str):
+ return CliRunner().invoke(_train_app(), ["--model", "m", "--dataset", "d", "--dry-run", *args])
+
+
+ ("flag", "value"),
+ [
+ ("--training-type", "lroa"),
+ ("--format-type", "chatlm"),
+ ("--gradient-checkpointing", "maybe"),
+ ],
+)
+def test_an_invalid_flag_value_exits_2_like_the_same_value_in_a_config(flag, value):
+ result = _dry_run(flag, value)
+
+ assert result.exit_code == 2
+ assert result.exception is None or isinstance(result.exception, SystemExit)
+ assert result.output.startswith("Error: ")
+ assert flag in result.output
+
+
+def test_every_invalid_flag_is_reported_at_once():
+ result = _dry_run(
+ "--training-type", "lroa", "--format-type", "chatlm", "--gradient-checkpointing", "maybe"
+ )
+
+ assert result.exit_code == 2
+ for flag in ("--training-type", "--format-type", "--gradient-checkpointing"):
+ assert flag in result.output
+
+
+def test_an_invalid_flag_is_rejected_over_a_valid_config(tmp_path):
+ path = tmp_path / "config.yaml"
+ path.write_text("training:\n training_type: lora\n", encoding = "utf-8")
+
+ result = _dry_run("--config", str(path), "--training-type", "lroa")
+
+ assert result.exit_code == 2
+ assert "--training-type" in result.output
+
+
+def test_valid_flags_still_override_the_config(tmp_path):
+ path = tmp_path / "config.yaml"
+ path.write_text("training:\n training_type: lora\n num_epochs: 1\n", encoding = "utf-8")
+
+ result = _dry_run(
+ "--config",
+ str(path),
+ "--training-type",
+ "full",
+ "--format-type",
+ "chatml",
+ "--gradient-checkpointing",
+ "none",
+ "--num-epochs",
+ "5",
+ )
+
+ assert result.exit_code == 0, result.output
+ assert "training_type: full" in result.output
+ assert "format_type: chatml" in result.output
+ assert "gradient_checkpointing: none" in result.output
+ assert "num_epochs: 5" in result.output
+
+
+def test_apply_overrides_raises_config_error_and_names_the_flag():
+ with pytest.raises(ConfigError) as excinfo:
+ Config().apply_overrides(training_type = "lroa")
+
+ message = str(excinfo.value)
+ assert "--training-type" in message
+ assert "'lora' or 'full'" in message
+
+
+ ("flag", "value", "resolved"),
+ [
+ ("--training-type", "LoRA", "training_type: lora"),
+ ("--format-type", "ChatML", "format_type: chatml"),
+ ("--format-type", "raw", "format_type: raw"),
+ ("--gradient-checkpointing", "yes", "gradient_checkpointing: 'true'"),
+ ("--gradient-checkpointing", "false", "gradient_checkpointing: none"),
+ ("--gradient-checkpointing", "off", "gradient_checkpointing: none"),
+ ("--gradient-checkpointing", "", "gradient_checkpointing: unsloth"),
+ ],
+)
+def test_spellings_the_trainer_already_accepted_still_work(flag, value, resolved):
+ result = _dry_run(flag, value)
+
+ assert result.exit_code == 0, result.output
+ assert resolved in result.output
+
+
+def test_a_yaml_boolean_gradient_checkpointing_is_accepted(tmp_path):
+ path = tmp_path / "config.yaml"
+ path.write_text("training:\n gradient_checkpointing: false\n", encoding = "utf-8")
+
+ result = _dry_run("--config", str(path))
+
+ assert result.exit_code == 0, result.output
+ assert "gradient_checkpointing: none" in result.output