Spaces:
Paused
Paused
Commit ·
ece563b
1
Parent(s): b269983
Wire AOTInductor compilation of the LTX-2 DiT (aokit) into the live pipeline
Browse filesaoti_dit.py: hooks LTXModel._process_transformer_blocks and, on the first real
forward, AOTI-compiles ONE audio+video block (weight-less, regional) and runs
all 48 blocks through that single optimized graph, each bound to its own
weights — the ahead-of-time replacement for torch.compile (no JIT). Installed
at module scope so the hook is live in FastVideo's spawned worker; eager
fallback on any failure. Inductor cache pinned to the overlay disk.
Verified end-to-end: full AV block exports at the real shape (video 3456x4096,
audio 68x2048), compiles in ~60s once, then generation drops from ~8.5s to
~3.8s/segment (~5.8s end-to-end incl. fMP4) — ~2.2x faster DiT.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- aoti_dit.py +182 -0
- app.py +8 -0
aoti_dit.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lazy, in-worker AOTInductor compilation of the LTX-2 DiT blocks (via aokit).
|
| 2 |
+
|
| 3 |
+
This is the ahead-of-time replacement for torch.compile on the transformer
|
| 4 |
+
(the DiT). DreamVerse JIT-compiles the blocks; we AOTI-compile ONE block
|
| 5 |
+
(weight-less) and run all 48 through that single optimized graph, each bound to
|
| 6 |
+
its own weights — aokit's regional design.
|
| 7 |
+
|
| 8 |
+
Wiring constraint: FastVideo runs the blocks inside a spawned worker, and AOTI
|
| 9 |
+
needs a real-shape example, so we hook `LTXModel._process_transformer_blocks`
|
| 10 |
+
and compile lazily on the first real forward (captures the true video+audio
|
| 11 |
+
shapes automatically). Installed at import time so the patch is live in the
|
| 12 |
+
worker (spawn re-imports the app module). Any failure → eager fallback, so the
|
| 13 |
+
app never breaks.
|
| 14 |
+
|
| 15 |
+
Set DREAMVERSE_AOTI=0 to disable.
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
import os
|
| 19 |
+
import tempfile
|
| 20 |
+
import time
|
| 21 |
+
import traceback
|
| 22 |
+
from dataclasses import replace
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
ENABLED = os.getenv("DREAMVERSE_AOTI", "1") == "1"
|
| 27 |
+
|
| 28 |
+
# Order of TransformerArgs fields we marshal (tuples expand to 2 tensors).
|
| 29 |
+
_TUPLE_FIELDS = {"positional_embeddings", "cross_positional_embeddings"}
|
| 30 |
+
_FIELDS = ["x", "context", "context_mask", "timesteps", "embedded_timestep",
|
| 31 |
+
"positional_embeddings", "cross_positional_embeddings",
|
| 32 |
+
"cross_scale_shift_timestep", "cross_gate_timestep"]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _flatten(ta):
|
| 36 |
+
"""TransformerArgs -> (list[Tensor], spec). spec records presence/shape."""
|
| 37 |
+
tensors, spec = [], []
|
| 38 |
+
for f in _FIELDS:
|
| 39 |
+
v = getattr(ta, f)
|
| 40 |
+
if v is None:
|
| 41 |
+
spec.append((f, "none"))
|
| 42 |
+
elif f in _TUPLE_FIELDS:
|
| 43 |
+
tensors.extend(v)
|
| 44 |
+
spec.append((f, "tuple2"))
|
| 45 |
+
else:
|
| 46 |
+
tensors.append(v)
|
| 47 |
+
spec.append((f, "tensor"))
|
| 48 |
+
return tensors, spec
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _unflatten(tensors, spec):
|
| 52 |
+
"""(iterator of Tensors, spec) -> TransformerArgs."""
|
| 53 |
+
from fastvideo.models.dits.ltx2 import TransformerArgs
|
| 54 |
+
it = iter(tensors)
|
| 55 |
+
kw = {}
|
| 56 |
+
for f, kind in spec:
|
| 57 |
+
if kind == "none":
|
| 58 |
+
kw[f] = None
|
| 59 |
+
elif kind == "tuple2":
|
| 60 |
+
kw[f] = (next(it), next(it))
|
| 61 |
+
else:
|
| 62 |
+
kw[f] = next(it)
|
| 63 |
+
kw["enabled"] = True
|
| 64 |
+
return TransformerArgs(**kw)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class _BlockWrapper(torch.nn.Module):
|
| 68 |
+
"""Flat-tensor view of ONE real AV block, for export."""
|
| 69 |
+
def __init__(self, block, vspec, aspec, n_video, scalars):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.block = block
|
| 72 |
+
self.vspec, self.aspec = vspec, aspec
|
| 73 |
+
self.n_video = n_video
|
| 74 |
+
self.scalars = scalars # video_original_seq_len, audio_original_seq_len
|
| 75 |
+
|
| 76 |
+
def forward(self, *flat):
|
| 77 |
+
video = _unflatten(flat[:self.n_video], self.vspec)
|
| 78 |
+
audio = _unflatten(flat[self.n_video:], self.aspec)
|
| 79 |
+
vout, aout = self.block(
|
| 80 |
+
video=video, audio=audio,
|
| 81 |
+
video_original_seq_len=self.scalars[0],
|
| 82 |
+
audio_original_seq_len=self.scalars[1],
|
| 83 |
+
skip_cross_modal_attn=False,
|
| 84 |
+
skip_video_self_attn=False,
|
| 85 |
+
skip_audio_self_attn=False,
|
| 86 |
+
)
|
| 87 |
+
return vout.x, aout.x
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _make_block_forward(orig_forward, lazy_with_weights, vspec, aspec, baked_vx_shape, baked_ax_shape):
|
| 91 |
+
"""Replacement block.forward: AOTI when shapes/flags match, else eager."""
|
| 92 |
+
def forward(video=None, audio=None, video_original_seq_len=None, audio_original_seq_len=None,
|
| 93 |
+
skip_cross_modal_attn=False, skip_video_self_attn=False, skip_audio_self_attn=False):
|
| 94 |
+
ok = (video is not None and audio is not None
|
| 95 |
+
and not skip_cross_modal_attn and not skip_video_self_attn and not skip_audio_self_attn
|
| 96 |
+
and tuple(video.x.shape) == baked_vx_shape and tuple(audio.x.shape) == baked_ax_shape)
|
| 97 |
+
if not ok:
|
| 98 |
+
return orig_forward(video=video, audio=audio,
|
| 99 |
+
video_original_seq_len=video_original_seq_len,
|
| 100 |
+
audio_original_seq_len=audio_original_seq_len,
|
| 101 |
+
skip_cross_modal_attn=skip_cross_modal_attn,
|
| 102 |
+
skip_video_self_attn=skip_video_self_attn,
|
| 103 |
+
skip_audio_self_attn=skip_audio_self_attn)
|
| 104 |
+
vt, _ = _flatten(video)
|
| 105 |
+
at, _ = _flatten(audio)
|
| 106 |
+
vx, ax = lazy_with_weights(*vt, *at)
|
| 107 |
+
return replace(video, x=vx), replace(audio, x=ax)
|
| 108 |
+
return forward
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _compile_blocks(model, video, audio, vsl, asl):
|
| 112 |
+
import aokit
|
| 113 |
+
blocks = model.transformer_blocks
|
| 114 |
+
block0 = blocks[0]
|
| 115 |
+
vt, vspec = _flatten(video)
|
| 116 |
+
at, aspec = _flatten(audio)
|
| 117 |
+
n_video = len(vt)
|
| 118 |
+
wrapper = _BlockWrapper(block0, vspec, aspec, n_video, (vsl, asl)).eval()
|
| 119 |
+
|
| 120 |
+
print(f"[AOTI] exporting AV block: video.x={tuple(video.x.shape)} audio.x={tuple(audio.x.shape)} "
|
| 121 |
+
f"({n_video}+{len(at)} tensors)", flush=True)
|
| 122 |
+
flat = (*vt, *at)
|
| 123 |
+
with torch.no_grad():
|
| 124 |
+
exported = torch.export.export(wrapper, flat, {})
|
| 125 |
+
print("[AOTI] torch.export OK; AOTInductor compiling ...", flush=True)
|
| 126 |
+
|
| 127 |
+
pkg_dir = tempfile.mkdtemp(prefix="aoti_dit_")
|
| 128 |
+
inductor_cfg = {"max_autotune": True, "max_autotune_gemm": True,
|
| 129 |
+
"coordinate_descent_tuning": True, "triton.cudagraphs": False}
|
| 130 |
+
t0 = time.perf_counter()
|
| 131 |
+
aokit.compile_and_save(pkg_dir, exported, inductor_configs=inductor_cfg, submodule="b")
|
| 132 |
+
pt2 = os.path.join(pkg_dir, "submodules", "b", "package.pt2")
|
| 133 |
+
print(f"[AOTI] compiled in {time.perf_counter()-t0:.0f}s -> {os.path.getsize(pt2)//1024} KB", flush=True)
|
| 134 |
+
|
| 135 |
+
try:
|
| 136 |
+
from aokit.aokit import LazyAOTIModel
|
| 137 |
+
except Exception:
|
| 138 |
+
from aokit import LazyAOTIModel # type: ignore
|
| 139 |
+
lazy = LazyAOTIModel(pt2)
|
| 140 |
+
|
| 141 |
+
baked_vx = tuple(video.x.shape)
|
| 142 |
+
baked_ax = tuple(audio.x.shape)
|
| 143 |
+
n = 0
|
| 144 |
+
for blk in blocks:
|
| 145 |
+
# Weights are external; the graph's constants are "block.<fqn>".
|
| 146 |
+
weights = {f"block.{k}": v for k, v in blk.state_dict().items()}
|
| 147 |
+
lww = lazy.with_weights(weights)
|
| 148 |
+
blk.forward = _make_block_forward(blk.forward, lww, vspec, aspec, baked_vx, baked_ax)
|
| 149 |
+
n += 1
|
| 150 |
+
print(f"[AOTI] installed AOTI forward on {n} blocks (shape {baked_vx})", flush=True)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def install():
|
| 154 |
+
if not ENABLED:
|
| 155 |
+
return
|
| 156 |
+
try:
|
| 157 |
+
from fastvideo.models.dits.ltx2 import LTXModel
|
| 158 |
+
except Exception as e:
|
| 159 |
+
print(f"[AOTI] fastvideo not importable here ({e}); skipping", flush=True)
|
| 160 |
+
return
|
| 161 |
+
if getattr(LTXModel, "_aoti_patched", False):
|
| 162 |
+
return
|
| 163 |
+
LTXModel._aoti_patched = True
|
| 164 |
+
orig = LTXModel._process_transformer_blocks
|
| 165 |
+
|
| 166 |
+
def patched(self, video, audio, video_original_seq_len=None, audio_original_seq_len=None,
|
| 167 |
+
skip_cross_modal_attn=False, skip_video_self_attn_blocks=None,
|
| 168 |
+
skip_audio_self_attn_blocks=None):
|
| 169 |
+
if (video is not None and audio is not None
|
| 170 |
+
and not getattr(self, "_aoti_ready", False) and not getattr(self, "_aoti_failed", False)):
|
| 171 |
+
try:
|
| 172 |
+
_compile_blocks(self, video, audio, video_original_seq_len, audio_original_seq_len)
|
| 173 |
+
self._aoti_ready = True
|
| 174 |
+
except Exception as e:
|
| 175 |
+
traceback.print_exc()
|
| 176 |
+
print(f"[AOTI] compile failed -> eager fallback: {e}", flush=True)
|
| 177 |
+
self._aoti_failed = True
|
| 178 |
+
return orig(self, video, audio, video_original_seq_len, audio_original_seq_len,
|
| 179 |
+
skip_cross_modal_attn, skip_video_self_attn_blocks, skip_audio_self_attn_blocks)
|
| 180 |
+
|
| 181 |
+
LTXModel._process_transformer_blocks = patched
|
| 182 |
+
print("[AOTI] installed lazy in-worker DiT compiler hook", flush=True)
|
app.py
CHANGED
|
@@ -29,9 +29,17 @@ import wave
|
|
| 29 |
|
| 30 |
os.environ.setdefault("FASTVIDEO_ATTENTION_BACKEND", "TORCH_SDPA")
|
| 31 |
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
|
|
|
|
|
|
| 32 |
|
| 33 |
import numpy as np
|
| 34 |
import spaces
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
from gradio import Server
|
| 36 |
from fastapi import WebSocket, WebSocketDisconnect
|
| 37 |
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
|
|
|
|
| 29 |
|
| 30 |
os.environ.setdefault("FASTVIDEO_ATTENTION_BACKEND", "TORCH_SDPA")
|
| 31 |
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 32 |
+
# Keep the AOTInductor/compile cache on the big overlay disk (not a small tmpfs).
|
| 33 |
+
os.environ.setdefault("TORCHINDUCTOR_CACHE_DIR", "/home/user/.cache/dreamverse_inductor")
|
| 34 |
|
| 35 |
import numpy as np
|
| 36 |
import spaces
|
| 37 |
+
|
| 38 |
+
# AOTI DiT compiler — installs a hook on LTXModel._process_transformer_blocks
|
| 39 |
+
# that AOTInductor-compiles the blocks (weight-less, regional) on first forward.
|
| 40 |
+
# At module scope so the hook is live in FastVideo's spawned worker too.
|
| 41 |
+
import aoti_dit
|
| 42 |
+
aoti_dit.install()
|
| 43 |
from gradio import Server
|
| 44 |
from fastapi import WebSocket, WebSocketDisconnect
|
| 45 |
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
|