Spaces:
Running on Zero
Running on Zero
Images/audio/video tab order, expandable image slots, native attention for the VAEs
Browse files65 unmodified lines66676869707149 unmodified lines12112212312412512668 unmodified lines1951961971981992002012022032042052062072082092102112129 unmodified lines22222322422522622722822923023180 unmodified lines3123133143153163173183193203218 unmodified lines33033133233333433533645 unmodified lines3823833843853863873883891 unmodified line3913923933943953963976 unmodified lines4044054064074084094104114124134144154164177 unmodified lines42542642742842943043143243343443543643743843965 unmodified linesMIN_DURATION = 5# A reference video shorter than 2 s gives the model almost no motion to read, and 15 s is the checkpoint's ceiling.MIN_REFERENCE_VIDEO, MAX_REFERENCE_VIDEO = 2.0, 15.0def snap_frames(seconds: float) -> int:49 unmodified linesprint(f"[ref2va] loading {[c.name for c in blocks.expected_components]} from {MODEL_REPO} ...", flush=True)pipe = blocks.init_pipeline(MODEL_REPO, components_manager=manager, collection="h3")pipe.load_components(dtype=torch.bfloat16, token=token)pipe.transformer_ref.set_attention_backend(ATTENTION)# Still startup, still free: an AoTI package carries no weights and opens its compiled archive lazily inside68 unmodified linesreturn video, audiodef collect(video_path, first_image_path, second_image_path, audio_path) -> list[tuple[str, str]]:"""The `(kind, path)` references of a request, **in the order the model reads them**.That order is semantic rather than cosmetic: it numbers the labels of MiniMax-H3's prompt presentation and itadvances the shared audio/video rotary clock, so the same references in a different order are a differentrequest. Video first, then images, then a standalone audio clip — which is also the order the packed sequencelays them out in."""ordered = [("video", video_path)] if video_path else []ordered += [("image", path) for path in (first_image_path, second_image_path) if path]if audio_path:ordered.append(("audio", audio_path))return ordered9 unmodified linesreturn carrieddef duration_controls(video_path, first_image_path, second_image_path, audio_path, match: bool):"""Show the duration slider unless a single soundtrack can set it, which is when MiniMax-H3 lets it be left out."""try:carried = audio_bearing(collect(video_path, first_image_path, second_image_path, audio_path))except Exception:carried = []# Exactly one soundtrack, and one long enough to be a duration MiniMax-H3 generates. Anything else and the80 unmodified linesdef generate(prompt,video_path=None,first_image_path=None,second_image_path=None,audio_path=None,canvas=DEFAULT_CANVAS,match=True,duration=5,8 unmodified linesfrom diffusers.utils import encode_videoreferences = collect(video_path, first_image_path, second_image_path, audio_path)check(prompt, references)# `0` is "leave it to the references" over the wire, which MiniMax-H3 accepts when exactly one of them carries a45 unmodified lines</div>**MiniMax-H3** is a 33B parameter state of the art video generation model that produces video and afully synchronized soundtrack (ambience, foley, speech). Bring your own subject, camera move or voice as areference — they are read **in tab order**, video then images then audio."""CSS = """1 unmodified line.dark .gradio-container { color: var(--body-text-color); }"""with gr.Blocks(title="MiniMax-H3 references") as demo:gr.Markdown(INTRO)with gr.Row():6 unmodified lines# One tab per modality, in the order the model reads them. A reference left in a tab that is not the# open one is still part of the request — the tabs lay the slots out, they do not choose between them.with gr.Tabs():with gr.Tab("Video"):video = gr.Video(label="Motion & camera, 2–15 s. Its soundtrack comes along.")with gr.Tab("Images"):with gr.Row():first_image = gr.Image(label="Subject, style or scene", type="filepath")second_image = gr.Image(label="Subject, style or scene", type="filepath")with gr.Tab("Audio"):audio = gr.Audio(label="A voice or a piece of music", type="filepath")run = gr.Button("Generate", variant="primary")with gr.Accordion("Advanced options", open=False):canvas = gr.Dropdown(label="Canvas", choices=list(CANVASES), value=DEFAULT_CANVAS)7 unmodified lineswith gr.Column():result = gr.Video(label="Video + soundtrack")slots = [video, first_image, second_image, audio]for control in [*slots, match]:control.change(duration_controls, [*slots, match], [match, duration], show_progress="hidden", api_name=False)run.click(generate,[prompt, *slots, canvas, match, duration, steps, seed],result,api_name="generate",)65 unmodified lines66676869707172737449 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514668 unmodified lines2152162172182192202212222232242252262272282292302312322339 unmodified lines24324424524624724824925025125225325425580 unmodified lines3363373383393403413423433443453463473483493503513528 unmodified lines36136236336436536636736845 unmodified lines4144154164174184194204211 unmodified line4234244254264274284296 unmodified lines4364374384394404414424434444454464474484494504514524534544554564574584597 unmodified lines46746846947047147247347447547647747847948048148248348448548648748848949049149265 unmodified linesMIN_DURATION = 5# A reference video shorter than 2 s gives the model almost no motion to read, and 15 s is the checkpoint's ceiling.MIN_REFERENCE_VIDEO, MAX_REFERENCE_VIDEO = 2.0, 15.0# `MINIMAX_H3_MAX_REFERENCE_IMAGES`, hardcoded so the UI renders before `diffusers` is importable. The slots are all# built up front and revealed one at a time, because a demo asking for two subjects should not open with nine boxes.MAX_IMAGE_SLOTS, OPEN_IMAGE_SLOTS = 9, 2def snap_frames(seconds: float) -> int:49 unmodified linesprint(f"[ref2va] loading {[c.name for c in blocks.expected_components]} from {MODEL_REPO} ...", flush=True)pipe = blocks.init_pipeline(MODEL_REPO, components_manager=manager, collection="h3")pipe.load_components(dtype=torch.bfloat16, token=token)# Pin the two autoencoders to torch SDPA *before* the transformer takes cuDNN, and in that order.## `set_attention_backend` does two things: it stamps the backend onto every attention processor of the model# it is called on, and it sets the registry's **global** active backend, which every processor that was not# stamped then falls through to. Both VAEs carry `AttentionModuleMixin` attention with `_attention_backend =# None`, so stamping only the transformer leaves them inheriting cuDNN — and they are float32, for which# cuDNN has no kernel:## RuntimeError: No available kernel. Aborting execution. # audio_vae pre_block, is_causal=True## It is `ref2va` that exposes this. The keyframe half only ever *decodes* audio, and the audio VAE's# attention is on its encoder side, so nothing reached it until a reference brought a soundtrack along.# Stamping the VAEs first leaves both explicitly on `native`; the transformer then stamps itself and takes# the global with it, which no longer matters to anyone.pipe.vae.set_attention_backend("native")pipe.audio_vae.set_attention_backend("native")pipe.transformer_ref.set_attention_backend(ATTENTION)# Still startup, still free: an AoTI package carries no weights and opens its compiled archive lazily inside68 unmodified linesreturn video, audiodef collect(image_paths, audio_path, video_path) -> list[tuple[str, str]]:"""The `(kind, path)` references of a request, **in the order the model reads them**.That order is semantic rather than cosmetic: it numbers the labels of MiniMax-H3's prompt presentation and itadvances the shared audio/video rotary clock, so the same references in a different order are a differentrequest. Images first, then a standalone audio clip, then the video — the order the tabs are laid out in, sowhat the UI shows is what the model is handed."""ordered = [("image", path) for path in image_paths if path]if audio_path:ordered.append(("audio", audio_path))if video_path:ordered.append(("video", video_path))return ordered9 unmodified linesreturn carrieddef duration_controls(audio_path, video_path, match: bool):"""Show the duration slider unless a single soundtrack can set it, which is when MiniMax-H3 lets it be left out.Only the audio and video slots matter here: an image reference never carries a waveform."""try:carried = audio_bearing(collect([], audio_path, video_path))except Exception:carried = []# Exactly one soundtrack, and one long enough to be a duration MiniMax-H3 generates. Anything else and the80 unmodified linesdef generate(prompt,image_1=None,image_2=None,image_3=None,image_4=None,image_5=None,image_6=None,image_7=None,image_8=None,image_9=None,audio_path=None,video_path=None,canvas=DEFAULT_CANVAS,match=True,duration=5,8 unmodified linesfrom diffusers.utils import encode_videoimages = [image_1, image_2, image_3, image_4, image_5, image_6, image_7, image_8, image_9]references = collect(images, audio_path, video_path)check(prompt, references)# `0` is "leave it to the references" over the wire, which MiniMax-H3 accepts when exactly one of them carries a45 unmodified lines</div>**MiniMax-H3** is a 33B parameter state of the art video generation model that produces video and afully synchronized soundtrack (ambience, foley, speech). Bring your own subject, voice or camera move as areference — they are read **in tab order**, images then audio then video."""CSS = """1 unmodified line.dark .gradio-container { color: var(--body-text-color); }"""with gr.Blocks(title="MiniMax-H3 Reference") as demo:gr.Markdown(INTRO)with gr.Row():6 unmodified lines# One tab per modality, in the order the model reads them. A reference left in a tab that is not the# open one is still part of the request — the tabs lay the slots out, they do not choose between them.with gr.Tabs():with gr.Tab("Images"):# One `gr.Row`, so gradio splits the width evenly and wraps once the slots hit `min_width`# rather than leaving a hole where a hidden slot used to be.with gr.Row():images = [gr.Image(label="Subject, style or scene",type="filepath",min_width=180,visible=index < OPEN_IMAGE_SLOTS,)for index in range(MAX_IMAGE_SLOTS)]add_image = gr.Button("+ Add another image", size="sm", variant="secondary")with gr.Tab("Audio"):audio = gr.Audio(label="A voice or a piece of music", type="filepath")with gr.Tab("Video"):video = gr.Video(label="Motion & camera, 2–15 s. Its soundtrack comes along.")run = gr.Button("Generate", variant="primary")with gr.Accordion("Advanced options", open=False):canvas = gr.Dropdown(label="Canvas", choices=list(CANVASES), value=DEFAULT_CANVAS)7 unmodified lineswith gr.Column():result = gr.Video(label="Video + soundtrack")open_slots = gr.State(OPEN_IMAGE_SLOTS)def reveal_image_slot(open_count):open_count = min(open_count + 1, MAX_IMAGE_SLOTS)return [open_count,*[gr.update(visible=index < open_count) for index in range(MAX_IMAGE_SLOTS)],gr.update(visible=open_count < MAX_IMAGE_SLOTS),]add_image.click(reveal_image_slot, open_slots, [open_slots, *images, add_image], api_name=False)for control in (audio, video, match):control.change(duration_controls, [audio, video, match], [match, duration], show_progress="hidden", api_name=False)run.click(generate,[prompt, *images, audio, video, canvas, match, duration, steps, seed],result,api_name="generate",)
app.py+76-23