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: report active training status (#7613)
oobabooga286b9527a4ad
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex b858fe6f178..661507423c7 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -251,6 +251,13 @@ class UnslothTrainer:trainer_ref = selfclass _ProgressCallback(TrainerCallback):+ def on_train_begin(self, args, state, control, **kwargs):+ # on_log reports an empty status, so without this the UI stays on the+ # pre-train "Starting training..." for the whole run.+ if trainer_ref.should_stop:+ return+ trainer_ref._update_progress(status_message = "Training in progress...")+def on_log(self,args,diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex b5fb5d224ee..74e7d13000f 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -24,7 +24,10 @@ import reimport typesimport subprocess as _spfrom pathlib import Path-from typing import Any, Callable+from typing import Any, Callable, TYPE_CHECKING++if TYPE_CHECKING:+ from core.training.training import TrainingProgress# ── WSL AMD Strix Halo (gfx1151): enable ROCDXG before any torch import ──────# Mirrors main.py. In WSL the AMD GPU is reached via the ROCDXG bridge@@ -2922,7 +2925,6 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->if backend_path not in sys.path:sys.path.insert(0, backend_path)- from core.training.training import TrainingProgressfrom core.training.trainer import UnslothTrainerfrom utils.paths import (ensure_dir,@@ -2968,31 +2970,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->trainer = UnslothTrainer()# Wire up progress callback → event_queue- def _on_progress(progress: TrainingProgress):- has_train_loss = progress.step > 0 and progress.loss is not None- has_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:- event_queue.put(- {- "type": "progress",- "step": progress.step,- "epoch": progress.epoch,- "loss": progress.loss,- "learning_rate": progress.learning_rate,- "total_steps": progress.total_steps,- "elapsed_seconds": progress.elapsed_seconds,- "eta_seconds": progress.eta_seconds,- "grad_norm": progress.grad_norm,- "num_tokens": progress.num_tokens,- "eval_loss": progress.eval_loss,- "status_message": progress.status_message,- "ts": time.time(),- }- )- if progress.status_message:- _send_status(event_queue, progress.status_message)-- trainer.add_progress_callback(_on_progress)+ trainer.add_progress_callback(_create_trainer_progress_callback(event_queue))# Wire up stop_queue polling to trainer.should_stopimport threading@@ -3465,6 +3443,109 @@ def _write_mlx_stop_checkpoint(trainer, optimizer, output_dir) -> bool:return _mlx_has_checkpoint_at_step(output_dir, step)+def _create_trainer_progress_callback(event_queue: Any) -> Callable[[TrainingProgress], None]:+ """UnslothTrainer callback that reports training progress to the parent.++ Status events go out only while the status is non-empty, so the empty status the+ trainer reports on every log leaves the parent's last real status standing.+ """++ def _on_progress(progress: TrainingProgress) -> None:+ has_train_loss = progress.step > 0 and progress.loss is not None+ has_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:+ event_queue.put(+ {+ "type": "progress",+ "step": progress.step,+ "epoch": progress.epoch,+ "loss": progress.loss,+ "learning_rate": progress.learning_rate,+ "total_steps": progress.total_steps,+ "elapsed_seconds": progress.elapsed_seconds,+ "eta_seconds": progress.eta_seconds,+ "grad_norm": progress.grad_norm,+ "num_tokens": progress.num_tokens,+ "eval_loss": progress.eval_loss,+ "status_message": progress.status_message,+ "ts": time.time(),+ }+ )+ if progress.status_message:+ _send_status(event_queue, progress.status_message)++ return _on_progress+++def _create_embedding_progress_callback(+ event_queue: Any,+ *,+ total_steps: int,+ training_start_time: float,+ should_stop: Callable[[], bool],+):+ """TrainerCallback that reports embedding training progress to the parent.++ ``should_stop`` is polled in on_train_begin and on_step_end, so a stop signal+ arriving mid-run is seen.+ """+ from transformers import TrainerCallback++ class _EmbeddingProgressCallback(TrainerCallback):+ def on_train_begin(self, args, state, control, **kwargs):+ # Progress events carry an empty status, so without this the parent keeps+ # showing "Starting embedding training..." for the whole run.+ if should_stop():+ return+ _send_status(event_queue, "Training in progress...")++ def on_log(+ self,+ args,+ state,+ control,+ logs = None,+ **kwargs,+ ):+ if not logs:+ return+ loss_value = logs.get("loss", logs.get("train_loss", None))+ current_step = state.global_step++ elapsed = time.time() - training_start_time+ eta = None+ if current_step > 0 and total_steps > 0:+ remaining = total_steps - current_step+ if remaining > 0:+ eta = (elapsed / current_step) * remaining++ event_queue.put(+ {+ "type": "progress",+ "step": current_step,+ "epoch": round(state.epoch, 2) if state.epoch else 0,+ "loss": loss_value,+ "learning_rate": logs.get("learning_rate", None),+ "total_steps": total_steps,+ "elapsed_seconds": elapsed,+ "eta_seconds": eta,+ "grad_norm": logs.get("grad_norm"),+ "num_tokens": getattr(state, "num_input_tokens_seen", None),+ "eval_loss": logs.get("eval_loss"),+ "status_message": "",+ "ts": time.time(),+ }+ )++ def on_step_end(self, args, state, control, **kwargs):+ if should_stop():+ logger.info("Embedding training: stop at step %d", state.global_step)+ control.should_training_stop = True+ return control++ return _EmbeddingProgressCallback()++def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) -> None:"""Self-contained embedding model training pipeline.@@ -3497,7 +3578,6 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->from sentence_transformers.training_args import BatchSamplersfrom datasets import Datasetfrom utils.datasets.cache_safe import load_dataset_cache_safe as load_dataset- from transformers import TrainerCallbackfrom utils.paths import datasets_root, resolve_output_dir, default_run_dir_nameexcept ImportError as e:event_queue.put(@@ -3887,52 +3967,12 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->total_steps = steps_per_epoch * effective_epochs# ── 8. Create progress callback ──- class _EmbeddingProgressCallback(TrainerCallback):- """Send training progress events to the parent via event_queue."""-- def on_log(- self,- args,- state,- control,- logs = None,- **kwargs,- ):- if not logs:- return- loss_value = logs.get("loss", logs.get("train_loss", None))- current_step = state.global_step-- elapsed = time.time() - training_start_time- eta = None- if current_step > 0 and total_steps > 0:- remaining = total_steps - current_step- if remaining > 0:- eta = (elapsed / current_step) * remaining-- event_queue.put(- {- "type": "progress",- "step": current_step,- "epoch": round(state.epoch, 2) if state.epoch else 0,- "loss": loss_value,- "learning_rate": logs.get("learning_rate", None),- "total_steps": total_steps,- "elapsed_seconds": elapsed,- "eta_seconds": eta,- "grad_norm": logs.get("grad_norm"),- "num_tokens": getattr(state, "num_input_tokens_seen", None),- "eval_loss": logs.get("eval_loss"),- "status_message": "",- "ts": time.time(),- }- )-- def on_step_end(self, args, state, control, **kwargs):- if _should_stop:- logger.info("Embedding training: stop at step %d", state.global_step)- control.should_training_stop = True- return control+ progress_callback = _create_embedding_progress_callback(+ event_queue,+ total_steps = total_steps,+ training_start_time = training_start_time,+ should_stop = lambda: _should_stop,+ )# ── 9. Create trainer and train ──_send_status(event_queue, "Starting embedding training...")@@ -3942,7 +3982,7 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->train_dataset = dataset,loss = loss,args = args,- callbacks = [_EmbeddingProgressCallback()],+ callbacks = [progress_callback],)trainer.train(resume_from_checkpoint = resume_from_checkpoint)diff --git a/studio/backend/tests/test_training_progress_callback.py b/studio/backend/tests/test_training_progress_callback.pynew file mode 100644index 00000000000..f0b32ddcd94--- /dev/null+++ b/studio/backend/tests/test_training_progress_callback.py@@ -0,0 +1,266 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Training progress callbacks must report an active status once training starts.++Both training paths used to leave the parent on the pre-train "Starting ..." status+for the whole run, so /api/train/status and the progress card read "Starting+training..." while the loss was already moving: the callbacks report an empty status+on every log and the parent only overwrites a non-empty one. These tests drive the+real callbacks, worker emit rule and parent handler. Fakes only; no GPU, no model.+"""++from __future__ import annotations++import importlib+import queue as _queue+import sys+import types+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++# core/training/trainer.py imports unsloth and trl at module level (heavy, GPU init).+# Stub whichever are missing just long enough to import it, then restore so this file+# never pollutes the shared session.+_STUBS = {+ "unsloth": ("FastLanguageModel", "FastVisionModel", "is_bfloat16_supported"),+ "unsloth.chat_templates": ("get_chat_template",),+ "trl": ("SFTTrainer", "SFTConfig"),+}+_STUBBED: list[str] = []+_TRAINER_PRE_IMPORTED = "core.training.trainer" in sys.modules+++def _stub_if_missing(name, attrs):+ """Stub ``name`` unless the real package is installed."""+ if name in sys.modules:+ return+ try:+ importlib.import_module(name)+ return+ except Exception:+ pass+ _STUBBED.append(name)+ module = types.ModuleType(name)+ # A spec-less module reads as "no namespace shadow" to ensure_real_packages.+ module.__spec__ = None+ for attr in attrs:+ setattr(module, attr, MagicMock())+ sys.modules[name] = module+ parent, _, child = name.rpartition(".")+ if parent and parent in sys.modules:+ setattr(sys.modules[parent], child, module)+++if not _TRAINER_PRE_IMPORTED:+ for _name, _attrs in _STUBS.items():+ _stub_if_missing(_name, _attrs)++from core.training.trainer import UnslothTrainer # noqa: E402+from core.training.training import TrainingBackend # noqa: E402+from core.training.worker import ( # noqa: E402+ _create_embedding_progress_callback,+ _create_trainer_progress_callback,+)++if not _TRAINER_PRE_IMPORTED:+ for _name in _STUBBED:+ sys.modules.pop(_name, None)+ # Drop the stub-bound module and its parent package (which still holds it as an+ # attribute) so a later test re-imports it against the real packages; the+ # UnslothTrainer class held above stays usable.+ sys.modules.pop("core.training.trainer", None)+ sys.modules.pop("core.training", None)++ACTIVE = "Training in progress..."+++class _FakeQueue:+ """Stands in for the mp.Queue the worker sends events on."""++ def __init__(self):+ self.events: list[dict] = []++ def put(self, event, *args, **kwargs):+ self.events.append(event)+++def _state():+ return SimpleNamespace(global_step = 0, epoch = 0.0, num_input_tokens_seen = 0)+++def _drive(+ callback,+ steps = 3,+ control = None,+ on_step = None,+):+ """Run the HuggingFace callback lifecycle the way Trainer.train() does."""+ state = _state()+ control = control if control is not None else SimpleNamespace(should_training_stop = False)+ callback.on_train_begin(None, state, control)+ for step in range(1, steps + 1):+ state.global_step = step+ state.epoch = round(0.5 * step, 2)+ state.num_input_tokens_seen = 128 * step+ callback.on_log(None, state, control, logs = {"loss": 1.0 / step, "learning_rate": 1e-4})+ callback.on_step_end(None, state, control)+ if on_step is not None:+ on_step(step)+ # Once at the end: HuggingFace calls on_epoch_end per epoch, not per step.+ callback.on_epoch_end(None, state, control)+ return state, control+++# ---------------------------------------------------------------------------+# LLM/VLM/audio path: UnslothTrainer._create_progress_callback ->+# worker._create_trainer_progress_callback+# ---------------------------------------------------------------------------+++def _make_owner():+ # __new__ dispatches to the MLX adapter on Apple hardware, which has no+ # _create_progress_callback; go straight to the class under test.+ owner = object.__new__(UnslothTrainer)+ UnslothTrainer.__init__(owner)+ owner._update_progress(is_training = True, total_steps = 4, status_message = "Starting training...")+ return owner+++def test_train_begin_reports_active_status():+ owner = _make_owner()+ callback = owner._create_progress_callback()++ callback.on_train_begin(None, _state(), SimpleNamespace())++ assert owner.training_progress.status_message == ACTIVE+++def test_logging_reports_an_empty_status_so_the_active_one_is_sent_once():+ # The parent keeps the last non-empty status, so a run costs one status event.+ owner = _make_owner()+ reported: list[str] = []+ owner.add_progress_callback(lambda progress: reported.append(progress.status_message))++ _drive(owner._create_progress_callback(), steps = 3)++ assert owner.training_progress.status_message == ""+ assert [status for status in reported if status] == [ACTIVE]+ assert owner.training_progress.step == 3+ assert owner.training_progress.loss == pytest.approx(1 / 3)+ assert owner.training_progress.num_tokens == 384+++def test_parent_status_advances_over_the_whole_chain():+ owner = _make_owner()+ backend = TrainingBackend()+ event_queue = _FakeQueue()+ owner.add_progress_callback(_create_trainer_progress_callback(event_queue))+ # The worker sends this right before trainer.train().+ event_queue.put({"type": "status", "message": "Starting training...", "ts": 0.0})++ _drive(owner._create_progress_callback(), steps = 3)+ for event in event_queue.events:+ backend._handle_event(event)++ assert backend._progress.status_message == ACTIVE+ assert backend._progress.step == 3+ assert backend._progress.is_training is True+++ "stop_status",+ [+ "Stopping training and saving checkpoint...",+ "Cancelling training...",+ ],+)+def test_stop_status_is_never_replaced_by_the_active_one(stop_status):+ owner = _make_owner()+ backend = TrainingBackend()+ event_queue = _FakeQueue()+ owner.add_progress_callback(_create_trainer_progress_callback(event_queue))+ callback = owner._create_progress_callback()++ def _stop_after_first_step(step):+ if step == 1:+ owner.should_stop = True+ owner._update_progress(status_message = stop_status)++ _, control = _drive(callback, steps = 2, on_step = _stop_after_first_step)+ # A resumed run re-enters on_train_begin; an already requested stop must survive.+ callback.on_train_begin(None, _state(), SimpleNamespace())+ for event in event_queue.events:+ backend._handle_event(event)++ assert [e["message"] for e in event_queue.events if e["type"] == "status"] == [+ ACTIVE,+ stop_status,+ ]+ assert backend._progress.status_message == stop_status+ assert control.should_training_stop is True+++# ---------------------------------------------------------------------------+# Embedding path: worker._create_embedding_progress_callback+# ---------------------------------------------------------------------------+++def _make_embedding_callback(event_queue, should_stop = lambda: False):+ return _create_embedding_progress_callback(+ event_queue,+ total_steps = 4,+ training_start_time = 0.0,+ should_stop = should_stop,+ )+++def test_embedding_parent_status_advances_over_the_whole_chain():+ event_queue = _FakeQueue()+ backend = TrainingBackend()+ # The worker sends this right before trainer.train().+ event_queue.put({"type": "status", "message": "Starting embedding training...", "ts": 0.0})++ _drive(_make_embedding_callback(event_queue), steps = 3)+ for event in event_queue.events:+ backend._handle_event(event)++ assert [e["message"] for e in event_queue.events if e["type"] == "status"] == [+ "Starting embedding training...",+ ACTIVE,+ ]+ assert backend._progress.status_message == ACTIVE+ assert backend._progress.step == 3+ assert backend._progress.loss == pytest.approx(1 / 3)+ assert backend._progress.total_steps == 4+++def test_embedding_train_begin_reports_nothing_once_a_stop_was_requested():+ event_queue = _FakeQueue()+ control = SimpleNamespace(should_training_stop = False)++ _drive(+ _make_embedding_callback(event_queue, should_stop = lambda: True), steps = 1, control = control+ )++ assert [e for e in event_queue.events if e["type"] == "status"] == []+ assert control.should_training_stop is True+++def test_embedding_callback_survives_a_real_queue():+ # The worker's queue is an mp.Queue; nothing put on it may be unpicklable.+ import pickle++ event_queue = _queue.Queue()+ _drive(_make_embedding_callback(event_queue), steps = 1)++ events = [event_queue.get_nowait() for _ in range(event_queue.qsize())]+ assert [e["type"] for e in events] == ["status", "progress"]+ assert pickle.loads(pickle.dumps(events)) == events