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
Studio: restore the MLX gradient-norm chart by matching CUDA's clipping default (#7917)
Long Yixing6b7997325018
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.pyindex 1e41a032224..05717d62417 100644--- a/studio/backend/core/training/training.py+++ b/studio/backend/core/training/training.py@@ -112,15 +112,15 @@ def _coerce_optional_bool(value, default: bool) -> bool:def _coerce_optional_nonneg_float(name: str, value):- """Reject negatives; HTTP `ge=0` doesn't cover raw `**kwargs` callers."""+ """Reject negatives and non-finite; `ge=0` misses raw callers, and inf never binds."""if value is None:return Nonetry:coerced = float(value)except (TypeError, ValueError):raise ValueError(f"Unsloth: {name}={value!r} must be a non-negative float or None.")- if coerced < 0:- raise ValueError(f"Unsloth: {name}={coerced} must be >= 0 (use 0 or None to disable).")+ if coerced < 0 or not math.isfinite(coerced):+ raise ValueError(f"Unsloth: {name}={coerced} must be finite and >= 0.")return coerced@@ -177,7 +177,9 @@ def _build_training_worker_config(values: dict[str, Any]) -> dict[str, Any]:"max_steps": values.get("max_steps", 0),"save_steps": values.get("save_steps", 0),"weight_decay": values.get("weight_decay", 0.001),- "max_grad_norm": values.get("max_grad_norm", 0.0),+ "max_grad_norm": _coerce_optional_nonneg_float(+ "max_grad_norm", values.get("max_grad_norm")+ ),"max_grad_value": _coerce_optional_nonneg_float("max_grad_value", values.get("max_grad_value")),diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 6eee954f7b0..89feefca8a8 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -1510,6 +1510,31 @@ def _resolve_mlx_output_dir(config, model_name):return str(resolve_output_dir(output_dir))+def _resolve_mlx_max_grad_norm(value):+ """Global-norm clip threshold for MLX runs; None keeps the trainer's default.++ The worker used to hardcode 0.0 and drop the requested value, so an API caller+ asking for a threshold got none. Unset stays 0.0 so MLX keeps its cheap+ per-parameter clipping: the gradient-norm chart is fed by report_grad_norm+ instead, which measures the same norm without changing what gets clipped.+ """+ if value is None:+ return 0.0+ try:+ value = float(value)+ except (TypeError, ValueError):+ raise ValueError(+ f"Unsloth MLX: max_grad_norm={value!r} must be a non-negative float or None."+ )+ # inf clears a >= 0 check but never binds, so the run would train unclipped.+ if value < 0 or not math.isfinite(value):+ raise ValueError(+ f"Unsloth MLX: max_grad_norm={value} must be a finite value >= 0 "+ "(use 0 to disable global norm clipping)."+ )+ return value++def _run_mlx_training(event_queue, stop_queue, config):"""Self-contained MLX training path for Apple Silicon.@@ -1960,23 +1985,22 @@ def _run_mlx_training(event_queue, stop_queue, config):else:eval_steps_val = int(eval_steps_val)- # Per-element clipping only; trainer owns the None default. Re-validate- # for direct worker callers (training.py normalizes the main path).- max_grad_norm = 0.0+ # Re-validate for direct worker callers; training.py normalizes the main path.+ max_grad_norm = _resolve_mlx_max_grad_norm(config.get("max_grad_norm"))max_grad_value = config.get("max_grad_value")if max_grad_value is not None:max_grad_value = float(max_grad_value)- if max_grad_value < 0:+ if max_grad_value < 0 or not math.isfinite(max_grad_value):raise ValueError(- f"Unsloth MLX: max_grad_value={max_grad_value} must be >= 0 "+ f"Unsloth MLX: max_grad_value={max_grad_value} must be finite and >= 0 ""(0 or None disables elementwise clipping).")max_grad_leaf_norm = config.get("max_grad_leaf_norm")if max_grad_leaf_norm is not None:max_grad_leaf_norm = float(max_grad_leaf_norm)- if max_grad_leaf_norm < 0:+ if max_grad_leaf_norm < 0 or not math.isfinite(max_grad_leaf_norm):raise ValueError(- f"Unsloth MLX: max_grad_leaf_norm={max_grad_leaf_norm} must be >= 0 "+ f"Unsloth MLX: max_grad_leaf_norm={max_grad_leaf_norm} must be finite and >= 0 ""(0 or None disables proportional leaf-norm clipping).")weight_decay = config.get("weight_decay", 0.001)@@ -2021,6 +2045,11 @@ def _run_mlx_training(event_queue, stop_queue, config):mlx_config_kwargs["dataset_order"] = "torch_randperm"if "max_grad_leaf_norm" in _supported_fields:mlx_config_kwargs["max_grad_leaf_norm"] = max_grad_leaf_norm+ if "report_grad_norm" in _supported_fields:+ # Refills the gradient-norm chart. MLX returns a norm for free only under+ # global-norm clipping; asking for it beats switching clip modes, which+ # would alter the loss trajectory and cost VLM runs mx.compile.+ mlx_config_kwargs["report_grad_norm"] = Trueif "append_eos" in _supported_fields:# Unsloth SFT formatting owns rendered examples; raw/CPT text still# needs MLX to append EOS like the CUDA raw-text path.diff --git a/studio/backend/models/training.py b/studio/backend/models/training.pyindex 81624a0c8da..8aa6b2d46ce 100644--- a/studio/backend/models/training.py+++ b/studio/backend/models/training.py@@ -414,14 +414,25 @@ class TrainingStartRequest(BaseModel):max_steps: Optional[int] = Field(None, description = "Maximum training steps")save_steps: int = Field(100, description = "Steps between checkpoints")weight_decay: float = Field(0.001, description = "Weight decay")- max_grad_norm: float = Field(- 0.0,+ # All three clip knobs are finite as well as non-negative: JSON 1e309 (and+ # FastAPI's Infinity literal) floats to inf, which clears ge=0 but never+ # binds, so the run would train unclipped while reporting a threshold.+ max_grad_norm: Optional[float] = Field(+ None,ge = 0,- description = "Global gradient norm clipping threshold. Set 0 to disable.",+ allow_inf_nan = False,+ description = (+ "Global gradient norm clipping threshold. Unset keeps the training "+ "backend's own default; 0 turns global-norm clipping off, which on "+ "MLX leaves per-parameter clipping in force unless max_grad_leaf_norm "+ "is also 0. Honored on MLX; the CUDA path trains with its own fixed "+ "thresholds."+ ),)max_grad_value: Optional[float] = Field(None,ge = 0,+ allow_inf_nan = False,description = ("MLX-only elementwise gradient value clipping threshold. ""If unset, MLX uses its runtime default."@@ -430,6 +441,7 @@ class TrainingStartRequest(BaseModel):max_grad_leaf_norm: Optional[float] = Field(None,ge = 0,+ allow_inf_nan = False,description = ("MLX-only proportional per-parameter gradient norm cap. ""Preserves each tensor's gradient direction without global norm "diff --git a/studio/backend/tests/test_training_raw_support.py b/studio/backend/tests/test_training_raw_support.pyindex 49281605e67..161801881c0 100644--- a/studio/backend/tests/test_training_raw_support.py+++ b/studio/backend/tests/test_training_raw_support.py@@ -160,6 +160,102 @@ class TestTrainingRawSupport(unittest.TestCase):self.assertNotIn("model_random_state", config)self.assertNotIn("lora_random_state", config)+ def test_mlx_max_grad_norm_is_honored_without_changing_the_default(self):+ # The worker used to hardcode 0.0 and drop the request, so an explicit+ # threshold never reached the trainer. Explicit values must pass through,+ # while unset stays 0.0 so the clip mode is unchanged.+ from pydantic import ValidationError++ from core.training.worker import _resolve_mlx_max_grad_norm+ from models.training import TrainingStartRequest++ self.assertEqual(_resolve_mlx_max_grad_norm(None), 0.0)+ self.assertEqual(_resolve_mlx_max_grad_norm(0), 0.0)+ self.assertEqual(_resolve_mlx_max_grad_norm(1.0), 1.0)+ self.assertEqual(_resolve_mlx_max_grad_norm(0.3), 0.3)+ with self.assertRaises(ValueError):+ _resolve_mlx_max_grad_norm(-1)+ with self.assertRaises(ValueError):+ _resolve_mlx_max_grad_norm("nope")+ # inf clears a >= 0 check but never binds, so it would train unclipped.+ with self.assertRaises(ValueError):+ _resolve_mlx_max_grad_norm(float("inf"))++ def request(**overrides):+ return TrainingStartRequest(+ model_name = "unsloth/test",+ training_type = "LoRA/QLoRA",+ format_type = "auto",+ **overrides,+ )++ with self.assertRaises(ValidationError):+ request(max_grad_norm = float("inf"))+ # Unset must survive to the resolver rather than being coerced en route,+ # so "no opinion" stays distinguishable from an explicit 0.+ self.assertIsNone(request().max_grad_norm)+ source = (_BACKEND_ROOT / "core" / "training" / "worker.py").read_text(encoding = "utf-8")+ self.assertIn(+ 'max_grad_norm = _resolve_mlx_max_grad_norm(config.get("max_grad_norm"))',+ source,+ )++ def test_mlx_worker_asks_the_trainer_to_report_the_gradient_norm(self):+ # What refills Studio's Gradient Norm chart on Apple Silicon; see the+ # rationale at the opt-in site in worker.py.+ source = (_BACKEND_ROOT / "core" / "training" / "worker.py").read_text(encoding = "utf-8")+ self.assertIn('if "report_grad_norm" in _supported_fields:', source)+ self.assertIn('mlx_config_kwargs["report_grad_norm"] = True', source)+ # Feature-detected like the other newer fields, so an older unsloth_zoo+ # without the flag keeps working instead of raising on construction.+ gated = source.split("_supported_fields = ")[1]+ self.assertNotIn(+ "report_grad_norm = True,", gated.split("MLXTrainer(")[0].split("dict(")[0]+ )++ def test_start_training_leaves_unset_max_grad_norm_for_worker_default(self):+ # None is what lets the worker apply the trainer's default; coercing it to+ # 0.0 here would make "no opinion" indistinguishable from an explicit 0.+ backend = TrainingBackend()++ class DummyProcess:+ pid = 4321++ def start(self):+ return None++ class DummyThread:+ def start(self):+ return None++ dummy_queue = object()++ with (+ patch(+ "core.training.training.prepare_gpu_selection",+ return_value = ([0], {"selection_mode": "auto"}),+ ),+ patch(+ "core.training.training._CTX.Queue",+ side_effect = [dummy_queue, dummy_queue],+ ),+ patch(+ "core.training.training._CTX.Process", return_value = DummyProcess()+ ) as mock_process,+ patch(+ "core.training.training.threading.Thread",+ return_value = DummyThread(),+ ),+ ):+ backend.start_training(+ job_id = "test-grad-clip-default",+ model_name = "unsloth/test",+ training_type = "LoRA/QLoRA",+ )++ config = mock_process.call_args.kwargs["kwargs"]["config"]+ self.assertIsNone(config["max_grad_norm"])+def test_route_forwards_all_grad_clipping_fields(self):# The HTTP route builds the config dict by hand; a schema field that# is not forwarded here is silently dropped for REST callers.@@ -211,12 +307,10 @@ class TestTrainingRawSupport(unittest.TestCase):)def test_training_backend_normalizes_explicit_none_seed_and_dtypes(self):- # Raw / backend callers can pass `random_seed=None`,- # `cast_norm_output_to_input_dtype=None`, and MLX clip knobs- # as None (or omit them) and must NOT leak the- # `None` past `TrainingBackend.start_training`. Otherwise- # transformers.set_seed(None) raises, PEFT init becomes- # nondeterministic, and the MLX norm-output cast silently flips.+ # `random_seed=None` and `cast_norm_output_to_input_dtype=None` must not+ # leak past `TrainingBackend.start_training`: set_seed(None) raises, PEFT+ # init goes nondeterministic, and the MLX norm-output cast flips. The MLX+ # clip knobs are the exception, where None means "owner picks the default".from core.training.training import (_coerce_seed,_coerce_optional_bool,@@ -245,6 +339,39 @@ class TestTrainingRawSupport(unittest.TestCase):with self.assertRaises(ValueError):_coerce_optional_nonneg_float("max_grad_leaf_norm", -1)+ # inf clears >= 0 but never binds, on all three knobs alike.+ for name in ("max_grad_norm", "max_grad_value", "max_grad_leaf_norm"):+ for bad in (float("inf"), float("-inf"), float("nan")):+ with self.assertRaises(ValueError):+ _coerce_optional_nonneg_float(name, bad)++ def test_mlx_clip_knobs_reject_non_finite_at_every_layer(self):+ # All three layers guard, since raw worker callers reach none above them.+ import math++ from pydantic import ValidationError++ from core.training.worker import _resolve_mlx_max_grad_norm+ from models.training import TrainingStartRequest++ for field in ("max_grad_norm", "max_grad_value", "max_grad_leaf_norm"):+ for bad in (float("inf"), float("nan")):+ with self.assertRaises(ValidationError):+ TrainingStartRequest(+ model_name = "unsloth/test",+ training_type = "LoRA/QLoRA",+ format_type = "auto",+ **{field: bad},+ )++ with self.assertRaises(ValueError):+ _resolve_mlx_max_grad_norm(float("inf"))++ source = (_BACKEND_ROOT / "core" / "training" / "worker.py").read_text(encoding = "utf-8")+ for name in ("max_grad_value", "max_grad_leaf_norm"):+ self.assertIn(f"if {name} < 0 or not math.isfinite({name}):", source)+ self.assertTrue(math.isfinite(_resolve_mlx_max_grad_norm(None)))+def test_mlx_worker_feature_detects_optional_mlx_config_fields(self):# `cast_norm_output_to_input_dtype`, `dataset_order`,# `max_grad_leaf_norm`, and `append_eos` ship in the paireddiff --git a/studio/frontend/src/features/training/api/mappers.ts b/studio/frontend/src/features/training/api/mappers.tsindex 1b90e67f7ff..893f8f82b69 100644--- a/studio/frontend/src/features/training/api/mappers.ts+++ b/studio/frontend/src/features/training/api/mappers.ts@@ -113,7 +113,9 @@ export function buildTrainingStartPayload(save_steps: config.saveSteps,eval_steps: config.evalSteps,weight_decay: config.weightDecay,- max_grad_norm: 0.0,+ // max_grad_norm omitted on purpose: the backend now honors an explicit value,+ // so hardcoding 0 here would pin every UI run to "clipping off" and override+ // that. Guarded by tests/training-start-payload-grad-norm.test.ts.max_grad_value: null,random_seed: config.randomSeed,packing: isEmbedding ? false : config.packing,diff --git a/studio/frontend/src/features/training/types/api.ts b/studio/frontend/src/features/training/types/api.tsindex 31aef4697c1..0f198c057ce 100644--- a/studio/frontend/src/features/training/types/api.ts+++ b/studio/frontend/src/features/training/types/api.ts@@ -40,7 +40,7 @@ export interface TrainingStartRequest {save_steps: number;eval_steps: number;weight_decay: number;- max_grad_norm: number;+ max_grad_norm?: number | null;max_grad_value?: number | null;random_seed: number;packing: boolean;diff --git a/studio/frontend/tests/training-start-payload-grad-norm.test.ts b/studio/frontend/tests/training-start-payload-grad-norm.test.tsnew file mode 100644index 00000000000..7a3df7d8db9--- /dev/null+++ b/studio/frontend/tests/training-start-payload-grad-norm.test.ts@@ -0,0 +1,113 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The mapper used to send max_grad_norm: 0.0 on every run. The backend now honors+// an explicit threshold on MLX instead of discarding it, so that hardcoded 0 would+// override the request for every UI run. Omitting the key is the fix, and nothing+// else catches it if undone: the field is optional in the request type, so+// restoring the literal would typecheck and pass every other suite.++import assert from "node:assert/strict";+import test from "node:test";++import { registerBundlerResolver } from "./helpers/kit.ts";++import type { TrainingConfigState } from "../src/features/training/types/config.ts";++registerBundlerResolver();+const { buildTrainingStartPayload } = await import(+ "../src/features/training/api/mappers.ts"+);++const CONFIG: TrainingConfigState = {+ currentStep: 5,+ modelType: "text",+ selectedModel: "unsloth/gemma-3-270m-it",+ projectName: "grad-norm",+ trainingMethod: "lora",+ hfToken: "",+ datasetSource: "huggingface",+ datasetFormat: "auto",+ dataset: "unsloth/test",+ datasetSubset: null,+ datasetSplit: "train",+ datasetEvalSplit: null,+ datasetStreaming: false,+ datasetManualMapping: {},+ datasetSystemPrompt: "",+ datasetUserTemplate: "",+ datasetAssistantTemplate: "",+ datasetLabelMapping: {},+ datasetAdvisorNotification: null,+ datasetSliceStart: null,+ datasetSliceEnd: null,+ uploadedFile: null,+ uploadedEvalFile: null,+ epochs: 1,+ contextLength: 2048,+ learningRate: 2e-4,+ embeddingLearningRate: null,+ optimizerType: "adamw_8bit",+ lrSchedulerType: "linear",+ loraRank: 16,+ loraAlpha: 16,+ loraDropout: 0,+ loraVariant: "lora",+ batchSize: 2,+ gradientAccumulation: 4,+ weightDecay: 0.001,+ warmupSteps: 5,+ maxSteps: 60,+ saveSteps: 100,+ evalSteps: 0,+ packing: false,+ trainOnCompletions: true,+ gradientCheckpointing: "unsloth",+ randomSeed: 3407,+ enableWandb: false,+ wandbToken: "",+ wandbProject: "",+ enableTensorboard: false,+ tensorboardDir: "",+ logFrequency: 1,+ isCheckingVision: false,+ isVisionModel: false,+ isEmbeddingModel: false,+ isAudioModel: false,+ isLoadingModelDefaults: false,+ modelDefaultsError: null,+ modelDefaultsAppliedFor: null,+ isCheckingDataset: false,+ isDatasetImage: false,+ isDatasetAudio: false,+ trustRemoteCode: false,+ approvedRemoteCodeFingerprint: null,+ finetuneVisionLayers: false,+ finetuneLanguageLayers: true,+ finetuneAttentionModules: true,+ finetuneMLPModules: true,+ targetModules: ["q_proj", "v_proj"],+ maxPositionEmbeddings: null,+ visionImageSize: null,+ s3Config: null,+};++test("the payload leaves max_grad_norm unset so the backend default governs", () => {+ const payload = buildTrainingStartPayload(CONFIG);++ assert.equal(+ Object.hasOwn(payload, "max_grad_norm"),+ false,+ "max_grad_norm must be absent, not null and not 0",+ );+ // An explicit null would serialize and pin the backend to "no global clipping"+ // just as 0.0 did, so check the wire form too.+ assert.equal("max_grad_norm" in JSON.parse(JSON.stringify(payload)), false);+});++test("the sibling clip knobs keep their existing wire contract", () => {+ const payload = buildTrainingStartPayload(CONFIG);++ assert.equal(payload.max_grad_value, null);+ assert.equal(payload.weight_decay, CONFIG.weightDecay);+});