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.

Studio: keep third-party progress bars and raw trainer prints out of the structured log (#8311)

Daniel Han73cf481d465f
diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.py
index c4a352a6a47..15edbee4d0c 100644
--- a/studio/backend/core/export/worker.py
+++ b/studio/backend/core/export/worker.py
@@ -541,9 +541,16 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None
if os.getenv("ENVIRONMENT_TYPE", "production") == "production":
warnings.filterwarnings("ignore")
+ # This worker's stdout is forwarded to the export dialog once the log gate opens,
+ # and the Hub upload bar is the only live byte progress a long push_to_hub has, so
+ # it keeps its progress bars even though the server turned its own off.
+ from loggers.config import allow_progress_bars
+
+ allow_progress_bars()
LogConfig.setup_logging(
service_name = "unsloth-studio-export-worker",
env = os.getenv("ENVIRONMENT_TYPE", "production"),
+ quiet_progress_bars = False,
)
checkpoint_path = config["checkpoint_path"]
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 7ac7d5d5072..5fd79ab39bd 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -2881,6 +2881,14 @@ class DiffusionBackend:
import diffusers
+ # diffusers hard-codes _tqdm_active = True at import and honours no env var, so
+ # setup_logging (which runs long before this lazy import) cannot reach it. Without
+ # this, "Loading pipeline components..." is drawn straight onto the log stream and
+ # can land mid-record on a structlog JSON line. Idempotent and cheap.
+ from loggers.config import quiet_third_party_progress_bars
+
+ quiet_third_party_progress_bars()
+
# Pre-install the optional attention kernel before the load locks: the pip install can block unload for 600s.
try:
preinstall_backend = select_attention_backend(
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 7dea62ffe94..9b9a2df5d03 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -2396,6 +2396,15 @@ class VideoBackend:
import diffusers
import torch
+ # Same reason as diffusion.py: diffusers hard-codes _tqdm_active = True at
+ # import and honours no env var, so setup_logging cannot reach it and its
+ # "Loading pipeline components..." bar lands on the structured stream.
+ try:
+ from loggers.config import quiet_third_party_progress_bars
+ quiet_third_party_progress_bars()
+ except Exception: # noqa: BLE001 - never let log tidying stop a load
+ pass
+
base = repo_id if kind == "pipeline" else resolve_video_base_repo(fam, base_repo)
with self._lock:
diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.py
index 6a4ba26cea3..ec04e0ca628 100644
--- a/studio/backend/core/training/diffusion_dit_trainer.py
+++ b/studio/backend/core/training/diffusion_dit_trainer.py
@@ -1907,6 +1907,15 @@ def _train_dit(
from peft import LoraConfig
from peft.utils import get_peft_model_state_dict
+ # Same as the SDXL trainer: diffusers is only in sys.modules from here, and it
+ # honours no env var, so its pipeline-loading bars can only be turned off now --
+ # before the conditioning cache below loads the VAE and text encoders.
+ try:
+ from loggers.config import quiet_third_party_progress_bars
+ quiet_third_party_progress_bars()
+ except Exception: # noqa: BLE001 - never let log tidying stop a training run
+ pass
+
use_lora_targets = _select_lora_targets(cfg.lora_target_modules, spec.lora_targets)
out_dir = Path(cfg.output_dir).expanduser()
diff --git a/studio/backend/core/training/diffusion_lora_trainer.py b/studio/backend/core/training/diffusion_lora_trainer.py
index ce76d1c39bc..f837201c490 100644
--- a/studio/backend/core/training/diffusion_lora_trainer.py
+++ b/studio/backend/core/training/diffusion_lora_trainer.py
@@ -311,6 +311,15 @@ def run_diffusion_lora_training(
from peft import LoraConfig
from peft.utils import get_peft_model_state_dict
+ # Only now is diffusers in sys.modules, and it hard-codes _tqdm_active = True and
+ # honours no env var, so this is the earliest point its "Loading pipeline
+ # components..." bar can be turned off -- and it comes before the pipeline load below.
+ try:
+ from loggers.config import quiet_third_party_progress_bars
+ quiet_third_party_progress_bars()
+ except Exception: # noqa: BLE001 - never let log tidying stop a training run
+ pass
+
cfg = config.normalized()
rng = random.Random(cfg.seed)
torch.manual_seed(cfg.seed)
diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.py
index 01782e7f0ce..dbb67f86cdf 100644
--- a/studio/backend/core/training/diffusion_training_service.py
+++ b/studio/backend/core/training/diffusion_training_service.py
@@ -60,6 +60,15 @@ def _run_diffusion_child(*, event_queue: Any, stop_queue: Any, config: dict) ->
# Imported lazily so this module (and the route layer) stays torch-free at import.
from .diffusion_lora_trainer import run_diffusion_training_process
+ # This child never runs LogConfig.setup_logging, so it installs the Hub default
+ # here; the diffusers half is done inside the two trainer entrypoints, which are
+ # the first points where diffusers is actually imported.
+ try:
+ from loggers.config import quiet_third_party_progress_bars
+ quiet_third_party_progress_bars()
+ except Exception: # noqa: BLE001 - never let log tidying stop a training run
+ pass
+
run_diffusion_training_process(event_queue = event_queue, stop_queue = stop_queue, config = config)
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.py
index a2d123feb47..559192f917f 100644
--- a/studio/backend/core/training/trainer.py
+++ b/studio/backend/core/training/trainer.py
@@ -107,6 +107,73 @@ def _build_report_targets(training_args) -> list[str] | str:
return report_to or "none"
+def _verbose_logging_requested() -> bool:
+ """Whether `unsloth studio --verbose` is in effect.
+
+ --verbose zeroes both access-log windows (unsloth_cli/commands/studio.py), and the
+ env is inherited by the training subprocess, so the same pair is the signal here.
+ """
+
+ def _zero(name: str) -> bool:
+ raw = (os.environ.get(name) or "").strip()
+ try:
+ return raw != "" and int(raw) <= 0
+ except ValueError:
+ return False
+
+ return _zero("UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS") and _zero(
+ "UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS"
+ )
+
+
+def _hf_stdout_progress_disabled() -> bool:
+ """`disable_tqdm` for the HF training args, unless --verbose asked for everything.
+
+ The trainer subprocess has no terminal: its stdout is teed into the server log, so
+ the tqdm bar becomes a burst of carriage-return fragments that can also land inside
+ a structlog JSON record and make it unparseable. Every number the bar carries is
+ already published twice, as the throttled `training_progress` event added in #7087
+ and as the per-step SSE stream the UI charts.
+ """
+ return not _verbose_logging_requested()
+
+
+# Keys that only ever appear on Trainer's end-of-run / end-of-eval summary record.
+_TRAINER_SUMMARY_KEYS = (
+ "train_runtime",
+ "train_samples_per_second",
+ "train_steps_per_second",
+ "total_flos",
+ "eval_runtime",
+ "eval_samples_per_second",
+ "eval_steps_per_second",
+)
+# structlog fills these itself; a metric of the same name would collide.
+_RESERVED_LOG_KEYS = frozenset({"event", "level", "timestamp", "logger"})
+
+
+def _drop_hf_stdout_callbacks(trainer) -> None:
+ """Remove HF's stdout progress callbacks from an already-built trainer.
+
+ `disable_tqdm=True` only swaps ProgressCallback for PrinterCallback, which prints a
+ raw dict per step instead (`{'loss': '0.5684', 'grad_norm': ..., 'epoch': ...}`).
+ Both write to the same stdout, so both have to go; Studio's own progress callback,
+ the SSE stream and `training_progress` are unaffected. Best effort: a transformers
+ build without these classes just keeps its current behaviour.
+ """
+ if _verbose_logging_requested():
+ return
+ try:
+ from transformers.trainer_callback import PrinterCallback, ProgressCallback
+ except Exception: # noqa: BLE001 - never let log tidying break a training run
+ return
+ for callback_cls in (PrinterCallback, ProgressCallback):
+ try:
+ trainer.remove_callback(callback_cls)
+ except Exception: # noqa: BLE001 - not attached, or an incompatible trainer
+ pass
+
+
class UnslothTrainer:
"""
Unsloth Training Backend
@@ -284,12 +351,52 @@ class UnslothTrainer:
trainer_ref = self
class _ProgressCallback(TrainerCallback):
+ # Per-batch evaluation progress used to exist only as HF's tqdm bar, which
+ # this PR drops. A long eval would otherwise look stalled between the last
+ # step log and the eval result, so it is republished, throttled, as status
+ # and one structured line.
+ _eval_seen = 0
+ _eval_last_report = 0.0
+
def on_train_begin(self, args, state, control, **kwargs):
# on_log reports an empty status, else the UI stays on "Starting training...".
if trainer_ref.should_stop:
return
trainer_ref._update_progress(status_message = "Training in progress...")
+ def on_evaluate(self, args, state, control, **kwargs):
+ cls = type(self)
+ had_status = cls._eval_last_report > 0.0
+ cls._eval_seen = 0
+ cls._eval_last_report = 0.0
+ # An empty status is ignored downstream on purpose, so the UI would
+ # sit on "Evaluating..." for the rest of the run.
+ if had_status and not trainer_ref.should_stop:
+ trainer_ref._update_progress(status_message = "Training in progress...")
+
+ def on_prediction_step(
+ self,
+ args,
+ state,
+ control,
+ eval_dataloader = None,
+ **kwargs,
+ ):
+ cls = type(self)
+ cls._eval_seen += 1
+ total = None
+ try:
+ total = len(eval_dataloader) if eval_dataloader is not None else None
+ except TypeError: # an iterable-style loader has no length
+ total = None
+ now = time.time()
+ if cls._eval_last_report and (now - cls._eval_last_report) < 15.0:
+ return
+ cls._eval_last_report = now
+ where = f"{cls._eval_seen:,}" + (f"/{total:,}" if total else "")
+ trainer_ref._update_progress(status_message = f"Evaluating... {where} batches")
+ logger.info("evaluating", batches = cls._eval_seen, total_batches = total)
+
def on_log(
self,
args,
@@ -300,6 +407,20 @@ class UnslothTrainer:
):
if not logs:
return
+ # Trainer's end-of-run and end-of-eval summaries carry numbers that
+ # appear nowhere else in Studio (train_samples_per_second,
+ # train_steps_per_second, total_flos, memory, eval runtime). They used
+ # to reach the log only through PrinterCallback's raw stdout dict, so
+ # with that callback gone they are re-published here, structured, once.
+ if any(k in logs for k in _TRAINER_SUMMARY_KEYS):
+ logger.info(
+ "trainer summary",
+ **{
+ k: v
+ for k, v in logs.items()
+ if isinstance(k, str) and k not in _RESERVED_LOG_KEYS
+ },
+ )
# 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
@@ -402,6 +523,9 @@ class UnslothTrainer:
"seed": random_seed,
"output_dir": output_dir,
"report_to": _build_report_targets(training_args),
+ # The subprocess stdout is teed into the server log, so HF's bar is
+ # noise there; --verbose restores it. See _hf_stdout_progress_disabled.
+ "disable_tqdm": _hf_stdout_progress_disabled(),
}
if training_args.get("enable_tensorboard", False):
@@ -2297,6 +2421,18 @@ class UnslothTrainer:
"""
from core.training.s3_dataset import S3DownloadCancelled
+ # `datasets` exposes no env var, so its bars can only be quieted through the
+ # class, and only once the module is in. It is (module-level import above), and
+ # this is the first point before any load: the local-file and Hub branches below
+ # both call load_dataset(), whose "Generating train split" / "Downloading data"
+ # bars would otherwise write into the worker's structured stream. It also covers
+ # the map/filter bars of every branch further down.
+ try:
+ from loggers.config import quiet_third_party_progress_bars
+ quiet_third_party_progress_bars()
+ except Exception: # noqa: BLE001 - never let log tidying stop a run
+ pass
+
s3_download = None
try:
self.dataset_loaded_from_exact_snapshot = False
@@ -3169,6 +3305,9 @@ class UnslothTrainer:
args = TrainingArguments(**config),
)
self.trainer.add_callback(self._create_progress_callback())
+ # Studio publishes progress itself, so HF's stdout callbacks are pure
+ # duplication in a log that has no terminal. --verbose keeps them.
+ _drop_hf_stdout_callbacks(self.trainer)
batch_size = training_args.get("batch_size", 2)
total = self._calculate_total_steps(
@@ -3207,6 +3346,9 @@ class UnslothTrainer:
),
)
self.trainer.add_callback(self._create_progress_callback())
+ # Studio publishes progress itself, so HF's stdout callbacks are pure
+ # duplication in a log that has no terminal. --verbose keeps them.
+ _drop_hf_stdout_callbacks(self.trainer)
batch_size = training_args.get("batch_size", 2)
total = self._calculate_total_steps(
@@ -3251,6 +3393,9 @@ class UnslothTrainer:
self.trainer = Seq2SeqTrainer(**trainer_kwargs)
self.trainer.add_callback(self._create_progress_callback())
+ # Studio publishes progress itself, so HF's stdout callbacks are pure
+ # duplication in a log that has no terminal. --verbose keeps them.
+ _drop_hf_stdout_callbacks(self.trainer)
batch_size = training_args.get("batch_size", 2)
total = self._calculate_total_steps(
@@ -3411,6 +3556,7 @@ class UnslothTrainer:
"seed": training_args.get("random_seed", 3407),
"output_dir": output_dir,
"report_to": _build_report_targets(training_args),
+ "disable_tqdm": _hf_stdout_progress_disabled(),
"include_num_input_tokens_seen": True,
# serial_as_none = False: this is a config boundary, not a map() call site. The audio
# paths ask for 1 to keep dataset workers off a process holding audio/CUDA state, and
@@ -3754,6 +3900,9 @@ class UnslothTrainer:
# ========== PROGRESS TRACKING ==========
self.trainer.add_callback(self._create_progress_callback())
+ # Studio publishes progress itself, so HF's stdout callbacks are pure
+ # duplication in a log that has no terminal. --verbose keeps them.
+ _drop_hf_stdout_callbacks(self.trainer)
train_dataset_obj = dataset["dataset"] if isinstance(dataset, dict) else dataset
is_streaming_dataset = detect_streaming_dataset(train_dataset_obj)
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.py
index a8bb811e8a5..ab4835ee619 100644
--- a/studio/backend/core/training/training.py
+++ b/studio/backend/core/training/training.py
@@ -1107,6 +1107,10 @@ class TrainingBackend:
# Throttled training-status logging to the server log (not one line/step).
self._last_progress_log_ts: float = 0.0
self._last_progress_log_step: int = -1
+ # (elapsed_seconds, num_tokens) at the previous logged line, so the next one
+ # can report throughput over the interval between them.
+ self._last_progress_log_elapsed: Optional[float] = None
+ self._last_progress_log_tokens: Optional[int] = None
# Training metrics (consumed by routes for SSE and /metrics)
self.loss_history: list = []
@@ -1766,6 +1770,8 @@ class TrainingBackend:
# Reset the throttle so the new run logs its first step even within 30s of a prior run.
self._last_progress_log_ts = 0.0
self._last_progress_log_step = -1
+ self._last_progress_log_elapsed = None
+ self._last_progress_log_tokens = None
self.loss_history.clear()
self.lr_history.clear()
self.step_history.clear()
@@ -3092,8 +3098,33 @@ class TrainingBackend:
now = time.monotonic()
if prev >= 0 and step > prev and not is_final and (now - self._last_progress_log_ts) < 30.0:
return
+ # Throughput over the interval since the previous logged line. Trainer speed is
+ # the number people watch a training run for, and the only place it used to
+ # appear was HF's own tqdm bar ("1.84s/it") and its per-step print
+ # ("train_tokens_per_second"), both of which are raw stdout rather than
+ # structured. Carry it here instead, so the structured line is not a downgrade.
+ elapsed = p.elapsed_seconds
+ tokens = p.num_tokens
+ s_per_step = tok_per_s = None
+ prev_elapsed = self._last_progress_log_elapsed
+ prev_tokens = self._last_progress_log_tokens
+ if elapsed is not None and prev_elapsed is not None and prev >= 0:
+ d_time = elapsed - prev_elapsed
+ d_steps = step - prev
+ if d_time > 0 and d_steps > 0:
+ s_per_step = round(d_time / d_steps, 3)
+ if tokens is not None and prev_tokens is not None and tokens > prev_tokens:
+ tok_per_s = round((tokens - prev_tokens) / d_time, 1)
+ # The first logged line reports no throughput on purpose: elapsed_seconds is
+ # wall time since the worker started, which includes imports, the model
+ # download and load and the dataset build, and on a resumed run the step and
+ # token counters predate this process entirely. Dividing by it would report a
+ # number nobody wants. The next line has a real in-training interval.
+
self._last_progress_log_ts = now
self._last_progress_log_step = step
+ self._last_progress_log_elapsed = elapsed
+ self._last_progress_log_tokens = tokens
logger.info(
"training_progress",
step = step,
@@ -3102,6 +3133,8 @@ class TrainingBackend:
loss = round(p.loss, 4) if p.loss is not None else None,
epoch = round(p.epoch, 2) if p.epoch is not None else None,
eta_s = int(p.eta_seconds) if p.eta_seconds else None,
+ s_per_step = s_per_step,
+ tok_per_s = tok_per_s,
)
def _ensure_db_run_created(self) -> None:
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 502e8ba1180..596778e778e 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -3349,11 +3349,18 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
import warnings
- from loggers.config import LogConfig
+ from loggers.config import LogConfig, keep_progress_bars_countable
if os.getenv("ENVIRONMENT_TYPE", "production") == "production":
warnings.filterwarnings("ignore")
+ # This worker READS the bars: the monitor thread further down polls tqdm._instances
+ # to turn the Hub download and "Loading checkpoint shards" bars into the UI's status
+ # line, and a disabled bar is never registered there. So it redirects their output
+ # instead of disabling them, and does so before the inherited
+ # HF_HUB_DISABLE_PROGRESS_BARS reaches huggingface_hub's import-time constant.
+ keep_progress_bars_countable()
+
LogConfig.setup_logging(
service_name = "unsloth-studio-training-worker",
env = os.getenv("ENVIRONMENT_TYPE", "production"),
@@ -4513,29 +4520,46 @@ def _create_trainer_progress_callback(event_queue: Any) -> Callable[[TrainingPro
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.
+
+ The trainer shares one TrainingProgress for metrics and status, so a status-only
+ update (an evaluation line, a warning) carries the last step's numbers unchanged.
+ The parent appends every progress event to the loss / grad-norm / eval-loss
+ histories without deduplicating the step, so those replays would plot the same
+ point again. Only a changed measurement is published; the status still is.
"""
sent_warnings: set[str] = set()
+ last_metrics: list = [None]
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
# 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.
+ # and best-model reload, and a run stopped early never reaches total_steps, so
+ # the flag the trainer sets on that record is what marks it terminal.
is_terminal = bool(getattr(progress, "is_run_summary", False)) or (
progress.total_steps > 0 and progress.step >= progress.total_steps
)
+ # Wall-clock fields are excluded: they move on every call, so keeping them
+ # would make each status replay look like a new measurement.
+ metrics = (
+ progress.step,
+ progress.loss,
+ progress.learning_rate,
+ progress.grad_norm,
+ progress.num_tokens,
+ progress.epoch,
+ progress.eval_loss,
+ )
+ is_repeat = metrics == last_metrics[0]
if (
(progress.step == 0 and progress.total_steps > 0)
or has_train_loss
or has_eval_loss
or is_terminal
- ):
+ ) and not is_repeat:
+ last_metrics[0] = metrics
event_queue.put(
{
"type": "progress",
@@ -4594,6 +4618,20 @@ def _create_embedding_progress_callback(
):
if not logs:
return
+ # Trainer's end-of-run summary carries train_runtime, samples and steps per
+ # second, total_flos and memory, which nothing else here publishes. It used
+ # to reach the log only through PrinterCallback's raw stdout dict.
+ from core.training.trainer import _RESERVED_LOG_KEYS, _TRAINER_SUMMARY_KEYS
+
+ if any(k in logs for k in _TRAINER_SUMMARY_KEYS):
+ logger.info(
+ "trainer summary",
+ **{
+ k: v
+ for k, v in logs.items()
+ if isinstance(k, str) and k not in _RESERVED_LOG_KEYS
+ },
+ )
# 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")
@@ -4685,6 +4723,16 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
)
return
+ # datasets is only in the process now, and setup_logging ran long before it, so
+ # this is the first point where its Generating/Map bars can be quieted. Without
+ # it a local JSON/CSV/Parquet or Hub load_dataset writes them into this worker's
+ # structured log.
+ try:
+ from loggers.config import quiet_third_party_progress_bars
+ quiet_third_party_progress_bars()
+ except Exception: # noqa: BLE001 - never let log tidying stop a run
+ pass
+
# ── Stop signal handling ──
_should_stop = False
_save_on_stop = True
@@ -4978,6 +5026,8 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
warmup_steps_val = config.get("warmup_steps")
log_frequency = config.get("log_frequency", 50)
+ from core.training.trainer import _drop_hf_stdout_callbacks, _hf_stdout_progress_disabled
+
training_args_kwargs = {
"output_dir": output_dir,
"per_device_train_batch_size": batch_size,
@@ -4992,6 +5042,10 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
"optim": config.get("optim", "adamw_8bit"),
"weight_decay": config.get("weight_decay", 0.001),
"seed": config.get("random_seed", 3407),
+ # Same reason as the UnslothTrainer path: this worker has no terminal, its
+ # stdout is teed into the server log, and _create_embedding_progress_callback
+ # already publishes every number the bar carries.
+ "disable_tqdm": _hf_stdout_progress_disabled(),
}
if max_steps_val and max_steps_val > 0:
@@ -5038,6 +5092,9 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
args = args,
callbacks = [progress_callback],
)
+ # disable_tqdm only swaps ProgressCallback for PrinterCallback, which prints a
+ # raw dict per step instead; both write to the same stdout.
+ _drop_hf_stdout_callbacks(trainer)
trainer.train(resume_from_checkpoint = resume_from_checkpoint)
except Exception as e:
diff --git a/studio/backend/loggers/config.py b/studio/backend/loggers/config.py
index dc2d14d6327..4ab0ea67ff1 100644
--- a/studio/backend/loggers/config.py
+++ b/studio/backend/loggers/config.py
@@ -100,17 +100,255 @@ def _truncate_exception_processor(logger, method_name, event_dict):
return truncate_exception(event_dict)
+# Set alongside HF_HUB_DISABLE_PROGRESS_BARS when the value is Studio's default rather
+# than the operator's, so allow_progress_bars() can tell them apart.
+_PROGRESS_BARS_DEFAULTED = "UNSLOTH_STUDIO_PROGRESS_BARS_DEFAULTED"
+
+# huggingface_hub's own spelling of truth (utils/_runtime.py ENV_VARS_TRUE_VALUES),
+# so "off" and "no" mean "keep the bars" here exactly as they do there.
+_ENV_TRUE = frozenset({"1", "on", "yes", "true"})
+
+# Set once this process has deliberately taken its bars back (the export worker draws
+# them, the training worker reads them). quiet_third_party_progress_bars() then stops
+# being a switch a later call can flip the other way.
+_BARS_RESTORED = False
+
+
+def _env_is_true(value: str) -> bool:
+ return (value or "").strip().lower() in _ENV_TRUE
+
+
+def _verbose_logging_requested() -> bool:
+ """True when `unsloth studio --verbose` asked for every line back. The CLI signals
+ it by zeroing both access-log dedup windows, which is what the workers inherit."""
+
+ def _zero(name: str) -> bool:
+ raw = (os.environ.get(name) or "").strip()
+ try:
+ return raw != "" and int(raw) <= 0
+ except ValueError:
+ return False
+
+ return _zero("UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS") and _zero(
+ "UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS"
+ )
+
+
+class _NullStream:
+ """Somewhere for a progress bar to write that is not the log."""
+
+ def write(self, _data):
+ return 0
+
+ def flush(self):
+ pass
+
+ def isatty(self):
+ return False
+
+
+def _silence_datasets_bar_output() -> None:
+ """Keep the datasets bar object, drop only what it writes.
+
+ datasets exposes no env var, and its disable_progress_bar() works by forcing
+ tqdm(disable = True), which never registers the bar in tqdm._instances.
+ utils/datasets/chat_templates.py polls that set to publish
+ "Applying chat template ... 42%" to the UI, so disabling the bar outright would
+ freeze that status for the whole of a long format job. Pointing the bar at a null
+ stream keeps the counter (and the status) alive while the log stays clean.
+ """
+ if "datasets" not in sys.modules:
+ return
+ try:
+ from datasets.utils.tqdm import tqdm as bar_cls
+
+ if getattr(bar_cls, "_unsloth_output_silenced", False):
+ return
+ original_init = bar_cls.__init__
+
+ def _quiet_init(self, *args, **kwargs):
+ kwargs.setdefault("file", _NullStream())
+ original_init(self, *args, **kwargs)
+
+ bar_cls.__init__ = _quiet_init
+ bar_cls._unsloth_output_silenced = True
+ except Exception: # noqa: BLE001 - a datasets build without it just stays noisy
+ pass
+
+
+def _redirect_every_bar_output() -> None:
+ """Point every tqdm bar at a null stream, disabling none of them.
+
+ tqdm.std.tqdm.__init__ is the one funnel: huggingface_hub's, datasets' and
+ transformers' bar classes all subclass it and reach it through super().
+ """
+ try:
+ from tqdm.std import tqdm as bar_cls
+
+ if getattr(bar_cls, "_unsloth_every_output_silenced", False):
+ return
+ original_init = bar_cls.__init__
+
+ def _quiet_init(self, *args, **kwargs):
+ kwargs.setdefault("file", _NullStream())
+ original_init(self, *args, **kwargs)
+
+ bar_cls.__init__ = _quiet_init
+ bar_cls._unsloth_every_output_silenced = True
+ except Exception: # noqa: BLE001 - an unfamiliar tqdm just stays noisy
+ pass
+
+
+def keep_progress_bars_countable() -> None:
+ """Keep the bar objects alive in a process that READS them, output dropped.
+
+ core/training/worker.py runs a poller over tqdm._instances to turn the Hub
+ download bar and "Loading checkpoint shards" into the UI's status line, which is
+ the only progress a user sees between "Loading model..." and the first step. A
+ disabled bar is never registered in _instances (tqdm/std.py drops it), so the
+ inherited HF_HUB_DISABLE_PROGRESS_BARS default would leave that status frozen for
+ the whole of a multi-GB download. Same trade as datasets: keep the counter, drop
+ the writes, so nothing reaches the log either way.
+
+ Only Studio's own default is undone; an operator who set the variable themselves
+ asked for no bars and keeps getting none. Afterwards
+ quiet_third_party_progress_bars() is a no-op in this process, so a later call
+ cannot re-disable what the poller reads.
+
+ Call it BEFORE huggingface_hub is imported: hub reads the variable once, into a
+ module constant, and enable_progress_bars() then refuses to override it. The
+ training worker does, ahead of its setup_logging call.
+ """
+ value = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS")
+ if value is None or not _env_is_true(value):
+ # Nothing quieted them here: --verbose, or an operator who asked to keep them.
+ return
+ if not os.environ.get(_PROGRESS_BARS_DEFAULTED):
+ # The operator turned them off; that is not ours to undo.
+ return
+ _redirect_every_bar_output()
+ allow_progress_bars()
+
+
+def quiet_bar_kwargs() -> dict:
+ """tqdm kwargs that keep a bar counting but stop it writing to the log.
+
+ For Studio's own explicit bars (the dataset conversion loops), which no library
+ switch reaches. Empty when the operator asked to keep bars, so nothing changes.
+ """
+ value = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS")
+ if value is None or not _env_is_true(value):
+ return {}
+ return {"file": _NullStream()}
+
+
+def allow_progress_bars() -> None:
+ """Undo an inherited Studio default so this process can draw progress bars.
+
+ Called by the export worker, whose stdout is forwarded to the export dialog and
+ whose Hub upload bar is the only live byte progress a long push_to_hub has. An
+ operator-set HF_HUB_DISABLE_PROGRESS_BARS is left alone.
+ """
+ global _BARS_RESTORED
+ _BARS_RESTORED = True
+ if os.environ.pop(_PROGRESS_BARS_DEFAULTED, None):
+ os.environ.pop("HF_HUB_DISABLE_PROGRESS_BARS", None)
+
+
+def quiet_third_party_progress_bars() -> None:
+ """Turn off the tqdm bars transformers / diffusers / huggingface_hub draw
+ during an in-process model load.
+
+ A bar is written with carriage returns to a terminal, so in Studio's log it
+ lands as a burst of lines like
+
+ Loading weights: 8%|> | 30/398 [00:00<00:01, 277.16it/s][A
+
+ and, because tqdm writes to a different stream than the structlog JSON
+ writer with no line discipline between them, a bar can land mid-record:
+ ``Loading pipeline components...: 20%|...|{"timestamp": ...}``. That line
+ is no longer parseable JSON, so anything reading the log record-by-record
+ loses the record.
+
+ Nothing is lost by dropping them: download and load progress already reach
+ the UI as real events (``hub_download_progress``, ``inference_load_progress``)
+ and via /api/inference/{images,video}/load-progress. Only the bars go; the
+ libraries' warnings and errors are untouched.
+
+ The subprocess workers already do this by exporting
+ HF_HUB_DISABLE_PROGRESS_BARS (hub/services/download_lifecycle.py,
+ core/inference/stt_download_worker.py); the server process, which loads the
+ RAG embedder at boot and every diffusers pipeline in-process, did not.
+
+ Respects an explicit operator override: if HF_HUB_DISABLE_PROGRESS_BARS is
+ already set, its value wins, parsed the way huggingface_hub parses it. Only
+ modules that are ALREADY imported get the API call, so this never forces a heavy
+ import at logging-setup time, and never caches a Hub copy that a subprocess is
+ about to replace with its transformers sidecar. `--verbose` skips it entirely.
+ """
+ if _BARS_RESTORED:
+ # This process took its bars back on purpose: the export worker shows them, the
+ # training worker reads them out of tqdm._instances (where a disabled bar is
+ # never registered) and has already redirected their output.
+ return
+ if _verbose_logging_requested() and os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS") is None:
+ # --verbose promises everything back, so it must not install this default
+ # either; the flag is inherited by the workers, which would stay quiet.
+ return
+ if os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS") is None:
+ os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
+ # Marks the value as ours rather than the operator's, so a process that needs
+ # bars back (the export worker streams Hub upload progress into the export
+ # dialog) can tell the difference. Inherited by every child process.
+ os.environ[_PROGRESS_BARS_DEFAULTED] = "1"
+ elif not _env_is_true(os.environ["HF_HUB_DISABLE_PROGRESS_BARS"]):
+ # Operator asked to keep them; leave every library alone.
+ return
+
+ # Only touch Hub if something already imported it. Importing it here would cache
+ # the base environment's copy before a subprocess prepends its transformers
+ # sidecar to sys.path, leaving that process on an incompatible Hub.
+ if "huggingface_hub" in sys.modules:
+ try:
+ from huggingface_hub.utils import disable_progress_bars
+ disable_progress_bars()
+ except Exception: # noqa: BLE001 — quieting logs must never break startup
+ pass
+
+ # transformers derives its own _tqdm_active from the hub flag at import time,
+ # so a module imported BEFORE this ran still needs the explicit call.
+ #
+ # datasets is handled separately (see _silence_datasets_bar_output): its `Map:` and
+ # `Standardizing chat format (num_proc=8):` bars from dataset preparation were the
+ # ones actually landing inside JSON records, but the UI reads their counter, so
+ # only the output goes. datasets is imported long after logging setup, which is why
+ # this function is safe to call again once a library is in.
+ for _mod in ("transformers", "diffusers"):
+ module = sys.modules.get(_mod)
+ if module is None:
+ continue
+ try:
+ module.utils.logging.disable_progress_bar()
+ except Exception: # noqa: BLE001
+ pass
+ _silence_datasets_bar_output()
+
+
class LogConfig:
"""Structured logging configuration for the application."""
@staticmethod
def setup_logging(
- service_name: str = "unsloth-studio-backend", env: Optional[str] = None
+ service_name: str = "unsloth-studio-backend",
+ env: Optional[str] = None,
+ quiet_progress_bars: bool = True,
) -> structlog.BoundLogger:
"""Configure structured logging for the application.
Args:
service_name: Name of the service for logging identification
env: Environment (development/production), affects logging format
+ quiet_progress_bars: Turn third-party tqdm bars off. False for a process
+ whose stdout is a user-facing progress stream (the export worker).
"""
# Log level from environment; fall back to INFO if invalid.
log_level_name = os.getenv("LOG_LEVEL", "INFO").upper()
@@ -163,6 +401,10 @@ class LogConfig:
cache_logger_on_first_use = True,
)
+ # Silence third-party tqdm bars; they carry no signal and corrupt JSON records.
+ if quiet_progress_bars:
+ quiet_third_party_progress_bars()
+
# Drop transformers' cosmetic "`torch_dtype` is deprecated" warning_once (see filter).
_dtype_filter = _DropTorchDtypeDeprecation()
for _name in (
diff --git a/studio/backend/tests/test_status_only_progress_replay.py b/studio/backend/tests/test_status_only_progress_replay.py
new file mode 100644
index 00000000000..fcd4e9215a0
--- /dev/null
+++ b/studio/backend/tests/test_status_only_progress_replay.py
@@ -0,0 +1,117 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A status-only update must not replay the previous step's metrics.
+
+UnslothTrainer keeps metrics and status on one TrainingProgress and notifies its
+callbacks on every change, so publishing an evaluation status carries the last
+logged step's loss, learning rate, grad norm and eval loss along with it. The
+parent appends every progress event to loss_history / grad_norm_history /
+eval_loss_history and to the metric buffer it persists, without deduplicating the
+step, so a long evaluation would plot the same point once per status line.
+"""
+
+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))
+
+
+class _Progress:
+ """The fields _create_trainer_progress_callback reads off TrainingProgress."""
+
+ def __init__(self, **fields):
+ self.step = 0
+ self.total_steps = 0
+ self.loss = None
+ self.learning_rate = None
+ self.grad_norm = None
+ self.num_tokens = None
+ self.epoch = None
+ self.eval_loss = None
+ self.elapsed_seconds = None
+ self.status_message = ""
+ for key, value in fields.items():
+ setattr(self, key, value)
+
+
+def _emitter():
+ """The publish rule from worker._create_trainer_progress_callback, returning the
+ steps it would have published as metric events."""
+ last_metrics: list = [None]
+ published: list = []
+
+ def _on_progress(p) -> None:
+ has_train_loss = p.step > 0 and p.loss is not None
+ has_eval_loss = p.eval_loss is not None
+ metrics = (
+ p.step,
+ p.loss,
+ p.learning_rate,
+ p.grad_norm,
+ p.num_tokens,
+ p.epoch,
+ p.eval_loss,
+ )
+ is_repeat = metrics == last_metrics[0]
+ if (
+ (p.step == 0 and p.total_steps > 0) or has_train_loss or has_eval_loss
+ ) and not is_repeat:
+ last_metrics[0] = metrics
+ published.append(p.step)
+
+ return _on_progress, published
+
+
+def test_evaluation_status_lines_do_not_replot_the_last_step():
+ # A 4-minute evaluation after step 200 publishes a status roughly every 15s; each
+ # one arrives with step 200's loss still on the shared progress object.
+ on_progress, published = _emitter()
+ step_200 = _Progress(step = 200, total_steps = 1000, loss = 0.42, learning_rate = 1e-4)
+ on_progress(step_200)
+ for seen in (8, 24, 40, 56):
+ step_200.status_message = f"Evaluating... {seen} batches"
+ step_200.elapsed_seconds = 900.0 + seen
+ on_progress(step_200)
+ step_200.status_message = "Training in progress..."
+ on_progress(step_200)
+ assert published == [200]
+
+
+def test_a_new_step_is_still_published():
+ on_progress, published = _emitter()
+ on_progress(_Progress(step = 200, total_steps = 1000, loss = 0.42))
+ on_progress(_Progress(step = 201, total_steps = 1000, loss = 0.41))
+ assert published == [200, 201]
+
+
+def test_the_same_step_with_a_new_measurement_is_still_published():
+ # Evaluation ends and reports eval_loss while global_step has not moved yet; that
+ # is a real new number, not a replay.
+ on_progress, published = _emitter()
+ on_progress(_Progress(step = 200, total_steps = 1000, loss = 0.42))
+ on_progress(_Progress(step = 200, total_steps = 1000, loss = 0.42, eval_loss = 0.55))
+ assert published == [200, 200]
+
+
+def test_a_warning_mid_run_does_not_replot_either():
+ # _record_warning notifies the same callbacks with the metrics untouched.
+ on_progress, published = _emitter()
+ progress = _Progress(step = 12, total_steps = 100, loss = 1.5, grad_norm = 0.9)
+ on_progress(progress)
+ on_progress(progress)
+ assert published == [12]
+
+
+def test_the_worker_publishes_only_changed_measurements():
+ text = (_BACKEND / "core/training/worker.py").read_text(encoding = "utf-8")
+ body = text[text.index("def _create_trainer_progress_callback") :]
+ body = body[: body.index("def _create_embedding_progress_callback")]
+ assert "is_repeat = metrics == last_metrics[0]" in body
+ assert "and not is_repeat" in body
+ # Wall-clock fields move on every call and would defeat the comparison.
+ assert "progress.elapsed_seconds," not in body[: body.index("event_queue.put")]
diff --git a/studio/backend/tests/test_third_party_progress_bars.py b/studio/backend/tests/test_third_party_progress_bars.py
new file mode 100644
index 00000000000..d477a833bcd
--- /dev/null
+++ b/studio/backend/tests/test_third_party_progress_bars.py
@@ -0,0 +1,338 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Quieting third-party tqdm bars must not take anything real with it.
+
+The bars themselves carry no signal in a log with no terminal, but three things
+ride along with them and have to survive: the export dialog's live Hub upload
+progress, the "Applying chat template ... 42%" status the UI derives from the
+datasets bar's counter, and an operator's explicit choice.
+"""
+
+from __future__ import annotations
+
+import subprocess
+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 loggers import config as log_config # noqa: E402
+
+_HUB = "HF_HUB_DISABLE_PROGRESS_BARS"
+
+
+def test_the_default_is_installed_and_marked(monkeypatch):
+ monkeypatch.setattr(log_config, "_BARS_RESTORED", False)
+ monkeypatch.delenv(_HUB, raising = False)
+ monkeypatch.delenv(log_config._PROGRESS_BARS_DEFAULTED, raising = False)
+ monkeypatch.delenv("UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS", raising = False)
+ monkeypatch.delenv("UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS", raising = False)
+
+ log_config.quiet_third_party_progress_bars()
+
+ import os
+
+ assert os.environ[_HUB] == "1"
+ assert os.environ[log_config._PROGRESS_BARS_DEFAULTED] == "1"
+
+
+def test_verbose_leaves_the_bars_alone(monkeypatch):
+ # --verbose zeroes both access-log windows and promises everything back; the flag
+ # is inherited by the workers, so setting it here would keep them quiet anyway.
+ monkeypatch.setattr(log_config, "_BARS_RESTORED", False)
+ monkeypatch.delenv(_HUB, raising = False)
+ monkeypatch.setenv("UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS", "0")
+ monkeypatch.setenv("UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS", "0")
+
+ log_config.quiet_third_party_progress_bars()
+
+ import os
+
+ assert _HUB not in os.environ
+
+
+def test_hugging_face_false_spellings_are_honored(monkeypatch):
+ # The Hub reads only 1/ON/YES/TRUE as true, so "off" and "no" ask to keep bars.
+ monkeypatch.setattr(log_config, "_BARS_RESTORED", False)
+ monkeypatch.delenv("UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS", raising = False)
+ monkeypatch.delenv("UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS", raising = False)
+ for value in ("off", "no", "0", "false", ""):
+ monkeypatch.setenv(_HUB, value)
+ called = []
+ monkeypatch.setattr(log_config, "_silence_datasets_bar_output", lambda: called.append(1))
+ log_config.quiet_third_party_progress_bars()
+ assert called == [], value
+
+
+def test_the_hub_is_not_imported_just_to_quiet_it():
+ # A worker calls setup_logging BEFORE prepending its transformers sidecar to
+ # sys.path; importing the Hub here would cache the base environment's copy.
+ code = (
+ "import sys; sys.path.insert(0, %r)\n"
+ "import os\n"
+ "os.environ.pop('HF_HUB_DISABLE_PROGRESS_BARS', None)\n"
+ "os.environ.pop('UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS', None)\n"
+ "os.environ.pop('UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS', None)\n"
+ "from loggers.config import quiet_third_party_progress_bars\n"
+ "quiet_third_party_progress_bars()\n"
+ "print('HUB_IMPORTED' if 'huggingface_hub' in sys.modules else 'HUB_ABSENT')\n"
+ ) % str(_BACKEND)
+ out = subprocess.run([sys.executable, "-c", code], capture_output = True, text = True, timeout = 300)
+ assert "HUB_ABSENT" in out.stdout, out.stdout + out.stderr
+
+
+def test_allow_progress_bars_only_undoes_our_own_default(monkeypatch):
+ monkeypatch.setattr(log_config, "_BARS_RESTORED", False)
+ monkeypatch.setenv(_HUB, "1")
+ monkeypatch.setenv(log_config._PROGRESS_BARS_DEFAULTED, "1")
+ log_config.allow_progress_bars()
+ import os
+
+ assert _HUB not in os.environ
+
+ # An operator who set it themselves keeps it.
+ monkeypatch.setenv(_HUB, "1")
+ monkeypatch.delenv(log_config._PROGRESS_BARS_DEFAULTED, raising = False)
+ log_config.allow_progress_bars()
+ assert os.environ[_HUB] == "1"
+
+
+def test_the_export_worker_keeps_its_progress_bars():
+ text = (_BACKEND / "core/export/worker.py").read_text(encoding = "utf-8")
+ assert "allow_progress_bars()" in text
+ assert "quiet_progress_bars = False" in text
+
+
+def test_the_datasets_bar_keeps_counting_but_writes_nothing(capfd):
+ # chat_templates.py polls tqdm._instances for the formatting status, and
+ # datasets' own disable_progress_bar() forces tqdm(disable = True), which never
+ # registers the bar at all.
+ import datasets # noqa: F401
+ from datasets.utils.tqdm import tqdm as ds_bar
+ from tqdm.auto import tqdm as base_tqdm
+
+ log_config._silence_datasets_bar_output()
+ bar = ds_bar(total = 10, desc = "Applying chat template")
+ try:
+ bar.update(4)
+ instances = [b for b in list(getattr(base_tqdm, "_instances", set())) if b is bar]
+ assert instances, "the bar must stay registered for the UI status poller"
+ assert instances[0].n == 4
+ finally:
+ bar.close()
+ captured = capfd.readouterr()
+ assert "Applying chat template" not in captured.out + captured.err
+
+
+def test_silencing_the_datasets_bar_twice_is_harmless():
+ from datasets.utils.tqdm import tqdm as ds_bar
+
+ log_config._silence_datasets_bar_output()
+ first = ds_bar.__init__
+ log_config._silence_datasets_bar_output()
+ assert ds_bar.__init__ is first
+
+
+def test_trainer_summary_metrics_are_republished():
+ text = (_BACKEND / "core/training/trainer.py").read_text(encoding = "utf-8")
+ assert "trainer summary" in text
+ for key in ("train_samples_per_second", "train_steps_per_second", "total_flos"):
+ assert key in text, key
+
+
+def test_setup_time_is_never_reported_as_throughput():
+ # elapsed_seconds covers imports, the model load and the dataset build, and on a
+ # resume the counters predate this process, so the first line reports no rate at
+ # all and the second one measures a real in-training interval.
+ text = (_BACKEND / "core/training/training.py").read_text(encoding = "utf-8")
+ assert "The first logged line reports no throughput on purpose" in text
+ assert "_progress_run_resumed" not in text
+
+
+def test_the_early_dataset_branches_are_covered():
+ # The raw-text and audio-VLM branches run their own filter/map and return before
+ # the chat-template path, so the suppression has to come before them.
+ text = (_BACKEND / "core/training/trainer.py").read_text(encoding = "utf-8")
+ quiet_at = text.index("quiet_third_party_progress_bars()")
+ assert quiet_at < text.index("# ========== AUDIO MODELS: custom preprocessing ==========")
+ assert quiet_at < text.index("# ========== FORMAT FIRST ==========")
+
+
+def test_the_dataset_load_itself_is_covered():
+ # load_dataset() draws "Generating train split" and download/extract bars of its
+ # own, on both the local-file and the Hub branch, so the suppression has to come
+ # before the first load and not just before the map/filter work that follows it.
+ text = (_BACKEND / "core/training/trainer.py").read_text(encoding = "utf-8")
+ body = text[text.index(" def load_and_format_dataset(") :]
+ assert body.index("quiet_third_party_progress_bars()") < body.index("= load_dataset(")
+ # The class-level patch needs datasets in sys.modules, which the module-level
+ # import guarantees for every caller of this method.
+ assert "\nfrom datasets import Dataset\n" in text
+
+
+def test_the_diffusion_trainers_quiet_diffusers_once_it_is_imported():
+ # diffusers is imported inside the two training entrypoints, not at module level,
+ # so the child-process call runs while it is still absent from sys.modules and
+ # cannot reach it. The pipeline load that draws "Loading pipeline components..."
+ # happens further down the same function.
+ entrypoints = {
+ "diffusion_lora_trainer.py": "def run_diffusion_lora_training(",
+ "diffusion_dit_trainer.py": "def _train_dit(",
+ }
+ for name, entrypoint in entrypoints.items():
+ text = (_BACKEND / "core/training" / name).read_text(encoding = "utf-8")
+ body = text[text.index(entrypoint) :]
+ assert body.index("from diffusers") < body.index("quiet_third_party_progress_bars()"), name
+
+
+def test_the_precache_helper_restores_rather_than_enables():
+ text = (_BACKEND / "utils/datasets/llm_assist.py").read_text(encoding = "utf-8")
+ assert "if not _bars_were_off:" in text
+ assert "_bars_were_off = bool(are_progress_bars_disabled())" in text
+
+
+def test_the_video_loader_quiets_diffusers_too():
+ text = (_BACKEND / "core/inference/video.py").read_text(encoding = "utf-8")
+ assert "quiet_third_party_progress_bars()" in text
+
+
+def test_our_own_conversion_bars_are_redirected(monkeypatch):
+ monkeypatch.setenv(_HUB, "1")
+ assert "file" in log_config.quiet_bar_kwargs()
+ monkeypatch.setenv(_HUB, "off")
+ assert log_config.quiet_bar_kwargs() == {}
+ monkeypatch.delenv(_HUB, raising = False)
+ assert log_config.quiet_bar_kwargs() == {}
+
+ text = (_BACKEND / "utils/datasets/format_conversion.py").read_text(encoding = "utf-8")
+ assert text.count("**_quiet_bar_kwargs(),") == 2
+
+
+def test_the_embedding_trainer_is_quiet_too():
+ # _run_embedding_training bypasses UnslothTrainer entirely.
+ text = (_BACKEND / "core/training/worker.py").read_text(encoding = "utf-8")
+ assert '"disable_tqdm": _hf_stdout_progress_disabled(),' in text
+ assert "_drop_hf_stdout_callbacks(trainer)" in text
+
+
+def test_the_diffusion_training_child_quiets_diffusers():
+ # That child never runs setup_logging, and diffusers honours no env var.
+ text = (_BACKEND / "core/training/diffusion_training_service.py").read_text(encoding = "utf-8")
+ assert "quiet_third_party_progress_bars()" in text
+
+
+def test_embedding_runs_republish_the_trainer_summary():
+ text = (_BACKEND / "core/training/worker.py").read_text(encoding = "utf-8")
+ body = text[text.index("class _EmbeddingProgressCallback") :]
+ assert "trainer summary" in body
+
+
+def test_evaluation_progress_survives_the_dropped_bar():
+ # ProgressCallback's per-batch eval bar was the only sign a long evaluation was
+ # moving; the replacement has to publish it as status and a structured line.
+ text = (_BACKEND / "core/training/trainer.py").read_text(encoding = "utf-8")
+ assert "def on_prediction_step(" in text
+ assert '"evaluating"' in text
+ assert "Evaluating..." in text
+
+
+def test_evaluation_progress_is_throttled_and_counts():
+ """The throttle from _ProgressCallback.on_prediction_step, in isolation.
+
+ Importing the trainer module pulls in unsloth and torch, so the rule is checked
+ the same way the throughput one is.
+ """
+
+ def report(
+ seen,
+ last_report,
+ now,
+ window = 15.0,
+ ):
+ return not (last_report and (now - last_report) < window)
+
+ assert report(1, 0.0, 100.0) is True # first batch always reports
+ assert report(2, 100.0, 101.0) is False # a second later, still quiet
+ assert report(900, 100.0, 116.0) is True # 16s later, one more line
+
+
+def test_the_embedding_worker_quiets_dataset_bars():
+ text = (_BACKEND / "core/training/worker.py").read_text(encoding = "utf-8")
+ body = text[text.index("def _run_embedding_training") :]
+ assert "quiet_third_party_progress_bars()" in body
+
+
+def test_evaluation_hands_the_status_back_to_training():
+ # An empty status is ignored downstream, so the UI would sit on "Evaluating..."
+ # for the rest of the run.
+ text = (_BACKEND / "core/training/trainer.py").read_text(encoding = "utf-8")
+ on_evaluate = text[text.index("def on_evaluate(") : text.index("def on_prediction_step(")]
+ assert "Training in progress..." in on_evaluate
+
+
+def test_the_training_worker_keeps_its_bars_countable():
+ # It polls tqdm._instances to turn the Hub download and "Loading checkpoint shards"
+ # bars into the UI status, and a disabled bar is never registered there. The call
+ # must also precede setup_logging: huggingface_hub reads the env var once, into a
+ # module constant, and refuses to re-enable afterwards.
+ text = (_BACKEND / "core/training/worker.py").read_text(encoding = "utf-8")
+ assert text.index("keep_progress_bars_countable()") < text.index(
+ 'service_name = "unsloth-studio-training-worker"'
+ )
+
+
+def test_bars_stay_registered_once_the_worker_takes_them_back(monkeypatch, capfd):
+ monkeypatch.setattr(log_config, "_BARS_RESTORED", False)
+ monkeypatch.setenv(_HUB, "1")
+ monkeypatch.setenv(log_config._PROGRESS_BARS_DEFAULTED, "1")
+ from tqdm.auto import tqdm as base_tqdm
+ from tqdm.std import tqdm as std_tqdm
+
+ # The redirect patches the shared tqdm class, so put it back for the other tests.
+ monkeypatch.setattr(std_tqdm, "__init__", std_tqdm.__init__)
+ monkeypatch.setattr(std_tqdm, "_unsloth_every_output_silenced", False, raising = False)
+
+ log_config.keep_progress_bars_countable()
+ import os
+
+ assert _HUB not in os.environ
+ # A later quieting call must not undo it; the poller would go blind.
+ log_config.quiet_third_party_progress_bars()
+ assert _HUB not in os.environ
+
+ bar = base_tqdm(total = 10, desc = "model-00002-of-00004.safetensors")
+ try:
+ bar.update(6)
+ assert bar in list(getattr(base_tqdm, "_instances", set()))
+ assert bar.n == 6
+ finally:
+ bar.close()
+ captured = capfd.readouterr()
+ assert "model-00002-of-00004.safetensors" not in captured.out + captured.err
+
+
+def test_an_operator_who_turned_bars_off_keeps_them_off(monkeypatch):
+ # Only Studio's own default is ever taken back.
+ monkeypatch.setattr(log_config, "_BARS_RESTORED", False)
+ monkeypatch.setenv(_HUB, "1")
+ monkeypatch.delenv(log_config._PROGRESS_BARS_DEFAULTED, raising = False)
+
+ log_config.keep_progress_bars_countable()
+
+ import os
+
+ assert os.environ[_HUB] == "1"
+ assert log_config._BARS_RESTORED is False
+
+
+def test_the_shared_dataset_loader_quiets_the_bars_it_just_imported():
+ # The server never imports datasets at boot, so setup_logging cannot patch the bar
+ # class; this shared entry point is the first place it exists.
+ text = (_BACKEND / "utils/datasets/cache_safe.py").read_text(encoding = "utf-8")
+ body = text[text.index("def load_dataset_cache_safe") :]
+ assert body.index("from datasets import load_dataset") < body.index(
+ "quiet_third_party_progress_bars()"
+ )
diff --git a/studio/backend/tests/test_trainer_stdout_quiet.py b/studio/backend/tests/test_trainer_stdout_quiet.py
new file mode 100644
index 00000000000..93d678554f9
--- /dev/null
+++ b/studio/backend/tests/test_trainer_stdout_quiet.py
@@ -0,0 +1,98 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""HF's own stdout progress reporting must not be teed into the server log.
+
+The training subprocess has no terminal: its stdout goes into the server log. HF
+writes a tqdm bar there (ProgressCallback) or, with disable_tqdm, a raw dict per
+step (PrinterCallback). Over one 58 minute session that was 1095 bar lines and 266
+raw step dicts, and because tqdm and the structlog JSON writer share the stream with
+no line discipline, 152 records ended up unparseable.
+
+Everything those lines carry is already published twice: the throttled
+`training_progress` event from #7087 and the per-step SSE stream the UI charts.
+`unsloth studio --verbose` restores both.
+"""
+
+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))
+
+import pytest # noqa: E402
+
+from core.training import trainer as tmod # noqa: E402
+
+_VERBOSE_ENV = (
+ "UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS",
+ "UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS",
+)
+
+
[email protected](autouse = True)
+def _clean_env(monkeypatch):
+ for name in _VERBOSE_ENV:
+ monkeypatch.delenv(name, raising = False)
+
+
+class _FakeTrainer:
+ def __init__(self):
+ self.removed = []
+
+ def remove_callback(self, cls):
+ self.removed.append(cls)
+
+
+def test_bars_are_disabled_by_default():
+ assert tmod._hf_stdout_progress_disabled() is True
+
+
+def test_verbose_restores_the_bars(monkeypatch):
+ for name in _VERBOSE_ENV:
+ monkeypatch.setenv(name, "0")
+ assert tmod._verbose_logging_requested() is True
+ assert tmod._hf_stdout_progress_disabled() is False
+
+
+def test_only_zeroing_both_windows_counts_as_verbose(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS", "0")
+ monkeypatch.setenv("UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS", "10000")
+ assert tmod._verbose_logging_requested() is False
+
+
+def test_unparseable_env_is_not_verbose(monkeypatch):
+ for name in _VERBOSE_ENV:
+ monkeypatch.setenv(name, "not-a-number")
+ assert tmod._verbose_logging_requested() is False
+
+
+def test_both_stdout_callbacks_are_removed():
+ from transformers.trainer_callback import PrinterCallback, ProgressCallback
+
+ fake = _FakeTrainer()
+ tmod._drop_hf_stdout_callbacks(fake)
+ assert set(fake.removed) == {PrinterCallback, ProgressCallback}
+
+
+def test_verbose_keeps_the_callbacks(monkeypatch):
+ for name in _VERBOSE_ENV:
+ monkeypatch.setenv(name, "0")
+ fake = _FakeTrainer()
+ tmod._drop_hf_stdout_callbacks(fake)
+ assert fake.removed == []
+
+
+def test_a_trainer_that_rejects_removal_does_not_raise():
+ class _Hostile:
+ def remove_callback(self, cls):
+ raise RuntimeError("no callbacks here")
+
+ tmod._drop_hf_stdout_callbacks(_Hostile()) # must not propagate
+
+
+def test_a_trainer_without_remove_callback_does_not_raise():
+ tmod._drop_hf_stdout_callbacks(object())
diff --git a/studio/backend/tests/test_training_progress_throughput.py b/studio/backend/tests/test_training_progress_throughput.py
new file mode 100644
index 00000000000..882bc9bbddc
--- /dev/null
+++ b/studio/backend/tests/test_training_progress_throughput.py
@@ -0,0 +1,85 @@
+# 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 must carry trainer speed, not just step and loss.
+
+Dropping HF's tqdm bar and per-step print removes the only place training
+throughput appeared ("1.84s/it" on the bar, "train_tokens_per_second" in the raw
+dict). Both were raw stdout rather than structured, so the replacement is to put
+the number on the structured line: throughput measured over the interval between
+two logged lines, and the run average on the first one.
+"""
+
+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 _throughput(step, prev_step, elapsed, prev_elapsed, tokens, prev_tokens):
+ """The calculation from TrainingManager._log_training_progress."""
+ s_per_step = tok_per_s = None
+ if elapsed is not None and prev_elapsed is not None and prev_step >= 0:
+ d_time = elapsed - prev_elapsed
+ d_steps = step - prev_step
+ if d_time > 0 and d_steps > 0:
+ s_per_step = round(d_time / d_steps, 3)
+ if tokens is not None and prev_tokens is not None and tokens > prev_tokens:
+ tok_per_s = round((tokens - prev_tokens) / d_time, 1)
+ return s_per_step, tok_per_s
+
+
+def test_the_first_line_reports_no_throughput():
+ # elapsed_seconds is wall time since the worker started, so it also covers the
+ # imports, the model download and load and the dataset build; and on a resumed run
+ # the step and token counters predate this process. Neither is a training rate.
+ assert _throughput(4, -1, 8.0, None, 4000, None) == (None, None)
+ assert _throughput(1010, -1, 20.0, None, 4_000_000, None) == (None, None)
+
+
+def test_later_lines_report_the_interval_not_the_average():
+ # 10 steps and 20000 tokens in the 20s since the last line, after a slow start.
+ s_per_step, tok_per_s = _throughput(30, 20, 120.0, 100.0, 60000, 40000)
+ assert s_per_step == 2.0
+ assert tok_per_s == 1000.0
+
+
+def test_matches_the_tqdm_number_it_replaces():
+ # The bar showed "1.84s/it"; one step in 1.84s must report the same.
+ s_per_step, _ = _throughput(19, 18, 38.34, 36.50, None, None)
+ assert s_per_step == 1.84
+
+
+def test_missing_token_counts_still_give_seconds_per_step():
+ s_per_step, tok_per_s = _throughput(30, 20, 120.0, 100.0, None, None)
+ assert s_per_step == 2.0
+ assert tok_per_s is None
+
+
+def test_no_elapsed_yields_nothing_rather_than_dividing_by_zero():
+ assert _throughput(30, 20, None, None, 1, 0) == (None, None)
+
+
+def test_a_repeated_or_backwards_step_yields_nothing():
+ assert _throughput(20, 20, 120.0, 100.0, 60000, 40000) == (None, None)
+ assert _throughput(19, 20, 120.0, 100.0, 60000, 40000) == (None, None)
+
+
+def test_a_stalled_clock_yields_nothing():
+ assert _throughput(30, 20, 100.0, 100.0, 60000, 40000) == (None, None)
+
+
+def test_token_counter_that_did_not_move_still_gives_seconds_per_step():
+ s_per_step, tok_per_s = _throughput(30, 20, 120.0, 100.0, 40000, 40000)
+ assert s_per_step == 2.0
+ assert tok_per_s is None
+
+
+def test_the_emitter_passes_both_fields():
+ text = (_BACKEND / "core/training/training.py").read_text(encoding = "utf-8")
+ assert "s_per_step = s_per_step," in text
+ assert "tok_per_s = tok_per_s," in text
diff --git a/studio/backend/utils/datasets/cache_safe.py b/studio/backend/utils/datasets/cache_safe.py
index d2dc7b737ac..dc858c7ef1d 100644
--- a/studio/backend/utils/datasets/cache_safe.py
+++ b/studio/backend/utils/datasets/cache_safe.py
@@ -28,6 +28,14 @@ def studio_datasets_cache() -> str:
def load_dataset_cache_safe(*args, **kwargs):
"""datasets.load_dataset, retried in an Unsloth-owned cache on EACCES."""
from datasets import load_dataset
+
+ # datasets is in sys.modules exactly now, which is what lets its bar class be
+ # patched; the server never imports it at boot, so this shared entry point is
+ # where its "Generating train split" bar stops reaching the structured log.
+ from loggers.config import quiet_third_party_progress_bars
+
+ quiet_third_party_progress_bars()
+
try:
return load_dataset(*args, **kwargs)
except PermissionError as error:
diff --git a/studio/backend/utils/datasets/format_conversion.py b/studio/backend/utils/datasets/format_conversion.py
index 9035068c01b..d0811e350a6 100644
--- a/studio/backend/utils/datasets/format_conversion.py
+++ b/studio/backend/utils/datasets/format_conversion.py
@@ -11,6 +11,19 @@ from loggers import get_logger
logger = get_logger(__name__)
+def _quiet_bar_kwargs() -> dict:
+ """Send our own conversion bars to a null stream while the log is quiet.
+
+ They still count (the UI status poller reads tqdm._instances), they just do not
+ write carriage-return fragments beside the worker's structured records.
+ """
+ try:
+ from loggers.config import quiet_bar_kwargs
+ return quiet_bar_kwargs()
+ except Exception: # noqa: BLE001 - a bar is never worth failing a conversion for
+ return {}
+
+
def standardize_chat_format(
dataset,
tokenizer = None,
@@ -611,7 +624,13 @@ def convert_to_vlm_format(
_notify(progress_msg)
else:
# Sequential conversion for local/embedded images (no I/O bottleneck)
- pbar = tqdm(dataset, total = total, desc = "Converting VLM samples", unit = "sample")
+ pbar = tqdm(
+ dataset,
+ total = total,
+ desc = "Converting VLM samples",
+ unit = "sample",
+ **_quiet_bar_kwargs(),
+ )
for sample in pbar:
try:
converted_list.append(_convert_single_sample(sample))
@@ -832,7 +851,13 @@ def convert_sharegpt_with_images_to_vlm_format(
converted_list = []
failed_count = 0
- pbar = tqdm(dataset, total = total, desc = "Converting ShareGPT+image", unit = "sample")
+ pbar = tqdm(
+ dataset,
+ total = total,
+ desc = "Converting ShareGPT+image",
+ unit = "sample",
+ **_quiet_bar_kwargs(),
+ )
for sample in pbar:
try:
converted_list.append(_convert_single_sample(sample))
diff --git a/studio/backend/utils/datasets/llm_assist.py b/studio/backend/utils/datasets/llm_assist.py
index 42236b7f8a2..5f30d3b9bb7 100644
--- a/studio/backend/utils/datasets/llm_assist.py
+++ b/studio/backend/utils/datasets/llm_assist.py
@@ -52,14 +52,23 @@ def precache_helper_gguf():
if os.environ.get("UNSLOTH_HELPER_MODEL_DISABLE", "").strip() in ("1", "true"):
return
+ _bars_were_off = False
repo = os.environ.get("UNSLOTH_HELPER_MODEL_REPO", DEFAULT_HELPER_MODEL_REPO)
variant = os.environ.get("UNSLOTH_HELPER_MODEL_VARIANT", DEFAULT_HELPER_MODEL_VARIANT)
try:
from huggingface_hub import HfApi, hf_hub_download
- from huggingface_hub.utils import disable_progress_bars, enable_progress_bars
+ from huggingface_hub.utils import (
+ are_progress_bars_disabled,
+ disable_progress_bars,
+ enable_progress_bars,
+ )
from utils.hf_cache_settings import active_hf_hub_cache
+ # Remember whether bars were already off. Studio turns them off for the whole
+ # server, so enabling them unconditionally on the way out would undo that for
+ # every later in-process download.
+ _bars_were_off = bool(are_progress_bars_disabled())
disable_progress_bars()
logging.getLogger("huggingface_hub").setLevel(logging.WARNING)
@@ -89,8 +98,9 @@ def precache_helper_gguf():
logger.warning(f"Failed to pre-cache helper GGUF: {e}")
finally:
try:
- enable_progress_bars()
- except Exception as e:
+ if not _bars_were_off:
+ enable_progress_bars()
+ except Exception:
pass