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 float64 VAE tile blend weights off MPS so tiled encode and decode work (#12937)

GokayAIce62144785a5
diff --git a/studio/backend/core/inference/diffusion_device.py b/studio/backend/core/inference/diffusion_device.py
index 1de1136bb6e..001463830e5 100644
--- a/studio/backend/core/inference/diffusion_device.py
+++ b/studio/backend/core/inference/diffusion_device.py
@@ -517,6 +517,12 @@ def diffusion_device_target_from_torch_device(
return _cpu_target(torch = None, dtype = dtype)
+def float64_device(device: Any) -> Any:
+ """Device to build float64 values on before moving the result to ``device``: itself, or CPU when it has no float64."""
+ target = diffusion_device_target_from_torch_device(str(device), None)
+ return device if target.supports_float64 else "cpu"
+
+
def _cuda_or_rocm_target(
torch: Any,
*,
diff --git a/studio/backend/core/inference/diffusion_vae_tiling.py b/studio/backend/core/inference/diffusion_vae_tiling.py
index cc527276a39..0db54c04f8e 100644
--- a/studio/backend/core/inference/diffusion_vae_tiling.py
+++ b/studio/backend/core/inference/diffusion_vae_tiling.py
@@ -18,6 +18,8 @@ import os
import types
from typing import Any, Optional
+from .diffusion_device import float64_device
+
WIDE_TILES_ENV = "UNSLOTH_DIFFUSION_VAE_WIDE_TILES"
TILE_LATENTS = 32
@@ -67,11 +69,12 @@ def axis_weights(
shared edge, linear over the next ``ramp``. Overlaps >= 16 put every pixel >= 8 latents inside some tile, so a
margin under 8 keeps the sum positive."""
size = min(tile, length) * scale
- pos = (torch.arange(size, dtype = torch.float64, device = device) + 0.5) / scale
- total = torch.zeros(length * scale, dtype = torch.float64, device = device)
+ build = float64_device(device)
+ pos = (torch.arange(size, dtype = torch.float64, device = build) + 0.5) / scale
+ total = torch.zeros(length * scale, dtype = torch.float64, device = build)
weights = []
for s in starts:
- w = torch.ones(size, dtype = torch.float64, device = device)
+ w = torch.ones(size, dtype = torch.float64, device = build)
if s > 0:
w = torch.minimum(w, ((pos - margin) / ramp).clamp(0, 1))
if s + tile < length:
@@ -80,7 +83,10 @@ def axis_weights(
weights.append(w)
if float(total.min()) <= 0.0:
raise ValueError(f"tiles {starts} leave pixels without weight on a {length}-latent axis")
- return [(w / total[s * scale : s * scale + size]).float() for w, s in zip(weights, starts)]
+ return [
+ (w / total[s * scale : s * scale + size]).float().to(device)
+ for w, s in zip(weights, starts)
+ ]
def _decode_tile(vae: Any, z: Any) -> Any:
diff --git a/studio/backend/core/inference/video_ltx2_vae_tiles.py b/studio/backend/core/inference/video_ltx2_vae_tiles.py
index 2d516bc96ec..fa7ffe946e8 100644
--- a/studio/backend/core/inference/video_ltx2_vae_tiles.py
+++ b/studio/backend/core/inference/video_ltx2_vae_tiles.py
@@ -14,6 +14,8 @@ import os
import types
from typing import Any, Optional
+from .diffusion_vae_tiling import axis_weights as _axis_weights
+
WIDE_TILES_ENV = "UNSLOTH_VIDEO_VAE_WIDE_TILES"
# Stock tile side: the smallest tile, so the tightest tier never needs more per tile than stock.
@@ -69,27 +71,16 @@ def axis_weights(
ramp: Optional[int] = None,
) -> list:
"""Per-tile fp32 weights along one axis summing to 1: 0 within ``margin`` of a shared edge, then a linear ``ramp``."""
- margin = MARGIN_LATENTS if margin is None else margin
- ramp = RAMP_LATENTS if ramp is None else ramp
- size = min(tile, length) * scale
- pos = (torch.arange(size, dtype = torch.float64, device = "cpu") + 0.5) / scale
- total = torch.zeros(length * scale, dtype = torch.float64, device = "cpu")
- weights = []
- for s in starts:
- w = torch.ones(size, dtype = torch.float64, device = "cpu")
- if s > 0:
- w = torch.minimum(w, ((pos - margin) / ramp).clamp(0, 1))
- if s + tile < length:
- w = torch.minimum(w, ((min(tile, length) - pos - margin) / ramp).clamp(0, 1))
- total[s * scale : s * scale + size] += w
- weights.append(w)
- if float(total.min()) <= 0.0:
- raise ValueError(f"tiles {starts} leave pixels without weight on a {length}-latent axis")
- # float64 on CPU: MPS has no float64.
- return [
- (w / total[s * scale : s * scale + size]).float().to(device)
- for w, s in zip(weights, starts)
- ]
+ return _axis_weights(
+ starts,
+ tile,
+ length,
+ scale,
+ torch,
+ device,
+ MARGIN_LATENTS if margin is None else margin,
+ RAMP_LATENTS if ramp is None else ramp,
+ )
def output_frames(vae: Any, latent_frames: int) -> int:
diff --git a/studio/backend/tests/test_diffusion_device.py b/studio/backend/tests/test_diffusion_device.py
index a8f7c463944..8e74ef47681 100644
--- a/studio/backend/tests/test_diffusion_device.py
+++ b/studio/backend/tests/test_diffusion_device.py
@@ -351,6 +351,15 @@ def test_only_mps_lacks_float64(monkeypatch):
assert dd.diffusion_device_target_from_torch_device("mps", FP32).supports_float64 is False
+def test_float64_is_built_on_the_device_unless_it_lacks_it():
+ for device in ("cuda", "cuda:1", "xpu", "cpu", "meta"):
+ assert dd.float64_device(device) is device
+ # Callers pass torch.device objects, which only stringify to the device name.
+ mps = type("Device", (), {"__str__": lambda self: "mps:0"})()
+ for device in ("mps", "mps:0", mps):
+ assert dd.float64_device(device) == "cpu"
+
+
class _RopeModule:
def __init__(self, double_precision = True):
self.double_precision = double_precision
diff --git a/studio/backend/tests/test_diffusion_vae_tiling.py b/studio/backend/tests/test_diffusion_vae_tiling.py
index 6df653de432..9f27968d364 100644
--- a/studio/backend/tests/test_diffusion_vae_tiling.py
+++ b/studio/backend/tests/test_diffusion_vae_tiling.py
@@ -87,6 +87,34 @@ def test_axis_weights_partition_unity_and_skip_shared_edges(length):
torch.testing.assert_close(total, torch.ones_like(total))
+def test_axis_weights_keep_float64_off_a_device_without_it(monkeypatch):
+ # MPS has no float64: the tiled encode on Apple Silicon raised before the first step (#12935).
+ from torch.utils._python_dispatch import TorchDispatchMode
+
+ asked, made = [], []
+
+ class Record(TorchDispatchMode):
+ def __torch_dispatch__(
+ self,
+ func,
+ types,
+ args = (),
+ kwargs = None,
+ ):
+ out = func(*args, **(kwargs or {}))
+ if torch.is_tensor(out):
+ made.append((out.dtype, out.device.type))
+ return out
+
+ monkeypatch.setattr(vt, "float64_device", lambda device: asked.append(device) or "cpu")
+ target = torch.device("meta")
+ with Record():
+ w = vt.axis_weights(vt.tile_starts(47), vt.TILE_LATENTS, 47, 16, torch, target)
+ assert asked == [target]
+ assert all(x.device.type == "meta" and x.dtype == torch.float32 for x in w)
+ assert (torch.float64, "cpu") in made and (torch.float64, "meta") not in made
+
+
@pytest.mark.parametrize("width, height", UI_SIZES)
def test_every_ui_size_tiles_without_slivers(width, height):
for side in (width, height):
diff --git a/studio/backend/tests/test_video_ltx2_vae_tiles.py b/studio/backend/tests/test_video_ltx2_vae_tiles.py
index 865c1e2b6ae..66faa554407 100644
--- a/studio/backend/tests/test_video_ltx2_vae_tiles.py
+++ b/studio/backend/tests/test_video_ltx2_vae_tiles.py
@@ -280,20 +280,8 @@ def test_video_load_installs_wide_tiles_on_every_tiling_load():
) # after tiling is enabled, before (so beneath) the resident untiled wrapper
-def test_blend_weights_never_put_float64_on_the_device(monkeypatch):
- made = []
- for name in ("arange", "zeros", "ones"):
- real = getattr(torch, name)
-
- def spy(
- *args,
- _real = real,
- **kwargs,
- ):
- made.append((kwargs.get("dtype"), str(kwargs.get("device", "cpu"))))
- return _real(*args, **kwargs)
-
- monkeypatch.setattr(torch, name, spy)
- w = vt.axis_weights(vt.tile_starts(38, 16), 16, 38, 4, torch, torch.device("meta"))
- assert all(x.device.type == "meta" and x.dtype == torch.float32 for x in w)
- assert all(dev == "cpu" for dtype, dev in made if dtype == torch.float64)
+def test_axis_weights_share_the_image_tile_blend(monkeypatch):
+ calls = []
+ monkeypatch.setattr(vt, "_axis_weights", lambda *args: calls.append(args) or "weights")
+ assert vt.axis_weights([0, 22], 16, 38, 4, torch, "mps") == "weights"
+ assert calls == [([0, 22], 16, 38, 4, torch, "mps", vt.MARGIN_LATENTS, vt.RAMP_LATENTS)]