fastframes-l-live / ff_aoti.py
linoyts's picture
linoyts HF Staff
Per-frame block as two graphs (ff_aoti) with FP8; optional aokit AOTI
e9f042c verified
Raw History Blame Contribute Delete
6.7 kB
"""FastFrames-L per-frame block as two AOTI-friendly graphs, with FP8 GEMMs.
Shared by the Space (eager or AOTI) and the HF Jobs build script, so the compiled graphs and the
eager fallback run exactly the same code.
The official ``CausalWanAttentionBlock.forward_frame`` (fast path) is split at the KV-cache write:
* ``PreAttn`` : modulation, norm1, fused QKV (FP8), q/k RMSNorm, RoPE -> q, k, v
* (eager) : write this frame's k, v into the cache slot
* ``PostAttn`` : self-attention over cache[:end], out-proj, text cross-attention, FFN -> x
so the only dynamic shape is the attention length ``end`` (1 to 21 frames of tokens).
"""
import json
import torch
import torch.nn as nn
from fastframes.wan.attention import attention
from fastframes.wan.causal_model import rope_real
E4M3_MAX = 448.0
_FP8_OK = [True]
def _quant_rows(t):
"""[M, K] -> (float8_e4m3fn [M, K], fp32 scale [M, 1]) with one scale per row."""
scale = t.abs().amax(dim=1, keepdim=True).float().clamp(min=1e-12) / E4M3_MAX
return (t.float() / scale).to(torch.float8_e4m3fn), scale
class FP8Linear(nn.Module):
"""y = x @ W.T + b with e4m3 weights (per-output-channel scale) and per-token activation scales."""
def __init__(self, weight, bias):
super().__init__()
w8, scale = _quant_rows(weight.detach())
self.register_buffer("w8", w8) # [N, K] row-major -> .t() is column-major
self.register_buffer("w_scale", scale.t().contiguous()) # [1, N]
self.register_buffer("bias", None if bias is None else bias.detach().to(torch.bfloat16))
def forward(self, x):
shape = x.shape
x2 = x.reshape(-1, shape[-1])
if _FP8_OK[0]:
x8, x_scale = _quant_rows(x2)
y = torch._scaled_mm(x8, self.w8.t(), scale_a=x_scale, scale_b=self.w_scale, bias=self.bias,
out_dtype=torch.bfloat16)
return y.reshape(*shape[:-1], -1)
w = self.w8.to(torch.bfloat16) * self.w_scale.t().to(torch.bfloat16)
return torch.nn.functional.linear(x2.to(torch.bfloat16), w, self.bias).reshape(*shape[:-1], -1)
class PreAttn(nn.Module):
def __init__(self, block, qkv):
super().__init__()
self.block = block
self.qkv = qkv
def forward(self, x, e, rope):
blk, sa = self.block, self.block.self_attn
tokens = x.shape[1]
e = (blk.modulation.unsqueeze(1) + e).chunk(6, dim=2)
h = (blk.norm1(x).unflatten(1, (1, tokens)) * (1 + e[1]) + e[0]).flatten(1, 2)
q, k, v = self.qkv(h).chunk(3, dim=-1)
shape = (x.shape[0], tokens, sa.num_heads, sa.head_dim)
q = rope_real(sa.norm_q(q).view(shape), rope)
k = rope_real(sa.norm_k(k).view(shape), rope)
return q, k, v.view(shape)
class PostAttn(nn.Module):
def __init__(self, block):
super().__init__()
self.block = block
def forward(self, x, e, q, k_all, v_all, text_k, text_v):
blk, sa = self.block, self.block.self_attn
tokens = x.shape[1]
e = (blk.modulation.unsqueeze(1) + e).chunk(6, dim=2)
y = sa.o(attention(q, k_all, v_all).flatten(2))
x = x + (y.unflatten(1, (1, tokens)) * e[2]).flatten(1, 2)
x = x + blk.cross_attn(blk.norm3(x), None, cache={"k": text_k, "v": text_v})
y = blk.ffn((blk.norm2(x).unflatten(1, (1, tokens)) * (1 + e[4]) + e[3]).flatten(1, 2))
return x + (y.unflatten(1, (1, tokens)) * e[5]).flatten(1, 2)
def install(pipe, fp8=True):
"""Swap the per-frame linears to FP8 and route every block's forward_frame through Pre/PostAttn.
Registers ``pipe.dit.ff_pre`` / ``pipe.dit.ff_post`` (ModuleLists) so aokit can patch them by name.
"""
dit, fast = pipe.dit, pipe.fast
qkv = []
for (w, b), blk in zip(fast.qkv, dit.blocks):
sa, ca = blk.self_attn, blk.cross_attn
if fp8:
qkv.append(FP8Linear(w, b))
sa.o = FP8Linear(sa.o.weight, sa.o.bias)
ca.q = FP8Linear(ca.q.weight, ca.q.bias)
ca.o = FP8Linear(ca.o.weight, ca.o.bias)
blk.ffn[0] = FP8Linear(blk.ffn[0].weight, blk.ffn[0].bias)
blk.ffn[2] = FP8Linear(blk.ffn[2].weight, blk.ffn[2].bias)
else:
lin = nn.Linear(w.shape[1], w.shape[0], device=w.device, dtype=w.dtype)
lin.weight.data, lin.bias.data = w, b
qkv.append(lin)
sa.q = sa.k = sa.v = None # superseded by the fused QKV of the fast path (text K/V use cross_attn)
fast.qkv = None
dit.ff_pre = nn.ModuleList(PreAttn(blk, q) for blk, q in zip(dit.blocks, qkv))
dit.ff_post = nn.ModuleList(PostAttn(blk) for blk in dit.blocks)
def make(pre, post):
def forward_frame(x, e, grid_sizes, freqs, cross_kv, kv_cache, frame, fast=None, layer=0):
tokens = x.shape[1]
start, end = frame * tokens, (frame + 1) * tokens
q, k, v = pre(x, e, fast.rope[frame])
kv_cache["k"][:, start:end].copy_(k)
kv_cache["v"][:, start:end].copy_(v)
return post(x, e, q, kv_cache["k"][:, :end], kv_cache["v"][:, :end], cross_kv["k"], cross_kv["v"])
return forward_frame
for blk, pre, post in zip(dit.blocks, dit.ff_pre, dit.ff_post):
blk.forward_frame = make(pre, post) # instance attribute shadows the method; block.forward dispatches here
def load_aoti(pipe, repo, token=None):
"""aokit.load the compiled Pre/PostAttn graphs; each call falls back to eager if the graph refuses it."""
import aokit
from huggingface_hub import hf_hub_download
config = json.load(open(hf_hub_download(repo, "config.json", token=token)))
if config.get("torch") != torch.__version__:
raise RuntimeError(f"AOTI built for torch {config.get('torch')}, runtime has {torch.__version__}")
if config.get("fp8") is not True:
raise RuntimeError("AOTI artifact was not built for the FP8 graph")
dit = pipe.dit
eager = {name: [m.forward for m in getattr(dit, name)] for name in ("ff_pre", "ff_post")}
aokit.load(dit, repo) # patches ff_pre[i].forward / ff_post[i].forward; weights stay live
for name in ("ff_pre", "ff_post"):
for m, fallback in zip(getattr(dit, name), eager[name]):
compiled = m.forward
def forward(*args, _c=compiled, _e=fallback, **kwargs):
try:
return _c(*args, **kwargs)
except Exception as exc: # noqa: BLE001
print(f"[aoti] eager fallback: {type(exc).__name__}: {str(exc)[:160]}", flush=True)
return _e(*args, **kwargs)
m.forward = forward
return config