fastframes-l / app.py
mfn
Keep the earlier 4-input API working
e42efea
Raw History Blame Contribute Delete
19.1 kB
import os
import random
import subprocess
import tempfile
import time
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import gradio as gr
import spaces
import torch
import mfn_hf # shared look + usage analytics; import before @spaces.GPU
from huggingface_hub import snapshot_download
# Inference code vendored from github.com/apple-aiml-research/ml-fastframes (commit a655ef0, fastframes/).
from fastframes.pipeline import MODELS, FastFrames, configure_backends, to_uint8
from fastframes.wan.causal_model import allocate_kv_cache
L_ID, L_REVISION = "apple/FastFrames-L", "18f30cbdd91943baa274e4237dd09b6d19e58ca9"
S_ID, S_REVISION = "apple/FastFrames-S", "aa099efcedf1b65447106bf9004cde75821f7387"
# FastFrames-S runs its add-on networks around the frozen Causal Forcing++ two-step generator (Apache-2.0).
CF_ID, CF_REVISION = "zhuhz22/Causal-Forcing", "2f8eb8bb6eeb1238da9d13e5420d342a74d634a6"
# umT5-XXL text encoder and tokenizer only; the file is identical in the 1.3B and 14B Wan repos, so both models share it.
WAN_ID, WAN_REVISION = "Wan-AI/Wan2.1-T2V-14B", "a064a6c71f5be440641209c07bf2a5ce7a2ff5e4"
FPS = 16
WIDTH, HEIGHT = 832, 480
MAX_SEED = 2**31 - 1
MAX_CHARS = 2000
# Lengths the released model supports: a prefix of its 21-latent-frame rollout (each latent frame = 4 video frames).
LENGTHS = {"2 s": 9, "3 s": 13, "4 s": 17, "5 s": 21}
DEFAULT_LENGTH = "5 s"
CHUNK = 3 # latent frames per streamed segment (0.75 s of video)
DECODER_CONTEXT = 6 # the pixel decoder's causal receptive field, in latent frames
# Segments are held back until every later one is predicted to reach the player at least this long before playback
# gets to it (covers segment hand-off and playlist polling). When generation outruns playback this starts almost
# immediately; when it is slower, playback starts late enough that it never has to stop and wait.
START_MARGIN = 1.0
# --------------------------------------------------------------------------------------------------- model
WAN_DIR = Path(snapshot_download(
WAN_ID, revision=WAN_REVISION, allow_patterns=["models_t5_umt5-xxl-enc-bf16.pth", "google/umt5-xxl/*"]))
L_SPEC = MODELS["ff-l"]
L_DIR = Path(snapshot_download(L_ID, revision=L_REVISION, allow_patterns=["fastframes-l/*"]))
PIPE_L = FastFrames.from_pretrained(L_SPEC.config, WAN_DIR, L_DIR / L_SPEC.dit, L_DIR / L_SPEC.refiner,
L_DIR / L_SPEC.decoder)
S_SPEC = MODELS["ff-s"]
S_DIR = Path(snapshot_download(S_ID, revision=S_REVISION, allow_patterns=["fastframes-s/*"]))
CF_DIR = Path(snapshot_download(CF_ID, revision=CF_REVISION, allow_patterns=[S_SPEC.dit]))
PIPE_S = FastFrames.from_pretrained(S_SPEC.config, WAN_DIR, CF_DIR / S_SPEC.dit, S_DIR / S_SPEC.refiner,
S_DIR / S_SPEC.decoder, text_encoder=PIPE_L.text_encoder)
PIPES = {"FastFrames-S": PIPE_S, "FastFrames-L": PIPE_L}
DEFAULT_MODEL = "FastFrames-S"
# --------------------------------------------------------------------------------------------------- video
_FFMPEG_IN = ["ffmpeg", "-y", "-v", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{WIDTH}x{HEIGHT}",
"-r", str(FPS), "-i", "-", "-c:v", "libx264", "-pix_fmt", "yuv420p"]
class Encoder:
"""Encodes off the generation loop: one worker thread copies each decoded chunk to the host on its own CUDA
stream, writes it as an MPEG-TS segment and appends it to the full MP4, while the GPU moves on."""
def __init__(self, out_dir):
self.out_dir = Path(out_dir)
self.pool = ThreadPoolExecutor(max_workers=1)
self.stream = torch.cuda.Stream()
self.mp4 = self.out_dir / "fastframes.mp4"
self.full = subprocess.Popen(_FFMPEG_IN + ["-preset", "fast", "-crf", "17", "-movflags", "+faststart",
str(self.mp4)], stdin=subprocess.PIPE)
self.count = 0
def _job(self, frames, ready, path):
with torch.cuda.stream(self.stream):
self.stream.wait_event(ready)
data = frames.cpu().numpy().tobytes()
self.full.stdin.write(data)
subprocess.run(_FFMPEG_IN + ["-preset", "ultrafast", "-crf", "18", "-f", "mpegts", str(path)],
input=data, check=True)
return str(path), frames.shape[0]
def submit(self, frames):
ready = torch.cuda.Event()
ready.record()
path = self.out_dir / f"part{self.count:03d}.ts"
self.count += 1
return self.pool.submit(self._job, frames, ready, path)
def finish(self):
self.pool.shutdown(wait=True)
self.full.stdin.close()
if self.full.wait() != 0:
raise RuntimeError("ffmpeg failed")
return str(self.mp4)
def _decode_window(pipe, features, modulation, start, end):
"""uint8 frames of latent frames ``[start, end)`` on the GPU; decoding from ``start - 6`` gives the causal
decoder its full history, so the frames match a one-shot decode."""
first = max(0, start - DECODER_CONTEXT)
feats = torch.cat(features[first:end], dim=1)
mods = torch.cat(modulation[first:end], dim=1)
height, width = pipe.config.latent_size
grid = torch.tensor([[end - first, height // 2, width // 2]], device=pipe.device, dtype=torch.long)
with torch.autocast("cuda", dtype=torch.bfloat16):
pixels = pipe.decoder(feats, mods, grid)[0]
pixels = pixels[4 * (start - first):]
if start == 0:
pixels = pixels[3:] # the decoder's first three frames are dropped (84 -> 81)
return to_uint8(pixels)
def _chunk_ends(num_latent):
"""``(last latent frame, video frames)`` of each streamed segment."""
ends, decoded = [], 0
for frame in range(num_latent):
if frame + 1 - decoded >= CHUNK or frame + 1 == num_latent:
ends.append((frame, 4 * (frame + 1 - decoded) - (3 if decoded == 0 else 0)))
decoded = frame + 1
return ends
def _ready_to_start(marks, num_latent):
"""Whether playback can start now and never catch up with generation.
Uses per-frame CUDA events that have already completed (no synchronisation), all on the GPU clock; the latest
completed event is a lower bound on "now", so the check errs towards starting later. Attention cost grows with
the cache, so the time per latent frame is extrapolated linearly. Every segment not yet generated must arrive
START_MARGIN before playback (starting now) reaches it.
"""
done = []
for event in marks[1:]:
if not event.query():
break
done.append(event)
if len(done) < 3:
return False
times = [marks[0].elapsed_time(e) / 1000 for e in done] # end of latent frames 0 .. n-1
per_frame = [b - a for a, b in zip(times, times[1:])] # frame 0 has extra steps, so it is left out
slope = (per_frame[-1] - per_frame[0]) / (len(per_frame) - 1) if len(per_frame) >= 2 else 0.0
slope = max(slope, 0.015 * per_frame[0])
now, last_done, before = times[-1], len(done) - 1, 0.0
for end, n in _chunk_ends(num_latent):
if end > last_done:
k = end - last_done
arrival = now + k * per_frame[-1] + slope * k * (k + 1) / 2
if arrival + START_MARGIN > now + before:
return False
before += n / FPS
return True
@torch.inference_mode()
def stream_video(pipe, prompt, seed, num_latent, out_dir):
"""FastFrames.rollout with the pixel decoder run every CHUNK latent frames.
Yields ``("chunk", ts_path, n_frames)`` once enough video is buffered for smooth playback, then
``("final", mp4_path, None)``.
"""
cfg = pipe.config
configure_backends(cfg) # each model's matmul precision (TF32 on for L, off for S)
enc = Encoder(out_dir)
pending, started = deque(), False
marks = [torch.cuda.Event(enable_timing=True)]
marks[0].record()
prompt_embeds = pipe.encode_prompt(prompt)
with pipe.autocast():
noise, transition = pipe._noise(seed)
text_cache = pipe.dit.text_cache(prompt_embeds)
kv_cache = allocate_kv_cache(pipe.dit, cfg.num_frames, pipe.frame_tokens, device=pipe.device)
features, modulation = [], []
decoded = 0
for frame in range(num_latent):
schedule = cfg.first_frame_timesteps if frame == 0 else cfg.timesteps
x = noise[:, frame:frame + 1]
for step, timestep in enumerate(schedule):
x0, feature, mod = pipe._predict(x, timestep, frame, text_cache, kv_cache)
if step + 1 < len(schedule):
next_t = torch.full((1,), schedule[step + 1], device=pipe.device, dtype=torch.float32)
eps = transition(step, frame)
x = pipe.scheduler.add_noise(x0.flatten(0, 1), eps, next_t).unflatten(0, x0.shape[:2])
features.append(feature)
modulation.append(mod)
last = frame + 1 == num_latent
if frame + 1 - decoded >= CHUNK or last:
frames = _decode_window(pipe, features, modulation, decoded, frame + 1)
pending.append(enc.submit(frames))
decoded = frame + 1
if not last:
if frame == 0:
pipe._predict(x0, 0.0, frame, text_cache, kv_cache)
else:
pipe._refine(x0, frame, kv_cache)
marks.append(torch.cuda.Event(enable_timing=True))
marks[-1].record()
if not started and pending:
started = last or _ready_to_start(marks, num_latent)
while started and pending: # flush the buffer
path, n = pending.popleft().result()
yield "chunk", path, n
while started and pending and (last or pending[0].done()):
path, n = pending.popleft().result()
yield "chunk", path, n
yield "final", enc.finish(), None
def gpu_duration(model, prompt, seed, length):
frames = LENGTHS.get(length, 21)
if model == "FastFrames-L":
return 20 + 2 * frames # about 0.35 s per latent frame on a full GPU
return 15 + frames // 2
@spaces.GPU(duration=gpu_duration, size="xlarge")
def _generate(model, prompt, seed, length):
out_dir = tempfile.mkdtemp(prefix="ff_")
for kind, path, _ in stream_video(PIPES[model], prompt, seed, LENGTHS.get(length, 21), out_dir):
yield kind, path
def generate(prompt, length, seed, randomize_seed, model):
prompt = (prompt or "").strip()
if not prompt:
raise gr.Error("Enter a prompt.")
if randomize_seed:
seed = random.randint(0, MAX_SEED)
seed = int(seed)
t0 = time.time()
if model not in PIPES:
model = "FastFrames-L" # callers of the earlier API, which had no model choice
for kind, path in _generate(model, prompt[:MAX_CHARS], seed, length):
if kind == "chunk":
yield path, gr.skip(), seed, gr.skip()
else:
yield gr.skip(), path, seed, f"Took {time.time() - t0:.1f} s"
# Prompts from the FastFrames project page (data/prompts/demos.txt of the official repository).
EXAMPLES = [
'A realistic photo of a llama wearing colorful pajamas dancing energetically on a stage under vibrant disco lighting. The llama has large floppy ears and a playful expression, moving its legs in a lively dance. It wears a red and yellow striped pajama top and matching pajama pants, with a fluffy tail swaying behind it. The stage is adorned with glittering disco balls and colorful lights, casting a lively and joyful atmosphere. The background features blurred audience members and a backdrop with disco-themed decorations. A dynamic shot capturing the llama mid-dance from a slightly elevated angle.',
'Late autumn in a cozy café, a woman in a burgundy sweater and gold earrings fills the foreground in UHD. She stirs coffee slowly, then smiles as she watches leaves tumble past the window and rain streaks the glass. The camera pushes in to capture steam curling around her face, then eases back to show warm lamps, glossy pastries, and wet pavement reflecting city lights outside. Crisp fabric detail, natural skin tones, and subtle film grain create a calm, cinematic mood.',
"A drone view of waves crashing against the rugged cliffs along Big Sur’s Garay Point beach. The crashing blue waters create white-tipped waves, while the golden light of the setting sun illuminates the rocky shore, casting long shadows. In the distance, a small island with a lighthouse stands tall, its beam piercing the twilight. Green shrubbery covers the cliff’s edge, and the steep drop from the road down to the beach is a dramatic feat, with the cliff’s edges jutting out over the sea. The camera angle provides a bird's-eye view, capturing the raw beauty of the coast and the rugged landscape of the Pacific Coast Highway. The scene is bathed in a warm, golden hue, highlighting the textures and details of the rocky terrain.",
'A serene watercolor painting of a mother duck leading her six ducklings across a tranquil pond. The mother duck has a gentle expression, her feathers glistening in the sunlight, and she frequently glances back to ensure all her ducklings are safely following in a neat little line. The ducklings follow closely behind, their small heads bobbing up and down as they waddle along. The background features a peaceful pond with lily pads and ducks floating nearby, creating a harmonious and natural scene. A mid-shot from a slightly elevated angle captures the mother duck and her ducklings in motion.',
'A slow-motion shot of a fiery volcanic landscape, with molten lava erupting from deep craters. The camera flies through the lava, capturing the intense heat and dramatic splashes as they hit the lens. The lighting is cinematic and moody, casting dramatic shadows and highlighting the vivid orange and red hues. The color grade is high-contrast and dramatic, emphasizing the raw power of the eruption. The background features towering cliffs and dense smoke, creating a sense of awe and danger. A dynamic overhead view, providing a thrilling and immersive experience.',
'At a rooftop garden above Seoul at night, a violinist in a black velvet coat and sparkling hairpin stands prominent in ultra-realistic 4K with city lights bokeh. First, she tightens one string and holds still as a breeze lifts her coat hem, distant traffic humming. Then she draws the bow into a bright phrase and takes two steps forward, the camera drifting closer as skyscrapers glitter behind her and lanterns glow, textures rich and the mood intensely alive. while the skyline shimmers softly.',
'A cinematic pov walkthrough in a winter wonderland style of the frozen streets of Manhattan, New York City. The camera moves slowly down the street, capturing the serene and tranquil atmosphere. The trees are covered in a thick layer of ice and snow, their branches heavy with frost. The Empire State Building stands tall and majestic, its structure glistening with ice crystals, reflecting the pale winter sunlight. The cityscape is bathed in a soft, ethereal light, with a slight mist creating a dreamlike effect. Snowflakes gently fall, adding to the magical ambiance. A wide-angle shot with the camera moving from the street to the iconic building.',
'A serene cinematic aerial descent over a broad black-sand beach at blue hour, where a thin silver tide advances beneath a lavender sky and distant cliffs disappear into mist. The camera lowers toward the shoreline as one smooth wave curls, spreads into lace-like foam, and retreats with unusual precision, leaving bright white strokes across the untouched wet sand. The foam and water must render the exact text "STAY CURIOUS" in very large, crisp uppercase letters, with accurate spelling, a distinct space between the words, and every character readable from the final overhead view. The phrase remains intact while shallow water glimmers around it, then a second gentle wave traces the letter edges without changing their shapes. Two tiny seabirds cross the upper frame and the camera holds perfectly still for a clear reading. No footprints, signs, or other readable text are present.',
]
_validate_inputs = gr.Blocks.validate_inputs
def _pad_inputs(self, block_fn, inputs):
# The model choice was added as the last input; pad requests from older API clients instead of rejecting them
# (Gradio's rejection message would also print the request's inputs, prompt included, to the log).
inputs.extend([None] * (len(block_fn.inputs) - len(inputs)))
return _validate_inputs(self, block_fn, inputs)
gr.Blocks.validate_inputs = _pad_inputs
with gr.Blocks(title="FastFrames") as demo:
mfn_hf.header(
"FastFrames",
model=[S_ID, L_ID],
description="Text to video that streams frame by frame while it generates: 832×480 at 16 fps, up to 5 seconds.",
flow_fn="/generate",
)
with gr.Row():
with gr.Column():
prompt = gr.Textbox(label="Prompt", lines=5, max_length=MAX_CHARS, value=EXAMPLES[0])
model = gr.Radio(list(PIPES), value=DEFAULT_MODEL, label="Model",
info="S (1.3B) is faster; L (14B) is higher quality and takes a few seconds to start.")
length = gr.Radio(list(LENGTHS), value=DEFAULT_LENGTH, label="Length")
with gr.Accordion("Settings", open=False):
with gr.Row():
seed = gr.Number(value=0, precision=0, label="Seed")
randomize_seed = gr.Checkbox(value=True, label="Randomize seed")
btn = gr.Button("Generate", variant="primary")
with gr.Column():
live = gr.Video(label="Live", streaming=True, autoplay=True, interactive=False)
video = gr.Video(label="Video", interactive=False)
took = mfn_hf.took()
gr.Examples([[e] for e in EXAMPLES], [prompt], label="Examples")
btn.click(generate, [prompt, length, seed, randomize_seed, model], [live, video, seed, took], api_name="generate")
gr.Markdown(
"Runs the official [FastFrames](https://github.com/apple-aiml-research/ml-fastframes) inference code by Apple. "
"Weights: [apple/FastFrames-S](https://huggingface.co/apple/FastFrames-S) and "
"[apple/FastFrames-L](https://huggingface.co/apple/FastFrames-L), released under the "
"[Apple Machine Learning Research Model license](https://huggingface.co/apple/FastFrames-L/blob/main/LICENSE) "
"for research use only; this demo is free and non-commercial. FastFrames-S builds on the "
"[Causal Forcing++](https://huggingface.co/zhuhz22/Causal-Forcing) generator (Apache-2.0); the text encoder "
"comes from [Wan2.1-T2V-14B](https://huggingface.co/Wan-AI/Wan2.1-T2V-14B) (Apache-2.0)."
)
mfn_hf.footer()
if __name__ == "__main__":
demo.launch() # mfn_hf patches launch: theme, CSS, queue and analytics