fastframes-voice / engine.py
fffiloni's picture
Write continuity frames during generation and queue the next direction
265f7ee verified
Raw History Blame Contribute Delete
7.84 kB
"""FastFrames S/L loading and rolling KV window adapted from linoyts’ live Spaces."""
from collections import deque
from pathlib import Path
import torch
from huggingface_hub import hf_hub_download, snapshot_download
from continuity import restore_frames, shift_keys
import fp8_blocks
from fastframes.pipeline import MODELS, FastFrames, configure_backends, to_uint8
from fastframes.wan.causal_model import allocate_kv_cache
FF_S_REVISION = "aa099efcedf1b65447106bf9004cde75821f7387"
FF_L_REVISION = "d18ec5f054bb03f6b8e561a63d52af3142b5b81d"
CF_REVISION = "2f8eb8bb6eeb1238da9d13e5420d342a74d634a6"
WAN_REVISION = "37ec512624d61f7aa208f7ea8140a131f93afc9a"
FPS = 16
WIDTH, HEIGHT = 832, 480
CHUNK = 2
ROLL_STRIDE = 4
SINK = True
DECODER_CONTEXT = 6
# ------------------------------------------------------------------------------------------- model
def load_pipelines():
encoder_dir = Path(snapshot_download("Wan-AI/Wan2.1-T2V-1.3B", revision=WAN_REVISION,
allow_patterns=["models_t5_umt5-xxl-enc-bf16.pth", "google/umt5-xxl/*"]))
pipelines = {}
encoder = None
for size, revision in (("S", FF_S_REVISION), ("L", FF_L_REVISION)):
spec = MODELS["ff-" + size.lower()]
weights = Path(snapshot_download("apple/FastFrames-" + size, revision=revision,
allow_patterns=[f"fastframes-{size.lower()}/*"]))
dit = (hf_hub_download("zhuhz22/Causal-Forcing", spec.dit, revision=CF_REVISION)
if size == "S" else weights / spec.dit)
configure_backends(spec.config)
pipe = FastFrames.from_pretrained(spec.config, encoder_dir, dit, weights / spec.refiner,
weights / spec.decoder, text_encoder=encoder)
if size == "L":
fp8_blocks.install(pipe)
encoder = pipe.text_encoder
pipelines[size] = pipe
print(f"[load] FastFrames-{size} ready", flush=True)
return pipelines
PIPELINES = load_pipelines()
# ------------------------------------------------------------------------------------------- stream engine
class LiveRollout:
"""FastFrames.rollout, one latent frame at a time, forever, with a sink + rolling KV window."""
def __init__(self, pipe, seed):
# one cache per session, reused across scenes: slots are overwritten in order and attention only
# reads filled slots, so no clearing is needed
self.pipe = pipe
self.tokens = pipe.frame_tokens
self.cap = pipe.config.num_frames
pairs = pipe.dit.dim // pipe.dit.num_heads // 2
self.temporal_pairs = pairs - 2 * (pairs // 3)
self.kv = allocate_kv_cache(pipe.dit, self.cap, self.tokens, device=pipe.device)
self.gen = torch.Generator(device=self.pipe.device).manual_seed(int(seed))
self.used = 0 # occupied cache slots
self.total = 0 # latent frames generated
self.features = deque(maxlen=DECODER_CONTEXT + CHUNK)
self.modulation = deque(maxlen=DECODER_CONTEXT + CHUNK)
self.decoded = 0 # latent frames already turned into pixels
self.rolls = 0
self.saved_frames = None
self.shift = pipe.dit.freqs[ROLL_STRIDE, :self.temporal_pairs].conj().to(pipe.device, torch.complex64)
def _noise(self):
return torch.randn((1, 1, 16, *self.pipe.config.latent_size), generator=self.gen, device=self.pipe.device,
dtype=torch.bfloat16)
def _roll(self):
"""Drop ROLL_STRIDE window frames; shift the rest down and re-rotate their keys by -ROLL_STRIDE."""
keep_from = 1 if SINK else 0
src = (keep_from + ROLL_STRIDE) * self.tokens
dst = keep_from * self.tokens
n = (self.cap - keep_from - ROLL_STRIDE) * self.tokens
for layer in self.kv:
layer["k"][:, dst:dst + n] = shift_keys(layer["k"][:, src:src + n], self.temporal_pairs, self.shift)
layer["v"][:, dst:dst + n] = layer["v"][:, src:src + n].clone()
self.used -= ROLL_STRIDE
self.rolls += 1
@torch.inference_mode()
def step(self, text_cache):
with self.pipe.autocast():
self._step(text_cache)
def _step(self, text_cache):
if self.used == self.cap:
self._roll()
slot = self.used
schedule = self.pipe.config.first_frame_timesteps if slot == 0 else self.pipe.config.timesteps
x = self._noise()
for i, timestep in enumerate(schedule):
x0, feature, mod = self.pipe._predict(x, timestep, slot, text_cache, self.kv)
if i + 1 < len(schedule):
next_t = torch.full((1,), schedule[i + 1], device=self.pipe.device, dtype=torch.float32)
eps = self._noise()[:, 0]
x = self.pipe.scheduler.add_noise(x0.flatten(0, 1), eps, next_t).unflatten(0, x0.shape[:2])
if slot == 0:
self.pipe._predict(x0, 0.0, slot, text_cache, self.kv) # frame 0 gets a clean DiT pass
else:
self.pipe._refine(x0, slot, self.kv) # later frames: KV refinement network
self.features.append(feature)
self.modulation.append(mod)
self.used += 1
self.total += 1
@torch.inference_mode()
def decode_pending(self):
"""uint8 frames for latent frames [decoded, total), decoded with up to 6 frames of causal history."""
new = self.total - self.decoded
history = min(DECODER_CONTEXT, self.decoded, len(self.features) - new)
feats = torch.cat(list(self.features)[-(new + history):], dim=1)
mods = torch.cat(list(self.modulation)[-(new + history):], dim=1)
h, w = self.pipe.config.latent_size
grid = torch.tensor([[new + history, h // 2, w // 2]], device=self.pipe.device, dtype=torch.long)
with torch.autocast("cuda", dtype=torch.bfloat16):
pixels = self.pipe.decoder(feats, mods, grid)[0]
pixels = pixels[4 * history:]
if self.decoded == 0:
pixels = pixels[3:] # the decoder's first three frames are dropped (84 -> 81 convention)
self.decoded = self.total
return to_uint8(pixels)
def save_history(self, folder, frames):
torch.save({
"frames": frames,
"model": self.pipe.config.name, "used": self.used, "total": self.total, "decoded": self.decoded, "rolls": self.rolls,
"rng": self.gen.get_state().cpu(),
"features": [value.cpu() for value in list(self.features)[-DECODER_CONTEXT:]],
"modulation": [value.cpu() for value in list(self.modulation)[-DECODER_CONTEXT:]],
}, folder / "history.pt")
def restore(self, folder, check_active):
history = torch.load(folder / "history.pt", map_location="cpu", weights_only=True)
if history["model"] != self.pipe.config.name:
raise ValueError("Checkpoint model mismatch")
self.used, self.total = history["used"], history["total"]
self.decoded, self.rolls = history["decoded"], history["rolls"]
self.gen.set_state(history["rng"])
self.features.extend(value.to(self.pipe.device) for value in history["features"])
self.modulation.extend(value.to(self.pipe.device) for value in history["modulation"])
self.saved_frames = history.get("frames")
if self.saved_frames is not None:
restore_frames(self, folder, self.saved_frames, ROLL_STRIDE, SINK, self.shift, check_active)
return
end = self.used * self.tokens
for index, layer in enumerate(self.kv):
check_active()
tensors = torch.load(folder / f"layer-{index}.pt", mmap=True, weights_only=True, map_location="cpu")
for name, value in tensors.items():
layer[name][:, :end].copy_(value)