"""FastFrames-S on MLX: a port of apple-aiml-research/ml-fastframes inference. Components, as in the reference pipeline: * umT5-XXL text encoder (run once per prompt), * the frame-wise causal Wan2.1-1.3B DiT (Causal Forcing++ 2-step generator) with a per-layer KV cache of one 1560-token slot per latent frame, * the KV refinement network, which repairs each finished frame's cache slot instead of a second, clean DiT pass, * the causal ConvNeXt pixel decoder, which replaces the Wan VAE. Weights are plain dicts of mx.arrays keyed exactly like the torch state dicts, and every op mirrors its torch counterpart (Linear y = x @ W.T + b, baddbmm y = b + x @ W). """ from __future__ import annotations import math import mlx.core as mx BF16 = mx.bfloat16 # ---------------------------------------------------------------------------- primitives def lin(x, W, name, bias=True): y = x @ W[name + ".weight"].T return y + W[name + ".bias"] if bias else y def layer_norm(x, eps, weight=None, bias=None): # torch computes half-precision LayerNorm in fp32 and returns the input dtype return mx.fast.layer_norm(x.astype(mx.float32), weight, bias, eps).astype(x.dtype) \ if weight is None else mx.fast.layer_norm(x.astype(mx.float32), weight.astype(mx.float32), bias.astype(mx.float32), eps).astype(x.dtype) def rms_norm(x, weight, eps): """WanRMSNorm / T5LayerNorm: normalise in fp32, cast back, then scale.""" xf = x.astype(mx.float32) y = (xf * mx.rsqrt((xf * xf).mean(-1, keepdims=True) + eps)).astype(x.dtype) return y * weight def gelu_tanh(x): return 0.5 * x * (1.0 + mx.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * x * x * x))) def gelu_exact(x): return 0.5 * x * (1.0 + mx.erf(x / math.sqrt(2.0))) def silu(x): return x * mx.sigmoid(x) def sdpa(q, k, v, mask=None, scale=None): """[B, H, L, D] attention.""" return mx.fast.scaled_dot_product_attention( q, k, v, scale=q.shape[-1] ** -0.5 if scale is None else scale, mask=mask) def sinusoidal(dim, t): half = dim // 2 t = mx.array(t, dtype=mx.float32).reshape(-1) freqs = mx.power(10000.0, -mx.arange(half, dtype=mx.float32) / half) a = t[:, None] * freqs[None] return mx.concatenate([mx.cos(a), mx.sin(a)], axis=1) # ---------------------------------------------------------------------------- scheduler class FlowMatch: """Wan rectified-flow schedule, shift 5, 1000-step grid (timesteps map to the nearest entry).""" def __init__(self, shift=5.0, steps=1000): import numpy as np # float32 like torch.linspace, then the shift, then the timestep grid s = np.linspace(1.0, 0.0, steps + 1, dtype=np.float32)[:-1] sig = (np.float32(shift) * s / (np.float32(1) + np.float32(shift - 1) * s)).astype(np.float32) self.sigmas = sig.astype(np.float64) self.timesteps = (sig * np.float32(1000)).astype(np.float64) def sigma(self, t): import numpy as np return float(self.sigmas[int(np.argmin(np.abs(self.timesteps - t)))]) # ---------------------------------------------------------------------------- Wan DiT DIM, HEADS, HD, LAYERS, FFN = 1536, 12, 128, 30, 8960 LAT_H, LAT_W, Z = 60, 104, 16 GH, GW = LAT_H // 2, LAT_W // 2 FRAME_TOKENS = GH * GW # 1560 def rope_tables(num_frames): """Per-frame (cos, sin) of the 3-D RoPE: [F][1560, 1, 64] each, fp32.""" import numpy as np c = HD // 2 # 64 complex pairs split = (c - 2 * (c // 3), c // 3, c // 3) # 22, 21, 21 def params(dim): return 1.0 / np.power(10000.0, np.arange(0, dim, 2, dtype=np.float64) / dim) ft = params(HD - 4 * (HD // 6)) # 22 freqs fh = params(2 * (HD // 6)) # 21 fw = params(2 * (HD // 6)) assert (len(ft), len(fh), len(fw)) == split hh = np.arange(GH)[:, None, None] * fh[None, None, :] ww = np.arange(GW)[None, :, None] * fw[None, None, :] out = [] for f in range(num_frames): ang = np.concatenate([ np.broadcast_to(f * ft, (GH, GW, len(ft))), np.broadcast_to(hh, (GH, GW, len(fh))), np.broadcast_to(ww, (GH, GW, len(fw))), ], axis=-1).reshape(FRAME_TOKENS, 1, c) out.append((mx.array(np.cos(ang), dtype=mx.float32), mx.array(np.sin(ang), dtype=mx.float32))) return out def rope(x, table): """x [L, H, D] (pairs interleaved) rotated in fp32, returned in x.dtype.""" cos, sin = table L, H, D = x.shape p = x.astype(mx.float32).reshape(L, H, D // 2, 2) re, im = p[..., 0], p[..., 1] out = mx.stack([re * cos - im * sin, re * sin + im * cos], axis=-1) return out.reshape(L, H, D).astype(x.dtype) class WanDiT: """Frame-wise causal Wan2.1-T2V-1.3B (batch 1).""" def __init__(self, W, num_frames=21): self.W = W self.num_frames = num_frames self.rope = rope_tables(num_frames) self.patch_w = W["patch_embedding.weight"].reshape(DIM, Z * 4) self.dtype = W["patch_embedding.weight"].dtype # -- conditioning def time_conditioning(self, t): W = self.W e = sinusoidal(256, [t]).astype(self.dtype) e = lin(silu(lin(e, W, "time_embedding.0")), W, "time_embedding.2") e0 = lin(silu(e), W, "time_projection.1").reshape(1, 6, DIM) return e0, e.reshape(1, 1, DIM) def text_cache(self, prompt_embeds): """prompt_embeds [L<=512, 4096] -> per-layer cross-attention (k, v) [1, H, 512, D].""" W = self.W ctx = mx.zeros((512, 4096), dtype=self.dtype) ctx = mx.concatenate([prompt_embeds.astype(self.dtype), ctx[prompt_embeds.shape[0]:]], axis=0) ctx = lin(gelu_tanh(lin(ctx[None], W, "text_embedding.0")), W, "text_embedding.2") caches = [] for i in range(LAYERS): p = f"blocks.{i}.cross_attn" k = rms_norm(lin(ctx, W, p + ".k"), W[p + ".norm_k.weight"], 1e-6) v = lin(ctx, W, p + ".v") caches.append((k.reshape(1, 512, HEADS, HD).transpose(0, 2, 1, 3), v.reshape(1, 512, HEADS, HD).transpose(0, 2, 1, 3))) return caches def new_kv_cache(self): shape = (1, HEADS, self.num_frames * FRAME_TOKENS, HD) return [{"k": mx.zeros(shape, dtype=self.dtype), "v": mx.zeros(shape, dtype=self.dtype)} for _ in range(LAYERS)] def patch_embed(self, latent): """latent [16, 60, 104] -> [1, 1560, 1536] in Conv3d channel order.""" x = latent.reshape(Z, GH, 2, GW, 2).transpose(1, 3, 0, 2, 4).reshape(1, FRAME_TOKENS, Z * 4) return x.astype(self.dtype) @ self.patch_w.T + self.W["patch_embedding.bias"] # -- one frame def forward_frame(self, latent, t_cond, text_cache, kv_cache, frame): """latent [16, 60, 104] -> (flow [16, 60, 104], pre-head hidden [1, 1560, 1536]).""" W = self.W e0, e_head = t_cond x = self.patch_embed(latent) start, end = frame * FRAME_TOKENS, (frame + 1) * FRAME_TOKENS for i in range(LAYERS): p = f"blocks.{i}" e = W[p + ".modulation"] + e0 # [1, 6, C] sh1, sc1, g1, sh2, sc2, g2 = (e[:, j:j + 1] for j in range(6)) h = layer_norm(x, 1e-6) * (1 + sc1) + sh1 sa = p + ".self_attn" q = rms_norm(lin(h, W, sa + ".q"), W[sa + ".norm_q.weight"], 1e-6) k = rms_norm(lin(h, W, sa + ".k"), W[sa + ".norm_k.weight"], 1e-6) v = lin(h, W, sa + ".v") q = rope(q.reshape(FRAME_TOKENS, HEADS, HD), self.rope[frame]) k = rope(k.reshape(FRAME_TOKENS, HEADS, HD), self.rope[frame]) v = v.reshape(FRAME_TOKENS, HEADS, HD) c = kv_cache[i] c["k"][:, :, start:end] = k.transpose(1, 0, 2)[None] c["v"][:, :, start:end] = v.transpose(1, 0, 2)[None] y = sdpa(q.transpose(1, 0, 2)[None], c["k"][:, :, :end], c["v"][:, :, :end]) y = lin(y.transpose(0, 2, 1, 3).reshape(1, FRAME_TOKENS, DIM), W, sa + ".o") x = x + y * g1 ca = p + ".cross_attn" hn = layer_norm(x, 1e-6, W[p + ".norm3.weight"], W[p + ".norm3.bias"]) qc = rms_norm(lin(hn, W, ca + ".q"), W[ca + ".norm_q.weight"], 1e-6) qc = qc.reshape(1, FRAME_TOKENS, HEADS, HD).transpose(0, 2, 1, 3) yc = sdpa(qc, *text_cache[i]) x = x + lin(yc.transpose(0, 2, 1, 3).reshape(1, FRAME_TOKENS, DIM), W, ca + ".o") h = layer_norm(x, 1e-6) * (1 + sc2) + sh2 y = lin(gelu_tanh(lin(h, W, p + ".ffn.0")), W, p + ".ffn.2") x = x + y * g2 eh = W["head.modulation"] + e_head # [1, 2, C] out = lin(layer_norm(x, 1e-6) * (1 + eh[:, 1:2]) + eh[:, 0:1], W, "head.head") # unpatchify "fhwpqrc->cfphqwr", p=1, q=r=2, c=16 flow = out.reshape(GH, GW, 2, 2, Z).transpose(4, 0, 2, 1, 3).reshape(Z, LAT_H, LAT_W) return flow, x # ---------------------------------------------------------------------------- KV refiner class KVRefiner: def __init__(self, W): self.W = W self.d_a = W["stem_in.weight"].shape[0] self.n_stem = len({k.split(".")[1] for k in W if k.startswith("stem_blocks.")}) self.dtype = W["stem_in.weight"].dtype def embed_timestep(self, t): W = self.W e = sinusoidal(256, [t]).astype(self.dtype) return lin(silu(lin(e, W, "t_embed.mlp.0")), W, "t_embed.mlp.2") # [1, d_a] def compute_phi(self, stem, e): W, d = self.W, self.d_a x = lin(stem.astype(self.dtype), W, "stem_in") S = x.shape[1] for i in range(self.n_stem): p = f"stem_blocks.{i}" mod = lin(silu(e), W, p + ".mod.lin")[:, None] # [1, 1, 6d] sh1, sc1, g1, sh2, sc2, g2 = (mod[..., j * d:(j + 1) * d] for j in range(6)) h = layer_norm(x, 1e-5) * (1 + sc1) + sh1 qkv = lin(h, W, p + ".qkv").reshape(1, S, 3, 8, d // 8).transpose(2, 0, 3, 1, 4) y = sdpa(qkv[0], qkv[1], qkv[2]).transpose(0, 2, 1, 3).reshape(1, S, d) x = x + g1 * lin(y, W, p + ".proj") h = layer_norm(x, 1e-5) * (1 + sc2) + sh2 x = x + g2 * lin(gelu_tanh(lin(h, W, p + ".mlp.0")), W, p + ".mlp.2") return layer_norm(x, 1e-5, W["stem_norm.weight"], W["stem_norm.bias"]) def repair_all(self, nK, nV, phi, e): """nK, nV [30, S, 1536]; phi [1, S, d_a]; e [1, d_a].""" W, d = self.W, self.d_a g = "heads_grouped.gemms.0." n = nK.shape[0] def bmm(x, name): return W[g + name + "_b"] + x @ W[g + name + "_w"] phi_v = mx.broadcast_to((phi[0] @ W[f"heads_grouped.phi_proj.{d}.weight"].T)[None], (n, *phi.shape[1:])) pk, pv = bmm(nK, "proj_k"), bmm(nV, "proj_v") h = bmm(mx.concatenate([pk, pv, phi_v], axis=-1), "fuse") e1 = mx.broadcast_to(silu(e).reshape(1, 1, d), (n, 1, d)) sm = bmm(e1, "mod") shift, scale = sm[..., :d], sm[..., d:] h = layer_norm(h, 1e-5) * (1 + scale) + shift h = bmm(gelu_tanh(bmm(h, "m0")), "m2") k = nK + bmm(h, "dK") kh = k.reshape(n, -1, HEADS, HD) rh = nK.reshape(n, -1, HEADS, HD) norm = lambda a: mx.sqrt((a.astype(mx.float32) ** 2).sum(-1, keepdims=True)).astype(a.dtype) k = (kh * (norm(rh) / (norm(kh) + 1e-6))).reshape(n, -1, DIM) v = (nV + bmm(h, "dV")) * mx.exp(W[g + "v_logscale"]) return k, v # ---------------------------------------------------------------------------- pixel decoder class PixelDecoder: """Causal ConvNeXt decoder: DiT hidden states [F*1560, 1536] -> RGB [4F, 480, 832, 3].""" def __init__(self, W, dtype=mx.float32): self.W = {k: v.astype(dtype) for k, v in W.items()} self.dtype = dtype self.low = len({k.split(".")[1] for k in W if k.startswith("conv_low.")}) self.high = len({k.split(".")[1] for k in W if k.startswith("conv_high.")}) def _block(self, x, p): """x [T, H, W, C] channels-last.""" W = self.W w = W[p + ".dw.weight"] # [C, 1, 3, 3, 3] T, H, Wd, C = x.shape xp = mx.pad(x, [(2, 0), (1, 1), (1, 1), (0, 0)]) acc = mx.zeros_like(x) for kt in range(3): for kh in range(3): for kw in range(3): acc = acc + xp[kt:kt + T, kh:kh + H, kw:kw + Wd] * w[:, 0, kt, kh, kw] y = acc + W[p + ".dw.bias"] y = layer_norm(y, 1e-6, W[p + ".norm.weight"], W[p + ".norm.bias"]) y = y @ W[p + ".pw1.weight"].reshape(-1, C).T + W[p + ".pw1.bias"] y = gelu_exact(y) y = y @ W[p + ".pw2.weight"].reshape(C, -1).T + W[p + ".pw2.bias"] return x + y def __call__(self, feats, e_mod): """feats [F, 1560, C]; e_mod [F, 1, C] -> pixels [4F, 480, 832, 3] in [-1, 1].""" W = self.W F_ = feats.shape[0] mod = W["modulation"] + e_mod.astype(self.dtype) # [F, 2, C] x = layer_norm(feats.astype(self.dtype), 1e-6) * (1 + mod[:, 1:2]) + mod[:, 0:1] x = x.reshape(F_, GH, GW, DIM) x = layer_norm(x, 1e-6, W["entry_norm.weight"], W["entry_norm.bias"]) x = x @ W["entry_pw.weight"].reshape(DIM, DIM).T + W["entry_pw.bias"] for i in range(self.low): x = self._block(x, f"conv_low.{i}") for i in range(self.high): x = self._block(x, f"conv_high.{i}") tok = lin(x.reshape(F_, FRAME_TOKENS, DIM), W, "fc_out") # [F, 1560, 3072] # "fhwpqrc->cfphqwr" with patch (4, 16, 16), channels-last output [F*4, H*16, W*16, 3] px = tok.reshape(F_, GH, GW, 4, 16, 16, 3).transpose(0, 3, 1, 4, 2, 5, 6) return px.reshape(F_ * 4, GH * 16, GW * 16, 3) # ---------------------------------------------------------------------------- umT5-XXL class UMT5Encoder: """Wan's umT5-XXL encoder: 24 layers, per-layer relative position bias, gated GELU.""" def __init__(self, W, layers=24, heads=64, buckets=32): self.W, self.layers, self.heads, self.buckets = W, layers, heads, buckets def _buckets(self, L): import numpy as np rel = np.arange(L)[None, :] - np.arange(L)[:, None] nb = self.buckets // 2 out = (rel > 0).astype(np.int64) * nb rel = np.abs(rel) max_exact = nb // 2 with np.errstate(divide="ignore"): large = max_exact + (np.log(rel.astype(np.float32) / max_exact) / math.log(128 / max_exact) * (nb - max_exact)).astype(np.int64) large = np.minimum(large, nb - 1) return mx.array(out + np.where(rel < max_exact, rel, large)) def __call__(self, ids, mask): """ids, mask [L] (L=512) -> [L, 4096], padding rows zeroed.""" W = self.W L = ids.shape[0] x = W["token_embedding.weight"][ids][None] dt = x.dtype buckets = self._buckets(L) keymask = mx.where(mask[None, None, None, :] > 0, 0.0, -3.0e38).astype(mx.float32) H = self.heads for i in range(self.layers): p = f"blocks.{i}" bias = W[p + ".pos_embedding.embedding.weight"][buckets].transpose(2, 0, 1)[None] h = rms_norm(x, W[p + ".norm1.weight"], 1e-6) q = lin(h, W, p + ".attn.q", False).reshape(1, L, H, -1).transpose(0, 2, 1, 3) k = lin(h, W, p + ".attn.k", False).reshape(1, L, H, -1).transpose(0, 2, 1, 3) v = lin(h, W, p + ".attn.v", False).reshape(1, L, H, -1).transpose(0, 2, 1, 3) att = (q @ k.transpose(0, 1, 3, 2)).astype(mx.float32) + bias.astype(mx.float32) + keymask att = mx.softmax(att, axis=-1).astype(dt) y = (att @ v).transpose(0, 2, 1, 3).reshape(1, L, -1) x = x + lin(y, W, p + ".attn.o", False) h = rms_norm(x, W[p + ".norm2.weight"], 1e-6) y = lin(h, W, p + ".ffn.fc1", False) * gelu_tanh(lin(h, W, p + ".ffn.gate.0", False)) x = x + lin(y, W, p + ".ffn.fc2", False) x = rms_norm(x, W["norm.weight"], 1e-6)[0] n = int(mask.sum().item()) return mx.concatenate([x[:n], mx.zeros((L - n, x.shape[1]), dtype=dt)], axis=0) # ---------------------------------------------------------------------------- pipeline FIRST_FRAME_T = (1000.0, 937.5, 833.3333129882812, 625.0) TIMESTEPS = (1000.0, 833.3333129882812) REFINE_T = 833.3333129882812 class FastFramesS: def __init__(self, dit_w, refiner_w, decoder_w, num_frames=21, decoder_dtype=mx.float32): self.dit = WanDiT(dit_w, num_frames) self.refiner = KVRefiner(refiner_w) self.decoder = PixelDecoder(decoder_w, decoder_dtype) self.sched = FlowMatch() self.num_frames = num_frames self._tc = {} self._ref_e = None def t_cond(self, t): if t not in self._tc: self._tc[t] = self.dit.time_conditioning(t) mx.eval(self._tc[t]) return self._tc[t] def predict(self, x, t, frame, text_cache, kv): flow, feat = self.dit.forward_frame(x, self.t_cond(t), text_cache, kv, frame) sigma = self.sched.sigma(t) x0 = (x.astype(mx.float32) - sigma * flow.astype(mx.float32)).astype(x.dtype) return x0, feat, self.t_cond(t)[1] def refine(self, x0, frame, kv): if self._ref_e is None: self._ref_e = self.refiner.embed_timestep(REFINE_T) e = self._ref_e s, t = frame * FRAME_TOKENS, (frame + 1) * FRAME_TOKENS phi = self.refiner.compute_phi(self.dit.patch_embed(x0), e) # cache is [1, H, T, D]; refiner wants [layers, tokens, H*D] keys = mx.stack([c["k"][0, :, s:t].transpose(1, 0, 2).reshape(FRAME_TOKENS, DIM) for c in kv]) vals = mx.stack([c["v"][0, :, s:t].transpose(1, 0, 2).reshape(FRAME_TOKENS, DIM) for c in kv]) keys, vals = self.refiner.repair_all(keys, vals, phi, e) for i, c in enumerate(kv): c["k"][:, :, s:t] = keys[i].reshape(FRAME_TOKENS, HEADS, HD).transpose(1, 0, 2)[None].astype(c["k"].dtype) c["v"][:, :, s:t] = vals[i].reshape(FRAME_TOKENS, HEADS, HD).transpose(1, 0, 2)[None].astype(c["v"].dtype) def rollout(self, prompt_embeds, noise, transition, on_frame=None): """noise [F, 16, 60, 104]; transition(step, frame) -> [16, 60, 104]. Returns per-frame decoder features [F, 1560, C] and head modulation [F, 1, C].""" text_cache = self.dit.text_cache(prompt_embeds) mx.eval(text_cache) kv = self.dit.new_kv_cache() feats, mods = [], [] for f in range(self.num_frames): sched = FIRST_FRAME_T if f == 0 else TIMESTEPS x = noise[f] for step, t in enumerate(sched): x0, feat, mod = self.predict(x, t, f, text_cache, kv) if step + 1 < len(sched): sig = self.sched.sigma(sched[step + 1]) eps = transition(step, f) x = ((1 - sig) * x0.astype(mx.float32) + sig * eps.astype(mx.float32)).astype(noise.dtype) feats.append(feat[0]) mods.append(mod[0]) if f == 0: self.predict(x0, 0.0, f, text_cache, kv) else: self.refine(x0, f, kv) mx.eval(feats[-1], mods[-1], [c["k"] for c in kv], [c["v"] for c in kv]) if on_frame is not None: on_frame(f) return mx.stack(feats), mx.stack(mods) def decode(self, feats, mods, num_pixel_frames=81): px = self.decoder(feats, mods) return px[px.shape[0] - num_pixel_frames:]