Spaces:
Running on Zero
Running on Zero
Write continuity frames during generation and queue the next direction
Browse files- README.md +3 -3
- assets/studio.js +9 -2
- continuity.py +110 -0
- engine.py +10 -14
- render.py +13 -5
README.md
CHANGED
|
@@ -29,15 +29,15 @@ models:
|
|
| 29 |
|
| 30 |
# FastFrames Voice
|
| 31 |
|
| 32 |
-
A private research prototype for directing a continuous generated shot with spoken or written cues. Version 0.8.
|
| 33 |
|
| 34 |
Choose FastFrames-S (default, 1.3B) or FastFrames-L (14B) before starting a shot. Each session uses the same model for its opening, continuations and variants. When the session ends, the model selector becomes available again.
|
| 35 |
|
| 36 |
-
Select Voice and start the microphone, or select Text, write a direction and press Generate segment (Enter to send, Shift+Enter for a new line). Text mode releases the microphone. Switching inputs preserves the shot. Each accepted direction generates one silent segment at 832 × 480 and 16 fps. Choose 1–8 whole seconds (default 4) before submitting each direction. Each second contains 16 frames. The opening generates one extra latent and trims one leading decoded frame after the model’s three startup frames to deliver an exact whole-second clip. The last segment loops locally while you think or the next cue is being prepared. Toggle Loop on the monitor to freeze it. Reduced-motion preferences disable looping by default. Repeats never enter the exported recording. End session joins completed segments into a downloadable MP4. Microphone mute discards unsubmitted audio and stops capture. Unmute continues the same take. The monitor plays the generated frames on an inline canvas, including on iPhone. The studio publishes JPEG strips of eight frames as the generator produces them. Inline playback starts at the first available strip, before the checkpoint and final MP4 are ready.
|
| 37 |
|
| 38 |
After a clip is complete, voice and text directions can continue the shot or redo its last segment. Check **Redo last segment** to force a variant for one instruction. A redo uses the duration and the starting state of the original (the same initial seed for the opening). The next-segment duration selector is preserved. With an ambiguous cue, answer “last segment” or “next segment” by voice, text or button; the studio keeps the original direction while waiting. Review both versions, then choose **Keep original** or **Use variant**. Ending during review exports the original. Only chosen clips enter the recording and future continuity.
|
| 39 |
|
| 40 |
-
Fluid Speech Pro transcribes voice on CPU. Typed directions bypass speech recognition. Inkling 2 Mini updates the last completed shot via Hugging Face Inference Providers when a provider credential is available. Only the text of the current direction, previous direction, target and visual prompt are sent to the HF router. Use the Hugging Face sign-in button below the studio title before starting a take to use your inference credits, or set a server-side HF_INFERENCE_TOKEN secret scoped to Inference Providers. Qwen runs locally when no credential is present or the provider call fails. The interpreted direction identifies the model used. Both video models use one xlarge ZeroGPU allocation per segment. The maximum duration is 60 seconds for S and 120 seconds for L. L uses eager FP8 blocks adapted from linoyts and requires more temporary checkpoint space. Both pipelines share the same umT5 text encoder and tokenizer. Between directions, the session keeps its exact occupied attention cache, decoder history, frame indices and random generator state on the Space's temporary filesystem. The latest clip and its immediate predecessor retain their checkpoints. A pending variant has its own temporary checkpoint until the user chooses a version. Ending a session releases the temporary continuity caches. The gallery saves one final MP4 per recording. The in-studio controls can still continue a shot or redo its last segment until the session ends.
|
| 41 |
|
| 42 |
For signed-in visitors, the app uses the OAuth contribute-repos scope to write the final MP4 to their private fastframes-voice-studio bucket. Browser-only recordings use the Space’s attached private bucket and a device key from local storage. The Space keeps a small private index with the recording ID, save date, duration, segment count and, for personal uploads, file integrity information. Gallery posters are decoded from the opening frame on demand. New recordings use the save date as their label. Previously saved sessions can still be watched and downloaded from their original location. A failed upload can be retried using the completed local MP4.
|
| 43 |
|
|
|
|
| 29 |
|
| 30 |
# FastFrames Voice
|
| 31 |
|
| 32 |
+
A private research prototype for directing a continuous generated shot with spoken or written cues. Version 0.8.1. The monitor fills the studio above a horizontal desk for the microphone, transcript and interpreted direction. Open Videos in the header to watch or download finished recordings.
|
| 33 |
|
| 34 |
Choose FastFrames-S (default, 1.3B) or FastFrames-L (14B) before starting a shot. Each session uses the same model for its opening, continuations and variants. When the session ends, the model selector becomes available again.
|
| 35 |
|
| 36 |
+
Select Voice and start the microphone, or select Text, write a direction and press Generate segment (Enter to send, Shift+Enter for a new line). Text mode releases the microphone. Switching inputs preserves the shot. Each accepted direction generates one silent segment at 832 × 480 and 16 fps. Choose 1–8 whole seconds (default 4) before submitting each direction. Each second contains 16 frames. The opening generates one extra latent and trims one leading decoded frame after the model’s three startup frames to deliver an exact whole-second clip. The last segment loops locally while you think or the next cue is being prepared. Toggle Loop on the monitor to freeze it. Reduced-motion preferences disable looping by default. Repeats never enter the exported recording. End session joins completed segments into a downloadable MP4. Microphone mute discards unsubmitted audio and stops capture. Unmute continues the same take. The monitor plays the generated frames on an inline canvas, including on iPhone. The studio publishes JPEG strips of eight frames as the generator produces them. Inline playback starts at the first available strip, before the checkpoint and final MP4 are ready. While the preview plays, the studio can queue the next spoken or written direction. Generation of the next segment starts after the current segment and its continuity window have committed and the first playback has finished. API clients can request the same preview events with stream_preview set to true on live_take. The complete take uses a native MP4 player with inline playback and download.
|
| 37 |
|
| 38 |
After a clip is complete, voice and text directions can continue the shot or redo its last segment. Check **Redo last segment** to force a variant for one instruction. A redo uses the duration and the starting state of the original (the same initial seed for the opening). The next-segment duration selector is preserved. With an ambiguous cue, answer “last segment” or “next segment” by voice, text or button; the studio keeps the original direction while waiting. Review both versions, then choose **Keep original** or **Use variant**. Ending during review exports the original. Only chosen clips enter the recording and future continuity.
|
| 39 |
|
| 40 |
+
Fluid Speech Pro transcribes voice on CPU. Typed directions bypass speech recognition. Inkling 2 Mini updates the last completed shot via Hugging Face Inference Providers when a provider credential is available. Only the text of the current direction, previous direction, target and visual prompt are sent to the HF router. Use the Hugging Face sign-in button below the studio title before starting a take to use your inference credits, or set a server-side HF_INFERENCE_TOKEN secret scoped to Inference Providers. Qwen runs locally when no credential is present or the provider call fails. The interpreted direction identifies the model used. Both video models use one xlarge ZeroGPU allocation per segment. The maximum duration is 60 seconds for S and 120 seconds for L. L uses eager FP8 blocks adapted from linoyts and requires more temporary checkpoint space. Both pipelines share the same umT5 text encoder and tokenizer. Between directions, the session keeps its exact occupied attention cache, decoder history, frame indices and random generator state on the Space's temporary filesystem. The studio transfers completed attention frames on a separate CUDA stream during the rollout. It keeps only frames needed for the final rolling window, shares unchanged frame files between local checkpoints, and joins the writer before publishing. Restore applies the same BF16 key rotations as the live window. The latest clip and its immediate predecessor retain their checkpoints. A pending variant has its own temporary checkpoint until the user chooses a version. Ending a session releases the temporary continuity caches. The gallery saves one final MP4 per recording. The in-studio controls can still continue a shot or redo its last segment until the session ends.
|
| 41 |
|
| 42 |
For signed-in visitors, the app uses the OAuth contribute-repos scope to write the final MP4 to their private fastframes-voice-studio bucket. Browser-only recordings use the Space’s attached private bucket and a device key from local storage. The Space keeps a small private index with the recording ID, save date, duration, segment count and, for personal uploads, file integrity information. Gallery posters are decoded from the opening frame on demand. New recordings use the save date as their label. Previously saved sessions can still be watched and downloaded from their original location. A failed upload can be retried using the completed local MP4.
|
| 43 |
|
assets/studio.js
CHANGED
|
@@ -37,6 +37,7 @@ const copy = {
|
|
| 37 |
voiceMode:["Voice","Voix"],textMode:["Text","Texte"],duration:["Next segment","Prochaine portion"],
|
| 38 |
textLabel:["Written direction","Consigne écrite"],textIdle:["Ready for a written direction","En attente d’une consigne écrite"],
|
| 39 |
providerHelp:["Use Inkling and save finished videos to your private HF bucket.","Utilise Inkling et enregistre tes vidéos finales dans ton bucket HF privé."],
|
|
|
|
| 40 |
send:["Generate segment","Générer la portion"],starting:["Opening session…","Ouverture de la session…"],
|
| 41 |
invalid_seconds:["Choose a duration from 1 to 8 s","Choisis une durée de 1 à 8 s"],
|
| 42 |
invalid_text:["Enter a direction of up to 1,200 characters","Écris une consigne de 1 200 caractères maximum"],
|
|
@@ -116,8 +117,10 @@ function label(){
|
|
| 116 |
for(const id of ["keep-original","use-variant","watch-original","watch-variant"])by(id).disabled=choosing;
|
| 117 |
by("watch-variant").setAttribute("aria-pressed",String(Boolean(variantClip&&lastSegment===variantClip)));
|
| 118 |
by("watch-original").setAttribute("aria-pressed",String(Boolean(variantClip&&lastSegment===approvedClip)));
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
| 121 |
by("input-label").textContent=tr((lastSource||inputMode)==="text"?"textLabel":"heard");
|
| 122 |
by("interpreter").textContent=interpreter;
|
| 123 |
const muted = Boolean(inputMode==="voice" && take && !stream && !opening && !stopped);
|
|
@@ -370,6 +373,10 @@ window.addEventListener("ffv-signal",e=>{
|
|
| 370 |
return;
|
| 371 |
}
|
| 372 |
if(["gpu_error","quota","hardware"].includes(d.phase)){
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
if(livePreview){
|
| 374 |
playback.clear();livePreview=null;
|
| 375 |
if(approvedClip){hold.src=approvedClip.still;setMode("hold");playback.repeatClip(approvedClip);syncLoop();}else setMode("cover");
|
|
|
|
| 37 |
voiceMode:["Voice","Voix"],textMode:["Text","Texte"],duration:["Next segment","Prochaine portion"],
|
| 38 |
textLabel:["Written direction","Consigne écrite"],textIdle:["Ready for a written direction","En attente d’une consigne écrite"],
|
| 39 |
providerHelp:["Use Inkling and save finished videos to your private HF bucket.","Utilise Inkling et enregistre tes vidéos finales dans ton bucket HF privé."],
|
| 40 |
+
queueDirection:["Queue direction","Mettre en attente"],directionQueued:["Direction queued","Consigne en attente"],
|
| 41 |
send:["Generate segment","Générer la portion"],starting:["Opening session…","Ouverture de la session…"],
|
| 42 |
invalid_seconds:["Choose a duration from 1 to 8 s","Choisis une durée de 1 à 8 s"],
|
| 43 |
invalid_text:["Enter a direction of up to 1,200 characters","Écris une consigne de 1 200 caractères maximum"],
|
|
|
|
| 117 |
for(const id of ["keep-original","use-variant","watch-original","watch-variant"])by(id).disabled=choosing;
|
| 118 |
by("watch-variant").setAttribute("aria-pressed",String(Boolean(variantClip&&lastSegment===variantClip)));
|
| 119 |
by("watch-original").setAttribute("aria-pressed",String(Boolean(variantClip&&lastSegment===approvedClip)));
|
| 120 |
+
const waiting=busy && queue.some(cue=>cue.text!==undefined);
|
| 121 |
+
const canQueue=busy && livePreview && !livePreview.failed && editOperation==="append" && !queue.length && !questionId;
|
| 122 |
+
send.textContent=tr(waiting?"directionQueued":canQueue?"queueDirection":forceRedo.checked?"redoSend":"send");
|
| 123 |
+
send.disabled=(busy&&!canQueue)||stopped||Boolean(variantClip)||submittedDraft!==null||!draft.value.trim();
|
| 124 |
by("input-label").textContent=tr((lastSource||inputMode)==="text"?"textLabel":"heard");
|
| 125 |
by("interpreter").textContent=interpreter;
|
| 126 |
const muted = Boolean(inputMode==="voice" && take && !stream && !opening && !stopped);
|
|
|
|
| 373 |
return;
|
| 374 |
}
|
| 375 |
if(["gpu_error","quota","hardware"].includes(d.phase)){
|
| 376 |
+
// A written direction queued against a failed segment stays in the editor.
|
| 377 |
+
if(queue.some(cue=>cue.text!==undefined)){
|
| 378 |
+
queue=queue.filter(cue=>cue.text===undefined);submittedDraft=null;
|
| 379 |
+
}
|
| 380 |
if(livePreview){
|
| 381 |
playback.clear();livePreview=null;
|
| 382 |
if(approvedClip){hold.src=approvedClip.still;setMode("hold");playback.repeatClip(approvedClip);syncLoop();}else setMode("cover");
|
continuity.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Temporary, lossless FastFrames attention windows. Each frame is written once per branch."""
|
| 2 |
+
from collections import deque
|
| 3 |
+
from contextlib import nullcontext
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def window_frames(total, capacity, stride, sink):
|
| 11 |
+
used = total if total <= capacity else capacity - stride + 1 + (total - capacity - 1) % stride
|
| 12 |
+
first = int(sink and total > 0)
|
| 13 |
+
return [*range(first), *range(total - used + first, total)]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def shift_keys(keys, pairs, shift):
|
| 17 |
+
# Repeat individual BF16 roundings on restore exactly as in the live rolling window.
|
| 18 |
+
complex_keys = torch.view_as_complex(keys.float().unflatten(-1, (-1, 2)).contiguous())
|
| 19 |
+
complex_keys[..., :pairs] *= shift
|
| 20 |
+
return torch.view_as_real(complex_keys).flatten(-2).to(keys.dtype)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def frame_file(folder, frame):
|
| 24 |
+
return folder / f"frame-{frame}.kv"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@torch.inference_mode()
|
| 28 |
+
def write_frame(path, packed, stream, ready):
|
| 29 |
+
with torch.cuda.stream(stream) if stream is not None else nullcontext():
|
| 30 |
+
if ready is not None:
|
| 31 |
+
stream.wait_event(ready)
|
| 32 |
+
mapped = torch.from_file(str(path), shared=True, size=packed.numel(), dtype=packed.dtype)
|
| 33 |
+
# A blocking copy on the transfer stream completes before the writer releases its inputs.
|
| 34 |
+
mapped.view_as(packed).copy_(packed)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class WindowWriter:
|
| 38 |
+
def __init__(self, folder, rollout, steps, stride, sink, pool, check_active):
|
| 39 |
+
self.folder = folder
|
| 40 |
+
folder.mkdir()
|
| 41 |
+
self.rollout = rollout
|
| 42 |
+
self.keep = set(window_frames(rollout.total + steps, rollout.cap, stride, sink))
|
| 43 |
+
self.records = {}
|
| 44 |
+
self.pool = pool
|
| 45 |
+
self.check_active = check_active
|
| 46 |
+
self.pending = deque()
|
| 47 |
+
self.stream = torch.cuda.Stream(device=rollout.pipe.device) if rollout.kv[0]["k"].is_cuda else None
|
| 48 |
+
|
| 49 |
+
def inherit(self, previous, stride, sink):
|
| 50 |
+
roll = self.rollout
|
| 51 |
+
for slot, frame in enumerate(window_frames(roll.total, roll.cap, stride, sink)):
|
| 52 |
+
if frame not in self.keep:
|
| 53 |
+
continue
|
| 54 |
+
self.check_active()
|
| 55 |
+
if roll.saved_frames is None: # The preceding checkpoint used the original per-layer layout.
|
| 56 |
+
self.capture(frame, slot)
|
| 57 |
+
else:
|
| 58 |
+
os.link(frame_file(previous, frame), frame_file(self.folder, frame))
|
| 59 |
+
self.records[frame] = roll.saved_frames[frame]
|
| 60 |
+
|
| 61 |
+
def capture(self, frame, slot):
|
| 62 |
+
if frame not in self.keep:
|
| 63 |
+
return
|
| 64 |
+
if len(self.pending) >= 2:
|
| 65 |
+
self.pending.popleft().result()
|
| 66 |
+
self.check_active()
|
| 67 |
+
roll = self.rollout
|
| 68 |
+
start = slot * roll.tokens
|
| 69 |
+
# Snapshot on the compute stream before a subsequent roll can overwrite this slot.
|
| 70 |
+
packed = torch.stack([layer[name][:, start:start + roll.tokens]
|
| 71 |
+
for layer in roll.kv for name in ("k", "v")])
|
| 72 |
+
ready = None
|
| 73 |
+
if self.stream is not None:
|
| 74 |
+
ready = torch.cuda.Event()
|
| 75 |
+
ready.record(torch.cuda.current_stream(roll.pipe.device))
|
| 76 |
+
self.pending.append(self.pool.submit(write_frame, frame_file(self.folder, frame), packed, self.stream, ready))
|
| 77 |
+
self.records[frame] = roll.rolls
|
| 78 |
+
|
| 79 |
+
def finish(self):
|
| 80 |
+
for future in self.pending:
|
| 81 |
+
future.result()
|
| 82 |
+
self.pending.clear()
|
| 83 |
+
self.check_active()
|
| 84 |
+
if self.records.keys() != self.keep:
|
| 85 |
+
raise ValueError("Incomplete continuity window")
|
| 86 |
+
return self.records
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def restore_frames(roll, folder, records, stride, sink, shift, check_active):
|
| 90 |
+
ids = window_frames(roll.total, roll.cap, stride, sink)
|
| 91 |
+
if len(ids) != roll.used or set(ids) != records.keys():
|
| 92 |
+
raise ValueError("Invalid continuity window")
|
| 93 |
+
example = roll.kv[0]["k"]
|
| 94 |
+
shape = (2 * len(roll.kv), *example[:, :roll.tokens].shape)
|
| 95 |
+
size = math.prod(shape)
|
| 96 |
+
for slot, frame in enumerate(ids):
|
| 97 |
+
check_active()
|
| 98 |
+
path = frame_file(folder, frame)
|
| 99 |
+
if path.stat().st_size != size * example.element_size() or not 0 <= records[frame] <= roll.rolls:
|
| 100 |
+
raise ValueError("Invalid continuity frame")
|
| 101 |
+
mapped = torch.from_file(str(path), shared=False, size=size, dtype=example.dtype)
|
| 102 |
+
packed = mapped.view(shape).to(roll.pipe.device)
|
| 103 |
+
keys = packed[0::2]
|
| 104 |
+
if not (sink and slot == 0):
|
| 105 |
+
for _ in range(roll.rolls - records[frame]):
|
| 106 |
+
keys = shift_keys(keys, roll.temporal_pairs, shift)
|
| 107 |
+
dest = slice(slot * roll.tokens, (slot + 1) * roll.tokens)
|
| 108 |
+
for index, layer in enumerate(roll.kv):
|
| 109 |
+
layer["k"][:, dest].copy_(keys[index])
|
| 110 |
+
layer["v"][:, dest].copy_(packed[2 * index + 1])
|
engine.py
CHANGED
|
@@ -4,6 +4,7 @@ from pathlib import Path
|
|
| 4 |
import torch
|
| 5 |
from huggingface_hub import hf_hub_download, snapshot_download
|
| 6 |
|
|
|
|
| 7 |
import fp8_blocks
|
| 8 |
from fastframes.pipeline import MODELS, FastFrames, configure_backends, to_uint8
|
| 9 |
from fastframes.wan.causal_model import allocate_kv_cache
|
|
@@ -68,6 +69,8 @@ class LiveRollout:
|
|
| 68 |
self.modulation = deque(maxlen=DECODER_CONTEXT + CHUNK)
|
| 69 |
self.decoded = 0 # latent frames already turned into pixels
|
| 70 |
self.rolls = 0
|
|
|
|
|
|
|
| 71 |
|
| 72 |
def _noise(self):
|
| 73 |
return torch.randn((1, 1, 16, *self.pipe.config.latent_size), generator=self.gen, device=self.pipe.device,
|
|
@@ -79,12 +82,8 @@ class LiveRollout:
|
|
| 79 |
src = (keep_from + ROLL_STRIDE) * self.tokens
|
| 80 |
dst = keep_from * self.tokens
|
| 81 |
n = (self.cap - keep_from - ROLL_STRIDE) * self.tokens
|
| 82 |
-
shift = self.pipe.dit.freqs[:, :self.temporal_pairs][ROLL_STRIDE].conj().to(self.pipe.device, torch.complex64)
|
| 83 |
for layer in self.kv:
|
| 84 |
-
k = layer["k"][:, src:src + n].
|
| 85 |
-
k = torch.view_as_complex(k.unflatten(-1, (-1, 2)).contiguous())
|
| 86 |
-
k[..., :self.temporal_pairs] *= shift
|
| 87 |
-
layer["k"][:, dst:dst + n] = torch.view_as_real(k).flatten(-2).to(layer["k"].dtype)
|
| 88 |
layer["v"][:, dst:dst + n] = layer["v"][:, src:src + n].clone()
|
| 89 |
self.used -= ROLL_STRIDE
|
| 90 |
self.rolls += 1
|
|
@@ -133,16 +132,9 @@ class LiveRollout:
|
|
| 133 |
return to_uint8(pixels)
|
| 134 |
|
| 135 |
|
| 136 |
-
|
| 137 |
-
def save(self, folder, check_active):
|
| 138 |
-
"""Keep only occupied KV slots, decoder history and exact RNG state on CPU."""
|
| 139 |
-
folder.mkdir()
|
| 140 |
-
end = self.used * self.tokens
|
| 141 |
-
for index, layer in enumerate(self.kv):
|
| 142 |
-
check_active()
|
| 143 |
-
tensors = {name: value[:, :end].contiguous().cpu() for name, value in layer.items()}
|
| 144 |
-
torch.save(tensors, folder / f"layer-{index}.pt")
|
| 145 |
torch.save({
|
|
|
|
| 146 |
"model": self.pipe.config.name, "used": self.used, "total": self.total, "decoded": self.decoded, "rolls": self.rolls,
|
| 147 |
"rng": self.gen.get_state().cpu(),
|
| 148 |
"features": [value.cpu() for value in list(self.features)[-DECODER_CONTEXT:]],
|
|
@@ -158,6 +150,10 @@ class LiveRollout:
|
|
| 158 |
self.gen.set_state(history["rng"])
|
| 159 |
self.features.extend(value.to(self.pipe.device) for value in history["features"])
|
| 160 |
self.modulation.extend(value.to(self.pipe.device) for value in history["modulation"])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
end = self.used * self.tokens
|
| 162 |
for index, layer in enumerate(self.kv):
|
| 163 |
check_active()
|
|
|
|
| 4 |
import torch
|
| 5 |
from huggingface_hub import hf_hub_download, snapshot_download
|
| 6 |
|
| 7 |
+
from continuity import restore_frames, shift_keys
|
| 8 |
import fp8_blocks
|
| 9 |
from fastframes.pipeline import MODELS, FastFrames, configure_backends, to_uint8
|
| 10 |
from fastframes.wan.causal_model import allocate_kv_cache
|
|
|
|
| 69 |
self.modulation = deque(maxlen=DECODER_CONTEXT + CHUNK)
|
| 70 |
self.decoded = 0 # latent frames already turned into pixels
|
| 71 |
self.rolls = 0
|
| 72 |
+
self.saved_frames = None
|
| 73 |
+
self.shift = pipe.dit.freqs[ROLL_STRIDE, :self.temporal_pairs].conj().to(pipe.device, torch.complex64)
|
| 74 |
|
| 75 |
def _noise(self):
|
| 76 |
return torch.randn((1, 1, 16, *self.pipe.config.latent_size), generator=self.gen, device=self.pipe.device,
|
|
|
|
| 82 |
src = (keep_from + ROLL_STRIDE) * self.tokens
|
| 83 |
dst = keep_from * self.tokens
|
| 84 |
n = (self.cap - keep_from - ROLL_STRIDE) * self.tokens
|
|
|
|
| 85 |
for layer in self.kv:
|
| 86 |
+
layer["k"][:, dst:dst + n] = shift_keys(layer["k"][:, src:src + n], self.temporal_pairs, self.shift)
|
|
|
|
|
|
|
|
|
|
| 87 |
layer["v"][:, dst:dst + n] = layer["v"][:, src:src + n].clone()
|
| 88 |
self.used -= ROLL_STRIDE
|
| 89 |
self.rolls += 1
|
|
|
|
| 132 |
return to_uint8(pixels)
|
| 133 |
|
| 134 |
|
| 135 |
+
def save_history(self, folder, frames):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
torch.save({
|
| 137 |
+
"frames": frames,
|
| 138 |
"model": self.pipe.config.name, "used": self.used, "total": self.total, "decoded": self.decoded, "rolls": self.rolls,
|
| 139 |
"rng": self.gen.get_state().cpu(),
|
| 140 |
"features": [value.cpu() for value in list(self.features)[-DECODER_CONTEXT:]],
|
|
|
|
| 150 |
self.gen.set_state(history["rng"])
|
| 151 |
self.features.extend(value.to(self.pipe.device) for value in history["features"])
|
| 152 |
self.modulation.extend(value.to(self.pipe.device) for value in history["modulation"])
|
| 153 |
+
self.saved_frames = history.get("frames")
|
| 154 |
+
if self.saved_frames is not None:
|
| 155 |
+
restore_frames(self, folder, self.saved_frames, ROLL_STRIDE, SINK, self.shift, check_active)
|
| 156 |
+
return
|
| 157 |
end = self.used * self.tokens
|
| 158 |
for index, layer in enumerate(self.kv):
|
| 159 |
check_active()
|
render.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
"""Advance a single rollout by the duration of each direction."""
|
|
|
|
| 2 |
import base64
|
| 3 |
import logging
|
| 4 |
import subprocess
|
|
@@ -10,6 +11,7 @@ import spaces
|
|
| 10 |
import torch
|
| 11 |
from PIL import Image
|
| 12 |
|
|
|
|
| 13 |
import takes
|
| 14 |
|
| 15 |
LOG = logging.getLogger("studio")
|
|
@@ -52,10 +54,13 @@ def generate(key, rev, previous, prompt, stage_name, seconds=4, seed=0, preview=
|
|
| 52 |
first = rollout.total
|
| 53 |
text = pipe.dit.text_cache(pipe.encode_prompt(prompt))
|
| 54 |
yield "generating"
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
# Four decoder frames per latent. The opening decoder trims three
|
| 57 |
# startup frames. Advance one extra latent and trim the fourth.
|
| 58 |
-
steps = 4 * takes.segment_seconds(seconds) + int(not previous)
|
| 59 |
opening = not previous
|
| 60 |
sent = 0
|
| 61 |
for step in range(steps):
|
|
@@ -72,11 +77,14 @@ def generate(key, rev, previous, prompt, stage_name, seconds=4, seed=0, preview=
|
|
| 72 |
out.flush()
|
| 73 |
sent = strips
|
| 74 |
yield strips
|
|
|
|
| 75 |
if out.tell() != seconds * 16 * 832 * 480 * 3:
|
| 76 |
raise ValueError("Unexpected segment frame count")
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
| 80 |
LOG.info("cue checkpoint %s rev=%d latent=%d..%d rolls=%d",key[:8],rev,first,rollout.total,rollout.rolls)
|
| 81 |
finally:
|
| 82 |
LOG.info("cue worker exit %s rev=%d elapsed=%.2f",key[:8],rev,time.monotonic()-started)
|
|
|
|
| 1 |
"""Advance a single rollout by the duration of each direction."""
|
| 2 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 3 |
import base64
|
| 4 |
import logging
|
| 5 |
import subprocess
|
|
|
|
| 11 |
import torch
|
| 12 |
from PIL import Image
|
| 13 |
|
| 14 |
+
from continuity import WindowWriter
|
| 15 |
import takes
|
| 16 |
|
| 17 |
LOG = logging.getLogger("studio")
|
|
|
|
| 54 |
first = rollout.total
|
| 55 |
text = pipe.dit.text_cache(pipe.encode_prompt(prompt))
|
| 56 |
yield "generating"
|
| 57 |
+
steps = 4 * takes.segment_seconds(seconds) + int(not previous)
|
| 58 |
+
with ThreadPoolExecutor(max_workers=1, thread_name_prefix="continuity") as pool, (stage / "pixels.rgb").open("wb") as out:
|
| 59 |
+
writer = WindowWriter(stage / "state", rollout, steps, en.ROLL_STRIDE, en.SINK, pool, check_active)
|
| 60 |
+
if previous:
|
| 61 |
+
writer.inherit(takes.completed(key, previous) / "state", en.ROLL_STRIDE, en.SINK)
|
| 62 |
# Four decoder frames per latent. The opening decoder trims three
|
| 63 |
# startup frames. Advance one extra latent and trim the fourth.
|
|
|
|
| 64 |
opening = not previous
|
| 65 |
sent = 0
|
| 66 |
for step in range(steps):
|
|
|
|
| 77 |
out.flush()
|
| 78 |
sent = strips
|
| 79 |
yield strips
|
| 80 |
+
writer.capture(rollout.total - 1, rollout.used - 1)
|
| 81 |
if out.tell() != seconds * 16 * 832 * 480 * 3:
|
| 82 |
raise ValueError("Unexpected segment frame count")
|
| 83 |
+
Image.fromarray(frames[-1]).save(stage / "hold.jpg", quality=92)
|
| 84 |
+
yield "saving"
|
| 85 |
+
tail_start = time.monotonic()
|
| 86 |
+
rollout.save_history(stage / "state", writer.finish())
|
| 87 |
+
LOG.info("continuity tail %s rev=%d elapsed=%.3f", key[:8], rev, time.monotonic()-tail_start)
|
| 88 |
LOG.info("cue checkpoint %s rev=%d latent=%d..%d rolls=%d",key[:8],rev,first,rollout.total,rollout.rolls)
|
| 89 |
finally:
|
| 90 |
LOG.info("cue worker exit %s rev=%d elapsed=%.2f",key[:8],rev,time.monotonic()-started)
|