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: decode the VAE untiled on CPU hosts when it fits in RAM (Wan2.2 VAE decode 1.5x) (#16766)
Daniel Han73984c4b35c2
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex b3452a0adc9..711aaa923b7 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -668,8 +668,10 @@ def _ltx23_prequant_pick(def _decodes_untiled_when_fits(family: str, offload_policy: str, device: str, speed: str) -> bool:"""Untiled when it fits (free memory read at decode time); not under sequential offload, nor on SPEED_OFF- (bit-identical) except Cosmos3, whose reference pipeline decodes untiled (stock tiles seam at 480 / 832 px)."""- if device != "cuda" or offload_policy not in (+ (bit-identical) except Cosmos3, whose reference pipeline decodes untiled (stock tiles seam at 480 / 832 px).+ On a CPU host "fits" is usable host RAM: the stock tiles recompute their overlaps (Wan2.2 at 896x512: 15 tiles+ covering 1.6x the frame's pixels), and the decode is the slowest stage there."""+ if device not in ("cuda", "cpu") or offload_policy not in (OFFLOAD_NONE,OFFLOAD_MODEL,OFFLOAD_GROUP,diff --git a/studio/backend/core/inference/video_ltx2_vae_tiles.py b/studio/backend/core/inference/video_ltx2_vae_tiles.pyindex 720edc5ed44..210cc895740 100644--- a/studio/backend/core/inference/video_ltx2_vae_tiles.py+++ b/studio/backend/core/inference/video_ltx2_vae_tiles.py@@ -249,7 +249,7 @@ def tiled_decode("""Decode ``z`` in the tiles ``plan_tiles`` picks; on OOM, once more in the stock-size 16-latent tiles."""from diffusers.models.autoencoders.vae import DecoderOutput- from .diffusion_batched import is_oom_error+ from .video_vae_untiled import _is_oom # CPU allocator refusals too: tiles plan from host RAM(th, tw), budgeted = _plan(vae, z)floor = (min(MIN_TILE_LATENTS, int(z.shape[-2])), min(MIN_TILE_LATENTS, int(z.shape[-1])))@@ -261,7 +261,7 @@ def tiled_decode(try:dec = _decode_tiles(vae, z, temb, causal, th, tw, budgeted)except Exception as exc: # noqa: BLE001- if (th, tw) == floor or not is_oom_error(exc):+ if (th, tw) == floor or not _is_oom(exc):raisefailed = Trueif failed and oom_free_first(vae, z):@@ -271,7 +271,7 @@ def tiled_decode(try:dec = _decode_tiles(vae, z, temb, causal, th, tw, budgeted)except Exception as exc: # noqa: BLE001- if not is_oom_error(exc):+ if not _is_oom(exc):raisefailed = Trueif failed:diff --git a/studio/backend/core/inference/video_vae_untiled.py b/studio/backend/core/inference/video_vae_untiled.pyindex 58740b5c8fd..a94eef1aefa 100644--- a/studio/backend/core/inference/video_vae_untiled.py+++ b/studio/backend/core/inference/video_vae_untiled.py@@ -155,7 +155,14 @@ def _decoder_itemsize(vae: Any) -> int:def _free_bytes(device: Any) -> Optional[int]:- """Device free memory plus torch's reusable cache (not CUDA graph pools), less the user's VRAM Budget reserve (raw at the default)."""+ """Free device memory + torch's reusable cache (not graph pools) minus the VRAM Budget reserve; CPU: cgroup-capped MemAvailable."""+ if getattr(device, "type", device) == "cpu":+ try:+ from .diffusion_memory import _available_system_memory_mib+ mib = _available_system_memory_mib()+ except Exception: # noqa: BLE001+ return None+ return None if mib is None else max(0, int(mib)) * 2**20try:import torch@@ -168,6 +175,12 @@ def _free_bytes(device: Any) -> Optional[int]:return None+def _is_oom(exc: BaseException) -> bool:+ """A device OOM, or the CPU allocator's ``not enough memory`` (raised e.g. on Windows commit limits)."""+ from .diffusion_batched import is_oom_error+ return is_oom_error(exc) or "not enough memory" in str(exc).lower()++def _in_chain(fn: Any, target: Any) -> bool:for _ in range(16):if fn is None:@@ -325,14 +338,12 @@ def install_untiled_decode()import torch- from .diffusion_batched import is_oom_error-try:out = decode(z, *args, **kwargs)stats["wide"] += 1return outexcept Exception as exc: # noqa: BLE001- if not is_oom_error(exc):+ if not _is_oom(exc):raisefinally:(@@ -354,15 +365,13 @@ def install_untiled_decode(return decode(z, *args, **kwargs)import torch- from .diffusion_batched import is_oom_error-vae.use_tiling = Falsetry:out = decode(z, *args, **kwargs)stats["untiled"] += 1return outexcept Exception as exc: # noqa: BLE001- if not is_oom_error(exc):+ if not _is_oom(exc):raisefinally:vae.use_tiling = Truediff --git a/studio/backend/tests/test_vae_tile_geometry.py b/studio/backend/tests/test_vae_tile_geometry.pyindex c08f84f9e0a..7b2bbedf727 100644--- a/studio/backend/tests/test_vae_tile_geometry.py+++ b/studio/backend/tests/test_vae_tile_geometry.py@@ -5,12 +5,14 @@from __future__ import annotations+import contextlibimport functoolsimport importlibimport jsonimport refrom dataclasses import dataclassfrom pathlib import Path+from unittest import mockimport pytest@@ -293,6 +295,21 @@ def _latent_channels(config: dict) -> int:return 16+def _no_memory_reading():+ """Probe the grid a decode takes with no free-memory reading: the smallest tiles, the same on every host.++ Budgeted planners (video_ltx2_vae_tiles) widen tiles, or go untiled, when the reading says they fit; on a CPU+ host that reading is host RAM, so an unpinned probe would see whatever the runner has free.+ """+ mod = _module("video_vae_untiled")+ if mod is None or not hasattr(mod, "_free_bytes"):+ yield+ return+ with mock.patch.object(mod, "_free_bytes", lambda device: None):+ yield++def probe_axis(vae, config: dict, length: int, other: int, video: bool) -> list[tuple[int, int]]:c = _latent_channels(config)for frames in (1, 2, 4, 8) if video else (None,):@@ -300,7 +317,7 @@ def probe_axis(vae, config: dict, length: int, other: int, video: bool) -> list[rec = _TileRecorder(shape[-2:])_ACTIVE.append(rec)try:- with rec, torch.no_grad():+ with rec, _no_memory_reading(), torch.no_grad():vae.decode(torch.zeros(shape), return_dict = False)return sorted(rec.axes[0])except Exception as exc: # noqa: BLE001 - a frame count the VAE's temporal chunking refuses@@ -471,3 +488,19 @@ def test_probe_reads_the_stock_grid():assert applied == []tiles = probe_axis(vae, {"z_dim": 16}, 64, 8, True)assert tiles == [(0, 32), (24, 56), (48, 64)]+++def test_probe_ignores_free_host_memory(monkeypatch):+ """A CPU host whose RAM fits the whole frame decodes LTX-2 untiled; the probe must still read the tiled grid."""+ untiled = pytest.importorskip("core.inference.video_vae_untiled")+ ltx = pytest.importorskip("core.inference.video_ltx2_vae_tiles")+ monkeypatch.setattr(untiled, "_free_bytes", lambda device: 1 << 50)+ kind, config = _family_configs()["ltx-2"]+ vae, applied = build_vae(config, kind)+ assert "video_ltx2_vae_tiles" in applied+ length = max(_sides("ltx-2")) // _ratio(vae)+ z = torch.zeros(1, _latent_channels(config), 1, length, length, device = "meta")+ # The planner itself takes the reading: one tile covering the frame.+ assert ltx.plan_tiles(vae, z) == (length, length)+ tiles = probe_axis(vae, config, length, max(1, MIN_SIDE // _ratio(vae)), True)+ assert len(tiles) >= 2, tilesdiff --git a/studio/backend/tests/test_video_cosmos3.py b/studio/backend/tests/test_video_cosmos3.pyindex a789c26cdba..520091b3b74 100644--- a/studio/backend/tests/test_video_cosmos3.py+++ b/studio/backend/tests/test_video_cosmos3.py@@ -1080,8 +1080,10 @@ def test_cosmos3_decodes_untiled_when_it_fits_even_at_speed_off(policy, speed):placed = policy != "sequential"for family in ("cosmos3-edge", "cosmos3-nano"):assert gate(family, policy, "cuda", speed) is placed- assert gate(family, policy, "cpu", speed) is False- assert gate("wan2.2-ti2v-5b", policy, "cuda", speed) is (placed and speed != "off")+ assert gate(family, policy, "cpu", speed) is placed+ assert gate(family, policy, "mps", speed) is False+ for device in ("cuda", "cpu"):+ assert gate("wan2.2-ti2v-5b", policy, device, speed) is (placed and speed != "off")def _diffusers_tiles(length, tile, stride):diff --git a/studio/backend/tests/test_video_ltx2_vae_tiles.py b/studio/backend/tests/test_video_ltx2_vae_tiles.pyindex fe06ccc8a8f..7d83687aaf5 100644--- a/studio/backend/tests/test_video_ltx2_vae_tiles.py+++ b/studio/backend/tests/test_video_ltx2_vae_tiles.py@@ -131,7 +131,19 @@ def test_temb_and_causal_reach_every_tile(free):assert len(seen) > 1 and all(t is temb and c is False for t, c in seen)-def test_oom_retries_in_stock_size_tiles(free, monkeypatch):+ "error",+ [+ lambda: torch.cuda.OutOfMemoryError("fake"),+ # CPU tiles plan from host RAM; Windows refuses past its commit limit with this, not an OOM type+ lambda: RuntimeError(+ "[enforce fail at alloc_cpu.cpp:117] data. DefaultCPUAllocator: not enough memory: "+ "you tried to allocate 123 bytes."+ ),+ ],+ ids = ["cuda", "cpu_allocator"],+)+def test_oom_retries_in_stock_size_tiles(free, monkeypatch, error):vae = _ltx_vae()z = torch.randn(1, 8, 1, 22, 38)vae.enable_tiling()@@ -151,7 +163,7 @@ def test_oom_retries_in_stock_size_tiles(free, monkeypatch):):calls.append((th, tw, fp32_accum))if len(calls) == 1:- raise torch.cuda.OutOfMemoryError("fake")+ raise error()return real(vae_, z_, temb, causal, th, tw, fp32_accum)monkeypatch.setattr(vt, "_decode_tiles", flaky)diff --git a/studio/backend/tests/test_video_vae_untiled.py b/studio/backend/tests/test_video_vae_untiled.pyindex cf3ddc010a5..a96ce406539 100644--- a/studio/backend/tests/test_video_vae_untiled.py+++ b/studio/backend/tests/test_video_vae_untiled.py@@ -202,6 +202,46 @@ def test_free_bytes_does_not_count_graph_held_cache(monkeypatch):assert U._free_bytes(torch.device("cuda", 0)) == 1100 * 2**20+def test_free_bytes_on_a_cpu_host_reads_usable_host_ram(monkeypatch):+ import core.inference.diffusion_memory as dm++ monkeypatch.setattr(+ torch.cuda, "mem_get_info", lambda device = None: pytest.fail("no CUDA read for a CPU decode")+ )+ monkeypatch.setattr(dm, "_available_system_memory_mib", lambda: 40 * 1024)+ assert U._free_bytes(torch.device("cpu")) == 40 * 2**30+ assert U._free_bytes("cpu") == 40 * 2**30+ monkeypatch.setattr(dm, "_available_system_memory_mib", lambda: None)+ assert U._free_bytes(torch.device("cpu")) is None+++def test_cpu_decode_untiled_only_when_host_ram_fits(monkeypatch):+ import core.inference.diffusion_memory as dm++ z = torch.zeros(1, 48, 2, 32, 56) # Wan2.2 896x512, 5 frames+ need = U.untiled_decode_bytes(WAN, tuple(z.shape), itemsize = 4)+ gate_mib = int((need * U._MARGIN + U._MARGIN_BYTES) / 2**20)+ vae = FakeVAE(dtype = torch.float32)+ U.install_untiled_decode(_pipe(vae), WAN)+ monkeypatch.setattr(dm, "_available_system_memory_mib", lambda: gate_mib + 1)+ assert vae.decode(z) == ("untiled",)+ monkeypatch.setattr(dm, "_available_system_memory_mib", lambda: gate_mib - 1)+ assert vae.decode(z) == ("tiled",)+ assert vae.use_tiling is True+++def test_cpu_allocator_refusal_falls_back_to_tiled(monkeypatch):+ monkeypatch.setattr(U, "_free_bytes", lambda device: 100 * 2**30)+ err = RuntimeError(+ "[enforce fail at alloc_cpu.cpp:121] DefaultCPUAllocator: not enough memory: you tried to allocate 9663676416 bytes."+ )+ vae = FakeVAE(error = err)+ U.install_untiled_decode(_pipe(vae), WAN)+ assert vae.decode(Z) == ("tiled",)+ assert vae.calls == [False, True]+ assert vae.use_tiling is True++class CpuOffload:def __init__(self,