Spaces:
Running on Zero
Running on Zero
Clip mode: regenerate a full clip on every prompt edit
Browse files
README.md
CHANGED
|
@@ -19,11 +19,13 @@ models:
|
|
| 19 |
- Wan-AI/Wan2.1-T2V-1.3B
|
| 20 |
---
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
|
| 25 |
-
-
|
| 26 |
-
|
|
|
|
|
|
|
| 27 |
- Unlimited length via a sink + rolling KV window: frame 0 stays as an attention sink, the oldest window frames are
|
| 28 |
dropped when the 21-slot cache is full and the remaining keys are re-rotated so RoPE positions stay in 0..20.
|
| 29 |
- Inference code is the official [ml-fastframes](https://github.com/apple-aiml-research/ml-fastframes) package
|
|
|
|
| 19 |
- Wan-AI/Wan2.1-T2V-1.3B
|
| 20 |
---
|
| 21 |
|
| 22 |
+
Real-time, prompt-reactive text-to-video with [apple/FastFrames-S](https://huggingface.co/apple/FastFrames-S).
|
| 23 |
+
Clip mode re-renders a full 5 s clip (official rollout) on every edit; Endless mode streams one continuous video.
|
| 24 |
|
| 25 |
+
- Both modes hold one ZeroGPU session per user; prompt edits reach it through a per-session file.
|
| 26 |
+
- Clip: each edit starts a fresh 21-latent-frame rollout (in-flight clips are dropped); fixed seed = same noise, so
|
| 27 |
+
edits keep the composition. No drift, since clips stay inside the trained horizon.
|
| 28 |
+
- Endless: 1 s streamed segments; edits keep the last K frames and re-cache them under the new prompt.
|
| 29 |
- Unlimited length via a sink + rolling KV window: frame 0 stays as an attention sink, the oldest window frames are
|
| 30 |
dropped when the 21-slot cache is full and the remaining keys are re-rotated so RoPE positions stay in 0..20.
|
| 31 |
- Inference code is the official [ml-fastframes](https://github.com/apple-aiml-research/ml-fastframes) package
|
app.py
CHANGED
|
@@ -23,6 +23,7 @@ from concurrent.futures import ThreadPoolExecutor
|
|
| 23 |
from pathlib import Path
|
| 24 |
|
| 25 |
import gradio as gr
|
|
|
|
| 26 |
import spaces
|
| 27 |
import torch
|
| 28 |
from huggingface_hub import hf_hub_download, snapshot_download
|
|
@@ -346,6 +347,135 @@ def go_live(prompt, seed, randomize, recache, keep, sid):
|
|
| 346 |
yield gr.skip(), payload, status + " Press Go live to start a new session.", gr.skip()
|
| 347 |
|
| 348 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
# ------------------------------------------------------------------------------------------- UI
|
| 350 |
|
| 351 |
EXAMPLES = [
|
|
@@ -363,58 +493,89 @@ CSS = """
|
|
| 363 |
.ffl-hint {opacity: 0.75; font-size: 0.9em;}
|
| 364 |
"""
|
| 365 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
with gr.Blocks(title="FastFrames-S Live") as demo:
|
|
|
|
| 367 |
with gr.Column(elem_classes="ffl-wrap"):
|
| 368 |
gr.Markdown(
|
| 369 |
"# FastFrames-S Live\n"
|
| 370 |
-
"
|
| 371 |
-
"
|
| 372 |
-
"Powered by [apple/FastFrames-S](https://huggingface.co/apple/FastFrames-S)."
|
| 373 |
)
|
| 374 |
-
with gr.
|
| 375 |
-
with gr.
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 409 |
|
| 410 |
-
sid = gr.Textbox(visible=False) # per-browser session id (a Textbox so the API can pass it too)
|
| 411 |
demo.load(lambda: uuid.uuid4().hex, None, sid)
|
| 412 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
prompt.change(push_prompt, [prompt, recache, keep, sid], None, show_progress="hidden", api_name="push_prompt")
|
| 414 |
recache.change(push_prompt, [prompt, recache, keep, sid], None, show_progress="hidden")
|
| 415 |
keep.change(push_prompt, [prompt, recache, keep, sid], None, show_progress="hidden")
|
| 416 |
-
|
| 417 |
-
|
| 418 |
restart.click(push_restart, [seed, randomize, sid], [seed], show_progress="hidden", api_name="restart")
|
| 419 |
stop.click(push_stop, [sid], None, show_progress="hidden", api_name="stop")
|
| 420 |
|
|
|
|
| 23 |
from pathlib import Path
|
| 24 |
|
| 25 |
import gradio as gr
|
| 26 |
+
from PIL import Image
|
| 27 |
import spaces
|
| 28 |
import torch
|
| 29 |
from huggingface_hub import hf_hub_download, snapshot_download
|
|
|
|
| 347 |
yield gr.skip(), payload, status + " Press Go live to start a new session.", gr.skip()
|
| 348 |
|
| 349 |
|
| 350 |
+
# ------------------------------------------------------------------------------------------- clip mode
|
| 351 |
+
# Every prompt (or seed) change starts a fresh, official 5 s rollout; an in-flight clip is dropped as soon
|
| 352 |
+
# as a newer prompt arrives. Same seed = same noise, so edits keep a similar composition. No drift: clips
|
| 353 |
+
# never leave the trained 21-latent-frame horizon.
|
| 354 |
+
|
| 355 |
+
PREVIEW_EVERY = 2 # latent frames between preview frames while a clip renders
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def _clip_channel(sid):
|
| 359 |
+
return f"{sid}-clip"
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@torch.inference_mode()
|
| 363 |
+
def clip_rollout(text_cache, seed):
|
| 364 |
+
"""FastFrames.rollout (official order: all initial noise first, transitions drawn when needed), one
|
| 365 |
+
latent frame per ``next``. Yields the growing (features, modulation) lists."""
|
| 366 |
+
noise, transition = PIPE._noise(seed)
|
| 367 |
+
kv = allocate_kv_cache(PIPE.dit, CFG.num_frames, TOKENS, device=PIPE.device)
|
| 368 |
+
features, modulation = [], []
|
| 369 |
+
with PIPE.autocast():
|
| 370 |
+
for frame in range(CFG.num_frames):
|
| 371 |
+
schedule = CFG.first_frame_timesteps if frame == 0 else CFG.timesteps
|
| 372 |
+
x = noise[:, frame:frame + 1]
|
| 373 |
+
for step, timestep in enumerate(schedule):
|
| 374 |
+
x0, feature, mod = PIPE._predict(x, timestep, frame, text_cache, kv)
|
| 375 |
+
if step + 1 < len(schedule):
|
| 376 |
+
next_t = torch.full((1,), schedule[step + 1], device=PIPE.device, dtype=torch.float32)
|
| 377 |
+
eps = transition(step, frame)
|
| 378 |
+
x = PIPE.scheduler.add_noise(x0.flatten(0, 1), eps, next_t).unflatten(0, x0.shape[:2])
|
| 379 |
+
features.append(feature)
|
| 380 |
+
modulation.append(mod)
|
| 381 |
+
if frame == 0:
|
| 382 |
+
PIPE._predict(x0, 0.0, frame, text_cache, kv)
|
| 383 |
+
else:
|
| 384 |
+
PIPE._refine(x0, frame, kv)
|
| 385 |
+
yield features, modulation
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
@torch.inference_mode()
|
| 389 |
+
def _preview(features, modulation, path):
|
| 390 |
+
"""Last pixel frame, decoded from at most 7 latent frames of causal history."""
|
| 391 |
+
k = min(len(features), DECODER_CONTEXT + 1)
|
| 392 |
+
h, w = CFG.latent_size
|
| 393 |
+
grid = torch.tensor([[k, h // 2, w // 2]], device=PIPE.device, dtype=torch.long)
|
| 394 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 395 |
+
pixels = PIPE.decoder(torch.cat(features[-k:], dim=1), torch.cat(modulation[-k:], dim=1), grid)[0]
|
| 396 |
+
Image.fromarray(to_uint8(pixels[-1:])[0].cpu().numpy()).save(path, quality=88)
|
| 397 |
+
return path
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
@torch.inference_mode()
|
| 401 |
+
def _finish_clip(features, modulation, path):
|
| 402 |
+
frames = to_uint8(PIPE.decode(torch.cat(features, dim=1), torch.cat(modulation, dim=1))[0]).cpu()
|
| 403 |
+
subprocess.run(_FFMPEG + ["-preset", "veryfast", "-crf", "18", "-movflags", "+faststart", path],
|
| 404 |
+
input=frames.numpy().tobytes(), check=True)
|
| 405 |
+
return path
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
@spaces.GPU(duration=SESSION_SECONDS, size=GPU_SIZE)
|
| 409 |
+
def clip_session(sid):
|
| 410 |
+
"""Hold the GPU; re-render a full clip whenever the prompt or seed changes. Yields (kind, path, status)."""
|
| 411 |
+
channel = _clip_channel(sid)
|
| 412 |
+
deadline = time.time() + RT_WINDOW
|
| 413 |
+
out_dir = tempfile.mkdtemp(prefix="ffc_")
|
| 414 |
+
stop_mark = (_read(channel) or {}).get("stop", 0)
|
| 415 |
+
last_ver, key, gen, n = -1, None, None, 0
|
| 416 |
+
clips = dropped = previews = 0
|
| 417 |
+
started = 0.0
|
| 418 |
+
while time.time() < deadline:
|
| 419 |
+
req = _read(channel)
|
| 420 |
+
if req and req["ver"] != last_ver:
|
| 421 |
+
last_ver = req["ver"]
|
| 422 |
+
if req.get("stop", 0) != stop_mark:
|
| 423 |
+
break
|
| 424 |
+
prompt, seed = (req.get("prompt") or "").strip(), int(req.get("seed", 0))
|
| 425 |
+
if prompt and (prompt, seed) != key:
|
| 426 |
+
dropped += gen is not None
|
| 427 |
+
key, n, started = (prompt, seed), 0, time.perf_counter()
|
| 428 |
+
with torch.inference_mode():
|
| 429 |
+
text_cache = PIPE.dit.text_cache(PIPE.encode_prompt(prompt))
|
| 430 |
+
gen = clip_rollout(text_cache, seed)
|
| 431 |
+
print(f"[clip] {sid[:6]} new clip seed={seed} {prompt[:60]!r}", flush=True)
|
| 432 |
+
if gen is None:
|
| 433 |
+
time.sleep(0.03)
|
| 434 |
+
continue
|
| 435 |
+
features, modulation = next(gen)
|
| 436 |
+
n += 1
|
| 437 |
+
if n < CAP and (n == 1 or n % PREVIEW_EVERY == 0):
|
| 438 |
+
previews += 1
|
| 439 |
+
path = _preview(features, modulation, os.path.join(out_dir, f"p{previews:05d}.jpg"))
|
| 440 |
+
yield "preview", path, f"Rendering {n}/{CAP} latent frames... ({time.perf_counter() - started:.1f} s)"
|
| 441 |
+
if n == CAP:
|
| 442 |
+
clips += 1
|
| 443 |
+
path = _finish_clip(features, modulation, os.path.join(out_dir, f"clip{clips:03d}.mp4"))
|
| 444 |
+
took = time.perf_counter() - started
|
| 445 |
+
status = (f"Clip ready in {took:.1f} s (5 s of video, {5 / took:.1f}x real time) | {clips} clips, "
|
| 446 |
+
f"{dropped} superseded | {max(0, deadline - time.time()):.0f} s of GPU session left")
|
| 447 |
+
print(f"[clip] {sid[:6]} {status}", flush=True)
|
| 448 |
+
yield "clip", path, status
|
| 449 |
+
gen = None
|
| 450 |
+
yield "end", None, f"Session ended ({clips} clips). Press Go live to start a new session."
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def push_clip(prompt, seed, sid):
|
| 454 |
+
"""Send the clip tab's prompt and seed to its running session (no GPU)."""
|
| 455 |
+
if sid:
|
| 456 |
+
_write(_clip_channel(sid), prompt=(prompt or "")[:MAX_CHARS], seed=int(seed or 0))
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def stop_clip(sid):
|
| 460 |
+
if sid:
|
| 461 |
+
state = _read(_clip_channel(sid)) or {}
|
| 462 |
+
_write(_clip_channel(sid), stop=int(state.get("stop", 0)) + 1)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def go_clip(prompt, seed, sid):
|
| 466 |
+
if not (prompt or "").strip():
|
| 467 |
+
raise gr.Error("Enter a prompt first.")
|
| 468 |
+
push_clip(prompt, seed, sid)
|
| 469 |
+
yield gr.skip(), gr.skip(), "Starting the GPU session..."
|
| 470 |
+
for kind, path, status in clip_session(sid):
|
| 471 |
+
if kind == "preview":
|
| 472 |
+
yield gr.skip(), path, status
|
| 473 |
+
elif kind == "clip":
|
| 474 |
+
yield path, gr.skip(), status
|
| 475 |
+
else:
|
| 476 |
+
yield gr.skip(), gr.skip(), status
|
| 477 |
+
|
| 478 |
+
|
| 479 |
# ------------------------------------------------------------------------------------------- UI
|
| 480 |
|
| 481 |
EXAMPLES = [
|
|
|
|
| 493 |
.ffl-hint {opacity: 0.75; font-size: 0.9em;}
|
| 494 |
"""
|
| 495 |
|
| 496 |
+
LICENSE_NOTE = (
|
| 497 |
+
"Runs the official [FastFrames](https://github.com/apple-aiml-research/ml-fastframes) inference code by Apple. "
|
| 498 |
+
"Weights: [apple/FastFrames-S](https://huggingface.co/apple/FastFrames-S) "
|
| 499 |
+
"([Apple ML Research Model license](https://huggingface.co/apple/FastFrames-S/blob/main/LICENSE), research use "
|
| 500 |
+
"only) with the Causal Forcing++ generator ([zhuhz22/Causal-Forcing](https://huggingface.co/zhuhz22/Causal-Forcing), "
|
| 501 |
+
"Apache-2.0) and the [Wan2.1](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B) text encoder (Apache-2.0)."
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
with gr.Blocks(title="FastFrames-S Live") as demo:
|
| 505 |
+
sid = gr.Textbox(visible=False) # per-browser session id (a Textbox so the API can pass it too)
|
| 506 |
with gr.Column(elem_classes="ffl-wrap"):
|
| 507 |
gr.Markdown(
|
| 508 |
"# FastFrames-S Live\n"
|
| 509 |
+
"Real-time text-to-video with [apple/FastFrames-S](https://huggingface.co/apple/FastFrames-S). "
|
| 510 |
+
"Press **Go live**, then keep editing the prompt."
|
|
|
|
| 511 |
)
|
| 512 |
+
with gr.Tabs():
|
| 513 |
+
with gr.Tab("Clip"):
|
| 514 |
+
with gr.Row(equal_height=False):
|
| 515 |
+
with gr.Column(scale=2, min_width=300):
|
| 516 |
+
clip_video = gr.Video(label="Latest clip (loops)", autoplay=True, loop=True,
|
| 517 |
+
interactive=False, height=420)
|
| 518 |
+
clip_status = gr.Markdown("", elem_classes="ffl-status")
|
| 519 |
+
with gr.Column(scale=1, min_width=260):
|
| 520 |
+
clip_prompt = gr.Textbox(label="Prompt (every edit renders a new 5 s clip)", lines=5,
|
| 521 |
+
max_length=MAX_CHARS, value=EXAMPLES[0])
|
| 522 |
+
with gr.Row():
|
| 523 |
+
clip_start = gr.Button("Go live", variant="primary")
|
| 524 |
+
clip_stop = gr.Button("Stop")
|
| 525 |
+
with gr.Row():
|
| 526 |
+
clip_seed = gr.Number(value=0, precision=0, label="Seed", min_width=100)
|
| 527 |
+
clip_reseed = gr.Button("New seed", min_width=100)
|
| 528 |
+
clip_preview = gr.Image(label="Rendering", interactive=False, height=180)
|
| 529 |
+
gr.Markdown(
|
| 530 |
+
f"Each session holds a GPU for about {RT_WINDOW} s. A clip takes about 3 s; a newer "
|
| 531 |
+
"edit replaces the clip in progress. Keep the seed fixed to see the same shot change "
|
| 532 |
+
"with your words.", elem_classes="ffl-hint")
|
| 533 |
+
gr.Examples([[e] for e in EXAMPLES], [clip_prompt], label="Examples")
|
| 534 |
+
with gr.Tab("Endless stream"):
|
| 535 |
+
with gr.Row(equal_height=False):
|
| 536 |
+
with gr.Column(scale=2, min_width=300):
|
| 537 |
+
live = gr.Video(label="Live", streaming=True, autoplay=True, interactive=False, height=420)
|
| 538 |
+
status = gr.Markdown("", elem_classes="ffl-status")
|
| 539 |
+
with gr.Column(scale=1, min_width=260):
|
| 540 |
+
prompt = gr.Textbox(label="Prompt (edit while it plays)", lines=5, max_length=MAX_CHARS,
|
| 541 |
+
value=EXAMPLES[0])
|
| 542 |
+
with gr.Row():
|
| 543 |
+
start = gr.Button("Go live", variant="primary")
|
| 544 |
+
stop = gr.Button("Stop")
|
| 545 |
+
restart = gr.Button("New scene")
|
| 546 |
+
with gr.Accordion("Settings", open=False):
|
| 547 |
+
seed = gr.Number(value=0, precision=0, label="Seed")
|
| 548 |
+
randomize = gr.Checkbox(value=True, label="Randomize seed")
|
| 549 |
+
recache = gr.Checkbox(value=True, label="Re-cache on prompt change",
|
| 550 |
+
info="Rebuild the cached frames under the new prompt so the "
|
| 551 |
+
"switch takes hold. Off = only new frames see the prompt.")
|
| 552 |
+
keep = gr.Slider(0, CAP, value=KEEP_ON_SWITCH, step=1,
|
| 553 |
+
label="Frames kept on prompt change",
|
| 554 |
+
info="Fewer = the new prompt takes over faster (0 = hard cut); "
|
| 555 |
+
f"{CAP} = keep the whole context.")
|
| 556 |
+
gr.Markdown(
|
| 557 |
+
"One continuous video with a rolling memory, so it can run for the whole session. "
|
| 558 |
+
"Expect some drift on long runs.", elem_classes="ffl-hint")
|
| 559 |
+
gr.Examples([[e] for e in EXAMPLES], [prompt], label="Examples")
|
| 560 |
+
recording = gr.Video(label="Session recording", interactive=False)
|
| 561 |
+
gr.Markdown(LICENSE_NOTE, elem_classes="ffl-hint")
|
| 562 |
|
|
|
|
| 563 |
demo.load(lambda: uuid.uuid4().hex, None, sid)
|
| 564 |
|
| 565 |
+
# clip mode
|
| 566 |
+
clip_prompt.change(push_clip, [clip_prompt, clip_seed, sid], None, show_progress="hidden", api_name="push_clip")
|
| 567 |
+
clip_seed.change(push_clip, [clip_prompt, clip_seed, sid], None, show_progress="hidden")
|
| 568 |
+
clip_reseed.click(lambda: random.randint(0, MAX_SEED), None, clip_seed, show_progress="hidden")
|
| 569 |
+
clip_start.click(go_clip, [clip_prompt, clip_seed, sid], [clip_video, clip_preview, clip_status],
|
| 570 |
+
api_name="go_clip", concurrency_limit=4)
|
| 571 |
+
clip_stop.click(stop_clip, [sid], None, show_progress="hidden", api_name="stop_clip")
|
| 572 |
+
|
| 573 |
+
# endless stream
|
| 574 |
prompt.change(push_prompt, [prompt, recache, keep, sid], None, show_progress="hidden", api_name="push_prompt")
|
| 575 |
recache.change(push_prompt, [prompt, recache, keep, sid], None, show_progress="hidden")
|
| 576 |
keep.change(push_prompt, [prompt, recache, keep, sid], None, show_progress="hidden")
|
| 577 |
+
start.click(go_live, [prompt, seed, randomize, recache, keep, sid], [live, recording, status, seed],
|
| 578 |
+
api_name="go_live", concurrency_limit=4)
|
| 579 |
restart.click(push_restart, [seed, randomize, sid], [seed], show_progress="hidden", api_name="restart")
|
| 580 |
stop.click(push_stop, [sid], None, show_progress="hidden", api_name="stop")
|
| 581 |
|