Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/ltx2_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@
del _diffusion_stage_cache
import services.patches.mps_transfer_sync as _mps_transfer_sync # pyright: ignore[reportUnusedImport] # Remove once ltx-core waits for queued MPS compute before a transfer and a 1080p stage 2 passes on a 48 GB Mac without it
del _mps_transfer_sync
import services.patches.mps_tiling_weights_sync as _mps_tiling_weights_sync # pyright: ignore[reportUnusedImport] # Remove once ltx-core _device_weights uploads with non_blocking=allow_async_transfer(...) and Refine Details gives a real picture on a Mac without it (LTX-Desktop#199)
del _mps_tiling_weights_sync
import services.patches.diffvae_decode_vram as _diffvae_decode_vram # pyright: ignore[reportUnusedImport] # Remove once upstream decode tiling is confirmed sufficient (E1)
del _diffvae_decode_vram
import services.patches.natten_libnatten_gate as _natten_libnatten_gate # pyright: ignore[reportUnusedImport] # Remove once ltx-core natten_available checks HAS_LIBNATTEN
Expand Down
63 changes: 63 additions & 0 deletions backend/services/patches/mps_tiling_weights_sync.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""Monkey-patch: upload tile blend weights to MPS with a blocking copy.

ltx-core 1.6.0 added ``_device_weights`` (``ltx_core/modality_tiling.py``). It builds a tile's blend
weights on the host and uploads them once per plan with ``non_blocking=True`` on every backend.
``ltx_core.devices.allow_async_transfer`` says only CUDA orders a non-blocking transfer against the
kernel that consumes it, and ``upload_from_host`` follows that rule. ``_device_weights`` does not.
On MPS ``VideoModalityTilingHelper.blend`` can then multiply the tile prediction by weights that
have not landed yet.

Every job that tiles the transformer is affected. On an M5 Pro (48 GB, macOS 26.5.1) Refine Details
finished as ``succeeded`` and wrote a video whose frames are all zero in Y, U and V (solid green),
at 540p, 720p and 1080p and with every tiling setting (LTX-Desktop#199).

Measured on that machine by running ``LTXIcLoraPipeline`` with hooks on ``LTXModel.forward`` and
``EulerDiffusionStep.step`` (refine-details, 9 frames, 576 x 1024, one tile, same seed):

- As shipped: transformer output of step 1 is in -6.9 .. 6.8, the blended ``denoised`` passed to the
Euler step is in -3.0e28 .. 3.8e28, step 2 is non-finite, the output is solid green.
- Blocking copy: ``denoised`` is in -5.9 .. 4.4, every step is finite, the picture is correct.

This patch keeps upstream's upload wherever ``allow_async_transfer`` allows it (CUDA) and copies
with a blocking ``.to`` everywhere else, so it is a no-op off Mac.

Remove once ltx-core's ``_device_weights`` passes ``non_blocking=allow_async_transfer(like.device)``
and Refine Details gives a real picture on a Mac without this patch.

Usage:
import services.patches.mps_tiling_weights_sync # noqa: F401
"""

from __future__ import annotations

import inspect
from collections.abc import Callable

import torch
from ltx_core import modality_tiling as _tiling
from ltx_core.devices import allow_async_transfer

_WeightsCache = dict[tuple[torch.dtype, torch.device], torch.Tensor]

_orig_device_weights: Callable[[_WeightsCache, Callable[[], torch.Tensor], torch.Tensor], torch.Tensor] = (
_tiling._device_weights # pyright: ignore[reportPrivateUsage]
)


def _device_weights_ordered(
cache: _WeightsCache,
weights: Callable[[], torch.Tensor],
like: torch.Tensor,
) -> torch.Tensor:
"""Like upstream ``_device_weights``, but the upload blocks where the backend does not order it."""
if allow_async_transfer(like.device):
return _orig_device_weights(cache, weights, like)
key = (like.dtype, like.device)
if key not in cache:
cache[key] = weights().to(dtype=like.dtype).to(device=like.device)
return cache[key]


if list(inspect.signature(_orig_device_weights).parameters) != ["cache", "weights", "like"]:
raise RuntimeError("modality_tiling._device_weights changed its signature — patch needs updating.")
_tiling._device_weights = _device_weights_ordered # pyright: ignore[reportPrivateUsage]
73 changes: 73 additions & 0 deletions backend/tests/test_mps_tiling_weights_sync.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Tile blend weights must reach MPS with a blocking copy (see ``mps_tiling_weights_sync``)."""

from __future__ import annotations

from typing import Any, cast

import pytest
import torch
from ltx_core import modality_tiling

from services.patches import mps_tiling_weights_sync as patch


class _HostWeights:
"""Stands in for the host tensor and records how it is moved."""

def __init__(self, moves: list[dict[str, Any]]) -> None:
self._moves = moves

def to(self, **kwargs: Any) -> _HostWeights:
self._moves.append(kwargs)
return self


class _Like:
def __init__(self, device: str) -> None:
self.dtype = torch.bfloat16
self.device = torch.device(device)


def _like(device: str) -> torch.Tensor:
return cast(torch.Tensor, _Like(device))


def test_patch_replaces_modality_tiling_device_weights() -> None:
assert modality_tiling._device_weights is patch._device_weights_ordered # pyright: ignore[reportPrivateUsage]


def test_mps_upload_is_never_non_blocking() -> None:
moves: list[dict[str, Any]] = []
host = _HostWeights(moves)
patch._device_weights_ordered({}, lambda: cast(torch.Tensor, host), _like("mps")) # pyright: ignore[reportPrivateUsage]
assert {"device": torch.device("mps")} in moves
assert not any(move.get("non_blocking") for move in moves)


def test_mps_weights_are_built_and_uploaded_once_per_plan() -> None:
moves: list[dict[str, Any]] = []
built: list[int] = []

def build() -> torch.Tensor:
built.append(1)
return cast(torch.Tensor, _HostWeights(moves))

cache: dict[tuple[torch.dtype, torch.device], torch.Tensor] = {}
first = patch._device_weights_ordered(cache, build, _like("mps")) # pyright: ignore[reportPrivateUsage]
second = patch._device_weights_ordered(cache, build, _like("mps")) # pyright: ignore[reportPrivateUsage]
assert second is first
assert len(built) == 1


def test_cuda_keeps_the_upstream_upload(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
sentinel = torch.zeros(1)

def upstream(_cache: object, _weights: object, like: torch.Tensor) -> torch.Tensor:
calls.append(like.device.type)
return sentinel

monkeypatch.setattr(patch, "_orig_device_weights", upstream)
result = patch._device_weights_ordered({}, lambda: torch.ones(1), _like("cuda")) # pyright: ignore[reportPrivateUsage]
assert result is sentinel
assert calls == ["cuda"]