Skip to content
Closed
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
6 changes: 6 additions & 0 deletions backend/ltx2_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,12 @@ def patched_sdpa(
import services.patches.mps_sdpa_torch as _mps_sdpa_torch
_mps_sdpa_torch.install()

# Darwin: MPS conv3d runs at ~1/5 of conv2d throughput, which makes the conv VAE
# decode ~4x slower than it needs to be. Run eligible Conv3d as per-tap conv2d.
# Remove once torch MPS conv3d reaches conv2d throughput.
import services.patches.mps_conv3d_as_conv2d as _mps_conv3d_as_conv2d
_mps_conv3d_as_conv2d.install()

# ============================================================
# Constants & Paths
# ============================================================
Expand Down
211 changes: 211 additions & 0 deletions backend/performance_runner/bench_mps_conv3d.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""Stock MPS Conv3d vs the per-tap conv2d patch (services/patches/mps_conv3d_as_conv2d).

Two checks, both on Apple Silicon only:

- Default: one 3x3x3 Conv3d per conv VAE decoder stage, bf16, in the decoder's
``channels_last_3d`` layout and in contiguous layout. Reports time, TFLOPS,
speedup, and the largest difference from stock. No model weights needed.
- ``--vae``: decodes one 1024x576, 121-frame latent with the real conv VAE
(``ltx-2.5-video-vae-conv``), stock then patched, the way the pipeline builds
it. Reports both decode times and the PSNR of patched vs stock frames.

Measurement and reporting are separate: the ``bench_*`` functions return results
and ``report`` prints them once at the end.

Use it to check the patch on your Mac and after every torch bump. Remove the
patch when stock is as fast in the ``channels_last_3d`` rows.

Usage (from backend/, no backend running):
uv run python performance_runner/bench_mps_conv3d.py
uv run python performance_runner/bench_mps_conv3d.py --vae
uv run python performance_runner/bench_mps_conv3d.py --vae --checkpoint /path/to/ltx-2.5-video-vae-conv-bf16.safetensors
"""

from __future__ import annotations

import argparse
import platform
import sys
import time
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path

import torch
from torch import nn

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import services.patches.mps_conv3d_as_conv2d as patch # noqa: E402

SEED = 42 # any fixed value; makes runs repeatable across machines and torch versions

# What the ``--vae`` check decodes: the app's default 540p, 5 s clip.
HEIGHT, WIDTH, NUM_FRAMES = 576, 1024, 121
# LTX-2 video VAE: 32x spatial and 8x temporal compression, 128 latent channels.
SPATIAL_SCALE, TEMPORAL_SCALE, LATENT_CHANNELS = 32, 8, 128
LATENT_SHAPE = (
1,
LATENT_CHANNELS,
(NUM_FRAMES - 1) // TEMPORAL_SCALE + 1,
HEIGHT // SPATIAL_SCALE,
WIDTH // SPATIAL_SCALE,
)

# One Conv3d per decoder stage: (channels, frames, height, width) for the clip above.
SHAPES = [(1024, 16, 18, 32), (512, 32, 36, 64), (256, 64, 72, 128), (128, 32, 144, 256)]
KERNEL_TAPS = 3 * 3 * 3 # a 3x3x3 kernel: 27 multiply-adds per output value per input channel
FLOPS_PER_MAC = 2 # one multiply and one add

DEFAULT_CHECKPOINT = (
Path.home() / "Library/Application Support/LTXDesktop/models/ltx-2.5/ltx-2.5-video-vae-conv-bf16.safetensors"
)
WARMUP, ITERS = 2, 5


@dataclass(frozen=True)
class OpResult:
layout: str
channels: int
frames: int
height: int
width: int
stock_s: float
patched_s: float
flops: int
max_abs_diff: float


@dataclass(frozen=True)
class VaeResult:
stock_s: float
patched_s: float
psnr_db: float
max_abs_diff: float
finite: bool


def _time(fn: Callable[[], torch.Tensor]) -> float:
for _ in range(WARMUP):
fn()
torch.mps.synchronize()
start = time.perf_counter()
for _ in range(ITERS):
fn()
torch.mps.synchronize()
return (time.perf_counter() - start) / ITERS


@torch.inference_mode()
def bench_ops() -> list[OpResult]:
torch.manual_seed(SEED)
results: list[OpResult] = []
for layout in (torch.channels_last_3d, torch.contiguous_format):
for channels, frames, height, width in SHAPES:
conv = nn.Conv3d(channels, channels, 3, padding=(0, 1, 1)).to("mps", torch.bfloat16)
conv = conv.to(memory_format=layout)
# No temporal padding: the 3-tap kernel turns frames + 2 input frames into frames output frames.
x = torch.randn(1, channels, frames + 2, height, width, device="mps", dtype=torch.bfloat16)
x = x.contiguous(memory_format=layout)
stock_s = _time(lambda: patch._original_forward(conv, x))
patched_s = _time(lambda: patch._patched_forward(conv, x))
diff = (patch._patched_forward(conv, x).float() - patch._original_forward(conv, x).float()).abs().max()
results.append(
OpResult(
layout="channels_last_3d" if layout is torch.channels_last_3d else "contiguous",
channels=channels,
frames=frames,
height=height,
width=width,
stock_s=stock_s,
patched_s=patched_s,
# in_channels == out_channels in every decoder stage, hence channels squared.
flops=FLOPS_PER_MAC * channels * channels * KERNEL_TAPS * frames * height * width,
max_abs_diff=diff.item(),
)
)
del conv, x
torch.mps.empty_cache()
return results


@torch.inference_mode()
def _decode(checkpoint: Path, latent: torch.Tensor) -> tuple[torch.Tensor, float]:
from ltx_pipelines.utils.blocks import VideoDecoder
from ltx_pipelines.utils.helpers import tiling_config_for_vae

device = torch.device("mps")
tiling = tiling_config_for_vae(str(checkpoint), height=HEIGHT, width=WIDTH, num_frames=NUM_FRAMES, device=device)
decoder = VideoDecoder(str(checkpoint), torch.bfloat16, device)
generator = torch.Generator(device="mps").manual_seed(SEED)
torch.mps.synchronize()
start = time.perf_counter()
frames = torch.cat([chunk.float().cpu() for chunk in decoder(latent, tiling, generator)], dim=0)
torch.mps.synchronize()
elapsed = time.perf_counter() - start
torch.mps.empty_cache()
return frames, elapsed


def bench_vae(checkpoint: Path) -> VaeResult:
torch.manual_seed(SEED)
latent = torch.randn(LATENT_SHAPE).to("mps", torch.bfloat16)
original = nn.Conv3d.forward
try:
nn.Conv3d.forward = original # type: ignore[method-assign]
stock, stock_s = _decode(checkpoint, latent)
nn.Conv3d.forward = patch._patched_forward # type: ignore[method-assign]
patched, patched_s = _decode(checkpoint, latent)
finally:
nn.Conv3d.forward = original # type: ignore[method-assign]
mse = (patched - stock).pow(2).mean().item()
span = (stock.max() - stock.min()).item()
psnr_db = float("inf") if mse == 0 else 10 * torch.log10(torch.tensor(span**2 / mse)).item()
return VaeResult(
stock_s=stock_s,
patched_s=patched_s,
psnr_db=psnr_db,
max_abs_diff=(patched - stock).abs().max().item(),
finite=bool(torch.isfinite(patched).all()),
)


def report(op_results: list[OpResult], vae: VaeResult | None) -> None:
print(f"torch {torch.__version__}, macOS {platform.mac_ver()[0]}, {platform.machine()}, bf16\n")
print(
f"{'layout':17} {'C':>5} {'T':>3} {'H':>4} {'W':>4} | {'stock ms':>9} {'TFLOPS':>6} | "
f"{'patch ms':>9} {'TFLOPS':>6} | speedup max|d|"
)
for row in op_results:
print(
f"{row.layout:17} {row.channels:>5} {row.frames:>3} {row.height:>4} {row.width:>4} | "
f"{row.stock_s * 1e3:>9.1f} {row.flops / row.stock_s / 1e12:>6.2f} | "
f"{row.patched_s * 1e3:>9.1f} {row.flops / row.patched_s / 1e12:>6.2f} | "
f"{row.stock_s / row.patched_s:>6.2f}x {row.max_abs_diff:.4f}"
)
if vae is None:
return
print()
print(f"stock decode {vae.stock_s:6.1f}s")
print(f"patched decode {vae.patched_s:6.1f}s ({vae.stock_s / vae.patched_s:.2f}x)")
print(f"patched vs stock: PSNR {vae.psnr_db:.1f} dB, max|d| {vae.max_abs_diff:.4f}")


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--vae", action="store_true", help="also decode with the real conv VAE (needs the checkpoint)")
parser.add_argument("--checkpoint", type=Path, default=DEFAULT_CHECKPOINT)
args = parser.parse_args()
if not torch.backends.mps.is_available():
sys.exit("MPS is not available. This benchmark needs an Apple Silicon Mac.")
if args.vae and not args.checkpoint.exists():
sys.exit(f"Conv VAE checkpoint not found: {args.checkpoint}\nDownload it in the app or pass --checkpoint.")
op_results = bench_ops()
vae = bench_vae(args.checkpoint) if args.vae else None
report(op_results, vae)
if vae is not None and not vae.finite:
sys.exit("FAIL: patched output has NaN or Inf values")


if __name__ == "__main__":
main()
108 changes: 108 additions & 0 deletions backend/services/patches/mps_conv3d_as_conv2d.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""Run MPS ``nn.Conv3d`` as a sum of ``conv2d`` calls, one per temporal tap.

The conv video VAE decoder (``ltx-2.5-video-vae-conv``, the Fast decode path) is
built from 3x3x3 ``CausalConv3d`` layers. On Apple Silicon, torch's MPS
``conv3d`` runs at ~3 TFLOPS while ``conv2d`` runs at ~16 TFLOPS on the same
M3 Max. A stride-1 Conv3d with no temporal padding is exactly the sum over its
temporal taps of a Conv2d on time-shifted frames batched into N, so the decoder
can take the conv2d path without changing its math. Measured on an M3 Max
48 GB, 540p/5s t2v, headless backend, purged page cache: VAE decode 1:30 ->
0:21, whole generation 6:20 -> 5:12. Decoded frames match stock at 48.7 dB
PSNR / 0.991 SSIM.

MPS ``conv2d`` returns wrong values, with no error, when its weight or input is
a strided view (torch 2.11): ``weight[:, :, i]``, or a channel slice of the
decoder's ``channels_last_3d`` workspace. Both are copied to a dense layout
before each call. Frames are processed in ~512 MiB chunks to bound these
copies: for a 540p/5s decode, peak MPS driver memory goes from 9.7 to 10.7 GiB.

Any other Conv3d (non-MPS, stride, dilation, groups, temporal padding,
non-zero padding mode) runs the original ``forward``.

Remove once torch MPS ``conv3d`` reaches ``conv2d`` throughput.

Usage:
import services.patches.mps_conv3d_as_conv2d as mps_conv3d_as_conv2d
mps_conv3d_as_conv2d.install()
"""

from __future__ import annotations

import logging
import sys

import torch
import torch.nn.functional as F
from torch import nn

logger = logging.getLogger(__name__)

# Input bytes per conv2d batch. Bounds the dense copies and the partial sums.
_CHUNK_BYTES = 512 * 2**20

_installed = False
_original_forward = nn.Conv3d.forward


def _supported(conv: nn.Conv3d, x: torch.Tensor) -> bool:
return (
x.device.type == "mps"
and x.dim() == 5
and conv.stride == (1, 1, 1)
and conv.dilation == (1, 1, 1)
and conv.groups == 1
and conv.padding_mode == "zeros"
and not isinstance(conv.padding, str)
and conv.padding[0] == 0
)


def _conv3d_as_conv2d(conv: nn.Conv3d, x: torch.Tensor) -> torch.Tensor:
weight = conv.weight
taps = [weight[:, :, tap].contiguous() for tap in range(weight.shape[2])]
batch, in_channels, in_frames, height, width = x.shape
out_frames = in_frames - len(taps) + 1
kernel_height, kernel_width = conv.kernel_size[1], conv.kernel_size[2]
pad_height, pad_width = conv.padding[1], conv.padding[2]
out_height = height + 2 * pad_height - kernel_height + 1
out_width = width + 2 * pad_width - kernel_width + 1
memory_format = (
torch.channels_last_3d if x.is_contiguous(memory_format=torch.channels_last_3d) else torch.contiguous_format
)
out = torch.empty(
(batch, conv.out_channels, out_frames, out_height, out_width),
device=x.device,
dtype=x.dtype,
memory_format=memory_format,
)
frames_per_chunk = max(1, _CHUNK_BYTES // (batch * in_channels * height * width * x.element_size()))
for start in range(0, out_frames, frames_per_chunk):
end = min(start + frames_per_chunk, out_frames)
chunk_frames = batch * (end - start)

def tap_input(tap: int) -> torch.Tensor:
# Frames start+tap .. end+tap, batched into N and copied dense: MPS conv2d misreads strided views.
shifted = x[:, :, start + tap : end + tap].transpose(1, 2).reshape(chunk_frames, in_channels, height, width)
return shifted.contiguous(memory_format=torch.channels_last)

total = F.conv2d(tap_input(0), taps[0], conv.bias, padding=(pad_height, pad_width))
for tap in range(1, len(taps)):
total.add_(F.conv2d(tap_input(tap), taps[tap], padding=(pad_height, pad_width)))
out[:, :, start:end] = total.reshape(batch, end - start, conv.out_channels, out_height, out_width).transpose(1, 2)
return out


def _patched_forward(self: nn.Conv3d, input: torch.Tensor) -> torch.Tensor: # noqa: A002 # torch's parameter name
if not _supported(self, input):
return _original_forward(self, input)
return _conv3d_as_conv2d(self, input)


def install() -> None:
"""Patch ``nn.Conv3d.forward`` on Darwin. Idempotent. No-op elsewhere."""
global _installed
if _installed or sys.platform != "darwin":
return
nn.Conv3d.forward = _patched_forward # type: ignore[method-assign]
_installed = True
logger.info("MPS Conv3d runs as per-tap conv2d (conv VAE decode)")
58 changes: 58 additions & 0 deletions backend/tests/test_mps_conv3d_as_conv2d.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Per-tap conv2d MPS Conv3d must match stock Conv3d. Needs an Apple Silicon GPU."""

from __future__ import annotations

import pytest
import torch
from torch import nn

import services.patches.mps_conv3d_as_conv2d as mps_conv3d_as_conv2d

pytestmark = pytest.mark.skipif(not torch.backends.mps.is_available(), reason="needs MPS")


def _assert_matches_stock(conv: nn.Conv3d, x: torch.Tensor, atol: float) -> None:
with torch.inference_mode():
expected = mps_conv3d_as_conv2d._original_forward(conv, x)
actual = mps_conv3d_as_conv2d._patched_forward(conv, x)
assert actual.shape == expected.shape
torch.testing.assert_close(actual.float(), expected.float(), atol=atol, rtol=0)


def test_channel_sliced_channels_last_input_matches_stock_conv3d() -> None:
# MPS conv2d misreads strided input views; the decoder feeds channel slices of its workspace.
torch.manual_seed(0)
channels = 128
conv = nn.Conv3d(channels, channels, 3, padding=(0, 1, 1)).to("mps", torch.bfloat16)
conv = conv.to(memory_format=torch.channels_last_3d)
workspace = torch.randn(1, 2 * channels, 10, 18, 32, device="mps", dtype=torch.bfloat16)
workspace = workspace.contiguous(memory_format=torch.channels_last_3d)
_assert_matches_stock(conv, workspace[:, :channels, 2:8], atol=0.1)


@pytest.mark.parametrize(
("stride", "padding"),
[((2, 2, 2), (0, 1, 1)), ((1, 1, 1), (1, 1, 1))],
ids=["strided", "temporally_padded"],
)
def test_strided_or_temporally_padded_conv3d_uses_original_forward(
stride: tuple[int, int, int], padding: tuple[int, int, int]
) -> None:
torch.manual_seed(0)
conv = nn.Conv3d(16, 16, 3, stride=stride, padding=padding).to("mps")
x = torch.randn(1, 16, 8, 12, 12, device="mps")
with torch.inference_mode():
expected = mps_conv3d_as_conv2d._original_forward(conv, x)
actual = mps_conv3d_as_conv2d._patched_forward(conv, x)
assert torch.equal(actual, expected)


def test_last_partial_chunk_matches_stock_conv3d(monkeypatch: pytest.MonkeyPatch) -> None:
torch.manual_seed(0)
channels, height, width = 32, 8, 8
frame_bytes = channels * height * width * 4
# 3 frames per chunk over 8 output frames: chunks of 3, 3, 2.
monkeypatch.setattr(mps_conv3d_as_conv2d, "_CHUNK_BYTES", 3 * frame_bytes)
conv = nn.Conv3d(channels, channels, 3, padding=(0, 1, 1)).to("mps")
x = torch.randn(1, channels, 10, height, width, device="mps")
_assert_matches_stock(conv, x, atol=1e-4)