Spaces:
Running on Zero
Running on Zero
Select FastFrames-S or FastFrames-L for a studio take
Browse files- README.md +7 -3
- app.py +8 -5
- assets/credits.html +1 -1
- assets/desk.html +3 -0
- assets/studio.css +5 -3
- assets/studio.js +7 -2
- engine.py +61 -39
- fastframes/pipeline.py +3 -2
- fp8_blocks.py +120 -0
- render.py +11 -6
- takes.py +5 -3
README.md
CHANGED
|
@@ -19,6 +19,7 @@ license_link: https://huggingface.co/apple/FastFrames-S/blob/main/LICENSE
|
|
| 19 |
short_description: Direct a continuous video shot by voice or text
|
| 20 |
models:
|
| 21 |
- apple/FastFrames-S
|
|
|
|
| 22 |
- FluidVoice-Labs/fluid-speech-pro-onnx
|
| 23 |
- thinkingmachines/Inkling-2-Mini
|
| 24 |
- Qwen/Qwen3-4B-Instruct-2507
|
|
@@ -28,17 +29,19 @@ models:
|
|
| 28 |
|
| 29 |
# FastFrames Voice
|
| 30 |
|
| 31 |
-
A private research prototype for directing a continuous generated shot with spoken or written cues. Version 0.
|
|
|
|
|
|
|
| 32 |
|
| 33 |
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. The next generation waits for the previous revision to commit. 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.
|
| 34 |
|
| 35 |
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.
|
| 36 |
|
| 37 |
-
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.
|
| 38 |
|
| 39 |
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.
|
| 40 |
|
| 41 |
-
API clients use the same Gradio session throughout. Call `begin`, then `voice_direction` with the take ID, increasing sequence number and base64 mono 16 kHz PCM WAV. Alternatively use `text_direction` with `text` (1–1200 characters). Both endpoints accept an optional integer `seconds` from 1 to 8, default 4. API calls without an `operation` retain append behavior. The studio sends `operation: "auto"` by default. Send `operation: "redo_last"` with the last accepted clip’s `target_rev` to override automatic routing. A `clarify` event carries a question ID. Send a higher sequence number with `reply_to` and either a spoken/written answer or an explicit `answer` of `append`, `redo_last` or `cancel`. For each accepted cue, call `live_take` with its take ID and revision. Its first video output contains the new MP4 when the phase is `segment` or `variant`. After a variant, call `choose_variant` with the take ID, revision and a `choice` of `original` or `variant`. Wait for completion before the next cue. `end_take` closes the shot, then `export_take` returns the full recording. A failed render can be retried with the same revision or replaced by a new direction.
|
| 42 |
|
| 43 |
## Running the Space
|
| 44 |
|
|
@@ -46,6 +49,7 @@ Use the Hugging Face Gradio SDK and ZeroGPU hardware. Attach a **private read-wr
|
|
| 46 |
|
| 47 |
## Credits and licenses
|
| 48 |
|
|
|
|
| 49 |
- [FastFrames-S](https://huggingface.co/apple/FastFrames-S) by Apple. Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement. The weights are for non-commercial research, with terms in MODEL-LICENSE.txt. Vendored inference code carries the accompanying LICENSE and ACKNOWLEDGEMENTS. Model dependencies include [Causal-Forcing++](https://huggingface.co/zhuhz22/Causal-Forcing) and [Wan2.1](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B).
|
| 50 |
- Streaming implementation adapted from [FastFrames-S Live](https://huggingface.co/spaces/linoyts/fastframes-s-live) by linoyts, revision 4675f39b08cd95fcecdb8f77d4e27b2dc8b35120. This prototype changes the prompt conditioning during a rollout and omits the periodic scene restart.
|
| 51 |
- [Fluid Speech Pro by FluidVoice](https://huggingface.co/FluidVoice-Labs/fluid-speech-pro), CC BY 4.0. Uses the authors’ ONNX int8 export.
|
|
|
|
| 19 |
short_description: Direct a continuous video shot by voice or text
|
| 20 |
models:
|
| 21 |
- apple/FastFrames-S
|
| 22 |
+
- apple/FastFrames-L
|
| 23 |
- FluidVoice-Labs/fluid-speech-pro-onnx
|
| 24 |
- thinkingmachines/Inkling-2-Mini
|
| 25 |
- Qwen/Qwen3-4B-Instruct-2507
|
|
|
|
| 29 |
|
| 30 |
# FastFrames Voice
|
| 31 |
|
| 32 |
+
A private research prototype for directing a continuous generated shot with spoken or written cues. Version 0.8.0. 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. The next generation waits for the previous revision to commit. 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 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 |
|
| 44 |
+
API clients use the same Gradio session throughout. Call `begin` with the take ID and an optional `model` of `S` or `L` (default `S`), then `voice_direction` with the take ID, increasing sequence number and base64 mono 16 kHz PCM WAV. Alternatively use `text_direction` with `text` (1–1200 characters). Both endpoints accept an optional integer `seconds` from 1 to 8, default 4. API calls without an `operation` retain append behavior. The studio sends `operation: "auto"` by default. Send `operation: "redo_last"` with the last accepted clip’s `target_rev` to override automatic routing. A `clarify` event carries a question ID. Send a higher sequence number with `reply_to` and either a spoken/written answer or an explicit `answer` of `append`, `redo_last` or `cancel`. For each accepted cue, call `live_take` with its take ID and revision. Its first video output contains the new MP4 when the phase is `segment` or `variant`. After a variant, call `choose_variant` with the take ID, revision and a `choice` of `original` or `variant`. Wait for completion before the next cue. `end_take` closes the shot, then `export_take` returns the full recording. A failed render can be retried with the same revision or replaced by a new direction.
|
| 45 |
|
| 46 |
## Running the Space
|
| 47 |
|
|
|
|
| 49 |
|
| 50 |
## Credits and licenses
|
| 51 |
|
| 52 |
+
- [FastFrames-L](https://huggingface.co/apple/FastFrames-L) by Apple, with the 14B Wan backbone. The eager FP8 blocks are adapted from [FastFrames-L Live](https://huggingface.co/spaces/linoyts/fastframes-l-live/tree/e9f042cfc08f3d3e6998e457efdbc6bd5e9308a6) by linoyts. The Apple ML Research Model license also applies to the L weights.
|
| 53 |
- [FastFrames-S](https://huggingface.co/apple/FastFrames-S) by Apple. Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement. The weights are for non-commercial research, with terms in MODEL-LICENSE.txt. Vendored inference code carries the accompanying LICENSE and ACKNOWLEDGEMENTS. Model dependencies include [Causal-Forcing++](https://huggingface.co/zhuhz22/Causal-Forcing) and [Wan2.1](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B).
|
| 54 |
- Streaming implementation adapted from [FastFrames-S Live](https://huggingface.co/spaces/linoyts/fastframes-s-live) by linoyts, revision 4675f39b08cd95fcecdb8f77d4e27b2dc8b35120. This prototype changes the prompt conditioning during a rollout and omits the periodic scene restart.
|
| 55 |
- [Fluid Speech Pro by FluidVoice](https://huggingface.co/FluidVoice-Labs/fluid-speech-pro), CC BY 4.0. Uses the authors’ ONNX int8 export.
|
app.py
CHANGED
|
@@ -33,9 +33,12 @@ def msg(take, phase, **data):
|
|
| 33 |
|
| 34 |
def begin(raw: str, request: gr.Request):
|
| 35 |
p,key = payload(raw,request)
|
|
|
|
|
|
|
|
|
|
| 36 |
with gallery.lock_for(request.session_hash):
|
| 37 |
-
takes.start(key,request.session_hash)
|
| 38 |
-
return msg(p["take"],"armed")
|
| 39 |
|
| 40 |
def phrase(raw: str, request: gr.Request, oauth: gr.OAuthToken | None):
|
| 41 |
yield from direction(raw, request, oauth, "voice")
|
|
@@ -195,7 +198,7 @@ def saved_sessions(raw: str, request: gr.Request, profile: gr.OAuthProfile | Non
|
|
| 195 |
with gallery.opened(who, p.get("archive"), personal) as folder:
|
| 196 |
yield gallery.viewing_copy(folder,request.session_hash),status("viewing",archive=folder.name)
|
| 197 |
return
|
| 198 |
-
|
| 199 |
except Exception:
|
| 200 |
LOG.exception("gallery action failed: %s",p.get("action"))
|
| 201 |
yield gr.skip(),status("collection_error")
|
|
@@ -230,7 +233,7 @@ def live(raw: str, request: gr.Request):
|
|
| 230 |
parent.mkdir(exist_ok=True)
|
| 231 |
early=Path(tempfile.mkdtemp(prefix=f"live-{rev}-",dir=parent))
|
| 232 |
count=0
|
| 233 |
-
stream = render.generate(key,rev,base,row["next_prompt"],str(stage),row["seconds"],row["seed"],early is not None)
|
| 234 |
for phase in stream:
|
| 235 |
if type(phase) is int:
|
| 236 |
render.write_strips(stage,count,phase)
|
|
@@ -249,7 +252,7 @@ def live(raw: str, request: gr.Request):
|
|
| 249 |
published=True
|
| 250 |
release_claim = False
|
| 251 |
folder = takes.completed(key,rev)
|
| 252 |
-
yield str(folder / filename),skip(),msg(tag,"variant" if variant else "segment",rev=rev,frames=count,seconds=row["seconds"],preview=str(takes.PREVIEWS / key / str(rev)),still=still)
|
| 253 |
except Exception as exc:
|
| 254 |
if takes.fail(key,rev):
|
| 255 |
release_claim = False
|
|
|
|
| 33 |
|
| 34 |
def begin(raw: str, request: gr.Request):
|
| 35 |
p,key = payload(raw,request)
|
| 36 |
+
model = p.get("model", "S")
|
| 37 |
+
if model not in ("S", "L"):
|
| 38 |
+
return msg(p["take"], "invalid_model")
|
| 39 |
with gallery.lock_for(request.session_hash):
|
| 40 |
+
takes.start(key,request.session_hash,model)
|
| 41 |
+
return msg(p["take"],"armed",model=model)
|
| 42 |
|
| 43 |
def phrase(raw: str, request: gr.Request, oauth: gr.OAuthToken | None):
|
| 44 |
yield from direction(raw, request, oauth, "voice")
|
|
|
|
| 198 |
with gallery.opened(who, p.get("archive"), personal) as folder:
|
| 199 |
yield gallery.viewing_copy(folder,request.session_hash),status("viewing",archive=folder.name)
|
| 200 |
return
|
| 201 |
+
yield gr.skip(),status("collection_error")
|
| 202 |
except Exception:
|
| 203 |
LOG.exception("gallery action failed: %s",p.get("action"))
|
| 204 |
yield gr.skip(),status("collection_error")
|
|
|
|
| 233 |
parent.mkdir(exist_ok=True)
|
| 234 |
early=Path(tempfile.mkdtemp(prefix=f"live-{rev}-",dir=parent))
|
| 235 |
count=0
|
| 236 |
+
stream = render.generate(key,rev,base,row["next_prompt"],str(stage),row["seconds"],row["seed"],early is not None,row["model"])
|
| 237 |
for phase in stream:
|
| 238 |
if type(phase) is int:
|
| 239 |
render.write_strips(stage,count,phase)
|
|
|
|
| 252 |
published=True
|
| 253 |
release_claim = False
|
| 254 |
folder = takes.completed(key,rev)
|
| 255 |
+
yield str(folder / filename),skip(),msg(tag,"variant" if variant else "segment",model=row["model"],rev=rev,frames=count,seconds=row["seconds"],preview=str(takes.PREVIEWS / key / str(rev)),still=still)
|
| 256 |
except Exception as exc:
|
| 257 |
if takes.fail(key,rev):
|
| 258 |
release_claim = False
|
assets/credits.html
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
<footer class="credit-line"><div><a href="https://huggingface.co/apple/FastFrames-S" target="_blank" rel="noopener">FastFrames-S <span>· Apple</span></a><a href="https://huggingface.co/FluidVoice-Labs/fluid-speech-pro" target="_blank" rel="noopener">Fluid Speech Pro <span>· FluidVoice</span></a><a href="https://huggingface.co/thinkingmachines/Inkling-2-Mini" target="_blank" rel="noopener">Inkling 2 Mini <span>· Thinking Machines</span></a><a href="https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507" target="_blank" rel="noopener">Qwen</a><a href="https://huggingface.co/spaces/linoyts/fastframes-s-live" target="_blank" rel="noopener"><span data-tr="source">Source Space</span> · linoyts</a></div><a href="https://huggingface.co/fffiloni" target="_blank" rel="noopener">UI/UX · Sylvain Filoni / fffiloni</a></footer>
|
|
|
|
| 1 |
+
<footer class="credit-line"><div><a href="https://huggingface.co/apple/FastFrames-S" target="_blank" rel="noopener">FastFrames-S</a><a href="https://huggingface.co/apple/FastFrames-L" target="_blank" rel="noopener">FastFrames-L <span>· Apple</span></a><a href="https://huggingface.co/FluidVoice-Labs/fluid-speech-pro" target="_blank" rel="noopener">Fluid Speech Pro <span>· FluidVoice</span></a><a href="https://huggingface.co/thinkingmachines/Inkling-2-Mini" target="_blank" rel="noopener">Inkling 2 Mini <span>· Thinking Machines</span></a><a href="https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507" target="_blank" rel="noopener">Qwen</a><a href="https://huggingface.co/spaces/linoyts/fastframes-s-live" target="_blank" rel="noopener"><span data-tr="source">Source Space</span> · linoyts</a></div><a href="https://huggingface.co/fffiloni" target="_blank" rel="noopener">UI/UX · Sylvain Filoni / fffiloni</a></footer>
|
assets/desk.html
CHANGED
|
@@ -29,6 +29,9 @@
|
|
| 29 |
<button type="button" id="mode-text" aria-pressed="false" data-tr="textMode">Text</button>
|
| 30 |
</div>
|
| 31 |
<label id="redo-control"><input type="checkbox" id="redo-last" disabled><span data-tr="redoLabel">Redo last segment</span></label>
|
|
|
|
|
|
|
|
|
|
| 32 |
<label class="duration" id="next-length"><span data-tr="duration">Next segment</span>
|
| 33 |
<select id="cue-seconds" aria-describedby="stage-text"><option value="1">1 s</option><option value="2">2 s</option><option value="3">3 s</option><option value="4" selected>4 s</option><option value="5">5 s</option><option value="6">6 s</option><option value="7">7 s</option><option value="8">8 s</option></select>
|
| 34 |
</label>
|
|
|
|
| 29 |
<button type="button" id="mode-text" aria-pressed="false" data-tr="textMode">Text</button>
|
| 30 |
</div>
|
| 31 |
<label id="redo-control"><input type="checkbox" id="redo-last" disabled><span data-tr="redoLabel">Redo last segment</span></label>
|
| 32 |
+
<label class="duration" id="model-choice"><span data-tr="videoModel">Video model</span>
|
| 33 |
+
<select id="video-model"><option value="S">FastFrames-S</option><option value="L">FastFrames-L · 14B</option></select>
|
| 34 |
+
</label>
|
| 35 |
<label class="duration" id="next-length"><span data-tr="duration">Next segment</span>
|
| 36 |
<select id="cue-seconds" aria-describedby="stage-text"><option value="1">1 s</option><option value="2">2 s</option><option value="3">3 s</option><option value="4" selected>4 s</option><option value="5">5 s</option><option value="6">6 s</option><option value="7">7 s</option><option value="8">8 s</option></select>
|
| 37 |
</label>
|
assets/studio.css
CHANGED
|
@@ -16,8 +16,8 @@
|
|
| 16 |
.stop:disabled{opacity:.5;cursor:default!important}.stop-icon{width:10px;height:10px;border-radius:2px;background:currentColor}
|
| 17 |
#monitor{isolation:isolate;position:relative!important;display:grid!important;overflow:hidden;aspect-ratio:832/480;width:100%;background:#080909;border:1px solid #373c3b;border-radius:6px;gap:0!important}
|
| 18 |
#monitor>#cover,#monitor #live-feed,#monitor #last-take,#monitor #cover{position:absolute!important;inset:0;width:100%!important;height:100%!important;min-height:0!important;margin:0!important;border:0!important}
|
| 19 |
-
#live-feed,#last-take{opacity:0;pointer-events:none;background:#080909!important}
|
| 20 |
-
#monitor[data-mode=saved] #last-take{opacity:1;pointer-events:auto;z-index:2}
|
| 21 |
#monitor[data-mode=saved] #cover{visibility:hidden}
|
| 22 |
#monitor video{width:100%!important;height:100%!important;max-height:none!important;object-fit:contain!important;display:block;background:#080909}
|
| 23 |
#cover .viewfinder,#cover .still{height:100%;width:100%;position:absolute;inset:0;object-fit:contain}
|
|
@@ -69,7 +69,7 @@
|
|
| 69 |
#studio .input-switch button[aria-pressed=true]{background:#354039;color:#fff;box-shadow:inset 0 -2px var(--studio-warm)}
|
| 70 |
.duration{font-size:14px;color:#c4ccc7;gap:8px}
|
| 71 |
#cue-seconds,#cue-text{color:#f4f4ef;background:#191d1b;border:1px solid #666f67;border-radius:5px;font:inherit}
|
| 72 |
-
#cue-seconds{min-height:44px;padding:0 10px;appearance:auto}
|
| 73 |
#text-control{margin-top:10px}#text-control label{display:block;margin-bottom:4px}
|
| 74 |
.composer{align-items:stretch;gap:8px}.composer textarea{flex:1;min-width:0;padding:9px 12px;resize:vertical}
|
| 75 |
#studio #send-text{padding:6px 14px;border-radius:5px;border:1px solid #a17a42;background:#f4b769;color:#211911;min-height:44px;font-weight:600}
|
|
@@ -176,3 +176,5 @@ html:has(#huggingface-space-header){scroll-padding-top:60px}
|
|
| 176 |
#studio #loop-preview{position:absolute;bottom:10px;right:10px;z-index:3;min-height:44px;padding:0 12px;border-radius:5px;border:1px solid #818883;background:#151918ed;color:#fff;font-size:13px}
|
| 177 |
#studio #loop-preview[aria-pressed=true]{border-color:#dcaf77}
|
| 178 |
#studio #loop-preview[hidden]{display:none}
|
|
|
|
|
|
|
|
|
| 16 |
.stop:disabled{opacity:.5;cursor:default!important}.stop-icon{width:10px;height:10px;border-radius:2px;background:currentColor}
|
| 17 |
#monitor{isolation:isolate;position:relative!important;display:grid!important;overflow:hidden;aspect-ratio:832/480;width:100%;background:#080909;border:1px solid #373c3b;border-radius:6px;gap:0!important}
|
| 18 |
#monitor>#cover,#monitor #live-feed,#monitor #last-take,#monitor #cover{position:absolute!important;inset:0;width:100%!important;height:100%!important;min-height:0!important;margin:0!important;border:0!important}
|
| 19 |
+
#live-feed,#last-take{visibility:hidden;opacity:0;pointer-events:none;background:#080909!important}
|
| 20 |
+
#monitor[data-mode=saved] #last-take{visibility:visible;opacity:1;pointer-events:auto;z-index:2}
|
| 21 |
#monitor[data-mode=saved] #cover{visibility:hidden}
|
| 22 |
#monitor video{width:100%!important;height:100%!important;max-height:none!important;object-fit:contain!important;display:block;background:#080909}
|
| 23 |
#cover .viewfinder,#cover .still{height:100%;width:100%;position:absolute;inset:0;object-fit:contain}
|
|
|
|
| 69 |
#studio .input-switch button[aria-pressed=true]{background:#354039;color:#fff;box-shadow:inset 0 -2px var(--studio-warm)}
|
| 70 |
.duration{font-size:14px;color:#c4ccc7;gap:8px}
|
| 71 |
#cue-seconds,#cue-text{color:#f4f4ef;background:#191d1b;border:1px solid #666f67;border-radius:5px;font:inherit}
|
| 72 |
+
#studio :is(#cue-seconds,#video-model){min-height:44px;padding:0 10px;appearance:auto}
|
| 73 |
#text-control{margin-top:10px}#text-control label{display:block;margin-bottom:4px}
|
| 74 |
.composer{align-items:stretch;gap:8px}.composer textarea{flex:1;min-width:0;padding:9px 12px;resize:vertical}
|
| 75 |
#studio #send-text{padding:6px 14px;border-radius:5px;border:1px solid #a17a42;background:#f4b769;color:#211911;min-height:44px;font-weight:600}
|
|
|
|
| 176 |
#studio #loop-preview{position:absolute;bottom:10px;right:10px;z-index:3;min-height:44px;padding:0 12px;border-radius:5px;border:1px solid #818883;background:#151918ed;color:#fff;font-size:13px}
|
| 177 |
#studio #loop-preview[aria-pressed=true]{border-color:#dcaf77}
|
| 178 |
#studio #loop-preview[hidden]{display:none}
|
| 179 |
+
|
| 180 |
+
#studio .desk-rail #video-model{width:auto;max-width:100%;min-height:44px}
|
assets/studio.js
CHANGED
|
@@ -4,6 +4,7 @@ const deskEl = by("voice-desk");
|
|
| 4 |
const mic = by("mic-key"), end = by("end-take"), monitor = by("monitor");
|
| 5 |
const retry = by("retry-cue");
|
| 6 |
const draft = by("cue-text"), send = by("send-text"), seconds = by("cue-seconds");
|
|
|
|
| 7 |
const forceRedo = by("redo-last");
|
| 8 |
const hold = by("held-frame");
|
| 9 |
const playback = inlinePlayback(monitor, by("cue-screen"),
|
|
@@ -32,6 +33,7 @@ const copy = {
|
|
| 32 |
endSave:["End session and save recording","Terminer la session et enregistrer la vidéo"],
|
| 33 |
end:["End session","Terminer"],intro:["Describe your opening shot.","Décris ton premier plan."],
|
| 34 |
preview:["Preview frame","Aperçu"],help:["Speak or type a direction to begin.","Utilise la voix ou le clavier pour commencer."],
|
|
|
|
| 35 |
voiceMode:["Voice","Voix"],textMode:["Text","Texte"],duration:["Next segment","Prochaine portion"],
|
| 36 |
textLabel:["Written direction","Consigne écrite"],textIdle:["Ready for a written direction","En attente d’une consigne écrite"],
|
| 37 |
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é."],
|
|
@@ -102,6 +104,8 @@ function label(){
|
|
| 102 |
by("loop-preview").textContent=tr(loopEnabled?"loopOn":"loopOff");
|
| 103 |
by("loop-preview").setAttribute("aria-pressed",String(loopEnabled));
|
| 104 |
collection?.controls();
|
|
|
|
|
|
|
| 105 |
forceRedo.disabled=!take||!approvedClip||busy||stopped||Boolean(questionId||variantClip);
|
| 106 |
by("next-length").hidden=forceRedo.checked;
|
| 107 |
by("fixed-length").hidden=!forceRedo.checked;
|
|
@@ -191,10 +195,10 @@ function sample(a){
|
|
| 191 |
if(quiet>=.75||blocks.length*dt>=13)flush();
|
| 192 |
}
|
| 193 |
function startTake(){
|
| 194 |
-
resetEditing();
|
| 195 |
take=crypto.randomUUID();seq=applied=visionRev=0;focus=prompt=lastHeard=lastSource=interpreter="";
|
| 196 |
ready=busy=stopped=false;queue=[];retryKind="";playback.clear();
|
| 197 |
-
setStatus("starting");emit("begin",{take});
|
| 198 |
watchdog=setTimeout(()=>{if(take&&!ready)finish("connection");},20000);
|
| 199 |
}
|
| 200 |
function chooseInput(next){
|
|
@@ -317,6 +321,7 @@ window.addEventListener("ffv-signal",e=>{
|
|
| 317 |
let d;try{d=JSON.parse(e.detail);}catch{return;}
|
| 318 |
if(collection?.signal(d))return;
|
| 319 |
if(!take||d.take!==take)return;
|
|
|
|
| 320 |
if(d.phase==="closed"||d.phase==="finished"){finish(d.phase);return;}
|
| 321 |
if(d.phase==="stopping"){
|
| 322 |
clearTimeout(watchdog);setStatus("finalizing");emit("export_take",{take,device:collection?.device});return;
|
|
|
|
| 4 |
const mic = by("mic-key"), end = by("end-take"), monitor = by("monitor");
|
| 5 |
const retry = by("retry-cue");
|
| 6 |
const draft = by("cue-text"), send = by("send-text"), seconds = by("cue-seconds");
|
| 7 |
+
const videoModel = by("video-model");
|
| 8 |
const forceRedo = by("redo-last");
|
| 9 |
const hold = by("held-frame");
|
| 10 |
const playback = inlinePlayback(monitor, by("cue-screen"),
|
|
|
|
| 33 |
endSave:["End session and save recording","Terminer la session et enregistrer la vidéo"],
|
| 34 |
end:["End session","Terminer"],intro:["Describe your opening shot.","Décris ton premier plan."],
|
| 35 |
preview:["Preview frame","Aperçu"],help:["Speak or type a direction to begin.","Utilise la voix ou le clavier pour commencer."],
|
| 36 |
+
videoModel:["Video model","Modèle vidéo"],modelLocked:["Model fixed for this shot","Modèle fixé pour ce plan"],invalid_model:["Choose FastFrames-S or FastFrames-L","Choisis FastFrames-S ou FastFrames-L"],
|
| 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é."],
|
|
|
|
| 104 |
by("loop-preview").textContent=tr(loopEnabled?"loopOn":"loopOff");
|
| 105 |
by("loop-preview").setAttribute("aria-pressed",String(loopEnabled));
|
| 106 |
collection?.controls();
|
| 107 |
+
videoModel.disabled=Boolean(take);
|
| 108 |
+
by("model-choice").title=take?tr("modelLocked"):"";
|
| 109 |
forceRedo.disabled=!take||!approvedClip||busy||stopped||Boolean(questionId||variantClip);
|
| 110 |
by("next-length").hidden=forceRedo.checked;
|
| 111 |
by("fixed-length").hidden=!forceRedo.checked;
|
|
|
|
| 195 |
if(quiet>=.75||blocks.length*dt>=13)flush();
|
| 196 |
}
|
| 197 |
function startTake(){
|
| 198 |
+
resetEditing();lastSegment=null;pendingStill="";saved=false;setMode("cover");
|
| 199 |
take=crypto.randomUUID();seq=applied=visionRev=0;focus=prompt=lastHeard=lastSource=interpreter="";
|
| 200 |
ready=busy=stopped=false;queue=[];retryKind="";playback.clear();
|
| 201 |
+
setStatus("starting");emit("begin",{take,model:videoModel.value});
|
| 202 |
watchdog=setTimeout(()=>{if(take&&!ready)finish("connection");},20000);
|
| 203 |
}
|
| 204 |
function chooseInput(next){
|
|
|
|
| 321 |
let d;try{d=JSON.parse(e.detail);}catch{return;}
|
| 322 |
if(collection?.signal(d))return;
|
| 323 |
if(!take||d.take!==take)return;
|
| 324 |
+
if(d.phase==="invalid_model"){finish("invalid_model");return;}
|
| 325 |
if(d.phase==="closed"||d.phase==="finished"){finish(d.phase);return;}
|
| 326 |
if(d.phase==="stopping"){
|
| 327 |
clearTimeout(watchdog);setStatus("finalizing");emit("export_take",{take,device:collection?.device});return;
|
engine.py
CHANGED
|
@@ -1,13 +1,15 @@
|
|
| 1 |
-
"""FastFrames
|
| 2 |
from collections import deque
|
| 3 |
from pathlib import Path
|
| 4 |
import torch
|
| 5 |
from huggingface_hub import hf_hub_download, snapshot_download
|
| 6 |
|
|
|
|
| 7 |
from fastframes.pipeline import MODELS, FastFrames, configure_backends, to_uint8
|
| 8 |
from fastframes.wan.causal_model import allocate_kv_cache
|
| 9 |
|
| 10 |
FF_S_REVISION = "aa099efcedf1b65447106bf9004cde75821f7387"
|
|
|
|
| 11 |
CF_REVISION = "2f8eb8bb6eeb1238da9d13e5420d342a74d634a6"
|
| 12 |
WAN_REVISION = "37ec512624d61f7aa208f7ea8140a131f93afc9a"
|
| 13 |
|
|
@@ -20,20 +22,29 @@ DECODER_CONTEXT = 6
|
|
| 20 |
|
| 21 |
# ------------------------------------------------------------------------------------------- model
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
# ------------------------------------------------------------------------------------------- stream engine
|
|
@@ -41,11 +52,16 @@ print(f"[load] FastFrames-S ready: tokens/frame={TOKENS} cap={CAP} temporal_pair
|
|
| 41 |
class LiveRollout:
|
| 42 |
"""FastFrames.rollout, one latent frame at a time, forever, with a sink + rolling KV window."""
|
| 43 |
|
| 44 |
-
def __init__(self,
|
| 45 |
# one cache per session, reused across scenes: slots are overwritten in order and attention only
|
| 46 |
# reads filled slots, so no clearing is needed
|
| 47 |
-
self.
|
| 48 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
self.used = 0 # occupied cache slots
|
| 50 |
self.total = 0 # latent frames generated
|
| 51 |
self.features = deque(maxlen=DECODER_CONTEXT + CHUNK)
|
|
@@ -54,20 +70,20 @@ class LiveRollout:
|
|
| 54 |
self.rolls = 0
|
| 55 |
|
| 56 |
def _noise(self):
|
| 57 |
-
return torch.randn((1, 1, 16, *
|
| 58 |
dtype=torch.bfloat16)
|
| 59 |
|
| 60 |
def _roll(self):
|
| 61 |
"""Drop ROLL_STRIDE window frames; shift the rest down and re-rotate their keys by -ROLL_STRIDE."""
|
| 62 |
keep_from = 1 if SINK else 0
|
| 63 |
-
src = (keep_from + ROLL_STRIDE) *
|
| 64 |
-
dst = keep_from *
|
| 65 |
-
n = (
|
| 66 |
-
shift =
|
| 67 |
for layer in self.kv:
|
| 68 |
k = layer["k"][:, src:src + n].float()
|
| 69 |
k = torch.view_as_complex(k.unflatten(-1, (-1, 2)).contiguous())
|
| 70 |
-
k[..., :
|
| 71 |
layer["k"][:, dst:dst + n] = torch.view_as_real(k).flatten(-2).to(layer["k"].dtype)
|
| 72 |
layer["v"][:, dst:dst + n] = layer["v"][:, src:src + n].clone()
|
| 73 |
self.used -= ROLL_STRIDE
|
|
@@ -75,21 +91,25 @@ class LiveRollout:
|
|
| 75 |
|
| 76 |
@torch.inference_mode()
|
| 77 |
def step(self, text_cache):
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
self._roll()
|
| 80 |
slot = self.used
|
| 81 |
-
schedule =
|
| 82 |
x = self._noise()
|
| 83 |
for i, timestep in enumerate(schedule):
|
| 84 |
-
x0, feature, mod =
|
| 85 |
if i + 1 < len(schedule):
|
| 86 |
-
next_t = torch.full((1,), schedule[i + 1], device=
|
| 87 |
eps = self._noise()[:, 0]
|
| 88 |
-
x =
|
| 89 |
if slot == 0:
|
| 90 |
-
|
| 91 |
else:
|
| 92 |
-
|
| 93 |
self.features.append(feature)
|
| 94 |
self.modulation.append(mod)
|
| 95 |
self.used += 1
|
|
@@ -102,10 +122,10 @@ class LiveRollout:
|
|
| 102 |
history = min(DECODER_CONTEXT, self.decoded, len(self.features) - new)
|
| 103 |
feats = torch.cat(list(self.features)[-(new + history):], dim=1)
|
| 104 |
mods = torch.cat(list(self.modulation)[-(new + history):], dim=1)
|
| 105 |
-
h, w =
|
| 106 |
-
grid = torch.tensor([[new + history, h // 2, w // 2]], device=
|
| 107 |
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 108 |
-
pixels =
|
| 109 |
pixels = pixels[4 * history:]
|
| 110 |
if self.decoded == 0:
|
| 111 |
pixels = pixels[3:] # the decoder's first three frames are dropped (84 -> 81 convention)
|
|
@@ -117,13 +137,13 @@ class LiveRollout:
|
|
| 117 |
def save(self, folder, check_active):
|
| 118 |
"""Keep only occupied KV slots, decoder history and exact RNG state on CPU."""
|
| 119 |
folder.mkdir()
|
| 120 |
-
end = self.used *
|
| 121 |
for index, layer in enumerate(self.kv):
|
| 122 |
check_active()
|
| 123 |
tensors = {name: value[:, :end].contiguous().cpu() for name, value in layer.items()}
|
| 124 |
torch.save(tensors, folder / f"layer-{index}.pt")
|
| 125 |
torch.save({
|
| 126 |
-
"used": self.used, "total": self.total, "decoded": self.decoded, "rolls": self.rolls,
|
| 127 |
"rng": self.gen.get_state().cpu(),
|
| 128 |
"features": [value.cpu() for value in list(self.features)[-DECODER_CONTEXT:]],
|
| 129 |
"modulation": [value.cpu() for value in list(self.modulation)[-DECODER_CONTEXT:]],
|
|
@@ -131,12 +151,14 @@ class LiveRollout:
|
|
| 131 |
|
| 132 |
def restore(self, folder, check_active):
|
| 133 |
history = torch.load(folder / "history.pt", map_location="cpu", weights_only=True)
|
|
|
|
|
|
|
| 134 |
self.used, self.total = history["used"], history["total"]
|
| 135 |
self.decoded, self.rolls = history["decoded"], history["rolls"]
|
| 136 |
self.gen.set_state(history["rng"])
|
| 137 |
-
self.features.extend(value.to(
|
| 138 |
-
self.modulation.extend(value.to(
|
| 139 |
-
end = self.used *
|
| 140 |
for index, layer in enumerate(self.kv):
|
| 141 |
check_active()
|
| 142 |
tensors = torch.load(folder / f"layer-{index}.pt", mmap=True, weights_only=True, map_location="cpu")
|
|
|
|
| 1 |
+
"""FastFrames S/L loading and rolling KV window adapted from linoyts’ live Spaces."""
|
| 2 |
from collections import deque
|
| 3 |
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
|
| 10 |
|
| 11 |
FF_S_REVISION = "aa099efcedf1b65447106bf9004cde75821f7387"
|
| 12 |
+
FF_L_REVISION = "18f30cbdd91943baa274e4237dd09b6d19e58ca9"
|
| 13 |
CF_REVISION = "2f8eb8bb6eeb1238da9d13e5420d342a74d634a6"
|
| 14 |
WAN_REVISION = "37ec512624d61f7aa208f7ea8140a131f93afc9a"
|
| 15 |
|
|
|
|
| 22 |
|
| 23 |
# ------------------------------------------------------------------------------------------- model
|
| 24 |
|
| 25 |
+
def load_pipelines():
|
| 26 |
+
encoder_dir = Path(snapshot_download("Wan-AI/Wan2.1-T2V-1.3B", revision=WAN_REVISION,
|
| 27 |
+
allow_patterns=["models_t5_umt5-xxl-enc-bf16.pth", "google/umt5-xxl/*"]))
|
| 28 |
+
pipelines = {}
|
| 29 |
+
encoder = None
|
| 30 |
+
for size, revision in (("S", FF_S_REVISION), ("L", FF_L_REVISION)):
|
| 31 |
+
spec = MODELS["ff-" + size.lower()]
|
| 32 |
+
weights = Path(snapshot_download("apple/FastFrames-" + size, revision=revision,
|
| 33 |
+
allow_patterns=[f"fastframes-{size.lower()}/*"]))
|
| 34 |
+
dit = (hf_hub_download("zhuhz22/Causal-Forcing", spec.dit, revision=CF_REVISION)
|
| 35 |
+
if size == "S" else weights / spec.dit)
|
| 36 |
+
configure_backends(spec.config)
|
| 37 |
+
pipe = FastFrames.from_pretrained(spec.config, encoder_dir, dit, weights / spec.refiner,
|
| 38 |
+
weights / spec.decoder, text_encoder=encoder)
|
| 39 |
+
if size == "L":
|
| 40 |
+
fp8_blocks.install(pipe)
|
| 41 |
+
encoder = pipe.text_encoder
|
| 42 |
+
pipelines[size] = pipe
|
| 43 |
+
print(f"[load] FastFrames-{size} ready", flush=True)
|
| 44 |
+
return pipelines
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
PIPELINES = load_pipelines()
|
| 48 |
|
| 49 |
|
| 50 |
# ------------------------------------------------------------------------------------------- stream engine
|
|
|
|
| 52 |
class LiveRollout:
|
| 53 |
"""FastFrames.rollout, one latent frame at a time, forever, with a sink + rolling KV window."""
|
| 54 |
|
| 55 |
+
def __init__(self, pipe, seed):
|
| 56 |
# one cache per session, reused across scenes: slots are overwritten in order and attention only
|
| 57 |
# reads filled slots, so no clearing is needed
|
| 58 |
+
self.pipe = pipe
|
| 59 |
+
self.tokens = pipe.frame_tokens
|
| 60 |
+
self.cap = pipe.config.num_frames
|
| 61 |
+
pairs = pipe.dit.dim // pipe.dit.num_heads // 2
|
| 62 |
+
self.temporal_pairs = pairs - 2 * (pairs // 3)
|
| 63 |
+
self.kv = allocate_kv_cache(pipe.dit, self.cap, self.tokens, device=pipe.device)
|
| 64 |
+
self.gen = torch.Generator(device=self.pipe.device).manual_seed(int(seed))
|
| 65 |
self.used = 0 # occupied cache slots
|
| 66 |
self.total = 0 # latent frames generated
|
| 67 |
self.features = deque(maxlen=DECODER_CONTEXT + CHUNK)
|
|
|
|
| 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,
|
| 74 |
dtype=torch.bfloat16)
|
| 75 |
|
| 76 |
def _roll(self):
|
| 77 |
"""Drop ROLL_STRIDE window frames; shift the rest down and re-rotate their keys by -ROLL_STRIDE."""
|
| 78 |
keep_from = 1 if SINK else 0
|
| 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].float()
|
| 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
|
|
|
|
| 91 |
|
| 92 |
@torch.inference_mode()
|
| 93 |
def step(self, text_cache):
|
| 94 |
+
with self.pipe.autocast():
|
| 95 |
+
self._step(text_cache)
|
| 96 |
+
|
| 97 |
+
def _step(self, text_cache):
|
| 98 |
+
if self.used == self.cap:
|
| 99 |
self._roll()
|
| 100 |
slot = self.used
|
| 101 |
+
schedule = self.pipe.config.first_frame_timesteps if slot == 0 else self.pipe.config.timesteps
|
| 102 |
x = self._noise()
|
| 103 |
for i, timestep in enumerate(schedule):
|
| 104 |
+
x0, feature, mod = self.pipe._predict(x, timestep, slot, text_cache, self.kv)
|
| 105 |
if i + 1 < len(schedule):
|
| 106 |
+
next_t = torch.full((1,), schedule[i + 1], device=self.pipe.device, dtype=torch.float32)
|
| 107 |
eps = self._noise()[:, 0]
|
| 108 |
+
x = self.pipe.scheduler.add_noise(x0.flatten(0, 1), eps, next_t).unflatten(0, x0.shape[:2])
|
| 109 |
if slot == 0:
|
| 110 |
+
self.pipe._predict(x0, 0.0, slot, text_cache, self.kv) # frame 0 gets a clean DiT pass
|
| 111 |
else:
|
| 112 |
+
self.pipe._refine(x0, slot, self.kv) # later frames: KV refinement network
|
| 113 |
self.features.append(feature)
|
| 114 |
self.modulation.append(mod)
|
| 115 |
self.used += 1
|
|
|
|
| 122 |
history = min(DECODER_CONTEXT, self.decoded, len(self.features) - new)
|
| 123 |
feats = torch.cat(list(self.features)[-(new + history):], dim=1)
|
| 124 |
mods = torch.cat(list(self.modulation)[-(new + history):], dim=1)
|
| 125 |
+
h, w = self.pipe.config.latent_size
|
| 126 |
+
grid = torch.tensor([[new + history, h // 2, w // 2]], device=self.pipe.device, dtype=torch.long)
|
| 127 |
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 128 |
+
pixels = self.pipe.decoder(feats, mods, grid)[0]
|
| 129 |
pixels = pixels[4 * history:]
|
| 130 |
if self.decoded == 0:
|
| 131 |
pixels = pixels[3:] # the decoder's first three frames are dropped (84 -> 81 convention)
|
|
|
|
| 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:]],
|
| 149 |
"modulation": [value.cpu() for value in list(self.modulation)[-DECODER_CONTEXT:]],
|
|
|
|
| 151 |
|
| 152 |
def restore(self, folder, check_active):
|
| 153 |
history = torch.load(folder / "history.pt", map_location="cpu", weights_only=True)
|
| 154 |
+
if history["model"] != self.pipe.config.name:
|
| 155 |
+
raise ValueError("Checkpoint model mismatch")
|
| 156 |
self.used, self.total = history["used"], history["total"]
|
| 157 |
self.decoded, self.rolls = history["decoded"], history["rolls"]
|
| 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()
|
| 164 |
tensors = torch.load(folder / f"layer-{index}.pt", mmap=True, weights_only=True, map_location="cpu")
|
fastframes/pipeline.py
CHANGED
|
@@ -126,7 +126,7 @@ class FastFrames:
|
|
| 126 |
self._refine_embedding = None
|
| 127 |
|
| 128 |
@classmethod
|
| 129 |
-
def from_pretrained(cls, config, wan_dir, dit, refiner, decoder, *, device="cuda"):
|
| 130 |
"""Build from checkpoint paths (or already-loaded state dicts)."""
|
| 131 |
def state(value, key=None):
|
| 132 |
return value if isinstance(value, dict) else load_state_dict(value, key)
|
|
@@ -145,7 +145,8 @@ class FastFrames:
|
|
| 145 |
decoder_net = PixelDecoder(wan.dim)
|
| 146 |
decoder_state = {k.removeprefix("pixel_head."): v for k, v in decoder_state.items()}
|
| 147 |
decoder_net.load_state_dict(decoder_state, strict=True)
|
| 148 |
-
text_encoder
|
|
|
|
| 149 |
return cls(config, dit, refiner_net.to(device).eval().requires_grad_(False),
|
| 150 |
decoder_net.to(device, dtype=config.decoder_dtype).eval().requires_grad_(False),
|
| 151 |
text_encoder)
|
|
|
|
| 126 |
self._refine_embedding = None
|
| 127 |
|
| 128 |
@classmethod
|
| 129 |
+
def from_pretrained(cls, config, wan_dir, dit, refiner, decoder, *, device="cuda", text_encoder=None):
|
| 130 |
"""Build from checkpoint paths (or already-loaded state dicts)."""
|
| 131 |
def state(value, key=None):
|
| 132 |
return value if isinstance(value, dict) else load_state_dict(value, key)
|
|
|
|
| 145 |
decoder_net = PixelDecoder(wan.dim)
|
| 146 |
decoder_state = {k.removeprefix("pixel_head."): v for k, v in decoder_state.items()}
|
| 147 |
decoder_net.load_state_dict(decoder_state, strict=True)
|
| 148 |
+
if text_encoder is None:
|
| 149 |
+
text_encoder = TextEncoder(Path(wan_dir)).to(device, dtype=torch.bfloat16)
|
| 150 |
return cls(config, dit, refiner_net.to(device).eval().requires_grad_(False),
|
| 151 |
decoder_net.to(device, dtype=config.decoder_dtype).eval().requires_grad_(False),
|
| 152 |
text_encoder)
|
fp8_blocks.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Eager FP8 blocks from linoyts/fastframes-l-live, revision e9f042c.
|
| 2 |
+
|
| 3 |
+
The official ``CausalWanAttentionBlock.forward_frame`` (fast path) is split at the KV-cache write:
|
| 4 |
+
|
| 5 |
+
* ``PreAttn`` : modulation, norm1, fused QKV (FP8), q/k RMSNorm, RoPE -> q, k, v
|
| 6 |
+
* (eager) : write this frame's k, v into the cache slot
|
| 7 |
+
* ``PostAttn`` : self-attention over cache[:end], out-proj, text cross-attention, FFN -> x
|
| 8 |
+
|
| 9 |
+
so the only dynamic shape is the attention length ``end`` (1 to 21 frames of tokens).
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
|
| 15 |
+
from fastframes.wan.attention import attention
|
| 16 |
+
from fastframes.wan.causal_model import rope_real
|
| 17 |
+
|
| 18 |
+
E4M3_MAX = 448.0
|
| 19 |
+
_FP8_OK = [True]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _quant_rows(t):
|
| 23 |
+
"""[M, K] -> (float8_e4m3fn [M, K], fp32 scale [M, 1]) with one scale per row."""
|
| 24 |
+
scale = t.abs().amax(dim=1, keepdim=True).float().clamp(min=1e-12) / E4M3_MAX
|
| 25 |
+
return (t.float() / scale).to(torch.float8_e4m3fn), scale
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class FP8Linear(nn.Module):
|
| 29 |
+
"""y = x @ W.T + b with e4m3 weights (per-output-channel scale) and per-token activation scales."""
|
| 30 |
+
|
| 31 |
+
def __init__(self, weight, bias):
|
| 32 |
+
super().__init__()
|
| 33 |
+
w8, scale = _quant_rows(weight.detach())
|
| 34 |
+
self.register_buffer("w8", w8) # [N, K] row-major -> .t() is column-major
|
| 35 |
+
self.register_buffer("w_scale", scale.t().contiguous()) # [1, N]
|
| 36 |
+
self.register_buffer("bias", None if bias is None else bias.detach().to(torch.bfloat16))
|
| 37 |
+
|
| 38 |
+
def forward(self, x):
|
| 39 |
+
shape = x.shape
|
| 40 |
+
x2 = x.reshape(-1, shape[-1])
|
| 41 |
+
if _FP8_OK[0]:
|
| 42 |
+
x8, x_scale = _quant_rows(x2)
|
| 43 |
+
y = torch._scaled_mm(x8, self.w8.t(), scale_a=x_scale, scale_b=self.w_scale, bias=self.bias,
|
| 44 |
+
out_dtype=torch.bfloat16)
|
| 45 |
+
return y.reshape(*shape[:-1], -1)
|
| 46 |
+
w = self.w8.to(torch.bfloat16) * self.w_scale.t().to(torch.bfloat16)
|
| 47 |
+
return torch.nn.functional.linear(x2.to(torch.bfloat16), w, self.bias).reshape(*shape[:-1], -1)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class PreAttn(nn.Module):
|
| 51 |
+
def __init__(self, block, qkv):
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.block = block
|
| 54 |
+
self.qkv = qkv
|
| 55 |
+
|
| 56 |
+
def forward(self, x, e, rope):
|
| 57 |
+
blk, sa = self.block, self.block.self_attn
|
| 58 |
+
tokens = x.shape[1]
|
| 59 |
+
e = (blk.modulation.unsqueeze(1) + e).chunk(6, dim=2)
|
| 60 |
+
h = (blk.norm1(x).unflatten(1, (1, tokens)) * (1 + e[1]) + e[0]).flatten(1, 2)
|
| 61 |
+
q, k, v = self.qkv(h).chunk(3, dim=-1)
|
| 62 |
+
shape = (x.shape[0], tokens, sa.num_heads, sa.head_dim)
|
| 63 |
+
q = rope_real(sa.norm_q(q).view(shape), rope)
|
| 64 |
+
k = rope_real(sa.norm_k(k).view(shape), rope)
|
| 65 |
+
return q, k, v.view(shape)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class PostAttn(nn.Module):
|
| 69 |
+
def __init__(self, block):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.block = block
|
| 72 |
+
|
| 73 |
+
def forward(self, x, e, q, k_all, v_all, text_k, text_v):
|
| 74 |
+
blk, sa = self.block, self.block.self_attn
|
| 75 |
+
tokens = x.shape[1]
|
| 76 |
+
e = (blk.modulation.unsqueeze(1) + e).chunk(6, dim=2)
|
| 77 |
+
y = sa.o(attention(q, k_all, v_all).flatten(2))
|
| 78 |
+
x = x + (y.unflatten(1, (1, tokens)) * e[2]).flatten(1, 2)
|
| 79 |
+
x = x + blk.cross_attn(blk.norm3(x), None, cache={"k": text_k, "v": text_v})
|
| 80 |
+
y = blk.ffn((blk.norm2(x).unflatten(1, (1, tokens)) * (1 + e[4]) + e[3]).flatten(1, 2))
|
| 81 |
+
return x + (y.unflatten(1, (1, tokens)) * e[5]).flatten(1, 2)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def install(pipe, fp8=True):
|
| 85 |
+
"""Swap the per-frame linears to FP8 and route every block's forward_frame through Pre/PostAttn.
|
| 86 |
+
|
| 87 |
+
Registers ``pipe.dit.ff_pre`` / ``pipe.dit.ff_post`` (ModuleLists) so aokit can patch them by name.
|
| 88 |
+
"""
|
| 89 |
+
dit, fast = pipe.dit, pipe.fast
|
| 90 |
+
qkv = []
|
| 91 |
+
for (w, b), blk in zip(fast.qkv, dit.blocks):
|
| 92 |
+
sa, ca = blk.self_attn, blk.cross_attn
|
| 93 |
+
if fp8:
|
| 94 |
+
qkv.append(FP8Linear(w, b))
|
| 95 |
+
sa.o = FP8Linear(sa.o.weight, sa.o.bias)
|
| 96 |
+
ca.q = FP8Linear(ca.q.weight, ca.q.bias)
|
| 97 |
+
ca.o = FP8Linear(ca.o.weight, ca.o.bias)
|
| 98 |
+
blk.ffn[0] = FP8Linear(blk.ffn[0].weight, blk.ffn[0].bias)
|
| 99 |
+
blk.ffn[2] = FP8Linear(blk.ffn[2].weight, blk.ffn[2].bias)
|
| 100 |
+
else:
|
| 101 |
+
lin = nn.Linear(w.shape[1], w.shape[0], device=w.device, dtype=w.dtype)
|
| 102 |
+
lin.weight.data, lin.bias.data = w, b
|
| 103 |
+
qkv.append(lin)
|
| 104 |
+
sa.q = sa.k = sa.v = None # superseded by the fused QKV of the fast path (text K/V use cross_attn)
|
| 105 |
+
fast.qkv = None
|
| 106 |
+
dit.ff_pre = nn.ModuleList(PreAttn(blk, q) for blk, q in zip(dit.blocks, qkv))
|
| 107 |
+
dit.ff_post = nn.ModuleList(PostAttn(blk) for blk in dit.blocks)
|
| 108 |
+
|
| 109 |
+
def make(pre, post):
|
| 110 |
+
def forward_frame(x, e, grid_sizes, freqs, cross_kv, kv_cache, frame, fast=None, layer=0):
|
| 111 |
+
tokens = x.shape[1]
|
| 112 |
+
start, end = frame * tokens, (frame + 1) * tokens
|
| 113 |
+
q, k, v = pre(x, e, fast.rope[frame])
|
| 114 |
+
kv_cache["k"][:, start:end].copy_(k)
|
| 115 |
+
kv_cache["v"][:, start:end].copy_(v)
|
| 116 |
+
return post(x, e, q, kv_cache["k"][:, :end], kv_cache["v"][:, :end], cross_kv["k"], cross_kv["v"])
|
| 117 |
+
return forward_frame
|
| 118 |
+
|
| 119 |
+
for blk, pre, post in zip(dit.blocks, dit.ff_pre, dit.ff_post):
|
| 120 |
+
blk.forward_frame = make(pre, post) # instance attribute shadows the method; block.forward dispatches here
|
render.py
CHANGED
|
@@ -25,8 +25,12 @@ class CueCancelled(Exception):
|
|
| 25 |
pass
|
| 26 |
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
"""A fresh GPU allocation for each cue. The CPU owns the committed checkpoint."""
|
| 31 |
started = time.monotonic()
|
| 32 |
stage = Path(stage_name)
|
|
@@ -36,16 +40,17 @@ def generate(key, rev, previous, prompt, stage_name, seconds=4, seed=0, preview=
|
|
| 36 |
|
| 37 |
try:
|
| 38 |
check_active()
|
| 39 |
-
LOG.info("cue enter %s rev=%d previous=%d", key[:8], rev, previous)
|
| 40 |
yield "allocated"
|
| 41 |
with torch.inference_mode():
|
| 42 |
-
|
| 43 |
-
|
|
|
|
| 44 |
if previous:
|
| 45 |
yield "restoring"
|
| 46 |
rollout.restore(takes.completed(key, previous) / "state", check_active)
|
| 47 |
first = rollout.total
|
| 48 |
-
text =
|
| 49 |
yield "generating"
|
| 50 |
with (stage / "pixels.rgb").open("wb") as out:
|
| 51 |
# Four decoder frames per latent. The opening decoder trims three
|
|
|
|
| 25 |
pass
|
| 26 |
|
| 27 |
|
| 28 |
+
def gpu_duration(key, rev, previous, prompt, stage_name, seconds=4, seed=0, preview=False, model="S"):
|
| 29 |
+
return 120 if model == "L" else 60
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@spaces.GPU(duration=gpu_duration, size="xlarge")
|
| 33 |
+
def generate(key, rev, previous, prompt, stage_name, seconds=4, seed=0, preview=False, model="S"):
|
| 34 |
"""A fresh GPU allocation for each cue. The CPU owns the committed checkpoint."""
|
| 35 |
started = time.monotonic()
|
| 36 |
stage = Path(stage_name)
|
|
|
|
| 40 |
|
| 41 |
try:
|
| 42 |
check_active()
|
| 43 |
+
LOG.info("cue enter %s rev=%d previous=%d model=%s", key[:8], rev, previous, model)
|
| 44 |
yield "allocated"
|
| 45 |
with torch.inference_mode():
|
| 46 |
+
pipe = en.PIPELINES[model]
|
| 47 |
+
en.configure_backends(pipe.config)
|
| 48 |
+
rollout = en.LiveRollout(pipe, seed)
|
| 49 |
if previous:
|
| 50 |
yield "restoring"
|
| 51 |
rollout.restore(takes.completed(key, previous) / "state", check_active)
|
| 52 |
first = rollout.total
|
| 53 |
+
text = pipe.dit.text_cache(pipe.encode_prompt(prompt))
|
| 54 |
yield "generating"
|
| 55 |
with (stage / "pixels.rgb").open("wb") as out:
|
| 56 |
# Four decoder frames per latent. The opening decoder trims three
|
takes.py
CHANGED
|
@@ -22,7 +22,7 @@ def connection():
|
|
| 22 |
|
| 23 |
with connection() as db:
|
| 24 |
db.execute("""CREATE TABLE takes (
|
| 25 |
-
id TEXT PRIMARY KEY, owner TEXT NOT NULL, phase TEXT NOT NULL,
|
| 26 |
seq INTEGER DEFAULT 0, rev INTEGER DEFAULT 0, rendered INTEGER DEFAULT 0,
|
| 27 |
title TEXT DEFAULT '', prompt TEXT DEFAULT '', last TEXT DEFAULT '', focus TEXT DEFAULT '',
|
| 28 |
parent INTEGER DEFAULT 0, seed INTEGER NOT NULL, last_seconds INTEGER DEFAULT 0,
|
|
@@ -64,13 +64,15 @@ def forget(owner):
|
|
| 64 |
shutil.rmtree(path, ignore_errors=True)
|
| 65 |
|
| 66 |
|
| 67 |
-
def start(key, owner):
|
|
|
|
|
|
|
| 68 |
with connection() as db:
|
| 69 |
db.execute("BEGIN IMMEDIATE")
|
| 70 |
if db.execute("SELECT 1 FROM takes WHERE id=?", (key,)).fetchone():
|
| 71 |
raise ValueError("Duplicate take")
|
| 72 |
old = remove_owner(db, owner)
|
| 73 |
-
db.execute("INSERT INTO takes(id,owner,phase,seed) VALUES(?,?,'armed',?)",(key,owner,secrets.randbits(31)))
|
| 74 |
(ROOT / key).mkdir()
|
| 75 |
for path in old:
|
| 76 |
shutil.rmtree(path, ignore_errors=True)
|
|
|
|
| 22 |
|
| 23 |
with connection() as db:
|
| 24 |
db.execute("""CREATE TABLE takes (
|
| 25 |
+
id TEXT PRIMARY KEY, owner TEXT NOT NULL, phase TEXT NOT NULL, model TEXT NOT NULL,
|
| 26 |
seq INTEGER DEFAULT 0, rev INTEGER DEFAULT 0, rendered INTEGER DEFAULT 0,
|
| 27 |
title TEXT DEFAULT '', prompt TEXT DEFAULT '', last TEXT DEFAULT '', focus TEXT DEFAULT '',
|
| 28 |
parent INTEGER DEFAULT 0, seed INTEGER NOT NULL, last_seconds INTEGER DEFAULT 0,
|
|
|
|
| 64 |
shutil.rmtree(path, ignore_errors=True)
|
| 65 |
|
| 66 |
|
| 67 |
+
def start(key, owner, model="S"):
|
| 68 |
+
if model not in ("S", "L"):
|
| 69 |
+
raise ValueError("Invalid video model")
|
| 70 |
with connection() as db:
|
| 71 |
db.execute("BEGIN IMMEDIATE")
|
| 72 |
if db.execute("SELECT 1 FROM takes WHERE id=?", (key,)).fetchone():
|
| 73 |
raise ValueError("Duplicate take")
|
| 74 |
old = remove_owner(db, owner)
|
| 75 |
+
db.execute("INSERT INTO takes(id,owner,phase,seed,model) VALUES(?,?,'armed',?,?)",(key,owner,secrets.randbits(31),model))
|
| 76 |
(ROOT / key).mkdir()
|
| 77 |
for path in old:
|
| 78 |
shutil.rmtree(path, ignore_errors=True)
|