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 video: size the VAE decode from free memory after the denoiser offload (wider tiles, same clip whether the CUDA graph is kept or dropped) (#15464)
Daniel Han63939abd1453
diff --git a/studio/backend/core/inference/video_vae_untiled.py b/studio/backend/core/inference/video_vae_untiled.pyindex 0ff44b71575..58740b5c8fd 100644--- a/studio/backend/core/inference/video_vae_untiled.py+++ b/studio/backend/core/inference/video_vae_untiled.py@@ -180,6 +180,50 @@ def _in_chain(fn: Any, target: Any) -> bool:return False+# Under model CPU offload the denoiser is still on the card until the VAE's hook runs inside decode. "0" = old behaviour.+FREE_AFTER_OFFLOAD_ENV = "UNSLOTH_VIDEO_VAE_FREE_AFTER_OFFLOAD"+++def _free_after_offload_enabled() -> bool:+ return os.environ.get(FREE_AFTER_OFFLOAD_ENV, "").strip().lower() not in (+ "0",+ "false",+ "no",+ "off",+ )+++def _on_device(module: Any) -> bool:+ try:+ first = next(iter(module.parameters()), None)+ except Exception: # noqa: BLE001+ return False+ return first is not None and first.device.type != "cpu"+++def run_offload_hook_first(vae: Any, logger: Any = None) -> bool:+ """Run the VAE's offload pre-hook before the fit check so it sees the decode's free memory (the decode's own hook+ call then moves nothing). True when the hook ran."""+ if not _free_after_offload_enabled():+ return False+ hook = getattr(vae, "_hf_hook", None)+ if hook is None or "CpuOffload" not in type(hook).__name__:+ return False+ pre_forward = getattr(hook, "pre_forward", None)+ if not callable(pre_forward):+ return False+ prev_model = getattr(getattr(hook, "prev_module_hook", None), "model", None)+ if not (prev_model is not None and _on_device(prev_model)) and _on_device(vae):+ return False+ try:+ pre_forward(vae)+ except Exception as exc: # noqa: BLE001 - the decode's own hook call still moves them+ if logger is not None:+ logger.debug("video.vae_untiled: offload hook before the fit check failed (%s)", exc)+ return False+ return True++def _decode_device(vae: Any, z: Any) -> Any:"""Where the decode allocates: the latent's card, unless a multi-GPU split put the VAE on another CUDA card (itsboundary moves the latent there inside this wrapper). An offloaded VAE (weights on the host) keeps the latent's."""@@ -337,6 +381,7 @@ def install_untiled_decode(def untiled_when_fits(*args: Any, **kwargs: Any) -> Any:try:+ run_offload_hook_first(vae, logger)return gated(*args, **kwargs)finally:# A failed VAE compile restores its eager decode into this slot; the guarded inner call already runs eager.diff --git a/studio/backend/tests/test_video_vae_untiled.py b/studio/backend/tests/test_video_vae_untiled.pyindex d709b46a0de..cf3ddc010a5 100644--- a/studio/backend/tests/test_video_vae_untiled.py+++ b/studio/backend/tests/test_video_vae_untiled.py@@ -200,3 +200,82 @@ def test_free_bytes_does_not_count_graph_held_cache(monkeypatch):monkeypatch.setattr(dm, "user_budget_reserve_bytes", lambda device, total: 0)monkeypatch.setattr(dm, "_graph_held_cache_bytes", lambda device = None: 500 * 2**20)assert U._free_bytes(torch.device("cuda", 0)) == 1100 * 2**20+++class CpuOffload:+ def __init__(+ self,+ prev_model,+ vae,+ fail = False,+ ):+ self.prev_module_hook = types.SimpleNamespace(model = prev_model)+ self.vae = vae+ self.fail = fail+ self.calls = 0++ def pre_forward(self, module, *args, **kwargs):+ self.calls += 1+ if self.fail:+ raise RuntimeError("hook")+ self.prev_module_hook.model.to_empty(device = "cpu")+ return args, kwargs+++class HookedVAE(FakeVAE):+ def parameters(self):+ return self.decoder.parameters()++ def decode(+ self,+ z,+ return_dict = False,+ ):+ self._hf_hook.pre_forward(self)+ return super().decode(z, return_dict = return_dict)+++def _offloaded_pipe(fail = False):+ denoiser = torch.nn.Linear(4, 4, device = "meta") # "on the card": any non-host device+ vae = HookedVAE()+ vae._hf_hook = CpuOffload(denoiser, vae, fail = fail)+ need = U.untiled_decode_bytes(WAN, tuple(Z.shape))+ big = int(need * U._MARGIN + U._MARGIN_BYTES) + 2**30++ def free(device):+ resident = next(denoiser.parameters()).device.type != "cpu"+ return big - 8 * 2**30 if resident else big++ return vae, denoiser, free+++def test_fit_check_reads_free_memory_after_the_denoiser_offload(monkeypatch):+ vae, denoiser, free = _offloaded_pipe()+ monkeypatch.setattr(U, "_free_bytes", free)+ assert U.install_untiled_decode(_pipe(vae), WAN)+ assert vae.decode(Z) == ("untiled",)+ assert next(denoiser.parameters()).device.type == "cpu"+ # once here, then the decode's own hook call (which finds everything in place)+ assert vae._hf_hook.calls == 2+ assert vae.calls == [False]+++def test_fit_check_offload_kill_switch_reads_before_the_hook(monkeypatch):+ monkeypatch.setenv(U.FREE_AFTER_OFFLOAD_ENV, "0")+ vae, _denoiser, free = _offloaded_pipe()+ monkeypatch.setattr(U, "_free_bytes", free)+ assert U.install_untiled_decode(_pipe(vae), WAN)+ assert vae.decode(Z) == ("tiled",)+ assert vae._hf_hook.calls == 1+++def test_fit_check_skips_the_hook_once_offloaded_and_survives_a_failing_hook(monkeypatch):+ vae, denoiser, free = _offloaded_pipe()+ denoiser.to_empty(device = "cpu")+ vae.decoder = vae.decoder.to("meta") # the VAE already on the card+ assert U.run_offload_hook_first(vae) is False+ assert vae._hf_hook.calls == 0+ failing, _d, free = _offloaded_pipe(fail = True)+ assert U.run_offload_hook_first(failing) is False+ plain = FakeVAE()+ assert U.run_offload_hook_first(plain) is False