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
Unsloth Studio: report the VAE decode on the image progress bar (#11740)
Leo Borcherding195d8dd0905d
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 8f4bdd1c2b8..cdac7bf05b2 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -132,6 +132,7 @@ from .diffusion_memory import (vae_is_sliced,)from .diffusion_torchao_patches import install_torchao_int_mm_patch+from .media_decode_phase import decode_phasefrom .diffusion_speed import (SPEED_DEFAULT,SPEED_EAGER,@@ -1118,6 +1119,8 @@ class _GenState:first_step_at: float = 0.0# Computed once per step (in the callback) so it's stable between polls.eta_seconds: Optional[float] = None+ # "decode" once pipe() enters its decoder, which runs after the last step callback.+ phase: str = "denoise"def _estimate_eta(total_steps: int, step: int, first_step_at: float, now: float) -> Optional[float]:@@ -8888,6 +8891,13 @@ class DiffusionBackend:# diffusers resets FBCache only after a SUCCESSFUL __call__; a raised call leaves a stale residual.self._reset_step_cache(state.pipe)protect_ctx = protect_generation(pipe, denoise_steps, logger = logger)+ # Per chunk: a later chunk denoises again after an earlier one decoded.+ gen.phase = "denoise"++ def _enter_decode_phase(gen = gen) -> None:+ gen.phase = "decode"+ gen.eta_seconds = None+try:# torchao aten.to fails torch's aliasing check under inference_mode; model offload moves weights.with (@@ -8898,6 +8908,7 @@ class DiffusionBackend:else torch.inference_mode()),protect_ctx,+ decode_phase(pipe, _enter_decode_phase),):out = render_thread.run("diffusion", lambda: pipe(**chunk_kwargs).images@@ -9060,6 +9071,7 @@ class DiffusionBackend:"total_steps": 0,"fraction": 0.0,"eta_seconds": None,+ "phase": "denoise",}return {"active": True,@@ -9067,6 +9079,7 @@ class DiffusionBackend:"total_steps": gen.total_steps,"fraction": gen.step / gen.total_steps, # step is 1..total, never over 1.0"eta_seconds": gen.eta_seconds,+ "phase": gen.phase,}def cancel_generate(self, expected_account: Optional[str] = None) -> bool:diff --git a/studio/backend/core/inference/media_decode_phase.py b/studio/backend/core/inference/media_decode_phase.pynew file mode 100644index 00000000000..3fc13857429--- /dev/null+++ b/studio/backend/core/inference/media_decode_phase.py@@ -0,0 +1,61 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Detect when a diffusion pipeline leaves its denoise loop and enters the decoder."""++from __future__ import annotations++import contextlib+from typing import Any++DECODE_ATTRS = ("vae", "audio_vae")+++def decode_phase(+ pipe: Any,+ on_decode: Any,+ attrs: "tuple[str, ...]" = DECODE_ATTRS,+):+ """Call ``on_decode`` (at most once, must not raise) when a decoder is first entered.++ The decode runs inside ``pipe()`` after the last step callback, so nothing outside can see it.+ This is a HOST position: denoise kernels may still be queued, so a caller moving the step count+ must treat it as a boundary mark (``_CompletedStepTicker.mark_boundary``). Wrappers are removed+ on every exit, restoring any compiled decode the speed layer put in the instance ``__dict__``.+ """+ fired = {"done": False}+ restore: list = []++ def _wrap(original: Any):+ def _decode(*args: Any, **kwargs: Any) -> Any:+ if not fired["done"]:+ fired["done"] = True+ on_decode()+ return original(*args, **kwargs)++ return _decode++ for name in attrs:+ owner = getattr(pipe, name, None)+ original = getattr(owner, "decode", None) if owner is not None else None+ if not callable(original):+ continue+ had_own = "decode" in getattr(owner, "__dict__", {})+ try:+ owner.decode = _wrap(original)+ except Exception: # noqa: BLE001 -- a decoder that refuses assignment goes unreported+ continue+ restore.append((owner, original, had_own))+ try:+ yield+ finally:+ for owner, original, had_own in restore:+ try:+ if had_own:+ owner.decode = original+ else:+ # A parked bound method would be a reference cycle back to the module.+ del owner.decode+ except Exception: # noqa: BLE001 -- cleanup is best-effort+ passdiff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 129353a7a4c..78565c610f2 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -100,6 +100,7 @@ from .diffusion_memory import (settled_snapshot_device_memory,)from .diffusion_torchao_patches import install_torchao_int_mm_patch+from .media_decode_phase import decode_phase as _decode_phasefrom . import diffusion_render_thread as render_threadfrom .diffusion_speed import (SPEED_DEFAULT,@@ -734,74 +735,10 @@ def _completed_step_poller(pump: Any, poll_seconds: float = 0.1):thread.join(timeout = 2.0)-# The decoders a video pipeline may run after its denoise loop, in the order the modular MiniMax-H3-# workflow runs them. Wrapping the bound method is the one hook every family shares.-_DECODE_ATTRS = ("vae", "audio_vae")--# How hard the end-of-denoise marker tries before it gives up and flips the phase at the host-# position. The hold-off refuses without blocking, so most refusals are the 10 Hz poller holding-# the lock for a couple of event queries; 20 tries 20 ms apart covers several poll ticks and costs-# nothing when uncontended, while a real capture outlasts it and takes the host-position fallback._BOUNDARY_MARK_ATTEMPTS = 20_BOUNDARY_MARK_RETRY_SECONDS = 0.02-def _decode_phase(pipe: Any, on_decode: Any):- """Flip the reported phase to "decode" the instant the decoder is entered.-- HunyuanVideo-1.5, Wan and MiniMax-H3's modular workflow all run the decode INSIDE the pipeline- call with nothing between the denoise loop and it, so a phase set only after ``pipe()`` returns- reports the whole decode as the last denoise step. On H3 that decode plus its post-processing- is ~3.9 s of the render, and the VAE decode is the memory peak.-- Note what this hook is and is not: it is the one HOST position that knows the denoise loop is- over, and nothing more. On a family where the host runs ahead of the device, the denoise- kernels can still be queued when it fires, so the caller must treat it as "mark the boundary",- not as "the denoise finished" -- see ``_CompletedStepTicker.mark_boundary``.-- ``on_decode`` fires at most once per generation and must not raise. Every wrapper installed- here is removed again, including when the decode raises -- and restored to whatever was there,- since the speed layer may have already put a compiled decode in the instance ``__dict__``.- """- fired = {"done": False}- restore: list = []-- def _wrap(original: Any):- def _decode(*args: Any, **kwargs: Any) -> Any:- if not fired["done"]:- fired["done"] = True- on_decode()- return original(*args, **kwargs)-- return _decode-- for name in _DECODE_ATTRS:- owner = getattr(pipe, name, None)- original = getattr(owner, "decode", None) if owner is not None else None- if not callable(original):- continue- had_own = "decode" in getattr(owner, "__dict__", {})- try:- owner.decode = _wrap(original)- except Exception: # noqa: BLE001 -- a decoder that refuses assignment goes unreported- continue- restore.append((owner, original, had_own))- try:- yield- finally:- for owner, original, had_own in restore:- try:- if had_own:- owner.decode = original- else:- # Nothing was shadowing the class method, so leave nothing behind -- a bound- # method parked in a module's __dict__ is a reference cycle back to the module.- del owner.decode- except Exception: # noqa: BLE001 -- cleanup is best-effort- pass--def _assert_pick_is_not_speech(repo_id: str,gguf_filename: Optional[str],diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex b1147b74b15..fb2ac7c5305 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -4372,6 +4372,9 @@ class DiffusionGenerateProgressResponse(BaseModel):total_steps: int = Field(0, description = "Total denoising steps for this run")fraction: float = Field(0.0, description = "step / total_steps, clamped to [0,1]")eta_seconds: Optional[float] = Field(None, description = "Estimated seconds remaining")+ phase: Optional[str] = Field(+ None, description = "denoise | decode; null from engines that report no phase (sd.cpp)"+ )class DiffusionLoadProgressResponse(BaseModel):diff --git a/studio/backend/tests/test_image_decode_phase.py b/studio/backend/tests/test_image_decode_phase.pynew file mode 100644index 00000000000..99400c42120--- /dev/null+++ b/studio/backend/tests/test_image_decode_phase.py@@ -0,0 +1,83 @@+# 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 image bar reports the decode, which runs inside pipe() after the last step callback."""++from __future__ import annotations++import pytest++from core.inference.media_decode_phase import decode_phase+++class _Vae:+ def __init__(self):+ self.calls = 0++ def decode(self, latents):+ self.calls += 1+ return f"decoded:{latents}"+++class _Pipe:+ def __init__(self):+ self.vae = _Vae()+++def test_the_hook_fires_on_the_first_decode_and_not_again():+ pipe, seen = _Pipe(), []+ with decode_phase(pipe, lambda: seen.append("decode")):+ assert pipe.vae.decode("a") == "decoded:a"+ assert pipe.vae.decode("b") == "decoded:b"+ assert seen == ["decode"]+ assert pipe.vae.calls == 2+++def test_the_wrapper_is_removed_even_when_the_decode_raises():+ """A leftover wrapper would fire a finished job's callback on the next generation."""+ pipe = _Pipe()+ boom = RuntimeError("vae oom")++ def _raise(_latents):+ raise boom++ pipe.vae.decode = _raise+ with pytest.raises(RuntimeError):+ with decode_phase(pipe, lambda: None):+ pipe.vae.decode("a")+ assert pipe.vae.decode is _raise+++def test_a_pipe_with_no_decoder_is_a_no_op():+ class _Bare:+ pass++ with decode_phase(_Bare(), lambda: pytest.fail("fired with no decoder")):+ pass+++def test_generate_progress_reports_the_phase():+ from core.inference.diffusion import _GenState++ gen = _GenState(total_steps = 40)+ assert gen.phase == "denoise"++ class _Backend:+ _gen = gen++ from core.inference.diffusion import DiffusionBackend++ progress = DiffusionBackend.generate_progress(_Backend())+ assert progress["phase"] == "denoise"++ gen.step, gen.phase = 40, "decode"+ progress = DiffusionBackend.generate_progress(_Backend())+ assert progress["phase"] == "decode"+ # The route returns this model; a field it lacks is dropped silently and the UI never sees it.+ from models.inference import DiffusionGenerateProgressResponse++ assert DiffusionGenerateProgressResponse(**progress).phase == "decode"+ assert DiffusionGenerateProgressResponse(active = False).phase is None++ _Backend._gen = None+ assert DiffusionBackend.generate_progress(_Backend())["phase"] == "denoise"diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 469172b66ad..0d5f96acf54 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -93,6 +93,8 @@ export interface DiffusionGenerateProgress {total_steps: number;fraction: number;eta_seconds: number | null;+ // Absent (sd.cpp engine) means "denoise".+ phase?: "denoise" | "decode" | null;}export interface DiffusionLoadProgress {diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex fb77e42e146..526521ff838 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -547,6 +547,7 @@ function formatTimestamp(epochSeconds: number): string {function genStepLabel(p: DiffusionGenerateProgress): string {// Text encoding happens before the first scheduler tick, so step 0 means "working, not denoising yet".if (p.step === 0) return "Preparing (text encoding + warmup)…";+ if (p.phase === "decode") return "Decoding…";const base = `Step ${p.step}/${p.total_steps}`;const eta = p.eta_seconds != null ? formatEta(p.eta_seconds) : "";return eta ? `${base} · ~${eta}` : base;@@ -2527,7 +2528,7 @@ export function ImagesPage({return;}setGenStep((prev) => {- if (prev && prev.step === p.step && prev.eta_seconds === p.eta_seconds) return prev;+ if (prev && prev.step === p.step && prev.eta_seconds === p.eta_seconds && prev.phase === p.phase) return prev;return p;});} catch {@@ -4090,7 +4091,7 @@ export function ImagesPage({// Skip the state update (and re-render) when nothing the bar shows moved.setGenStep((prev) => {if (!p.active) return null;- if (prev && prev.step === p.step && prev.eta_seconds === p.eta_seconds) return prev;+ if (prev && prev.step === p.step && prev.eta_seconds === p.eta_seconds && prev.phase === p.phase) return prev;return p;});} catch {