fastframes-voice / fp8_blocks.py
fffiloni's picture
Select FastFrames-S or FastFrames-L for a studio take
4e162b1 verified
Raw History Blame Contribute Delete
5.24 kB
"""Eager FP8 blocks from linoyts/fastframes-l-live, revision e9f042c.
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 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