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: harden the codec-audio eval config added in #10259 (#10477)
Daniel Han20d34514b4d3
diff --git a/studio/backend/core/training/eval_dataset.py b/studio/backend/core/training/eval_dataset.pyindex 520b4a8a036..6cf8efad6d1 100644--- a/studio/backend/core/training/eval_dataset.py+++ b/studio/backend/core/training/eval_dataset.py@@ -18,7 +18,8 @@ def evaluation_enabled(value: Any) -> bool:return Falsetry:interval = float(value)- except (TypeError, ValueError):+ except (TypeError, ValueError, OverflowError):+ # OverflowError, not ValueError: float() refuses a JSON int too large to represent.return Falsereturn math.isfinite(interval) and interval > 0diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex cb771824443..b8f8468260f 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -56,6 +56,7 @@ import timefrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Callablefrom datasets import Dataset+from core.training.eval_dataset import evaluation_enabledfrom utils.datasets.audio_decode import ensure_audio_decodingfrom utils.datasets.cache_safe import load_dataset_cache_safe as load_datasetfrom utils.hf_dataset_options import hf_dataset_split_instruction_names@@ -2366,9 +2367,17 @@ class UnslothTrainer:"""Preprocess eval data, warning and dropping it on failure."""if eval_dataset is None:return None+ if self.should_stop:+ # A stopped train pass still returns partial rows, so eval would reload a codec model.+ logger.info("Stopped before eval preprocessing\n")+ return Nonetry:return preprocess(eval_dataset, custom_format_mapping)except Exception as e:+ if self.should_stop:+ # A stop reads as "no valid examples": the cancel, not a bad eval file.+ logger.info("Stopped during eval preprocessing\n")+ return Noneself._record_warning("The eval dataset could not be prepared for this audio model, so this run has "f"no evaluation: {e}"@@ -2401,16 +2410,25 @@ class UnslothTrainer:eval_steps = training_args.get("eval_steps", 0.00)if eval_dataset is None:return {}, None- if not eval_steps or eval_steps <= 0:+ # evaluation_enabled rejects bools and non-finite values, which `eval_steps <= 0` does not:+ # True means "every step", inf raises inside TrainingArguments, NaN never fires.+ if not evaluation_enabled(eval_steps):logger.info(f"⚠️ Eval dataset provided but eval_steps={eval_steps} (disabled)\n")return {}, Nonerows = len(eval_dataset) if hasattr(eval_dataset, "__len__") else "?"+ if rows == 0:+ # An empty dataloader yields no eval_loss, so the run would report none.+ self._record_warning(+ "The eval dataset is empty after preprocessing, so this run has no evaluation."+ )+ return {}, Nonelogger.info(f"✅ Evaluation enabled: eval_steps={eval_steps}, eval rows={rows}\n")return {"eval_strategy": "steps",- "eval_steps": eval_steps,+ # float(): a numeric string passes the gate but TrainingArguments needs a number.+ "eval_steps": float(eval_steps),# Avoid HF's default of 8, which can OOM audio runs.- "per_device_eval_batch_size": training_args.get("batch_size", 2),+ "per_device_eval_batch_size": training_args.get("batch_size") or 2,}, eval_datasetdef _preprocess_whisper_dataset(@@ -2632,7 +2650,8 @@ class UnslothTrainer:eval_dataset = Nonedataset_attestation_source = Nonehas_separate_eval_source = False- eval_enabled = eval_steps is not None and eval_steps > 0+ # Not `eval_steps > 0`: inf and NaN pass that and codec-encode a split later discarded.+ eval_enabled = evaluation_enabled(eval_steps)raw_text_mode = is_cpt or format_type == "raw"dataset_loaded_from_cache = False@@ -3109,7 +3128,8 @@ class UnslothTrainer:elif self._audio_type == "whisper":train_data, eval_data = self._preprocess_whisper_dataset(dataset,- eval_split = eval_split,+ # Whisper's 6% carve-out keys off eval_split, not the cadence, so gate it here.+ eval_split = eval_split if eval_enabled else None,custom_format_mapping = custom_format_mapping,eval_dataset = eval_dataset,)@@ -3861,10 +3881,16 @@ class UnslothTrainer:from utils.datasets import DataCollatorSpeechSeq2SeqWithPaddingeval_dataset = training_args.get("eval_dataset", None)+ eval_steps_val = training_args.get("eval_steps", 5)extra = {"remove_unused_columns": False, "label_names": ["labels"]}- if eval_dataset:+ if eval_dataset and not evaluation_enabled(eval_steps_val):+ # The carve-out keys off eval_split, not the cadence: only this gate stops inf.+ logger.info(+ f"⚠️ Eval dataset provided but eval_steps={eval_steps_val} (disabled)\n"+ )+ elif eval_dataset:extra["eval_strategy"] = "steps"- extra["eval_steps"] = training_args.get("eval_steps", 5)+ extra["eval_steps"] = float(eval_steps_val)# HF's default of 8 can OOM audio runs, as the codec branches already note.extra["per_device_eval_batch_size"] = training_args.get("batch_size") or 2@@ -4094,24 +4120,31 @@ class UnslothTrainer:eval_dataset = training_args.get("eval_dataset", None)eval_steps_val = training_args.get("eval_steps", 0.00)if eval_dataset is not None:- if eval_steps_val > 0:+ eval_rows = len(eval_dataset) if hasattr(eval_dataset, "__len__") else None+ # Same gate as _audio_eval_config: BiCodec and DAC land here, not an audio branch.+ if not evaluation_enabled(eval_steps_val):+ logger.info(+ f"⚠️ Eval dataset provided but eval_steps={eval_steps_val} (disabled)\n"+ )+ logger.info("To enable evaluation, set eval_steps > 0.0\n")+ elif eval_rows == 0:+ self._record_warning(+ "The eval dataset is empty after preprocessing, so this run has no "+ "evaluation."+ )+ else:config_args["eval_strategy"] = "steps"- config_args["eval_steps"] = eval_steps_val+ config_args["eval_steps"] = float(eval_steps_val)config_args["per_device_eval_batch_size"] = config_args["per_device_train_batch_size"]logger.info(f"✅ Evaluation enabled: eval_steps={eval_steps_val} (fraction of total steps)\n")- if hasattr(eval_dataset, "__len__"):- logger.info(f"Eval dataset: {len(eval_dataset)} rows\n")- else:+ if eval_rows is None:logger.info("Eval dataset is streaming / length unknown\n")- else:- logger.info(- f"⚠️ Eval dataset provided but eval_steps={eval_steps_val} (disabled)\n"- )- logger.info("To enable evaluation, set eval_steps > 0.0\n")+ else:+ logger.info(f"Eval dataset: {eval_rows} rows\n")else:logger.info("No eval dataset — evaluation disabled\n")diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.pyindex 24e6d4e939b..77d3663ab4b 100644--- a/studio/backend/core/training/training.py+++ b/studio/backend/core/training/training.py@@ -36,6 +36,7 @@ from utils.native_path_leases import (run_without_native_path_secret,)from utils.paths import is_local_path, outputs_root+from utils.training_runs import drop_non_finitefrom utils.utils import canonical_model_repo_idlogger = get_logger(__name__)@@ -304,7 +305,7 @@ def _sanitize_db_config(config: dict[str, Any]) -> dict[str, Any]:"prefix": s3_config.get("prefix"),"use_iam_role": bool(s3_config.get("use_iam_role")),}- return db_config+ return drop_non_finite(db_config)_MODEL_SNAPSHOT_METADATA = ("config.json", "adapter_config.json")diff --git a/studio/backend/models/training.py b/studio/backend/models/training.pyindex b5a9e6ca670..ed66ce00afb 100644--- a/studio/backend/models/training.py+++ b/studio/backend/models/training.py@@ -5,6 +5,7 @@Pydantic schemas for Training API"""+import mathimport refrom pathlib import Path, PureWindowsPathfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator@@ -206,6 +207,24 @@ class TrainingStartRequest(BaseModel):def _normalize_project_name(cls, value: Optional[str]) -> Optional[str]:return normalize_project_name(value)+ @field_validator("eval_steps", mode = "before")+ @classmethod+ def _normalize_eval_steps(cls, value: Any) -> Any:+ # float is not strict, so `"eval_steps": true` would arrive as 1.0, a cadence of every step.+ if isinstance(value, bool):+ raise ValueError("eval_steps must be a number, not a boolean")+ # `1e309` is a plain JSON number that coerces to inf, which every gate reads as disabled.+ # Store it as that, so config_json never gets an `Infinity` literal Starlette then 500s on.+ try:+ if not math.isfinite(float(value)):+ return 0.0+ except OverflowError:+ # float() refuses a JSON int too large to represent: same unusable cadence as inf.+ return 0.0+ except (TypeError, ValueError):+ pass+ return value+# pydantic runs all mode="after" validators in definition order and _check_steps_or_epochs is lower# in this class, so keep these checks order-independent.@model_validator(mode = "after")diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex cc1ee228bc9..423d0bc1cd2 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -38,6 +38,7 @@ if str(backend_path) not in sys.path:try:from core.training import get_training_backendfrom core.training.diffusion_clip_formats import CLIP_EXTS as _CLIP_EXTS+ from core.training.eval_dataset import evaluation_enabledfrom core.training.training import (TrainingStartCancellationCapacityError,TrainingStatusIdentitySnapshot,@@ -59,6 +60,7 @@ except ImportError:sys.path.insert(0, str(parent_backend))from core.training import get_training_backendfrom core.training.diffusion_clip_formats import CLIP_EXTS as _CLIP_EXTS+ from core.training.eval_dataset import evaluation_enabledfrom core.training.training import (TrainingStartCancellationCapacityError,TrainingStatusIdentitySnapshot,@@ -1332,7 +1334,8 @@ async def start_training(request.local_datasets = _validate_local_dataset_paths(request.local_datasets, "Local dataset")- if request.local_eval_datasets and request.eval_steps > 0:+ # Not `eval_steps > 0`: inf passes that but reads as disabled everywhere in the trainer.+ if request.local_eval_datasets and evaluation_enabled(request.eval_steps):request.local_eval_datasets = _validate_local_dataset_paths(request.local_eval_datasets, "Local eval dataset")@@ -1374,7 +1377,7 @@ async def start_training(status_code = 422,detail = "dataset_streaming is not supported with train_on_completions yet.",)- if request.eval_steps > 0:+ if evaluation_enabled(request.eval_steps):train_split = request.train_split or "train"if not request.eval_split or request.eval_split == train_split:raise HTTPException(diff --git a/studio/backend/routes/training_history.py b/studio/backend/routes/training_history.pyindex dc5767ce99e..acb1adbef11 100644--- a/studio/backend/routes/training_history.py+++ b/studio/backend/routes/training_history.py@@ -17,6 +17,7 @@ from loggers import get_loggerfrom auth.authentication import authenticated_without_credential, get_current_subjectfrom core.training.resume import artifacts_present, can_resume_run+from utils.training_runs import drop_non_finitefrom models import (TrainingRunDeleteResponse,TrainingRunDetailResponse,@@ -310,7 +311,8 @@ async def get_training_run_detail(raise HTTPException(status_code = 404, detail = f"Run {run_id} not found")try:- config = json.loads(run.get("config_json", "{}"))+ # An older install may have stored `Infinity` / `NaN`, which Starlette refuses to render.+ config = drop_non_finite(json.loads(run.get("config_json", "{}")))except (json.JSONDecodeError, TypeError):logger.debug("Failed to parse config_json for run %s", run_id)config = {}diff --git a/studio/backend/tests/test_audio_eval_dataset.py b/studio/backend/tests/test_audio_eval_dataset.pyindex afc0624beaa..1f16bcbb166 100644--- a/studio/backend/tests/test_audio_eval_dataset.py+++ b/studio/backend/tests/test_audio_eval_dataset.py@@ -148,3 +148,217 @@ def test_eval_steps_zero_disables_evaluation(audio_trainer):def test_no_eval_dataset_disables_evaluation(audio_trainer):args, eval_dataset = audio_trainer._audio_eval_config({"eval_dataset": None, "eval_steps": 0.1})assert (args, eval_dataset) == ({}, None)++[email protected]("eval_steps", [True, float("inf"), float("nan"), "abc"])+def test_hostile_eval_steps_disable_evaluation(audio_trainer, eval_steps):+ """`eval_steps <= 0` lets these through: True is every step, inf raises, NaN never fires."""+ args, eval_dataset = audio_trainer._audio_eval_config(+ {"eval_dataset": ["a", "b"], "eval_steps": eval_steps, "batch_size": 2}+ )+ assert (args, eval_dataset) == ({}, None)+++def test_audio_eval_config_agrees_with_the_shared_validator(audio_trainer):+ from core.training.eval_dataset import evaluation_enabled+ for value in (0.1, 0.25, 1, 2, 0, 0.0, -1, None, True, False, float("inf"), float("nan")):+ _args, eval_dataset = audio_trainer._audio_eval_config(+ {"eval_dataset": ["a"], "eval_steps": value, "batch_size": 2}+ )+ assert (eval_dataset is not None) == evaluation_enabled(value), value+++def test_empty_eval_split_disables_evaluation_with_a_warning(audio_trainer):+ args, eval_dataset = audio_trainer._audio_eval_config(+ {"eval_dataset": [], "eval_steps": 0.1, "batch_size": 2}+ )+ assert (args, eval_dataset) == ({}, None)+ assert any("empty" in w for w in audio_trainer.training_progress.warnings)+++def test_missing_batch_size_falls_back_instead_of_passing_none(audio_trainer):+ args, _ = audio_trainer._audio_eval_config(+ {"eval_dataset": ["a"], "eval_steps": 0.1, "batch_size": None}+ )+ assert args["per_device_eval_batch_size"] == 2+++def test_a_stop_during_eval_preprocessing_is_not_reported_as_a_bad_eval_file(audio_trainer):+ """A stop is reported as "no valid examples"; that is the cancel, not the user's upload."""+ audio_trainer.should_stop = True++ def stopped(dataset, custom_format_mapping = None):+ raise ValueError("No valid examples after CSM preprocessing (skipped 4)")++ assert audio_trainer._preprocess_audio_eval_split(object(), stopped, None) is None+ assert not audio_trainer.training_progress.warnings+++def test_a_real_failure_still_warns_when_not_stopping(audio_trainer):+ def explode(dataset, custom_format_mapping = None):+ raise ValueError("no audio column found in dataset")++ assert audio_trainer._preprocess_audio_eval_split(object(), explode, None) is None+ assert any("no evaluation" in w for w in audio_trainer.training_progress.warnings)+++def test_numeric_string_eval_steps_is_normalised(audio_trainer):+ """A numeric string is a valid cadence, but TrainingArguments compares it against an int."""+ args, eval_dataset = audio_trainer._audio_eval_config(+ {"eval_dataset": ["a"], "eval_steps": "0.1", "batch_size": 2}+ )+ assert eval_dataset is not None+ assert isinstance(args["eval_steps"], float) and args["eval_steps"] == 0.1+++def test_a_length_less_eval_split_still_enables_evaluation(audio_trainer):+ """A streaming split has no row count and must not be mistaken for an empty one."""++ class _NoLen:+ pass++ args, eval_dataset = audio_trainer._audio_eval_config(+ {"eval_dataset": _NoLen(), "eval_steps": 0.1, "batch_size": 2}+ )+ assert eval_dataset is not None+ assert args["eval_strategy"] == "steps"++[email protected]("batch_size", [1, 2, 8])+def test_explicit_batch_sizes_are_preserved(audio_trainer, batch_size):+ args, _ = audio_trainer._audio_eval_config(+ {"eval_dataset": ["a"], "eval_steps": 0.1, "batch_size": batch_size}+ )+ assert args["per_device_eval_batch_size"] == batch_size++[email protected]("eval_steps,expected", [(0.1, 0.1), (0.25, 0.25), (1, 1), (2, 2)])+def test_transformers_accepts_the_produced_config(audio_trainer, tmp_path, eval_steps, expected):+ """Normalising eval_steps to float must not change the cadence transformers ends up with."""+ transformers = pytest.importorskip("transformers")++ training_args = {+ "eval_dataset": ["a", "b"],+ "eval_steps": eval_steps,+ "batch_size": 2,+ "max_steps": 8,+ "optim": "adamw_torch",+ }+ eval_args, eval_dataset = audio_trainer._audio_eval_config(training_args)+ assert eval_dataset is not None+ config = audio_trainer._build_audio_training_args(+ training_args, str(tmp_path), extra_args = {"remove_unused_columns": False, **eval_args}+ )+ config.update(bf16 = False, fp16 = False, use_cpu = True, report_to = [])+ args = transformers.TrainingArguments(**config)+ assert args.eval_strategy == "steps"+ assert args.eval_steps == expected+ assert args.per_device_eval_batch_size == 2+++def test_a_stop_skips_the_eval_preprocessor_entirely(audio_trainer):+ """A stopped train pass returns partial rows, so eval would reload a codec model to abort."""+ audio_trainer.should_stop = True+ calls = []++ def preprocess(dataset, custom_format_mapping = None):+ calls.append(dataset)+ return dataset++ assert audio_trainer._preprocess_audio_eval_split(object(), preprocess, None) is None+ assert calls == [], "the codec preprocessor ran after the run was stopped"+ assert not audio_trainer.training_progress.warnings++[email protected]("eval_steps", [float("inf"), float("nan"), 0, -1])[email protected]("audio_type", CODEC_TYPES)+def test_an_invalid_cadence_never_preprocesses_the_eval_split(+ audio_trainer, tmp_path, monkeypatch, audio_type, eval_steps+):+ """Gating on `eval_steps > 0` let inf and NaN codec-encode a split _audio_eval_config drops."""+ audio_trainer._audio_type = audio_type+ monkeypatch.setattr(tmod, "ensure_audio_decoding", lambda: True)+ seen = []+ monkeypatch.setattr(+ audio_trainer,+ f"_preprocess_{audio_type}_dataset",+ lambda ds, m = None: (seen.append(len(ds)), ds)[1],+ raising = True,+ )++ _train, evaluation = audio_trainer.load_and_format_dataset(+ None,+ local_datasets = [_rows(tmp_path / "train.jsonl", "train")],+ local_eval_datasets = [_rows(tmp_path / "eval.jsonl", "eval")],+ eval_steps = eval_steps,+ )++ assert evaluation is None+ assert len(seen) == 1, f"eval_steps={eval_steps} still preprocessed the eval split"+++ "eval_steps,expect_enabled",+ [(0.25, True), (2, True), (float("inf"), False), (float("nan"), False), (0, False)],+)+def test_the_generic_sft_path_uses_the_same_cadence_gate(+ audio_trainer, tmp_path, monkeypatch, eval_steps, expect_enabled+):+ """BiCodec and DAC fall through here, so this gate must match the one in _audio_eval_config."""+ captured = {}++ class _FakeSFTConfig:+ def __init__(self, **kwargs):+ captured.update(kwargs)++ class _FakeSFTTrainer:+ def __init__(self, **kwargs):+ captured["trainer_kwargs"] = kwargs++ def add_callback(self, cb):+ pass++ def train(self, **kwargs):+ pass++ monkeypatch.setattr(tmod, "SFTConfig", _FakeSFTConfig, raising = False)+ monkeypatch.setattr(tmod, "SFTTrainer", _FakeSFTTrainer, raising = False)+ monkeypatch.setattr(tmod, "resolve_output_dir", lambda p: tmp_path, raising = True)+ monkeypatch.setattr(tmod, "ensure_dir", lambda p: p, raising = True)+ monkeypatch.setattr(tmod, "_drop_hf_stdout_callbacks", lambda trainer: None, raising = True)+ monkeypatch.setattr(+ tmod.UnslothTrainer, "_finalize_training", lambda self, *a, **k: None, raising = True+ )+ monkeypatch.setattr(+ tmod.UnslothTrainer, "_preflight_first_batch", lambda self: None, raising = True+ )++ audio_trainer._audio_type = "bicodec"+ audio_trainer.model = object()+ audio_trainer.tokenizer = object()+ audio_trainer.model_name = "unsloth/spark-tts"++ rows = [{"text": "a"}, {"text": "b"}]+ try:+ audio_trainer._train_worker(+ {"dataset": rows, "final_format": "audio_bicodec"},+ eval_dataset = rows,+ eval_steps = eval_steps,+ batch_size = 2,+ gradient_accumulation_steps = 1,+ max_steps = 8,+ warmup_steps = 0,+ output_dir = str(tmp_path),+ )+ except Exception:+ # The generic path needs a real model; the eval decision happens before that, so only+ # the captured config matters.+ pass++ if expect_enabled:+ assert captured.get("eval_strategy") == "steps", f"eval_steps={eval_steps} was not enabled"+ else:+ assert captured, "the config was never built, so this asserts nothing"+ assert (+ "eval_strategy" not in captured+ ), f"eval_steps={eval_steps} reached TrainingArguments as a cadence"diff --git a/studio/backend/tests/test_training_cached_start.py b/studio/backend/tests/test_training_cached_start.pyindex 7b1af0d2e0c..4b4da5b201d 100644--- a/studio/backend/tests/test_training_cached_start.py+++ b/studio/backend/tests/test_training_cached_start.py@@ -3,6 +3,7 @@import asyncioimport importlib.util+import contextlibimport jsonimport osimport sys@@ -13,6 +14,7 @@ from unittest.mock import Mock, call, patchimport pytestfrom fastapi import HTTPException+from fastapi.responses import JSONResponsefrom pydantic import ValidationErrorfrom hub.utils import hf_cache_state@@ -1446,7 +1448,7 @@ def test_reset_route_without_body_stays_supported():route = _load_route_module("training_route_unscoped_reset")calls: list[str | None] = []backend = SimpleNamespace(- reset_training_state = lambda expected_job_id = None: (calls.append(expected_job_id) or "ok")+ reset_training_state = lambda expected_job_id = None: calls.append(expected_job_id) or "ok")with (@@ -2336,8 +2338,9 @@ def test_worker_security_scans_exact_model_load_target(offline):),patch("utils.security.evaluate_file_security",- side_effect = lambda target, **kwargs: scanned.append((target, kwargs["local_only_load"]))- or decision,+ side_effect = lambda target, **kwargs: (+ scanned.append((target, kwargs["local_only_load"])) or decision+ ),),patch("utils.utils.hf_env_offline", return_value = offline),):@@ -2370,8 +2373,9 @@ def test_worker_remote_retry_security_scan_is_not_local_only():patch("utils.security.security_load_subdirs", return_value = ()),patch("utils.security.evaluate_file_security",- side_effect = lambda target, **kwargs: scanned.append((target, kwargs["local_only_load"]))- or decision,+ side_effect = lambda target, **kwargs: (+ scanned.append((target, kwargs["local_only_load"])) or decision+ ),),patch("utils.utils.hf_env_offline", return_value = False),):@@ -2403,12 +2407,13 @@ def test_worker_security_scopes_pinned_target_before_registry_fallback():),patch("utils.security.security_load_subdirs",- side_effect = lambda target, _token: (("LLM",) if target == snapshot else ("registry",)),+ side_effect = lambda target, _token: ("LLM",) if target == snapshot else ("registry",),),patch("utils.security.evaluate_file_security",- side_effect = lambda target, **kwargs: scanned.append((target, kwargs["load_subdirs"]))- or decision,+ side_effect = lambda target, **kwargs: (+ scanned.append((target, kwargs["load_subdirs"])) or decision+ ),),patch("utils.utils.hf_env_offline", return_value = False),):@@ -3296,3 +3301,140 @@ def test_cache_local_paths_blank_normalizes_to_none():request = _request(model_local_path = " ", dataset_local_path = "")assert request.model_local_path is Noneassert request.dataset_local_path is None++[email protected]("value", [True, False])+def test_boolean_eval_steps_is_rejected_by_the_request_model(value):+ """`float` is not strict, so `"eval_steps": true` arrived as 1.0 before any trainer check."""+ with pytest.raises(ValidationError):+ _request(eval_steps = value)++[email protected]("value", [0, 0.0, 0.25, 1, 2, "0.1"])+def test_numeric_eval_steps_still_accepted(value):+ assert _request(eval_steps = value).eval_steps == float(value)+++def test_a_json_number_too_large_for_a_float_arrives_as_infinity():+ """Pins the premise: `1e309` is a plain JSON number, not a non-standard `Infinity` literal,+ and pydantic's non-strict `float` coerces it to inf."""+ from pydantic import BaseModel++ class _Bare(BaseModel):+ eval_steps: float = 0.0++ assert json.loads("1e309") == float("inf")+ assert _Bare.model_validate_json('{"eval_steps": 1e309}').eval_steps == float("inf")++[email protected]("cadence", [float("inf"), float("nan")])+def test_a_disabled_cadence_does_not_validate_the_local_eval_paths(cadence):+ """A non-finite cadence is evaluation off, so the route must not 400 over unused paths."""+ route = _load_route_module("training_route_disabled_cadence_skips_eval_paths")+ request = _request(eval_steps = cadence, local_eval_datasets = [""])++ labels: list[str] = []++ with patch.object(+ route,+ "_validate_local_dataset_paths",+ side_effect = lambda paths, label: labels.append(label) or paths,+ ):+ with contextlib.suppress(Exception):+ _start(route, request)++ assert labels == [], f"eval paths were validated for eval_steps={cadence}"+++def test_a_disabled_cadence_does_not_demand_a_separate_streaming_eval_split():+ """`eval_steps > 0` let inf through, rejecting a streaming run over a split it did not need."""+ route = _load_route_module("training_route_disabled_cadence_streaming_eval_split")+ request = _request(+ dataset_streaming = True, max_steps = 10, eval_steps = float("inf"), eval_split = None+ )++ detail = None+ try:+ _start(route, request)+ except HTTPException as exc:+ detail = exc.detail++ assert detail != "dataset_streaming with evaluation requires a separate eval_split."+++def test_a_usable_cadence_still_demands_a_separate_streaming_eval_split():+ route = _load_route_module("training_route_usable_cadence_streaming_eval_split")+ request = _request(dataset_streaming = True, max_steps = 10, eval_steps = 0.25, eval_split = None)++ with pytest.raises(HTTPException) as exc_info:+ _start(route, request)++ assert (+ exc_info.value.detail == "dataset_streaming with evaluation requires a separate eval_split."+ )++[email protected]("literal", ["1e309", "-1e309", "Infinity", "NaN"])+def test_a_non_finite_cadence_is_stored_as_disabled(literal):+ """json writes inf/NaN as the non-standard `Infinity` / `NaN` literals but Starlette renders+ with `allow_nan = False`, so a config_json carrying one 500s the run's detail view."""+ request = TrainingStartRequest.model_validate_json(+ '{"model_name": "unsloth/test", "training_type": "LoRA/QLoRA", '+ '"format_type": "alpaca", "hf_dataset": "org/dataset", '+ f'"eval_steps": {literal}}}'+ )+ assert request.eval_steps == 0.0+++def test_the_persisted_config_never_carries_a_non_finite_value():+ from core.training.training import _sanitize_db_config++ sanitized = _sanitize_db_config(+ {+ "eval_steps": float("inf"),+ "learning_rate": float("nan"),+ "nested": {"a": [float("-inf"), 1.0]},+ "keep": 0.25,+ "flag": True,+ }+ )++ assert sanitized["eval_steps"] is None+ assert sanitized["learning_rate"] is None+ assert sanitized["nested"] == {"a": [None, 1.0]}+ assert sanitized["keep"] == 0.25+ assert sanitized["flag"] is True+ JSONResponse(content = sanitized).render(sanitized)+++def test_a_run_stored_by_an_older_install_still_renders():+ """An older install can already hold `Infinity` in config_json; the request model cannot."""+ from utils.training_runs import drop_non_finite++ stored = json.dumps({"eval_steps": float("inf"), "model_name": "unsloth/test"})+ config = drop_non_finite(json.loads(stored))++ assert config == {"eval_steps": None, "model_name": "unsloth/test"}+ JSONResponse(content = config).render(config)+++def test_a_json_integer_too_large_for_a_float_is_disabled_not_a_500():+ """`float()` on a huge JSON int raises OverflowError, which is not a ValueError, so it+ escaped the validator and 500d the start endpoint."""+ huge = "1" + "0" * 310+ assert isinstance(json.loads(huge), int)+ with pytest.raises(OverflowError):+ float(json.loads(huge))++ request = TrainingStartRequest.model_validate_json(+ '{"model_name": "unsloth/test", "training_type": "LoRA/QLoRA", '+ '"format_type": "alpaca", "hf_dataset": "org/dataset", '+ f'"eval_steps": {huge}}}'+ )+ assert request.eval_steps == 0.0+++def test_the_shared_cadence_gate_survives_an_unrepresentable_integer():+ """`evaluation_enabled` caught only TypeError and ValueError, so this took down every caller."""+ from core.training.eval_dataset import evaluation_enabled+ assert evaluation_enabled(int("1" + "0" * 310)) is Falsediff --git a/studio/backend/tests/test_whisper_audio_vlm_eval_dataset.py b/studio/backend/tests/test_whisper_audio_vlm_eval_dataset.pyindex 274e1245e2d..fbd9233e965 100644--- a/studio/backend/tests/test_whisper_audio_vlm_eval_dataset.py+++ b/studio/backend/tests/test_whisper_audio_vlm_eval_dataset.py@@ -421,7 +421,14 @@ def test_audio_vlm_matching_eval_split_leaves_the_column_alone(assert audio_trainer._audio_vlm_audio_col == "audio"-def _drive_whisper_branch(audio_trainer, tmp_path, monkeypatch, *, eval_rows):+def _drive_whisper_branch(+ audio_trainer,+ tmp_path,+ monkeypatch,+ *,+ eval_rows,+ eval_steps = 0.25,+):"""Drive the real Whisper _train_worker branch; only train() is stubbed, so the assertedargs and eval dataset are genuine transformers objects."""transformers = pytest.importorskip("transformers")@@ -463,7 +470,7 @@ def _drive_whisper_branch(audio_trainer, tmp_path, monkeypatch, *, eval_rows):audio_trainer._train_worker([{"input_features": [0.0], "labels": [1]}] * 4,eval_dataset = eval_rows,- eval_steps = 0.25,+ eval_steps = eval_steps,batch_size = 2,gradient_accumulation_steps = 1,max_steps = 8,@@ -507,6 +514,74 @@ def test_whisper_trainer_branch_omits_eval_for_an_empty_split(audio_trainer, tmpassert trainer.args.eval_strategy == "no"[email protected]("bad", [float("inf"), float("nan"), True, 0, -1])+def test_whisper_trainer_branch_refuses_an_unusable_cadence(+ audio_trainer, tmp_path, monkeypatch, bad+):+ """inf raised inside Seq2SeqTrainingArguments, NaN and 0 never ran, True ran every step."""+ trainer = _drive_whisper_branch(+ audio_trainer,+ tmp_path,+ monkeypatch,+ eval_rows = [{"input_features": [0.0], "labels": [2]}] * 2,+ eval_steps = bad,+ )++ assert trainer is not None, f"eval_steps={bad!r} took the Whisper branch down"+ assert trainer.args.eval_strategy == "no"+++def test_whisper_trainer_branch_normalises_a_numeric_string_cadence(+ audio_trainer, tmp_path, monkeypatch+):+ """A numeric string is usable, but TrainingArguments compares eval_steps against an int."""+ trainer = _drive_whisper_branch(+ audio_trainer,+ tmp_path,+ monkeypatch,+ eval_rows = [{"input_features": [0.0], "labels": [2]}] * 2,+ eval_steps = "0.1",+ )++ assert trainer is not None+ assert trainer.args.eval_strategy == "steps"+ assert trainer.args.eval_steps == 0.1+++def test_whisper_carve_out_is_skipped_when_the_cadence_is_unusable(audio_trainer, monkeypatch):+ """The 6% carve-out keys off eval_split, not the cadence, so it used to feature-extract rows+ for an evaluation the trainer branch then refuses."""+ seen = {}++ def fake(+ dataset,+ eval_split = None,+ custom_format_mapping = None,+ eval_dataset = None,+ ):+ seen["eval_split"] = eval_split+ return ([{"input_features": [0.0], "labels": [1]}], None)++ datasets = pytest.importorskip("datasets")+ audio_trainer._audio_type = "whisper"+ monkeypatch.setattr(audio_trainer, "_preprocess_whisper_dataset", fake, raising = True)+ monkeypatch.setattr(tmod, "ensure_audio_decoding", lambda: True, raising = False)+ monkeypatch.setattr(+ tmod,+ "load_dataset",+ lambda *a, **k: datasets.Dataset.from_dict({"audio": ["a"] * 4, "text": ["x"] * 4}),+ raising = False,+ )++ audio_trainer.load_and_format_dataset(+ "some/dataset", eval_split = "validation", eval_steps = float("inf")+ )+ assert seen["eval_split"] is None++ audio_trainer.load_and_format_dataset("some/dataset", eval_split = "validation", eval_steps = 0.25)+ assert seen["eval_split"] == "validation"++def test_whisper_eval_split_whose_rows_are_all_skipped_warns(audio_trainer):class _EmptyRows(_FakeAudioDataset):def __getitem__(self, idx):diff --git a/studio/backend/utils/training_runs.py b/studio/backend/utils/training_runs.pyindex 1d39c58a1f7..f236ef36fa7 100644--- a/studio/backend/utils/training_runs.py+++ b/studio/backend/utils/training_runs.py@@ -5,6 +5,7 @@from __future__ import annotations+import mathimport reimport timefrom typing import Any, Optional@@ -151,3 +152,20 @@ def extract_project_name(config: Any) -> Optional[str]:if not isinstance(config, dict):return Nonereturn normalize_project_name(config.get("project_name"))+++def drop_non_finite(value: Any) -> Any:+ """Replace inf and NaN with None, recursively.++ json writes them as the non-standard ``Infinity`` / ``NaN`` literals, but Starlette renders+ with ``allow_nan = False``, so a stored config carrying one 500s the view that returns it.+ """+ if isinstance(value, bool):+ return value+ if isinstance(value, float) and not math.isfinite(value):+ return None+ if isinstance(value, dict):+ return {k: drop_non_finite(v) for k, v in value.items()}+ if isinstance(value, (list, tuple)):+ return [drop_non_finite(v) for v in value]+ return value