From 39e3243956aa8b765c2c10752be5f34b97dbe332 Mon Sep 17 00:00:00 2001 From: Sabbagh Fares Date: Sat, 31 Oct 2026 14:58:05 +0100 Subject: [PATCH 1/6] Use conv2d for MPS Conv3d in the conv VAE decoder On Apple Silicon, torch MPS conv3d is approximately 5 times slower than conv2d. The conv VAE decoder uses 3x3x3 Conv3d layers. Thus, the VAE decode is slow. This patch changes each applicable Conv3d into one conv2d for each temporal tap. Then it adds the results. The math does not change. For all other Conv3d layers, the patch uses the original forward. MPS conv2d gives incorrect values when the weight or the input is a strided view. The patch copies the weight and the input into a dense layout before each conv2d call. On an M3 Max with 48 GB, the VAE decode time decreases from 1:30 to 0:21. The full 540p/5 s generation time decreases from 6:20 to 5:12. --- backend/ltx2_server.py | 6 ++ .../services/patches/mps_conv3d_as_conv2d.py | 102 ++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 backend/services/patches/mps_conv3d_as_conv2d.py diff --git a/backend/ltx2_server.py b/backend/ltx2_server.py index ebc838ca5..d0cc35aa9 100644 --- a/backend/ltx2_server.py +++ b/backend/ltx2_server.py @@ -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 # ============================================================ diff --git a/backend/services/patches/mps_conv3d_as_conv2d.py b/backend/services/patches/mps_conv3d_as_conv2d.py new file mode 100644 index 000000000..53ed8c74d --- /dev/null +++ b/backend/services/patches/mps_conv3d_as_conv2d.py @@ -0,0 +1,102 @@ +"""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 chunks so these copies stay small +next to a decode tile (~7 GiB at 128 ch, 80 x 448 x 768). + +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[:, :, i].contiguous() for i in range(weight.shape[2])] + bsz, c_in, t_in, h, w = x.shape + t_out = t_in - len(taps) + 1 + kh, kw = conv.kernel_size[1], conv.kernel_size[2] + ph, pw = conv.padding[1], conv.padding[2] + h_out, w_out = h + 2 * ph - kh + 1, w + 2 * pw - kw + 1 + memory_format = ( + torch.channels_last_3d if x.is_contiguous(memory_format=torch.channels_last_3d) else torch.contiguous_format + ) + out = torch.empty( + (bsz, conv.out_channels, t_out, h_out, w_out), device=x.device, dtype=x.dtype, memory_format=memory_format + ) + step = max(1, _CHUNK_BYTES // (bsz * c_in * h * w * x.element_size())) + for start in range(0, t_out, step): + end = min(start + step, t_out) + frames = bsz * (end - start) + acc: torch.Tensor | None = None + for i, tap in enumerate(taps): + x_i = x[:, :, start + i : end + i].transpose(1, 2).reshape(frames, c_in, h, w) + x_i = x_i.contiguous(memory_format=torch.channels_last) + y_i = F.conv2d(x_i, tap, conv.bias if i == 0 else None, padding=(ph, pw)) + acc = y_i if acc is None else acc.add_(y_i) + assert acc is not None + out[:, :, start:end] = acc.reshape(bsz, end - start, conv.out_channels, h_out, w_out).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)") From f8bf642d97a7fbd8a0529ef43fc1799738c8c6cf Mon Sep 17 00:00:00 2001 From: Sabbagh Fares Date: Sat, 31 Oct 2026 15:04:18 +0100 Subject: [PATCH 2/6] Add tests for the MPS Conv3d patch The tests compare the patched forward with the stock Conv3d forward. They run only on a Mac with an MPS GPU. On other machines, pytest skips them. Each test finds one possible defect: - The patch does not copy a strided input into a dense layout. - The patch changes a Conv3d with stride or temporal padding. - The patch loses frames in the last partial chunk. --- backend/tests/test_mps_conv3d_as_conv2d.py | 58 ++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 backend/tests/test_mps_conv3d_as_conv2d.py diff --git a/backend/tests/test_mps_conv3d_as_conv2d.py b/backend/tests/test_mps_conv3d_as_conv2d.py new file mode 100644 index 000000000..1dc7db424 --- /dev/null +++ b/backend/tests/test_mps_conv3d_as_conv2d.py @@ -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) From f910415a1945ae2f7410b3657a1040fea28d485f Mon Sep 17 00:00:00 2001 From: Sabbagh Fares Date: Sat, 31 Oct 2026 15:38:14 +0100 Subject: [PATCH 3/6] Add a benchmark script for the MPS Conv3d patch The script compares the stock Conv3d with the patch on Apple Silicon. It does not need model weights. It uses one Conv3d for each stage of the conv VAE decoder. It shows the time, the TFLOPS, and the speedup. With --vae, the script also decodes one latent with the real conv VAE. It shows the stock and the patched decode times and the PSNR. Use the script to check the patch on a Mac and after a torch update. --- .../performance_runner/bench_mps_conv3d.py | 135 ++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 backend/performance_runner/bench_mps_conv3d.py diff --git a/backend/performance_runner/bench_mps_conv3d.py b/backend/performance_runner/bench_mps_conv3d.py new file mode 100644 index 000000000..0c45d2524 --- /dev/null +++ b/backend/performance_runner/bench_mps_conv3d.py @@ -0,0 +1,135 @@ +#!/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. Prints 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. Prints both decode times and the PSNR of patched vs stock frames. + +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 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 + +# One Conv3d per decoder stage: (channels, frames, height, width) for a 1024x576 decode. +SHAPES = [(1024, 16, 18, 32), (512, 32, 36, 64), (256, 64, 72, 128), (128, 32, 144, 256)] +DEFAULT_CHECKPOINT = ( + Path.home() / "Library/Application Support/LTXDesktop/models/ltx-2.5/ltx-2.5-video-vae-conv-bf16.safetensors" +) +LATENT_SHAPE = (1, 128, 16, 18, 32) # stage-2 latent for 1024x576, 121 frames +WARMUP, ITERS = 2, 5 + + +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() -> None: + torch.manual_seed(0) + print(f"{'layout':17} {'C':>5} {'T':>3} {'H':>4} {'W':>4} | {'stock ms':>9} {'TFLOPS':>6} | {'patch ms':>9} {'TFLOPS':>6} | speedup max|d|") + for layout in (torch.channels_last_3d, torch.contiguous_format): + for c, t, h, w in SHAPES: + conv = nn.Conv3d(c, c, 3, padding=(0, 1, 1)).to("mps", torch.bfloat16).to(memory_format=layout) + x = torch.randn(1, c, t + 2, h, w, device="mps", dtype=torch.bfloat16).contiguous(memory_format=layout) + flops = 2 * c * c * 27 * t * h * w + t_stock = _time(lambda: patch._original_forward(conv, x)) + t_patch = _time(lambda: patch._patched_forward(conv, x)) + diff = (patch._patched_forward(conv, x).float() - patch._original_forward(conv, x).float()).abs().max() + name = "channels_last_3d" if layout is torch.channels_last_3d else "contiguous" + print( + f"{name:17} {c:>5} {t:>3} {h:>4} {w:>4} | {t_stock * 1e3:>9.1f} {flops / t_stock / 1e12:>6.2f} | " + f"{t_patch * 1e3:>9.1f} {flops / t_patch / 1e12:>6.2f} | {t_stock / t_patch:>6.2f}x {diff.item():.4f}", + flush=True, + ) + del conv, x + torch.mps.empty_cache() + + +@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=576, width=1024, num_frames=121, device=device) + decoder = VideoDecoder(str(checkpoint), torch.bfloat16, device) + generator = torch.Generator(device="mps").manual_seed(0) + 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) -> None: + if not checkpoint.exists(): + sys.exit(f"Conv VAE checkpoint not found: {checkpoint}\nDownload it in the app or pass --checkpoint.") + torch.manual_seed(0) + latent = torch.randn(LATENT_SHAPE).to("mps", torch.bfloat16) + original = nn.Conv3d.forward + try: + nn.Conv3d.forward = original # type: ignore[method-assign] + stock, t_stock = _decode(checkpoint, latent) + print(f"stock decode {t_stock:6.1f}s", flush=True) + nn.Conv3d.forward = patch._patched_forward # type: ignore[method-assign] + patched, t_patch = _decode(checkpoint, latent) + print(f"patched decode {t_patch:6.1f}s ({t_stock / t_patch:.2f}x)", flush=True) + finally: + nn.Conv3d.forward = original # type: ignore[method-assign] + if not torch.isfinite(patched).all(): + sys.exit("FAIL: patched output has NaN or Inf values") + mse = (patched - stock).pow(2).mean().item() + span = (stock.max() - stock.min()).item() + psnr = float("inf") if mse == 0 else 10 * torch.log10(torch.tensor(span**2 / mse)).item() + print(f"patched vs stock: PSNR {psnr:.1f} dB, max|d| {(patched - stock).abs().max().item():.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.") + print(f"torch {torch.__version__}, macOS {platform.mac_ver()[0]}, {platform.machine()}, bf16\n") + bench_ops() + if args.vae: + print() + bench_vae(args.checkpoint) + + +if __name__ == "__main__": + main() From 9557da2295d0ab057df522dc27773d80260b7e5d Mon Sep 17 00:00:00 2001 From: Sabbagh Fares Date: Sat, 31 Oct 2026 15:47:46 +0100 Subject: [PATCH 4/6] Correct the memory note in the MPS Conv3d patch The old note gave a 7 GiB tile size. That value was not correct. The memory-efficient decoder does not keep a full tile in memory. The new note gives the measured cost. For a 540p/5 s decode, the peak MPS driver memory increases from 9.7 GiB to 10.7 GiB. --- backend/services/patches/mps_conv3d_as_conv2d.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/services/patches/mps_conv3d_as_conv2d.py b/backend/services/patches/mps_conv3d_as_conv2d.py index 53ed8c74d..affe566ae 100644 --- a/backend/services/patches/mps_conv3d_as_conv2d.py +++ b/backend/services/patches/mps_conv3d_as_conv2d.py @@ -13,8 +13,8 @@ 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 chunks so these copies stay small -next to a decode tile (~7 GiB at 128 ch, 80 x 448 x 768). +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``. From ca5e08bd714c414ad2db78a01bde2434e11b2444 Mon Sep 17 00:00:00 2001 From: Sabbagh Fares Date: Sun, 1 Nov 2026 21:58:08 +0100 Subject: [PATCH 5/6] Start the tap sum from the first conv2d The per-tap loop built its accumulator from None and asserted it after the loop. Running the first tap, which carries the bias, before the loop removes the Optional and the assert, and names the frame batching in one helper. Claude-Session: https://claude.ai/code/session_01M8Y4f9pRwDZfXY2VAqZNvz --- backend/services/patches/mps_conv3d_as_conv2d.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/backend/services/patches/mps_conv3d_as_conv2d.py b/backend/services/patches/mps_conv3d_as_conv2d.py index affe566ae..4d0d54e70 100644 --- a/backend/services/patches/mps_conv3d_as_conv2d.py +++ b/backend/services/patches/mps_conv3d_as_conv2d.py @@ -75,13 +75,15 @@ def _conv3d_as_conv2d(conv: nn.Conv3d, x: torch.Tensor) -> torch.Tensor: for start in range(0, t_out, step): end = min(start + step, t_out) frames = bsz * (end - start) - acc: torch.Tensor | None = None - for i, tap in enumerate(taps): + + def tap_input(i: int) -> torch.Tensor: + # Frames start+i .. end+i, batched into N and copied dense: MPS conv2d misreads strided views. x_i = x[:, :, start + i : end + i].transpose(1, 2).reshape(frames, c_in, h, w) - x_i = x_i.contiguous(memory_format=torch.channels_last) - y_i = F.conv2d(x_i, tap, conv.bias if i == 0 else None, padding=(ph, pw)) - acc = y_i if acc is None else acc.add_(y_i) - assert acc is not None + return x_i.contiguous(memory_format=torch.channels_last) + + acc = F.conv2d(tap_input(0), taps[0], conv.bias, padding=(ph, pw)) + for i in range(1, len(taps)): + acc.add_(F.conv2d(tap_input(i), taps[i], padding=(ph, pw))) out[:, :, start:end] = acc.reshape(bsz, end - start, conv.out_channels, h_out, w_out).transpose(1, 2) return out From d0320ae04f4d67dedf5cbb8fcc426bc179cb3b93 Mon Sep 17 00:00:00 2001 From: Sabbagh Fares Date: Mon, 2 Nov 2026 17:45:18 +0100 Subject: [PATCH 6/6] Name the factors and separate measurement from output in the Conv3d bench The bench script names the FLOP factors (FLOPS_PER_MAC, KERNEL_TAPS), derives the latent shape from the clip and VAE constants, uses one SEED constant (42), and returns results from bench_ops and bench_vae so that report prints once at the end. The patch and the bench use full variable names instead of two-letter ones. No change in behaviour: the tests pass and the --vae run gives the same 4.3x speedup and 54.3 dB PSNR. Claude-Session: https://claude.ai/code/session_01M8Y4f9pRwDZfXY2VAqZNvz --- .../performance_runner/bench_mps_conv3d.py | 150 +++++++++++++----- .../services/patches/mps_conv3d_as_conv2d.py | 46 +++--- 2 files changed, 138 insertions(+), 58 deletions(-) diff --git a/backend/performance_runner/bench_mps_conv3d.py b/backend/performance_runner/bench_mps_conv3d.py index 0c45d2524..04cac09d7 100644 --- a/backend/performance_runner/bench_mps_conv3d.py +++ b/backend/performance_runner/bench_mps_conv3d.py @@ -4,11 +4,14 @@ 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. Prints time, TFLOPS, + ``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. Prints both decode times and the PSNR of patched vs stock frames. + 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. @@ -26,6 +29,7 @@ import sys import time from collections.abc import Callable +from dataclasses import dataclass from pathlib import Path import torch @@ -34,15 +38,53 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import services.patches.mps_conv3d_as_conv2d as patch # noqa: E402 -# One Conv3d per decoder stage: (channels, frames, height, width) for a 1024x576 decode. +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" ) -LATENT_SHAPE = (1, 128, 16, 18, 32) # stage-2 latent for 1024x576, 121 frames 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() @@ -55,25 +97,36 @@ def _time(fn: Callable[[], torch.Tensor]) -> float: @torch.inference_mode() -def bench_ops() -> None: - torch.manual_seed(0) - print(f"{'layout':17} {'C':>5} {'T':>3} {'H':>4} {'W':>4} | {'stock ms':>9} {'TFLOPS':>6} | {'patch ms':>9} {'TFLOPS':>6} | speedup max|d|") +def bench_ops() -> list[OpResult]: + torch.manual_seed(SEED) + results: list[OpResult] = [] for layout in (torch.channels_last_3d, torch.contiguous_format): - for c, t, h, w in SHAPES: - conv = nn.Conv3d(c, c, 3, padding=(0, 1, 1)).to("mps", torch.bfloat16).to(memory_format=layout) - x = torch.randn(1, c, t + 2, h, w, device="mps", dtype=torch.bfloat16).contiguous(memory_format=layout) - flops = 2 * c * c * 27 * t * h * w - t_stock = _time(lambda: patch._original_forward(conv, x)) - t_patch = _time(lambda: patch._patched_forward(conv, x)) + 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() - name = "channels_last_3d" if layout is torch.channels_last_3d else "contiguous" - print( - f"{name:17} {c:>5} {t:>3} {h:>4} {w:>4} | {t_stock * 1e3:>9.1f} {flops / t_stock / 1e12:>6.2f} | " - f"{t_patch * 1e3:>9.1f} {flops / t_patch / 1e12:>6.2f} | {t_stock / t_patch:>6.2f}x {diff.item():.4f}", - flush=True, + 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() @@ -82,9 +135,9 @@ def _decode(checkpoint: Path, latent: torch.Tensor) -> tuple[torch.Tensor, float from ltx_pipelines.utils.helpers import tiling_config_for_vae device = torch.device("mps") - tiling = tiling_config_for_vae(str(checkpoint), height=576, width=1024, num_frames=121, device=device) + 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(0) + 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) @@ -94,27 +147,48 @@ def _decode(checkpoint: Path, latent: torch.Tensor) -> tuple[torch.Tensor, float return frames, elapsed -def bench_vae(checkpoint: Path) -> None: - if not checkpoint.exists(): - sys.exit(f"Conv VAE checkpoint not found: {checkpoint}\nDownload it in the app or pass --checkpoint.") - torch.manual_seed(0) +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, t_stock = _decode(checkpoint, latent) - print(f"stock decode {t_stock:6.1f}s", flush=True) + stock, stock_s = _decode(checkpoint, latent) nn.Conv3d.forward = patch._patched_forward # type: ignore[method-assign] - patched, t_patch = _decode(checkpoint, latent) - print(f"patched decode {t_patch:6.1f}s ({t_stock / t_patch:.2f}x)", flush=True) + patched, patched_s = _decode(checkpoint, latent) finally: nn.Conv3d.forward = original # type: ignore[method-assign] - if not torch.isfinite(patched).all(): - sys.exit("FAIL: patched output has NaN or Inf values") mse = (patched - stock).pow(2).mean().item() span = (stock.max() - stock.min()).item() - psnr = float("inf") if mse == 0 else 10 * torch.log10(torch.tensor(span**2 / mse)).item() - print(f"patched vs stock: PSNR {psnr:.1f} dB, max|d| {(patched - stock).abs().max().item():.4f}") + 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: @@ -124,11 +198,13 @@ def main() -> None: args = parser.parse_args() if not torch.backends.mps.is_available(): sys.exit("MPS is not available. This benchmark needs an Apple Silicon Mac.") - print(f"torch {torch.__version__}, macOS {platform.mac_ver()[0]}, {platform.machine()}, bf16\n") - bench_ops() - if args.vae: - print() - bench_vae(args.checkpoint) + 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__": diff --git a/backend/services/patches/mps_conv3d_as_conv2d.py b/backend/services/patches/mps_conv3d_as_conv2d.py index 4d0d54e70..d631b05a4 100644 --- a/backend/services/patches/mps_conv3d_as_conv2d.py +++ b/backend/services/patches/mps_conv3d_as_conv2d.py @@ -59,32 +59,36 @@ def _supported(conv: nn.Conv3d, x: torch.Tensor) -> bool: def _conv3d_as_conv2d(conv: nn.Conv3d, x: torch.Tensor) -> torch.Tensor: weight = conv.weight - taps = [weight[:, :, i].contiguous() for i in range(weight.shape[2])] - bsz, c_in, t_in, h, w = x.shape - t_out = t_in - len(taps) + 1 - kh, kw = conv.kernel_size[1], conv.kernel_size[2] - ph, pw = conv.padding[1], conv.padding[2] - h_out, w_out = h + 2 * ph - kh + 1, w + 2 * pw - kw + 1 + 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( - (bsz, conv.out_channels, t_out, h_out, w_out), device=x.device, dtype=x.dtype, memory_format=memory_format + (batch, conv.out_channels, out_frames, out_height, out_width), + device=x.device, + dtype=x.dtype, + memory_format=memory_format, ) - step = max(1, _CHUNK_BYTES // (bsz * c_in * h * w * x.element_size())) - for start in range(0, t_out, step): - end = min(start + step, t_out) - frames = bsz * (end - start) - - def tap_input(i: int) -> torch.Tensor: - # Frames start+i .. end+i, batched into N and copied dense: MPS conv2d misreads strided views. - x_i = x[:, :, start + i : end + i].transpose(1, 2).reshape(frames, c_in, h, w) - return x_i.contiguous(memory_format=torch.channels_last) - - acc = F.conv2d(tap_input(0), taps[0], conv.bias, padding=(ph, pw)) - for i in range(1, len(taps)): - acc.add_(F.conv2d(tap_input(i), taps[i], padding=(ph, pw))) - out[:, :, start:end] = acc.reshape(bsz, end - start, conv.out_channels, h_out, w_out).transpose(1, 2) + 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