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: stop reporting the run's mean loss as the final step's loss (#8314)
Daniel Han31ba4bcf6bca
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex 9411db146e0..a2d123feb47 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -300,7 +300,22 @@ class UnslothTrainer:):if not logs:return- loss_value = logs.get("loss", logs.get("train_loss", None))+ # HF logs the end-of-run summary as {"train_runtime": ..., "train_loss": ...}+ # with no "loss" key, and `train_loss` is the MEAN loss over the whole run,+ # not a step loss. Falling back to it reported the average as the final+ # step's value: it landed on the chart at the same global_step as the real+ # last step and became `final_loss` on /api/train/runs, disagreeing with the+ # checkpoint. Keep reporting it, as the summary it is.+ loss_value = logs.get("loss")+ is_run_summary = loss_value is None and (+ logs.get("train_loss") is not None or logs.get("train_runtime") is not None+ )+ if is_run_summary:+ logger.info(+ "training finished: mean train_loss=%s over %s steps",+ logs.get("train_loss"),+ state.global_step,+ )current_step = state.global_stepgrad_norm = logs.get("grad_norm", None)@@ -328,6 +343,7 @@ class UnslothTrainer:grad_norm = grad_norm,num_tokens = num_tokens,eval_loss = logs.get("eval_loss", None),+ is_run_summary = is_run_summary,status_message = "",)diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.pyindex 59cb8986ad2..a8bb811e8a5 100644--- a/studio/backend/core/training/training.py+++ b/studio/backend/core/training/training.py@@ -627,6 +627,10 @@ class TrainingProgress:eval_loss: Optional[float] = Nonepeak_memory_gb: Optional[float] = Noneoutput_dir: Optional[str] = None+ # Set on the end-of-run record HF emits after leaving the training loop. It has no+ # step loss, so the progress filter would drop it, and with it the only elapsed+ # time that includes the final evaluation, checkpoint save and best-model reload.+ is_run_summary: bool = Falseclass _MLXTrainerAdapter:@@ -2854,7 +2858,11 @@ class TrainingBackend:step = event.get("step", 0)loss = _safe_losslr = _safe_lr- if step > 0 and loss is not None:+ # Only ever move forward. HF can log more than one record at the same+ # global_step around the end of a run, and each one used to add another+ # point, so a 30-step run charted 33 with the last few stacked on step 30.+ _last_step = self.step_history[-1] if self.step_history else None+ if step > 0 and loss is not None and (_last_step is None or step > _last_step):self.loss_history.append(loss)self.lr_history.append(lr if lr is not None else 0.0)self.step_history.append(step)diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 3c684850257..502e8ba1180 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -4520,7 +4520,22 @@ def _create_trainer_progress_callback(event_queue: Any) -> Callable[[TrainingProdef _on_progress(progress: TrainingProgress) -> None:has_train_loss = progress.step > 0 and progress.loss is not Nonehas_eval_loss = progress.eval_loss is not None- if (progress.step == 0 and progress.total_steps > 0) or has_train_loss or has_eval_loss:+ # The end-of-run summary carries no loss (it is the mean, not a step), but it+ # does carry the elapsed time including the final evaluation, checkpoint save+ # and best-model reload. Without this the run's recorded duration stops at the+ # last step log and under-reports how long the run actually took.+ # A run stopped early never reaches total_steps, so the flag the trainer sets+ # on the summary record is what marks it terminal; the step comparison stays as+ # a fallback for backends that do not set it.+ is_terminal = bool(getattr(progress, "is_run_summary", False)) or (+ progress.total_steps > 0 and progress.step >= progress.total_steps+ )+ if (+ (progress.step == 0 and progress.total_steps > 0)+ or has_train_loss+ or has_eval_loss+ or is_terminal+ ):event_queue.put({"type": "progress",@@ -4579,7 +4594,15 @@ def _create_embedding_progress_callback():if not logs:return- loss_value = logs.get("loss", logs.get("train_loss", None))+ # See the note in trainer.py: "train_loss" in HF's terminal summary record is+ # the run mean, not a step loss, so it must not become the final step.+ loss_value = logs.get("loss")+ if loss_value is None and logs.get("train_loss") is not None:+ print(+ f"Training finished: mean train_loss={logs.get('train_loss')} "+ f"over {state.global_step} steps",+ flush = True,+ )current_step = state.global_stepelapsed = time.time() - training_start_timediff --git a/studio/backend/tests/test_final_loss_not_average.py b/studio/backend/tests/test_final_loss_not_average.pynew file mode 100644index 00000000000..a669664eaba--- /dev/null+++ b/studio/backend/tests/test_final_loss_not_average.py@@ -0,0 +1,205 @@+# 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 run's mean loss must not be reported as the final step's loss.++HF logs the end-of-run summary as {"train_runtime": ..., "train_loss": <mean>}+with no "loss" key. `logs.get("loss", logs.get("train_loss"))` therefore fell back+to the mean and published it at the same global_step as the real last step, so:++ - the loss chart gained points stacked on the final step, the last of them the+ run average (a 30 step run charted 33 points, ending 0.3205, 0.3205, 0.3834),+ - `final_loss` on /api/train/runs became the average while+ /api/models/checkpoints reported the true last-step loss for the same run,+ - the UI stat card showed the average, so loss appeared to jump on the last step.+"""++from __future__ import annotations++import sys+from pathlib import Path++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))+++def _extract_loss(logs: dict):+ """The corrected reading of an HF on_log record: only a real per-step loss."""+ return logs.get("loss")+++def test_a_step_record_still_reports_its_loss():+ logs = {"loss": 0.3205, "grad_norm": 0.4, "learning_rate": 1e-5, "epoch": 1.0}+ assert _extract_loss(logs) == 0.3205+++def test_the_summary_record_reports_no_step_loss():+ logs = {"train_runtime": 23.18, "train_loss": 0.3834, "train_samples_per_second": 5.2}+ assert _extract_loss(logs) is None+++class _History:+ """The append rule from TrainingManager's event pump."""++ def __init__(self):+ self.steps: list[int] = []+ self.loss: list[float] = []++ def offer(self, step, loss):+ last = self.steps[-1] if self.steps else None+ if step > 0 and loss is not None and (last is None or step > last):+ self.steps.append(step)+ self.loss.append(loss)+++def test_series_ignores_repeats_at_the_same_step():+ h = _History()+ for step, loss in [(28, 0.27), (29, 0.32), (30, 0.3205), (30, 0.3205), (30, None)]:+ h.offer(step, loss)+ assert h.steps == [28, 29, 30]+ assert h.loss[-1] == 0.3205+++def test_series_never_ends_on_the_average():+ h = _History()+ # The exact tail a 30 step run produced before the fix.+ for step, loss in [(30, 0.3205), (30, 0.3205), (30, 0.3834), (30, 0.3834)]:+ h.offer(step, loss)+ assert h.steps == [30]+ assert h.loss == [0.3205]+++def test_a_step_zero_record_is_still_ignored():+ h = _History()+ h.offer(0, 1.23)+ assert h.steps == []+++def test_normal_monotonic_run_is_unchanged():+ h = _History()+ for step in range(1, 31):+ h.offer(step, 1.0 / step)+ assert h.steps == list(range(1, 31))+ assert len(h.loss) == 30+++def test_the_shipped_call_sites_no_longer_fall_back_to_train_loss():+ # Guard the actual source: the fallback is what caused this.+ for rel in ("core/training/trainer.py", "core/training/worker.py"):+ text = (_BACKEND / rel).read_text(encoding = "utf-8")+ assert 'logs.get("loss", logs.get("train_loss", None))' not in text, rel+++def test_the_terminal_summary_still_reports_elapsed_time():+ # The summary record has no step loss, so the progress filter dropped it; the+ # elapsed time it carries (final eval, checkpoint save, best-model reload) is the+ # run's real duration and must still reach the parent.+ import sys+ from pathlib import Path++ backend = Path(__file__).resolve().parent.parent+ if str(backend) not in sys.path:+ sys.path.insert(0, str(backend))+ from core.training.worker import _create_trainer_progress_callback++ class _P:+ step = 30+ total_steps = 30+ loss = None+ eval_loss = None+ epoch = 3.0+ learning_rate = 0.0+ elapsed_seconds = 412.5+ eta_seconds = None+ grad_norm = None+ num_tokens = 12345+ status_message = ""+ warnings: list = []++ events = []++ class _Q:+ def put(self, e):+ events.append(e)++ _create_trainer_progress_callback(_Q())(_P())+ progress = [e for e in events if e.get("type") == "progress"]+ assert progress, events+ assert progress[0]["elapsed_seconds"] == 412.5+ assert progress[0]["loss"] is None+++def test_a_lossless_mid_run_record_is_still_dropped():+ import sys+ from pathlib import Path++ backend = Path(__file__).resolve().parent.parent+ if str(backend) not in sys.path:+ sys.path.insert(0, str(backend))+ from core.training.worker import _create_trainer_progress_callback++ class _P:+ step = 12+ total_steps = 30+ loss = None+ eval_loss = None+ epoch = 1.0+ learning_rate = 0.0+ elapsed_seconds = 40.0+ eta_seconds = None+ grad_norm = None+ num_tokens = 1+ status_message = ""+ warnings: list = []++ events = []++ class _Q:+ def put(self, e):+ events.append(e)++ _create_trainer_progress_callback(_Q())(_P())+ assert [e for e in events if e.get("type") == "progress"] == []+++def test_an_early_stopped_run_still_reports_its_duration():+ # Stopping at step 12 of 30 still produces HF's lossless summary; the step+ # comparison alone would discard it and finalize the run with stale timing.+ import sys+ from pathlib import Path++ backend = Path(__file__).resolve().parent.parent+ if str(backend) not in sys.path:+ sys.path.insert(0, str(backend))+ from core.training.worker import _create_trainer_progress_callback++ class _P:+ step = 12+ total_steps = 30+ loss = None+ eval_loss = None+ epoch = 1.0+ learning_rate = 0.0+ elapsed_seconds = 91.0+ eta_seconds = None+ grad_norm = None+ num_tokens = 5+ status_message = ""+ is_run_summary = True+ warnings: list = []++ events = []++ class _Q:+ def put(self, e):+ events.append(e)++ _create_trainer_progress_callback(_Q())(_P())+ progress = [e for e in events if e.get("type") == "progress"]+ assert progress and progress[0]["elapsed_seconds"] == 91.0+++def test_the_trainer_marks_the_summary_record():+ text = (_BACKEND / "core/training/trainer.py").read_text(encoding = "utf-8")+ assert "is_run_summary = is_run_summary," in text