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: size seam-free VAE tiles from measured peaks (no slower than stock, no low-VRAM OOM) (#12764)

Daniel Han1fb38f991ed9
diff --git a/studio/backend/core/inference/diffusion_vae_fused.py b/studio/backend/core/inference/diffusion_vae_fused.py
index 6437a431cf4..a55f47150a9 100644
--- a/studio/backend/core/inference/diffusion_vae_fused.py
+++ b/studio/backend/core/inference/diffusion_vae_fused.py
@@ -1111,7 +1111,7 @@ def uninstall(vae: Any) -> None:
for m in vae.modules():
if isinstance(getattr(m, "processor", None), FusedSingleHeadProcessor):
m.processor = m.processor.fallback
- for attr in ("tiled_decode", "blend_v", "blend_h", "blend_t"):
+ for attr in ("tiled_decode", "blend_v", "blend_h", "blend_t", "_unsloth_wide_stock_decode"):
if getattr(vae.__dict__.get(attr), "_unsloth_vae_fused", False):
delattr(vae, attr)
for module in vae.modules():
@@ -1607,9 +1607,11 @@ def _stock_tiled_decode_clamps(cls: type) -> Optional[bool]:
def install_wan_tile_batch(vae: Any, logger: Any = None) -> bool:
+ # Under the wide tiles the batched loop only backs their stock-tile fallback.
+ wide = vae is not None and bool(getattr(vae, "_unsloth_wide_tiles", False))
if (
vae is None
- or "tiled_decode" in vae.__dict__
+ or ("tiled_decode" in vae.__dict__ and not wide)
or not callable(getattr(vae, "tiled_decode", None))
):
return False
@@ -1635,6 +1637,9 @@ def install_wan_tile_batch(vae: Any, logger: Any = None) -> bool:
return stock(z, return_dict = return_dict)
tiled_decode._unsloth_vae_fused = True
+ if wide:
+ vae._unsloth_wide_stock_decode = tiled_decode
+ return False
vae.tiled_decode = tiled_decode
return True
diff --git a/studio/backend/core/inference/diffusion_vae_tiling.py b/studio/backend/core/inference/diffusion_vae_tiling.py
index a8241c5e296..cc527276a39 100644
--- a/studio/backend/core/inference/diffusion_vae_tiling.py
+++ b/studio/backend/core/inference/diffusion_vae_tiling.py
@@ -25,7 +25,7 @@ OVERLAP_LATENTS = 16
# Blend: a tile gets no weight within MARGIN latents of an edge it shares, then ramps to full over RAMP latents.
MARGIN_LATENTS = 4
RAMP_LATENTS = 8
-# Encode: a 1024 px reference image (Studio's default) is one tile, bit-identical to the untiled encode.
+# Encode: a 1024 px reference is one tile (bit-identical); the encoder attends over the whole tile.
ENCODE_TILE_LATENTS = 64
ENCODE_OVERLAP_LATENTS = 32
ENCODE_MARGIN_LATENTS = 8
@@ -93,13 +93,60 @@ def _decode_tile(vae: Any, z: Any) -> Any:
vae.use_tiling = prev
-# Unfused bf16 decode peak per latent of tile area at 16x (1,697 MiB at 32x32); other ratios scale by tile pixels.
+# bf16 decode peak MiB per latent of tile area, (unfused, fused): worst measured tile side 8 to 128, real weights.
+# Per class (VAEs of one ratio differ 2x); an unmeasured class takes its ratio's worst.
+DECODE_MIB_PER_LATENT_BY_CLASS = {
+ "AutoencoderKLQwenImage": (0.27, 0.18),
+ "AutoencoderKLQwenImage21": (1.7, 0.43),
+ "AutoencoderKLHunyuanImage": (1.3, 1.3),
+ "AutoencoderKL": (0.17, 0.09),
+ "AutoencoderKLFlux2": (0.17, 0.09),
+}
+DECODE_MIB_PER_LATENT_BY_RATIO = {8: (0.27, 0.18), 16: (1.7, 0.43), 32: (1.3, 1.3)}
DECODE_MIB_PER_LATENT = 1.7
DECODE_MIB_RATIO = 16
FREE_FRACTION = 0.75
MAX_TILE_ENV = "UNSLOTH_DIFFUSION_VAE_MAX_TILE"
+def decode_mib_per_latent(
+ ratio: int,
+ fused: bool = False,
+ cls: Optional[str] = None,
+) -> float:
+ """bf16 decode peak MiB per latent: by class, else ratio, else the 16x figure scaled by tile pixels."""
+ known = DECODE_MIB_PER_LATENT_BY_CLASS.get(cls or "") or DECODE_MIB_PER_LATENT_BY_RATIO.get(
+ int(ratio)
+ )
+ if known is not None:
+ return known[1] if fused else known[0]
+ return DECODE_MIB_PER_LATENT * (int(ratio) / DECODE_MIB_RATIO) ** 2
+
+
+def _geometry(vae: Any) -> tuple[int, int, int]:
+ """(ratio, floor tile, floor overlap), cached on the VAE at install."""
+ cached = getattr(vae, "__dict__", {}).get("_unsloth_wide_geometry")
+ if cached is not None:
+ return cached
+ ratio = compression_ratio(vae)
+ tile, overlap = floor_tiles(vae)
+ return ratio, tile, overlap
+
+
+def _cached_axis_weights(
+ vae: Any, starts: list[int], tile: int, length: int, ratio: int, torch: Any, device: Any
+):
+ """``axis_weights`` memoised per VAE (a repeat decode syncs no device)."""
+ cache = vae.__dict__.setdefault("_unsloth_wide_weights", {}) if hasattr(vae, "__dict__") else {}
+ key = (tuple(starts), int(tile), int(length), int(ratio), str(device))
+ hit = cache.get(key)
+ if hit is None:
+ if len(cache) >= 64:
+ cache.clear()
+ hit = cache[key] = axis_weights(starts, tile, length, ratio, torch, device)
+ return hit
+
+
def _axis_tiles(
length: int,
count: int,
@@ -113,24 +160,67 @@ def _axis_tiles(
return side if side < length else None
+def _stock_span(length: int, tile: int, overlap: int) -> int:
+ """Latents diffusers' stock loop decodes along one side: a tile every ``tile - overlap``, the last cut short."""
+ if length <= tile:
+ return length
+ return sum(min(tile, length - s) for s in range(0, length, tile - overlap))
+
+
+def _large_stock_sides(length: int, tile: int, overlap: int) -> list[int]:
+ """Per tile count, the smallest covering side and the widest decoding no more latents than the stock loop."""
+ if length <= tile:
+ return [length]
+ span = _stock_span(length, tile, overlap)
+ out = {length}
+ for n in range(2, len(tile_starts(length, tile, overlap)) + 1):
+ low = _axis_tiles(length, n, TILE_LATENTS, overlap)
+ if low is None:
+ continue
+ out.add(low)
+ for side in range(min(span // n, length - 1), low, -1):
+ if len(tile_starts(length, side, overlap)) * side <= span:
+ out.add(side)
+ break
+ return sorted(out)
+
+
def choose_tiles(
height: int,
width: int,
max_area: Optional[int],
tile: int = TILE_LATENTS,
overlap: int = OVERLAP_LATENTS,
+ stock_tile: int = 0,
) -> tuple[int, int]:
- """Tile (height, width) in latents decoding the fewest latents (overlaps counted) within ``max_area``; ``tile`` floor."""
+ """Tile (height, width) in latents within ``max_area`` (at least the floor tile). Stock tiles under the floor:
+ fewest decoded latents. Stock tile == floor (AutoencoderKL, FLUX.2 edge sliver): fewest calls, then largest
+ tile, never decoding more latents per side than stock (1600 px: two 120-latent tiles, not 128 + 104 + 8)."""
floor = (min(tile, height), min(tile, width))
if max_area is None or max_area <= floor[0] * floor[1]:
- return floor
+ max_area = floor[0] * floor[1]
+ if stock_tile >= tile > TILE_LATENTS:
+ best, best_key = None, None
+ for th in _large_stock_sides(height, tile, overlap):
+ for tw in _large_stock_sides(width, tile, overlap):
+ if th * tw > max_area:
+ continue
+ key = (
+ len(tile_starts(height, th, overlap)) * len(tile_starts(width, tw, overlap)),
+ -th * tw,
+ )
+ if best_key is None or key < best_key:
+ best, best_key = (th, tw), key
+ if best is not None:
+ return best
+ side_min = min(tile, TILE_LATENTS)
best, best_cost = floor, None
sides_h = [
- _axis_tiles(height, n, tile, overlap)
+ _axis_tiles(height, n, side_min, overlap)
for n in range(1, len(tile_starts(height, tile, overlap)) + 1)
]
sides_w = [
- _axis_tiles(width, n, tile, overlap)
+ _axis_tiles(width, n, side_min, overlap)
for n in range(1, len(tile_starts(width, tile, overlap)) + 1)
]
for th in sides_h:
@@ -149,30 +239,81 @@ def choose_tiles(
return best
+def _free_mib(
+ vae: Any,
+ z: Any,
+ cached: bool = True,
+) -> Optional[tuple[float, float]]:
+ """(free MiB after the fp32 output accumulator, decoder bytes per param / 2); None off CUDA."""
+ import torch
+
+ if getattr(z, "device", None) is None or z.device.type != "cuda":
+ return None
+ free, _ = torch.cuda.mem_get_info(z.device)
+ if cached:
+ free += torch.cuda.memory_reserved(z.device) - torch.cuda.memory_allocated(z.device)
+ ratio = _geometry(vae)[0]
+ frames = z.shape[2] if z.dim() == 5 else 1
+ # fp32 accumulator
+ out_bytes = 4 * 4 * z.shape[0] * frames * z.shape[-2] * z.shape[-1] * ratio * ratio
+ elem = next(vae.decoder.parameters()).element_size()
+ return (free - out_bytes) / 2**20, elem / 2
+
+
+def _fused(vae: Any) -> bool:
+ return bool(getattr(vae, "_unsloth_vae_fused_installed", 0)) and not getattr(
+ vae, "_unsloth_vae_fused_failed", False
+ )
+
+
def decode_tile_budget(vae: Any, z: Any) -> Optional[int]:
"""Largest decode tile area (latents) that fits ``FREE_FRACTION`` of the free VRAM now; None off CUDA."""
raw = (os.environ.get(MAX_TILE_ENV) or "").strip()
if raw.isdigit() and int(raw) > 0:
return int(raw) ** 2
try:
- import torch
-
- if getattr(z, "device", None) is None or z.device.type != "cuda":
+ _, tile, _ = _geometry(vae)
+ # Stock tile == floor: grow only into device-free memory; decoding out of the allocator cache stalled on
+ # flushes (FLUX.1 1600 px, 8 GB tier: 0.21 s vs stock 0.08).
+ stock_tile = vae.__dict__.get("_unsloth_wide_stock_tile") or (stock_tiles(vae) or (0, 0))[0]
+ large_stock = stock_tile >= tile > TILE_LATENTS
+ free = _free_mib(vae, z, cached = not large_stock)
+ if free is None:
return None
- free, _ = torch.cuda.mem_get_info(z.device)
- free += torch.cuda.memory_reserved(z.device) - torch.cuda.memory_allocated(z.device)
- ratio = compression_ratio(vae)
- frames = z.shape[2] if z.dim() == 5 else 1
- # fp32 accumulator
- out_bytes = 4 * 4 * z.shape[0] * frames * z.shape[-2] * z.shape[-1] * ratio * ratio
- elem = next(vae.decoder.parameters()).element_size()
- mib = FREE_FRACTION * (free - out_bytes) / 2**20
- per_latent = DECODE_MIB_PER_LATENT * (ratio / DECODE_MIB_RATIO) ** 2
- return max(0, int(mib / (per_latent * elem / 2)))
+ mib, scale = free
+ per_latent = (
+ decode_mib_per_latent(_geometry(vae)[0], _fused(vae), type(vae).__name__) * scale
+ )
+ return max(0, int(FREE_FRACTION * mib / per_latent))
except Exception: # noqa: BLE001 - unknown budget: the 32-latent tiles the planner budgeted
return None
+def floor_shortfall(vae: Any, z: Any) -> Optional[str]:
+ """Why even the floor tile cannot fit the free VRAM now, else None (also for unknown memory or an explicit
+ max tile). Only VAEs whose stock tile is under the floor can fall short."""
+ if (os.environ.get(MAX_TILE_ENV) or "").strip():
+ return None
+ try:
+ free = _free_mib(vae, z)
+ if free is None:
+ return None
+ mib, scale = free
+ ratio, tile, _ = _geometry(vae)
+ stock = vae.__dict__.get("_unsloth_wide_stock_tile") or (stock_tiles(vae) or (0, 0))[0]
+ if stock >= tile:
+ return None
+ area = min(tile, z.shape[-2]) * min(tile, z.shape[-1])
+ need = area * decode_mib_per_latent(ratio, _fused(vae), type(vae).__name__) * scale
+ except Exception: # noqa: BLE001
+ return None
+ if need <= mib:
+ return None
+ return (
+ f"a {tile}-latent floor tile needs about {need:.0f} MiB and {max(0.0, mib):.0f} MiB is free"
+ )
+
+
def tiled_decode(
vae: Any,
z: Any,
@@ -184,19 +325,19 @@ def tiled_decode(
from diffusers.models.autoencoders.vae import DecoderOutput
height, width = z.shape[-2], z.shape[-1]
- ratio = compression_ratio(vae)
- tile, overlap = floor_tiles(vae)
+ ratio, tile, overlap = _geometry(vae)
if max_area == "auto":
max_area = decode_tile_budget(vae, z)
- th, tw = choose_tiles(height, width, max_area, tile, overlap)
+ stock_tile = vae.__dict__.get("_unsloth_wide_stock_tile") or (stock_tiles(vae) or (0, 0))[0]
+ th, tw = choose_tiles(height, width, max_area, tile, overlap, stock_tile)
vae._unsloth_last_decode_tile = (th, tw, max_area)
hs = tile_starts(height, th, overlap)
ws = tile_starts(width, tw, overlap)
if len(hs) == 1 and len(ws) == 1:
dec = _decode_tile(vae, z)
else:
- wy = axis_weights(hs, th, height, ratio, torch, z.device)
- wx = axis_weights(ws, tw, width, ratio, torch, z.device)
+ wy = _cached_axis_weights(vae, hs, th, height, ratio, torch, z.device)
+ wx = _cached_axis_weights(vae, ws, tw, width, ratio, torch, z.device)
out, dtype = None, None
for i, y in enumerate(hs):
for j, x in enumerate(ws):
@@ -357,6 +498,43 @@ def _wide_encode(vae: Any) -> bool:
)
+def _is_oom(exc: BaseException) -> bool:
+ try:
+ import torch
+ oom = getattr(torch, "OutOfMemoryError", None) or getattr(
+ torch.cuda, "OutOfMemoryError", None
+ )
+ if oom is not None and isinstance(exc, oom):
+ return True
+ except Exception: # noqa: BLE001
+ pass
+ return isinstance(exc, RuntimeError) and "out of memory" in str(exc).lower()
+
+
+def _release_cache(z: Any) -> None:
+ try:
+ import torch
+ if getattr(z, "device", None) is not None and z.device.type == "cuda":
+ torch.cuda.empty_cache()
+ except Exception: # noqa: BLE001
+ pass
+
+
+def _log_stock_fallback(vae: Any, reason: str) -> None:
+ logger = vae.__dict__.get("_unsloth_wide_logger")
+ seen = vae.__dict__.setdefault("_unsloth_wide_fallback_logged", set())
+ kind = reason.split(" ", 3)[:3]
+ key = " ".join(kind)
+ msg = "diffusion.vae_tiling: %s decodes in its stock tiles (seams possible): %s"
+ if logger is None:
+ return
+ if key in seen:
+ logger.debug(msg, type(vae).__name__, reason)
+ else:
+ seen.add(key)
+ logger.warning(msg, type(vae).__name__, reason)
+
+
def install(vae: Any, logger: Any = None) -> bool:
"""Route ``vae``'s tiled decode / encode through the wide tiles where stock falls under the floor. Idempotent;
False when not covered. ``_unsloth_decode_tile_side`` carries the real decode tile side for the memory estimates."""
@@ -371,14 +549,35 @@ def install(vae: Any, logger: Any = None) -> bool:
geometry = stock_tiles(vae)
ratio = compression_ratio(vae)
+ def _stock(z: Any, return_dict: bool) -> Any:
+ fast = vae.__dict__.get("_unsloth_wide_stock_decode")
+ return (fast or stock)(z, return_dict = return_dict)
+
def _tiled_decode(
self: Any,
z: Any,
return_dict: bool = True,
) -> Any:
if wide_tiles_disabled() or stock_layout_ok(geometry, z.shape[-2], z.shape[-1]):
- return stock(z, return_dict = return_dict)
- return tiled_decode(self, z, return_dict = return_dict)
+ return _stock(z, return_dict)
+ # Never trade an OOM for quality: floor tile cannot fit (or OOMs) -> the smaller stock tiles.
+ reason = floor_shortfall(self, z)
+ if reason is None:
+ for max_area in ("auto", 0):
+ try:
+ return tiled_decode(self, z, return_dict = return_dict, max_area = max_area)
+ except Exception as exc: # noqa: BLE001
+ if not _is_oom(exc):
+ raise
+ reason = f"the wide tiles ran out of memory ({type(exc).__name__})"
+ tried = (self.__dict__.get("_unsloth_last_decode_tile") or (0, 0))[:2]
+ # outside the except block, so the failed attempt's tensors are freed
+ _release_cache(z)
+ ratio, tile, _ = _geometry(self)
+ if tuple(tried) == (min(tile, z.shape[-2]), min(tile, z.shape[-1])):
+ break
+ _log_stock_fallback(self, reason)
+ return _stock(z, return_dict)
def _tiled_encode(self: Any, x: Any) -> Any:
if wide_tiles_disabled() or stock_layout_ok(
@@ -388,6 +587,9 @@ def install(vae: Any, logger: Any = None) -> bool:
return tiled_encode(self, x)
vae._unsloth_wide_tiles_own = own
+ vae._unsloth_wide_geometry = (ratio, *floor_tiles(vae))
+ vae._unsloth_wide_stock_tile = geometry[0]
+ vae._unsloth_wide_logger = logger
vae.tiled_decode = types.MethodType(_tiled_decode, vae)
if _wide_encode(vae):
vae._unsloth_wide_tiles_own_encode = own_encode
@@ -412,6 +614,7 @@ def install(vae: Any, logger: Any = None) -> bool:
def uninstall(vae: Any) -> None:
if not getattr(vae, "_unsloth_wide_tiles", False):
return
+ fast = vae.__dict__.pop("_unsloth_wide_stock_decode", None)
for attr, saved in (
("tiled_decode", "_unsloth_wide_tiles_own"),
("tiled_encode", "_unsloth_wide_tiles_own_encode"),
@@ -427,6 +630,13 @@ def uninstall(vae: Any) -> None:
"_unsloth_wide_tiles_own",
"_unsloth_wide_tiles_own_encode",
"_unsloth_decode_tile_side",
+ "_unsloth_wide_geometry",
+ "_unsloth_wide_weights",
+ "_unsloth_wide_logger",
+ "_unsloth_wide_fallback_logged",
+ "_unsloth_wide_stock_tile",
):
vae.__dict__.pop(name, None)
+ if fast is not None and "tiled_decode" not in vae.__dict__:
+ vae.tiled_decode = fast
vae._unsloth_wide_tiles = False
diff --git a/studio/backend/tests/test_diffusion_vae_tiling_general.py b/studio/backend/tests/test_diffusion_vae_tiling_general.py
index 4d964d632fc..988db8d9b30 100644
--- a/studio/backend/tests/test_diffusion_vae_tiling_general.py
+++ b/studio/backend/tests/test_diffusion_vae_tiling_general.py
@@ -226,7 +226,9 @@ def test_kl_vae_takes_the_wide_tiles_for_an_edge_sliver():
assert vt.stock_layout_ok(vt.stock_tiles(vae), 100, 100) is False
stock_err, wide_err = _line_error(stock, untiled), _line_error(wide, untiled)
assert wide_err < stock_err / 3, (stock_err, wide_err)
- assert vae._unsloth_last_decode_tile[:2] == (64, 64)
+ # two 60-latent tiles per side (120 decoded latents, as many as the stock 64 + 52 + 4, in 2 calls instead of 3),
+ # not two 64s with a 28-latent overlap (128)
+ assert vae._unsloth_last_decode_tile[:2] == (60, 60)
def test_kl_encode_is_untouched_and_qwen_image_encode_is_wide():
@@ -299,32 +301,303 @@ def test_unreadable_geometry_keeps_the_stock_decode():
assert vt.install(vae) is False
[email protected]("ratio", [8, 16, 32])
-def test_decode_budget_scales_with_the_tile_pixels(ratio):
- """1.7 MiB per latent at 16x, the per-pixel figure for every ratio, so Qwen-Image-2.1's budget is unchanged."""
- per_latent = vt.DECODE_MIB_PER_LATENT * (ratio / vt.DECODE_MIB_RATIO) ** 2
- assert per_latent / ratio**2 == pytest.approx(1.7 / 256)
- if ratio == 16:
- assert per_latent == vt.DECODE_MIB_PER_LATENT
-
-
-# Unfused bf16 decode peak over the weights with floor tiles, real diffusers VAE weights on a B200, worst over 1024 to
-# 2048 px canvases (fp32 output accumulator included): the per-pixel budget figure must bound each covered VAE.
-_MEASURED_FLOOR_TILE_PEAK_MIB = {
- (8, 32): 314, # Qwen-Image / Qwen-Image-Edit / Krea-2 (AutoencoderKLQwenImage)
- (16, 32): 1_697, # Qwen-Image-2.1 (AutoencoderKLQwenImage21, #12696)
- (32, 32): 1_332, # HunyuanImage-2.1 (AutoencoderKLHunyuanImage)
- (
- 8,
- 128,
- ): 2_486, # FLUX.1 / FLUX.2 / SDXL (AutoencoderKL, AutoencoderKLFlux2) at an edge-sliver size
+# bf16 decode peak per latent of tile area, (unfused, fused) MiB: one untiled ``_decode`` of a t x t latent, t = 8 to
+# 128, on the real diffusers VAE weights (B200, diffusers 0.41.0.dev0, temp calibration run); the worst side per VAE.
+_MEASURED_MIB_PER_LATENT = {
+ "AutoencoderKLQwenImage": (8, 0.270, 0.179), # Qwen-Image / Qwen-Image-Edit / Krea-2
+ "AutoencoderKLQwenImage21": (
+ 16,
+ 1.650,
+ 0.425,
+ ), # Qwen-Image-2.1 (the 8-latent fused side, 0.59, is never a tile)
+ "AutoencoderKLHunyuanImage": (32, 1.255, 1.255), # HunyuanImage-2.1, no fused path
+ "AutoencoderKL": (8, 0.166, 0.086), # FLUX.1 / Kontext / Z-Image / HiDream / Lumina 2 / SDXL
+ "AutoencoderKLFlux2": (8, 0.166, 0.086), # FLUX.2 / Ideogram 4
}
-def test_budget_figure_bounds_the_measured_floor_tile_peaks():
- for (ratio, tile), peak in _MEASURED_FLOOR_TILE_PEAK_MIB.items():
- budget = vt.DECODE_MIB_PER_LATENT * (ratio / vt.DECODE_MIB_RATIO) ** 2 * tile * tile
- assert budget >= peak, (ratio, tile, budget, peak)
[email protected]("cls", sorted(_MEASURED_MIB_PER_LATENT))
+def test_calibrated_figures_bound_the_measured_peaks_and_are_tight(cls):
+ """Not the old per-pixel scaling (6.8 MiB per latent at 32x, 5x HunyuanImage's peak; 0.43 at 8x, 2.9x
+ AutoencoderKL's): within 10% of each VAE's measured peak (Qwen-Image-2.1: #12696's 1.7), so the free VRAM buys
+ the largest tiles it really holds."""
+ ratio, unfused, fused = _MEASURED_MIB_PER_LATENT[cls]
+ assert unfused <= vt.decode_mib_per_latent(ratio, False, cls) <= 1.1 * unfused
+ assert fused <= vt.decode_mib_per_latent(ratio, True, cls) <= 1.1 * fused
+ # a class not measured takes the worst VAE of its ratio
+ worst = max(u for r, u, _ in _MEASURED_MIB_PER_LATENT.values() if r == ratio)
+ worst_fused = max(f for r, _, f in _MEASURED_MIB_PER_LATENT.values() if r == ratio)
+ assert vt.decode_mib_per_latent(ratio, False, "SomeFutureVAE") >= worst
+ assert vt.decode_mib_per_latent(ratio, True, "SomeFutureVAE") >= worst_fused
+
+
+def test_calibrated_figures_other_ratios():
+ # Qwen-Image-2.1's unfused figure is #12696's
+ assert vt.decode_mib_per_latent(16) == 1.7
+ # an unmeasured ratio keeps the per-pixel scaling of the 16x figure
+ assert vt.decode_mib_per_latent(4) == pytest.approx(1.7 / 16)
+
+
[email protected]("fused", [False, True])
+def test_budget_uses_the_fused_figure_only_where_the_fused_kernels_are_installed(
+ monkeypatch, fused
+):
+ vae = _hunyuan_image()
+ qi = _qwen_image()
+ monkeypatch.delenv(vt.MAX_TILE_ENV)
+ monkeypatch.setattr(vt, "_free_mib", lambda v, z, **k: (1000.0, 1.0))
+ for v in (vae, qi):
+ assert vt.install(v)
+ if fused:
+ v._unsloth_vae_fused_installed = 7
+ z = torch.zeros(1, 4, 1, 64, 64)
+ want = int(vt.FREE_FRACTION * 1000 / (0.18 if fused else 0.27))
+ assert vt.decode_tile_budget(qi, z) == want
+ assert vt.decode_tile_budget(vae, torch.zeros(1, 8, 64, 64)) == int(
+ vt.FREE_FRACTION * 1000 / 1.3
+ )
+ kl = _kl()
+ assert vt.install(kl)
+ if fused:
+ kl._unsloth_vae_fused_installed = 3
+ assert vt.decode_tile_budget(kl, torch.zeros(1, 4, 64, 64)) == int(
+ vt.FREE_FRACTION * 1000 / (0.09 if fused else 0.17)
+ )
+ qi._unsloth_vae_fused_failed = True
+ assert vt.decode_tile_budget(qi, z) == int(vt.FREE_FRACTION * 1000 / 0.27)
+
+
+def test_only_large_stock_tile_vaes_size_past_the_floor_from_device_free_memory(monkeypatch):
+ """AutoencoderKL / FLUX.2 take the wide tiles only to drop a sliver: their tiles grow past the floor only into the
+ device's free memory, not the allocator's cached blocks (an untiled FLUX.1 decode out of the denoiser's cache
+ stalled on cache flushes at 8 GB: 0.21 s median against stock's 0.08). The Wan family and HunyuanImage count the
+ cache, as #12696 does for Qwen-Image-2.1 (it measured faster there)."""
+ monkeypatch.delenv(vt.MAX_TILE_ENV)
+ seen = {}
+
+ def free(
+ v,
+ z,
+ cached = True,
+ ):
+ seen[type(v).__name__] = cached
+ return 1000.0 if cached else 100.0, 1.0
+
+ monkeypatch.setattr(vt, "_free_mib", free)
+ for build, z in (
+ (_kl, torch.zeros(1, 4, 64, 64)),
+ (lambda: _kl(cls = "AutoencoderKLFlux2"), torch.zeros(1, 4, 64, 64)),
+ (_qwen_image, torch.zeros(1, 4, 1, 64, 64)),
+ (_qwen_image_21, torch.zeros(1, 4, 1, 64, 64)),
+ (_hunyuan_image, torch.zeros(1, 8, 64, 64)),
+ ):
+ vae = build()
+ assert vt.install(vae)
+ vt.decode_tile_budget(vae, z)
+ assert seen == {
+ "AutoencoderKL": False,
+ "AutoencoderKLFlux2": False,
+ "AutoencoderKLQwenImage": True,
+ "AutoencoderKLQwenImage21": True,
+ "AutoencoderKLHunyuanImage": True,
+ }
+ # and the floor-fit check (stock fallback) still counts the cache for every VAE
+ vae = _hunyuan_image()
+ assert vt.install(vae)
+ seen.clear()
+ vt.floor_shortfall(vae, torch.zeros(1, 8, 64, 64))
+ assert seen == {"AutoencoderKLHunyuanImage": True}
+
+
+def _stock_decoded(length, tile, overlap):
+ """Latents diffusers' stock loop decodes along one side (a tile every tile - overlap, the last one cut short)."""
+ if length <= tile:
+ return length
+ return sum(min(tile, length - s) for s in range(0, length, tile - overlap))
+
+
[email protected]("length", list(range(129, 420)))
[email protected]("max_area", [None, 23_200, 10**6])
+def test_large_floor_tiles_never_decode_more_than_stock(length, max_area):
+ """FLUX.1 / SDXL / FLUX.2 sliver sizes. Before, the floor kept 128-latent tiles and spread them (two 128s with a
+ 56-latent overlap on a 200-latent side: 7% more decode than stock, 9% slower). Now, per side, no more decoded
+ latents than the stock loop (up to rounding where only the smallest covering side exists), fewer decoder calls,
+ no sliver, every overlap >= 32, and the widest tile that allows (two 120s on a 200-latent side)."""
+ if vt.stock_layout_ok((128, 32), length, length):
+ return # no sliver: these sizes decode through the stock tiles
+ th, tw = vt.choose_tiles(length, length, max_area, 128, 32, 128)
+ assert th * tw <= max(max_area or 0, 128 * 128) and min(th, tw) >= vt.TILE_LATENTS
+ stock_calls = len(range(0, length, 96))
+ span = _stock_decoded(length, 128, 32)
+ for side in (th, tw):
+ starts = vt.tile_starts(length, side, 32)
+ assert starts[0] == 0 and starts[-1] + side == length or starts == [0]
+ assert all(b + 32 <= a + side for a, b in zip(starts, starts[1:]))
+ assert len(starts) < stock_calls
+ assert len(starts) * side <= span + len(starts) - 1
+ if length == 200:
+ assert (th, tw) == {None: (120, 120), 23_200: (116, 200), 10**6: (200, 200)}[max_area]
+ if max_area is None:
+ assert vt.tile_starts(200, 120, 32) == [0, 80]
+
+
+def test_qwen_family_layout_ignores_the_large_stock_rule():
+ """Only a VAE whose stock tile is the floor tile takes the stock-work rule; the 32-latent floor VAEs keep #12696's
+ fewest-latents choice whatever stock tile is passed."""
+ for length in (64, 100, 128, 166, 256):
+ for area in (None, 1500, 4000, 10**6):
+ assert vt.choose_tiles(length, length, area) == vt.choose_tiles(
+ length, length, area, 32, 16, 16
+ )
+ assert vt.choose_tiles(length, length, area) == vt.choose_tiles(
+ length, length, area, 32, 16, 32
+ )
+
+
[email protected]("length", list(range(1, 400)))
[email protected]("max_area", [None, 0, 1024])
+def test_the_32_latent_floor_layout_is_unchanged(length, max_area):
+ """Qwen-Image, Qwen-Image-2.1 and HunyuanImage at the floor: 32-latent tiles, as #12696 picks."""
+ assert vt.choose_tiles(length, length, max_area) == (min(32, length), min(32, length))
+
+
+def _decode_with(vae, z):
+ with torch.no_grad():
+ vae.enable_tiling()
+ return vae.decode(z).sample
+
+
+class _Log:
+ def __init__(self):
+ self.records = []
+
+ def info(self, *a):
+ pass
+
+ def debug(self, *a):
+ self.records.append(("debug", a[0] % a[1:]))
+
+ def warning(self, *a):
+ self.records.append(("warning", a[0] % a[1:]))
+
+
+def test_floor_that_cannot_fit_decodes_in_the_stock_tiles_and_says_why(monkeypatch):
+ """HunyuanImage's 32-latent floor tile peaks at ~1.3 GiB, its 12-latent stock tile at ~0.2: with less free than the
+ floor needs, OOM loses to a seam, so the decode takes the stock tiles and logs the reason (once per VAE)."""
+ vae = _hunyuan_image()
+ z = torch.randn(1, 8, 40, 40, generator = torch.Generator().manual_seed(1))
+ stock = _decode_with(vae, z)
+ log = _Log()
+ assert vt.install(vae, log)
+ monkeypatch.delenv(vt.MAX_TILE_ENV)
+ monkeypatch.setattr(
+ vt, "_free_mib", lambda v, zz, **k: (500.0, 1.0)
+ ) # 32x32 x 1.3 MiB = 1,331 MiB needed
+ assert "floor tile needs about 1331 MiB" in vt.floor_shortfall(vae, z)
+ assert torch.equal(_decode_with(vae, z), stock)
+ assert _decode_with(vae, z).shape == stock.shape
+ assert [k for k, _ in log.records] == ["warning", "debug"]
+ assert "HunyuanImage" in log.records[0][1] and "stock tiles" in log.records[0][1]
+ # with room for the floor, the wide tiles again
+ monkeypatch.setattr(vt, "_free_mib", lambda v, zz, **k: (2000.0, 1.0))
+ assert vt.floor_shortfall(vae, z) is None
+ assert not torch.equal(_decode_with(vae, z), stock)
+ # unknown free memory (CPU) and an explicit tile cap are never a shortfall
+ monkeypatch.setattr(vt, "_free_mib", lambda v, zz, **k: None)
+ assert vt.floor_shortfall(vae, z) is None
+ monkeypatch.setattr(vt, "_free_mib", lambda v, zz, **k: (1.0, 1.0))
+ monkeypatch.setenv(vt.MAX_TILE_ENV, "32")
+ assert vt.floor_shortfall(vae, z) is None
+
+
[email protected]("build", [_qwen_image, _kl, lambda: _kl(cls = "AutoencoderKLFlux2")])
+def test_no_stock_fallback_where_the_stock_tile_is_as_large(monkeypatch, build):
+ """Qwen-Image (32-latent stock tiles) and AutoencoderKL / FLUX.2 (128): the stock tiles need as much memory as the
+ floor, so a low free VRAM keeps the wide tiles (the FLUX.1 sliver fix held at 2 GiB free only after this)."""
+ vae = build()
+ assert vt.install(vae)
+ vae._unsloth_vae_fused_installed = 3
+ monkeypatch.delenv(vt.MAX_TILE_ENV)
+ monkeypatch.setattr(vt, "_free_mib", lambda v, zz, **k: (1.0, 1.0))
+ z = (
+ torch.zeros(1, 4, 1, 200, 200)
+ if hasattr(vae, "tile_sample_stride_height")
+ else torch.zeros(1, 4, 200, 200)
+ )
+ assert vt.floor_shortfall(vae, z) is None
+
+
+def test_floor_fit_uses_the_fused_peak_so_qwen_image_21_keeps_its_wide_floor(monkeypatch):
+ """Qwen-Image-2.1's fused floor tile peaks at ~0.43 GiB: it stays on the wide floor down to that (where #12696
+ would OOM), not at the 1.7 GiB unfused figure."""
+ vae = _qwen_image_21()
+ assert vt.install(vae)
+ vae._unsloth_vae_fused_installed = 5
+ monkeypatch.delenv(vt.MAX_TILE_ENV)
+ z = torch.zeros(1, 4, 1, 64, 64)
+ monkeypatch.setattr(vt, "_free_mib", lambda v, zz, **k: (500.0, 1.0))
+ assert vt.floor_shortfall(vae, z) is None
+ monkeypatch.setattr(vt, "_free_mib", lambda v, zz, **k: (400.0, 1.0))
+ assert vt.floor_shortfall(vae, z)
+ vae._unsloth_vae_fused_failed = True
+ monkeypatch.setattr(vt, "_free_mib", lambda v, zz, **k: (1500.0, 1.0))
+ assert vt.floor_shortfall(vae, z)
+
+
+def test_oom_retries_at_the_floor_then_in_the_stock_tiles(monkeypatch):
+ vae = _qwen_image()
+ z = torch.randn(1, 4, 1, 64, 64, generator = torch.Generator().manual_seed(1))
+ stock = _decode_with(vae, z)
+ assert vt.install(vae, _Log())
+ floor = _decode_with(vae, z) # the autouse 1-latent cap: the floor tiles
+ real = vt.tiled_decode
+ calls = []
+
+ def flaky(
+ v,
+ zz,
+ return_dict = True,
+ max_area = "auto",
+ fail = ("auto",),
+ ):
+ calls.append(max_area)
+ if max_area in fail:
+ v._unsloth_last_decode_tile = (48, 48, 2304) if max_area == "auto" else (32, 32, 0)
+ raise torch.OutOfMemoryError("CUDA out of memory. Tried to allocate 1 GiB")
+ return real(v, zz, return_dict = return_dict, max_area = max_area)
+
+ monkeypatch.setattr(vt, "tiled_decode", flaky)
+ assert torch.equal(_decode_with(vae, z), floor)
+ assert calls == ["auto", 0]
+ calls.clear()
+ monkeypatch.setattr(vt, "tiled_decode", lambda *a, **k: flaky(*a, **k, fail = ("auto", 0)))
+ assert torch.equal(_decode_with(vae, z), stock)
+ assert calls == ["auto", 0]
+ # an error that is not an OOM propagates
+ monkeypatch.setattr(
+ vt, "tiled_decode", lambda *a, **k: (_ for _ in ()).throw(ValueError("bad"))
+ )
+ with pytest.raises(ValueError):
+ _decode_with(vae, z)
+
+
+def test_geometry_and_blend_weights_are_cached_per_vae(monkeypatch):
+ vae = _qwen_image()
+ assert vt.install(vae)
+ assert vae._unsloth_wide_geometry == (8, 32, 16)
+ built = []
+ real = vt.axis_weights
+ monkeypatch.setattr(vt, "axis_weights", lambda *a, **k: built.append(a[:3]) or real(*a, **k))
+ monkeypatch.setattr(vt, "compression_ratio", lambda v: pytest.fail("ratio re-read per decode"))
+ z = torch.randn(1, 4, 1, 48, 48, generator = torch.Generator().manual_seed(1))
+ first = _decode_with(vae, z)
+ assert len(built) == 1
+ second = _decode_with(vae, z)
+ assert len(built) == 1 and torch.equal(first, second)
+ vt.uninstall(vae)
+ assert (
+ "_unsloth_wide_weights" not in vae.__dict__ and "_unsloth_wide_geometry" not in vae.__dict__
+ )
def _image_family_vae_classes():
@@ -382,3 +655,40 @@ def test_load_installs_for_every_image_family():
assert (
"fam" not in ast.unparse(node.test) and "vae" not in ast.unparse(node.test).lower()
)
+
+
+def test_stock_fallback_keeps_the_fused_batched_loop_on_the_wan_family(monkeypatch):
+ """Under the wide tiles the fused VAE layer cannot take ``tiled_decode`` (they own it), so before this the stock
+ fallback (kill switch, or a floor that cannot fit) ran diffusers' one-tile-per-call loop, slower than main's
+ batched one. Now the batched loop backs the fallback, and is ``tiled_decode`` again after an uninstall."""
+ from core.inference import diffusion_vae_fused as fused
+
+ vae = _qwen_image_21()
+ assert vt.install(vae)
+ ours = vae.__dict__["tiled_decode"]
+ assert fused.install_wan_tile_batch(vae) is False
+ assert vae.__dict__["tiled_decode"] is ours
+ batched = vae.__dict__["_unsloth_wide_stock_decode"]
+ assert getattr(batched, "_unsloth_vae_fused", False)
+ calls = []
+ vae._unsloth_wide_stock_decode = lambda z, return_dict = True: calls.append(z.shape) or batched(
+ z, return_dict = return_dict
+ )
+ z = torch.randn(1, 4, 1, 48, 48, generator = torch.Generator().manual_seed(1))
+ with torch.no_grad():
+ vae.enable_tiling()
+ monkeypatch.setenv(vt.WIDE_TILES_ENV, "0")
+ killed = vae.decode(z).sample
+ monkeypatch.delenv(vt.WIDE_TILES_ENV)
+ monkeypatch.delenv(vt.MAX_TILE_ENV)
+ monkeypatch.setattr(vt, "_free_mib", lambda v, zz, **k: (1.0, 1.0))
+ short = vae.decode(z).sample
+ assert len(calls) == 2 and torch.equal(killed, short)
+ vae._unsloth_wide_stock_decode = batched
+ vt.uninstall(vae)
+ assert vae.__dict__.get("tiled_decode") is batched
+ # without the wide tiles the batched loop installs on ``tiled_decode`` as before
+ plain = _qwen_image_21()
+ assert fused.install_wan_tile_batch(plain)
+ assert getattr(plain.__dict__["tiled_decode"], "_unsloth_vae_fused", False)
+ assert "_unsloth_wide_stock_decode" not in plain.__dict__