#!/usr/bin/env python3 """Generate FastFrames-L video with MLX using an existing FastFrames-S port.""" import argparse from functools import cache import gc import html import importlib.util import json import os from pathlib import Path import re import shutil import subprocess import sys from tempfile import NamedTemporaryFile from time import perf_counter import mlx.core as mx import numpy as np from quantize import BITS, GROUP_SIZE, METADATA PROJECT_ROOT = Path(__file__).resolve().parent DEFAULT_S_MODEL = PROJECT_ROOT / "dependencies/FastFrames-S" DEFAULT_TOKENIZER = PROJECT_ROOT / "dependencies/Wan2.1-T2V-1.3B/google/umt5-xxl" FIRST_FRAME_STEPS = (1000.0, 937.0, 833.0, 625.0) FOLLOWING_STEPS = (1000.0, 833.0) LAYERS, HEADS, WIDTH, FFN = 40, 40, 5120, 13824 GIB = 1024**3 def q8_projection(x, weight, scales, offsets): return mx.quantized_matmul( x, weight, scales, offsets, transpose=True, group_size=GROUP_SIZE, bits=BITS, ) def load_large_backbone(port_path): # Load a private module so the S text encoder and 1536-wide pixel head # can keep using their original dimensions in the normal import. spec = importlib.util.spec_from_file_location("_fastframes_l_backbone", port_path / "ff_ref.py") backbone = importlib.util.module_from_spec(spec) spec.loader.exec_module(backbone) backbone.DIM = WIDTH backbone.HEADS = HEADS backbone.LAYERS = LAYERS backbone.FFN = FFN backbone.REFINE_T = FOLLOWING_STEPS[-1] dense_linear = backbone.lin def linear(x, weights, name, bias=True): weight = weights[name + ".weight"] if weight.dtype != mx.uint32: return dense_linear(x, weights, name, bias) y = q8_projection(x, weight, weights[name + ".scales"], weights[name + ".biases"]) return y + weights[name + ".bias"] if bias else y backbone.lin = linear return backbone def load_nax_attention(): steel = Path(mx.__file__).parent / "include/mlx/backend/metal/kernels/steel" fragments = [] for filename in ("defines.h", "utils/integral_constant.h", "utils/type_traits.h", "attn/nax.h"): lines = (steel / filename).read_text().splitlines() fragments.extend(line for line in lines if not line.startswith(("#pragma once", '#include "mlx/'))) operations, body = (PROJECT_ROOT / "fastframes_attention.metal").read_text().split("// Kernel body") kernel = mx.fast.metal_kernel( name="fastframes_register_attention", input_names=["query", "keys", "values", "range_end"], output_names=["result"], header="\n".join(fragments) + "\n" + operations, source=body, ) @cache def range_end(end): return mx.array([end], dtype=mx.int32) def attend(query, keys, values, end): # The Metal source uses strides of 1,600 query and 1,560 output rows. query = mx.pad(query, [(0, 0), (0, 0), (0, 40), (0, 0)]) return kernel( inputs=[query, keys, values, range_end(end)], template=[("CACHE_ROWS", keys.shape[2]), ("KEY_ALIGNED", end % 32 == 0)], grid=(49 * 64, HEADS, 1), threadgroup=(64, 1, 1), output_shapes=[(1, HEADS, 1560, 128)], output_dtypes=[mx.bfloat16], )[0] return attend def make_model( backbone, dit_weights, refiner_weights, frame_count, eval_every=1, nax_attention=None, compile_ffn=False, ): gelu = backbone.gelu_tanh def q8_ffn(h, residual, gate, up, down): hidden = gelu(q8_projection(h, *up[:3]) + up[3]) return residual + gate * (q8_projection(hidden, *down[:3]) + down[3]) compiled_ffn = mx.compile(q8_ffn) if compile_ffn else None class BoundedWanDiT(backbone.WanDiT): def __init__(self, weights, frames): super().__init__(weights, frames) if compiled_ffn is not None: self.ffn_parameters = [ tuple( tuple(weights[f"blocks.{i}.ffn.{layer}.{field}"] for field in ("weight", "scales", "biases", "bias")) for layer in (0, 2) ) for i in range(LAYERS) ] def forward_frame(self, latent, t_cond, text_cache, kv_cache, frame): weights = self.W e0, e_head = t_cond x = self.patch_embed(latent) tokens, head_dim = backbone.FRAME_TOKENS, backbone.HD start, end = frame * tokens, (frame + 1) * tokens lin, norm, rms = backbone.lin, backbone.layer_norm, backbone.rms_norm pending = [] for index, cache in enumerate(kv_cache): block = f"blocks.{index}" modulation = weights[block + ".modulation"] + e0 sh1, sc1, g1, sh2, sc2, g2 = mx.split(modulation, 6, axis=1) h = norm(x, 1e-6) * (1 + sc1) + sh1 attn = block + ".self_attn" q = rms(lin(h, weights, attn + ".q"), weights[attn + ".norm_q.weight"], 1e-6) k = rms(lin(h, weights, attn + ".k"), weights[attn + ".norm_k.weight"], 1e-6) v = lin(h, weights, attn + ".v") q = backbone.rope(q.reshape(tokens, HEADS, head_dim), self.rope[frame]) k = backbone.rope(k.reshape(tokens, HEADS, head_dim), self.rope[frame]) cache["k"][:, :, start:end] = k.transpose(1, 0, 2)[None] cache["v"][:, :, start:end] = v.reshape(tokens, HEADS, head_dim).transpose(1, 0, 2)[None] q = q.transpose(1, 0, 2)[None] if nax_attention is None: attended = backbone.sdpa(q, cache["k"][:, :, :end], cache["v"][:, :, :end]) else: attended = nax_attention(q, cache["k"], cache["v"], end) x = x + g1 * lin(attended.transpose(0, 2, 1, 3).reshape(1, tokens, WIDTH), weights, attn + ".o") attn = block + ".cross_attn" h = norm(x, 1e-6, weights[block + ".norm3.weight"], weights[block + ".norm3.bias"]) q = rms(lin(h, weights, attn + ".q"), weights[attn + ".norm_q.weight"], 1e-6) q = q.reshape(1, tokens, HEADS, head_dim).transpose(0, 2, 1, 3) attended = backbone.sdpa(q, *text_cache[index]) x = x + lin(attended.transpose(0, 2, 1, 3).reshape(1, tokens, WIDTH), weights, attn + ".o") h = norm(x, 1e-6) * (1 + sc2) + sh2 if compiled_ffn is None: x = x + g2 * lin(gelu(lin(h, weights, block + ".ffn.0")), weights, block + ".ffn.2") else: x = compiled_ffn(h, x, g2, *self.ffn_parameters[index]) pending.extend((cache["k"], cache["v"])) if (index + 1) % eval_every == 0 or index + 1 == len(kv_cache): mx.eval(x, pending) pending.clear() shift, scale = mx.split(weights["head.modulation"] + e_head, 2, axis=1) flow = lin(norm(x, 1e-6) * (1 + scale) + shift, weights, "head.head") flow = flow.reshape(backbone.GH, backbone.GW, 2, 2, backbone.Z) return flow.transpose(4, 0, 2, 1, 3).reshape(latent.shape), x class FastFramesL(backbone.FastFramesS): def __init__(self): self.dit = BoundedWanDiT(dit_weights, frame_count) self.refiner = backbone.KVRefiner(refiner_weights) self.sched = backbone.FlowMatch() self._tc = {} self._ref_e = None def rollout(self, embedding, seed): shape = (frame_count, backbone.Z, backbone.LAT_H, backbone.LAT_W) mx.random.seed(seed) noise = mx.random.normal(shape, dtype=mx.bfloat16) transitions = mx.random.normal((3, *shape), dtype=mx.bfloat16) text_cache = self.dit.text_cache(embedding) kv_cache = self.dit.new_kv_cache() mx.eval(noise, transitions, text_cache, kv_cache) features, modulations = [], [] started = perf_counter() for frame in range(frame_count): schedule = FIRST_FRAME_STEPS if frame == 0 else FOLLOWING_STEPS latent = noise[frame] for step, timestep in enumerate(schedule): clean, feature, mod = self.predict(latent, timestep, frame, text_cache, kv_cache) if step + 1 < len(schedule): sigma = self.sched.sigma(schedule[step + 1]) latent = ((1 - sigma) * clean.astype(mx.float32) + sigma * transitions[step, frame].astype(mx.float32)).astype(mx.bfloat16) mx.eval(clean, feature, mod, latent) print(f"Latent {frame + 1}/{frame_count}, étape {step + 1}/{len(schedule)}", flush=True) features.append(feature[0]) modulations.append(mod[0]) if frame == 0: self.predict(clean, 0.0, frame, text_cache, kv_cache) elif frame + 1 < frame_count: self.refine(clean, frame, kv_cache) mx.eval(kv_cache, features[-1], modulations[-1]) print(f"Latent {frame + 1}/{frame_count} terminé à {perf_counter() - started:.1f} s", flush=True) return mx.stack(features), mx.stack(modulations) return FastFramesL() def encode_prompt(prompt, tokenizer_dir, model_dir, encoder_type): from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(str(tokenizer_dir), local_files_only=True) cleaned = re.sub(r"\s+", " ", html.unescape(html.unescape(prompt)).strip()).strip() tokens = tokenizer( [cleaned], padding="max_length", truncation=True, max_length=512, add_special_tokens=True, return_tensors="np", ) encoder = encoder_type(mx.load(str(model_dir / "umt5_xxl.safetensors"))) embedding = encoder(mx.array(tokens["input_ids"][0]), mx.array(tokens["attention_mask"][0])) mx.eval(embedding) return embedding, mx.get_peak_memory() / GIB def write_mp4(pixels, output, fps): ffmpeg = shutil.which("ffmpeg") if ffmpeg is None: raise RuntimeError("FFmpeg est requis pour exporter la vidéo.") _, height, width, _ = pixels.shape with NamedTemporaryFile(dir=output.parent, suffix=".mp4", delete=False) as temp: pending = Path(temp.name) try: subprocess.run( [ffmpeg, "-y", "-v", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{width}x{height}", "-r", str(fps), "-i", "-", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-movflags", "+faststart", str(pending)], input=pixels.tobytes(), check=True, ) os.link(pending, output) finally: pending.unlink() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("prompt") parser.add_argument("output", type=Path) parser.add_argument("--weights", type=Path, default=PROJECT_ROOT / "weights/fastframes-l") parser.add_argument("--s-model", type=Path, default=DEFAULT_S_MODEL) parser.add_argument("--tokenizer", type=Path, default=DEFAULT_TOKENIZER) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--latent-frames", type=int, choices=range(2, 22), default=5, metavar="2–21") parser.add_argument("--dit", choices=("bf16", "q8"), default="bf16") parser.add_argument("--eval-every", type=int, choices=(1, 2, 4), default=1) parser.add_argument("--attention", choices=("mlx", "nax"), default="mlx") parser.add_argument("--compile-ffn", action="store_true", help="compile the Q8 feed-forward block") args = parser.parse_args() if args.compile_ffn and args.dit != "q8": parser.error("--compile-ffn nécessite --dit q8") dit_name = "dit-q8" if args.dit == "q8" else "dit" for name in (dit_name, "kv_refiner", "pixel_decoder"): if not (args.weights / f"{name}.safetensors").is_file(): parser.error(f"Poids manquants : {args.weights / (name + '.safetensors')}") if not all((args.s_model / filename).is_file() for filename in ("ff_ref.py", "umt5_xxl.safetensors")): parser.error(f"Code ou encodeur FastFrames-S introuvable dans {args.s_model}") if not (args.tokenizer / "spiece.model").is_file(): parser.error(f"Tokenizer Wan introuvable dans {args.tokenizer}") if args.output.suffix.lower() != ".mp4" or not args.output.parent.is_dir(): parser.error("La sortie doit être un fichier .mp4 dans un dossier existant.") if args.output.exists() or args.output.with_suffix(".json").exists(): parser.error(f"Sortie déjà existante : {args.output}") sys.path.insert(0, str(args.s_model)) import ff_ref mx.set_default_device(mx.gpu) mx.set_cache_limit(2 * GIB) mx.reset_peak_memory() started = perf_counter() embedding, text_peak = encode_prompt(args.prompt, args.tokenizer, args.s_model, ff_ref.UMT5Encoder) gc.collect() mx.clear_cache() stats = {"model": "apple/FastFrames-L", "prompt": args.prompt, "seed": args.seed, "dit_precision": args.dit, "eval_every": args.eval_every, "attention": args.attention, "compiled_ffn": args.compile_ffn, "text_s": perf_counter() - started, "text_peak_gib": text_peak} print(f"Texte encodé en {stats['text_s']:.1f} s", flush=True) mx.reset_peak_memory() started = perf_counter() backbone = load_large_backbone(args.s_model) dit_weights, metadata = mx.load(str(args.weights / f"{dit_name}.safetensors"), return_metadata=True) if args.dit == "q8" and metadata != METADATA: raise ValueError(f"Métadonnées Q8 incompatibles : {metadata}") refiner_weights = mx.load(str(args.weights / "kv_refiner.safetensors")) if dit_weights["patch_embedding.weight"].shape != (WIDTH, 16, 1, 2, 2): raise ValueError("Le checkpoint ne correspond pas au générateur FastFrames-L.") attention = load_nax_attention() if args.attention == "nax" else None model = make_model( backbone, dit_weights, refiner_weights, args.latent_frames, eval_every=args.eval_every, nax_attention=attention, compile_ffn=args.compile_ffn, ) mx.eval(dit_weights, refiner_weights) stats["load_s"] = perf_counter() - started print(f"Générateur chargé en {stats['load_s']:.1f} s", flush=True) started = perf_counter() features, modulations = model.rollout(embedding, args.seed) mx.eval(features, modulations) stats["rollout_s"] = perf_counter() - started stats["rollout_peak_gib"] = mx.get_peak_memory() / GIB del model, dit_weights, refiner_weights gc.collect() mx.clear_cache() started = perf_counter() weights = mx.load(str(args.weights / "pixel_decoder.safetensors")) bridge = weights["bridge.weight"].astype(mx.bfloat16) decoder_weights = { name.removeprefix("pixel_head."): weight for name, weight in weights.items() if name.startswith("pixel_head.") } decoder = ff_ref.PixelDecoder(decoder_weights, dtype=mx.bfloat16) pixels = decoder(features.astype(mx.bfloat16) @ bridge.T, modulations.astype(mx.bfloat16) @ bridge.T) frame_count = 4 * args.latent_frames - 3 # Wan convention: the first latent supplies one RGB frame, then four per latent. pixels = pixels[-frame_count:].astype(mx.float32) if not mx.all(mx.isfinite(pixels)).item(): raise RuntimeError("Pixels non finis dans la sortie du décodeur.") pixels = np.asarray(mx.round((mx.clip(pixels, -1, 1) + 1) * 127.5).astype(mx.uint8)) stats["decode_s"] = perf_counter() - started stats["frames"] = list(pixels.shape) stats["fps"] = 16 write_mp4(pixels, args.output, fps=stats["fps"]) args.output.with_suffix(".json").write_text(json.dumps(stats, indent=2) + "\n") print(json.dumps(stats, indent=2), flush=True) if __name__ == "__main__": main()