Spaces:
Running on Zero
Running on Zero
Upload folder using huggingface_hub
Browse files- README.md +53 -7
- app.py +533 -0
- dmad_h3/__init__.py +25 -0
- dmad_h3/lora.py +76 -0
- dmad_h3/model.py +64 -0
- dmad_h3/packing.py +143 -0
- dmad_h3/sampling.py +147 -0
- dmad_h3/text_encoder.py +60 -0
- requirements.txt +13 -0
README.md
CHANGED
|
@@ -1,13 +1,59 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.29.1
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: DMAD — 4-step MiniMax-H3 student
|
| 3 |
+
emoji: 🎬
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: green
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.29.1
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
python_version: "3.12"
|
| 10 |
+
startup_duration_timeout: 1h
|
| 11 |
+
suggested_hardware: zero-a10g
|
| 12 |
+
short_description: 4-step text-to-audio-video generation, distilled from H3
|
| 13 |
---
|
| 14 |
|
| 15 |
+
# DMAD — Distribution Matching as Adversarial Distillation
|
| 16 |
+
|
| 17 |
+
**DMAD** ([Yu et al., 2610.02188](https://arxiv.org/abs/2610.02188) · [project](https://yzmblog.github.io/projects/DMAD/) ·
|
| 18 |
+
[code](https://github.com/Yzmblog/DMAD) · [weights](https://huggingface.co/ZhengmingYu/DMAD)) distills a multi-step
|
| 19 |
+
teacher into few-step students by matching the *distribution* of the student's samples to the teacher's — no data, no
|
| 20 |
+
extra inference cost. This Space serves the released **4-step MiniMax-H3 student**: a rank-128 LoRA over the 33B
|
| 21 |
+
omni-modal H3 transformer that turns the 50-step teacher into a **4-step** generator of 1344x768 video with a
|
| 22 |
+
synchronized stereo soundtrack.
|
| 23 |
+
|
| 24 |
+
Everything here is inference only — the demo runs the distilled student with the paper's own re-noise sampler, not the
|
| 25 |
+
training procedure.
|
| 26 |
+
|
| 27 |
+
## The sampler
|
| 28 |
+
|
| 29 |
+
The paper's results (and this demo) use the **re-noise multistep rule** the students were trained with: denoise
|
| 30 |
+
`x0 = xt + σ·v`, then re-noise to the next sigma with *fresh* noise, over a shifted linear sigma grid — 4 model
|
| 31 |
+
evaluations, video shift 12.0, audio shift 2.0 (the `--video-shift/--audio-shift` defaults of the reference
|
| 32 |
+
`inference.py`). The bundled `dmad_h3` package is the authors' own code (Apache-2.0, verbatim from the DMAD repo):
|
| 33 |
+
packed-sequence geometry, VAE decode, and mp4 mux.
|
| 34 |
+
|
| 35 |
+
## Why the conditioner is a separate Space
|
| 36 |
+
|
| 37 |
+
MiniMax-H3 is 195.9 GiB in bfloat16 and a ZeroGPU Space is evicted at 150 GB of storage, so one Space cannot hold it
|
| 38 |
+
unquantized. The 62.14 GiB Qwen3-VL conditioner runs in
|
| 39 |
+
[`multimodalart/qwen3vl-conditioner`](https://huggingface.co/spaces/multimodalart/qwen3vl-conditioner); this Space
|
| 40 |
+
calls its `/encode` over the gradio API per request and holds the transformer + both VAEs (77.3 GB download). The wire
|
| 41 |
+
format — `prompt_embeds` (layer-50 Qwen3-VL hidden states, prompt verbatim) + `text_token_tags` — is exactly what
|
| 42 |
+
`dmad_h3.encode_prompt` produces, i.e. what the student was trained on. Both Spaces pin the same 1344x768 canvas.
|
| 43 |
+
|
| 44 |
+
Weights are placed onto the card on the **first GPU call** (not at startup): `spaces`'s startup pack would need ~155 GB
|
| 45 |
+
of disk at once and is evicted by the 150 GB quota — the same trick the unquantized H3 Spaces use.
|
| 46 |
+
|
| 47 |
+
## Settings
|
| 48 |
+
|
| 49 |
+
Fixed by the checkpoint: 24 fps, ~5.2 s (124 frames), 1344x768, stereo 32 kHz audio, no CFG / negative prompt
|
| 50 |
+
(the student is guidance-distilled; every step is one forward pass). Only the **prompt** and **seed** vary. Seed 42 +
|
| 51 |
+
the `lora_critic` checkpoint reproduces the repo's `dmad_sweater` showcase video.
|
| 52 |
+
|
| 53 |
+
## Credits
|
| 54 |
+
|
| 55 |
+
- DMAD student weights: [`ZhengmingYu/DMAD`](https://huggingface.co/ZhengmingYu/DMAD) (Apache-2.0).
|
| 56 |
+
- Teacher checkpoint: [`MiniMaxAI/MiniMax-H3`](https://huggingface.co/MiniMaxAI/MiniMax-H3).
|
| 57 |
+
- `dmad_h3` inference code: [`Yzmblog/DMAD`](https://github.com/Yzmblog/DMAD) (Apache-2.0), bundled verbatim.
|
| 58 |
+
- Example prompts: the DMAD authors' own showcase prompts (project page / `prompts/`).
|
| 59 |
+
- Qwen3-VL conditioning: [`multimodalart/qwen3vl-conditioner`](https://huggingface.co/spaces/multimodalart/qwen3vl-conditioner).
|
app.py
ADDED
|
@@ -0,0 +1,533 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DMAD 4-step student of MiniMax-H3 — text to video + native stereo audio in 4 denoising steps.
|
| 2 |
+
|
| 3 |
+
DMAD ([Distribution Matching as Adversarial Distillation](https://arxiv.org/abs/2610.02188), Yu et al.) distills a
|
| 4 |
+
50-step teacher into few-step students by matching the *distribution* of the student's generated samples to the
|
| 5 |
+
teacher's — a critic scores real / teacher / student samples and the student gradient is the difference of the two
|
| 6 |
+
log-likelihood ratios — with **no data** and no NFE overhead at inference beyond the step count itself. This Space
|
| 7 |
+
serves the released **4-step MiniMax-H3 student** (33B omni-modal text-to-audio-video): a rank-128 LoRA over the H3
|
| 8 |
+
transformer that turns the 50-step teacher into a 4-step generator of 1344x768 video with a synchronized stereo
|
| 9 |
+
soundtrack, sampled with the re-noise step rule the students were trained with.
|
| 10 |
+
|
| 11 |
+
Inference follows the reference implementation (`inference.py` / `dmad_h3` of the
|
| 12 |
+
[DMAD repo](https://github.com/Yzmblog/DMAD)) 1:1 — same sigma grids (video shift 12, audio shift 2, 4 model
|
| 13 |
+
evaluations), same re-noise multistep rule, same packed-sequence geometry, same VAE decode and mp4 mux — with one
|
| 14 |
+
deviation forced by the host: MiniMax-H3 is 195.9 GiB bf16 and a ZeroGPU Space is evicted at 150 GB of storage, so
|
| 15 |
+
the 62.14 GiB Qwen3-VL text encoder runs in a separate Space,
|
| 16 |
+
[`multimodalart/qwen3vl-conditioner`](https://huggingface.co/spaces/multimodalart/qwen3vl-conditioner), and this one
|
| 17 |
+
calls it over the gradio API for every request. The wire format it returns — `prompt_embeds` (layer-50 Qwen3-VL
|
| 18 |
+
hidden states, the prompt verbatim) + `text_token_tags` — is exactly what `dmad_h3.encode_prompt` produces, and what
|
| 19 |
+
the student was trained on.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import os
|
| 25 |
+
import tempfile
|
| 26 |
+
import time
|
| 27 |
+
import traceback
|
| 28 |
+
from functools import cache
|
| 29 |
+
|
| 30 |
+
import spaces # must precede any torch import
|
| 31 |
+
import gradio as gr
|
| 32 |
+
|
| 33 |
+
MODEL_REPO = os.environ.get("DMAD_MODEL_REPO", "MiniMaxAI/MiniMax-H3")
|
| 34 |
+
LORA_REPO = os.environ.get("DMAD_LORA_REPO", "ZhengmingYu/DMAD")
|
| 35 |
+
# The checkpoint of the paper: EMA of the student at iteration 800 of the main run. (`full_critic`, iteration 1600
|
| 36 |
+
# live weights, scores higher on AVGen-Bench; both are rank-128 LoRAs over the same 312 modules.)
|
| 37 |
+
LORA_FILE = os.environ.get(
|
| 38 |
+
"DMAD_LORA_FILE", "minimax_h3/dmad_minimax_h3_4step_lora_critic.safetensors"
|
| 39 |
+
)
|
| 40 |
+
CONDITIONER_SPACE = os.environ.get("DMAD_CONDITIONER", "multimodalart/qwen3vl-conditioner")
|
| 41 |
+
ATTENTION = os.environ.get("DMAD_ATTENTION", "_native_cudnn").lower()
|
| 42 |
+
GPU_SIZE = os.environ.get("DMAD_GPU_SIZE", "xlarge")
|
| 43 |
+
|
| 44 |
+
# The paper's sampler: a shifted linear grid from 1 to 0 with 5 points = 4 model evaluations, video and audio on
|
| 45 |
+
# their own shift (`sigma_grid` of `dmad_h3.sampling`; the repo's defaults `--video-shift 12.0 --audio-shift 2.0`).
|
| 46 |
+
NUM_STEPS = 4
|
| 47 |
+
VIDEO_SHIFT = 12.0
|
| 48 |
+
AUDIO_SHIFT = 2.0
|
| 49 |
+
|
| 50 |
+
# Fixed by the checkpoint: 24 fps, num_frames = 17n+5, 1344x768 canvas, 32 kHz stereo audio, no CFG.
|
| 51 |
+
FPS = 24
|
| 52 |
+
AUDIO_SAMPLE_RATE = 32000
|
| 53 |
+
NUM_FRAMES = 124 # 17*7+5, ~5.2 s
|
| 54 |
+
HEIGHT, WIDTH = 768, 1344 # the resolution the students were trained at
|
| 55 |
+
SEED = 42 # seed 42 + lora_critic reproduces the repo's dmad_sweater showcase video
|
| 56 |
+
# The canvas the conditioner and this Space pin for every request: the students' 1344x768 training resolution.
|
| 57 |
+
DEFAULT_CANVAS = "1344x768 · 16:9 full"
|
| 58 |
+
|
| 59 |
+
OUTPUT_DIR = os.path.join(tempfile.gettempdir(), "dmad-out")
|
| 60 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 61 |
+
|
| 62 |
+
PIPE = None
|
| 63 |
+
LOAD_ERROR: str | None = None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# ── Model loading ───────────────────────────────────────────────────────────
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def shift_sigma(sigma, shift):
|
| 70 |
+
"""`dmad_h3.sampling.shift_sigma` — the exponential sigma shift `s*σ / (1 + (s-1)*σ)`."""
|
| 71 |
+
return shift * sigma / (1.0 + (shift - 1.0) * sigma)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def sigma_grid(steps, shift):
|
| 75 |
+
"""`dmad_h3.sampling.sigma_grid` — shifted linear grid, `steps` evaluations = `steps + 1` points."""
|
| 76 |
+
import torch
|
| 77 |
+
|
| 78 |
+
return shift_sigma(torch.linspace(1.0, 0.0, steps + 1, dtype=torch.float32), shift)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def load_models() -> str | None:
|
| 82 |
+
"""Load transformer + both VAEs at startup (the pack of 77.3 GB fits the disk quota; placement is lazy)."""
|
| 83 |
+
global PIPE, LOAD_ERROR
|
| 84 |
+
|
| 85 |
+
if PIPE is not None or LOAD_ERROR is not None:
|
| 86 |
+
return LOAD_ERROR
|
| 87 |
+
|
| 88 |
+
started = time.time()
|
| 89 |
+
try:
|
| 90 |
+
import torch
|
| 91 |
+
from diffusers import AutoencoderKLMiniMaxH3, AutoencoderKLMiniMaxH3Audio, MiniMaxH3Transformer3DModel
|
| 92 |
+
from huggingface_hub import hf_hub_download
|
| 93 |
+
|
| 94 |
+
print(f"[dmad] loading transformer + VAEs from {MODEL_REPO} ...", flush=True)
|
| 95 |
+
transformer = MiniMaxH3Transformer3DModel.from_pretrained(
|
| 96 |
+
MODEL_REPO,
|
| 97 |
+
subfolder="transformer",
|
| 98 |
+
torch_dtype=torch.bfloat16,
|
| 99 |
+
low_cpu_mem_usage=True,
|
| 100 |
+
)
|
| 101 |
+
transformer.requires_grad_(False).eval()
|
| 102 |
+
transformer.set_attention_backend(ATTENTION)
|
| 103 |
+
vae = AutoencoderKLMiniMaxH3.from_pretrained(MODEL_REPO, subfolder="vae").eval()
|
| 104 |
+
audio_vae = AutoencoderKLMiniMaxH3Audio.from_pretrained(MODEL_REPO, subfolder="audio_vae").eval()
|
| 105 |
+
|
| 106 |
+
lora_status = fold_lora(transformer)
|
| 107 |
+
print(f"[dmad] {lora_status}", flush=True)
|
| 108 |
+
|
| 109 |
+
# The generator half's components are ~77.3 GB on disk. `spaces`'s startup pack writes a second copy of every
|
| 110 |
+
# startup-resident CUDA tensor before deleting the originals, which needs ~155 GB at once and is evicted by
|
| 111 |
+
# the 150 GB storage quota — so nothing is moved onto the card here. Placement happens on the first GPU call.
|
| 112 |
+
PIPE = {
|
| 113 |
+
"transformer": transformer,
|
| 114 |
+
"vae": vae,
|
| 115 |
+
"audio_vae": audio_vae,
|
| 116 |
+
}
|
| 117 |
+
print(f"[dmad] ready in {time.time() - started:.0f}s", flush=True)
|
| 118 |
+
except Exception as error: # noqa: BLE001
|
| 119 |
+
traceback.print_exc()
|
| 120 |
+
LOAD_ERROR = f"**Loading failed** after {time.time() - started:.0f}s: `{type(error).__name__}: {error}`"
|
| 121 |
+
return LOAD_ERROR
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# ── LoRA folding ─────────────────────────────────────────────────────────────
|
| 125 |
+
#
|
| 126 |
+
# The released DMAD files use the diffusers LoRA layout of the *transformer's own module names* —
|
| 127 |
+
# `transformer_blocks.3.attn.to_q.lora.down.weight` / `.up.weight` for attention projections and
|
| 128 |
+
# `...ff.net.0.proj.lora_A.weight` / `...lora_B.weight` for the feed-forward layers — so no FlashGen-style
|
| 129 |
+
# remap is needed. The safetensors metadata carries the fusion rule:
|
| 130 |
+
# W_base += lora_scale * (lora_B @ lora_A), lora_scale = alpha / rank = 128 / 128 = 1.0
|
| 131 |
+
# Folding at startup (rather than a runtime PEFT adapter) costs nothing per request and keeps the forward
|
| 132 |
+
# path free of adapter code. Accumulation is fp32 so a bf16 base does not swallow the update.
|
| 133 |
+
|
| 134 |
+
_SUFFIXES = {
|
| 135 |
+
".lora.down.weight": ("A", ".weight"),
|
| 136 |
+
".lora.up.weight": ("B", ".weight"),
|
| 137 |
+
".lora_A.weight": ("A", ".weight"),
|
| 138 |
+
".lora_B.weight": ("B", ".weight"),
|
| 139 |
+
".lora_A.default.weight": ("A", ".weight"),
|
| 140 |
+
".lora_B.default.weight": ("B", ".weight"),
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def fold_lora(transformer) -> str:
|
| 145 |
+
"""Download the DMAD student LoRA and fold ``scale * (B @ A)`` into the base weights."""
|
| 146 |
+
import torch
|
| 147 |
+
from huggingface_hub import hf_hub_download
|
| 148 |
+
from safetensors import safe_open
|
| 149 |
+
|
| 150 |
+
path = hf_hub_download(LORA_REPO, LORA_FILE)
|
| 151 |
+
pairs: dict[str, dict[str, torch.Tensor]] = {}
|
| 152 |
+
with safe_open(path, framework="pt") as handle:
|
| 153 |
+
meta = dict(handle.metadata() or {})
|
| 154 |
+
for key in handle.keys():
|
| 155 |
+
for suffix, (part, _) in _SUFFIXES.items():
|
| 156 |
+
if key.endswith(suffix):
|
| 157 |
+
module = key[: -len(suffix)]
|
| 158 |
+
if module.startswith("transformer."):
|
| 159 |
+
module = module[len("transformer.") :]
|
| 160 |
+
pairs.setdefault(module, {})[part] = handle.get_tensor(key)
|
| 161 |
+
break
|
| 162 |
+
|
| 163 |
+
if not pairs:
|
| 164 |
+
raise ValueError(f"No LoRA pairs found in {LORA_FILE}")
|
| 165 |
+
incomplete = [m for m, p in pairs.items() if set(p) != {"A", "B"}]
|
| 166 |
+
if incomplete:
|
| 167 |
+
raise ValueError(f"LoRA modules missing A or B: {incomplete[:5]}")
|
| 168 |
+
|
| 169 |
+
ranks = {p["A"].shape[0] for p in pairs.values()}
|
| 170 |
+
if len(ranks) != 1:
|
| 171 |
+
raise ValueError(f"Mixed LoRA ranks: {sorted(ranks)}")
|
| 172 |
+
rank = ranks.pop()
|
| 173 |
+
alpha = float(meta.get("lora_alpha", rank))
|
| 174 |
+
scale = alpha / rank
|
| 175 |
+
|
| 176 |
+
params = dict(transformer.named_parameters())
|
| 177 |
+
folded, missed = 0, []
|
| 178 |
+
with torch.no_grad():
|
| 179 |
+
for module, parts in pairs.items():
|
| 180 |
+
key = f"{module}.weight"
|
| 181 |
+
param = params.get(key)
|
| 182 |
+
if param is None:
|
| 183 |
+
missed.append(key)
|
| 184 |
+
continue
|
| 185 |
+
delta = scale * (parts["B"].to(torch.float32) @ parts["A"].to(torch.float32))
|
| 186 |
+
if delta.shape != param.shape:
|
| 187 |
+
raise ValueError(
|
| 188 |
+
f"LoRA delta for `{key}` has shape {tuple(delta.shape)}, base weight is {tuple(param.shape)}"
|
| 189 |
+
)
|
| 190 |
+
param.data = (param.data.float() + delta).to(param.dtype)
|
| 191 |
+
folded += 1
|
| 192 |
+
|
| 193 |
+
if missed:
|
| 194 |
+
raise ValueError(
|
| 195 |
+
f"{len(missed)} LoRA targets matched no transformer weight, e.g. {missed[:5]}. "
|
| 196 |
+
"The LoRA and the diffusers transformer disagree on module naming."
|
| 197 |
+
)
|
| 198 |
+
return (
|
| 199 |
+
f"DMAD LoRA folded · {folded}/{len(pairs)} modules · rank {rank}, alpha {alpha:g}, scale {scale:g} · {LORA_FILE}"
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# ── Remote conditioning ──────────────────────────────────────────────────────
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _caller_ip_token() -> str | None:
|
| 207 |
+
from gradio.context import LocalContext
|
| 208 |
+
|
| 209 |
+
request = LocalContext.request.get()
|
| 210 |
+
return request.headers.get("x-ip-token") if request is not None else None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@cache
|
| 214 |
+
def _conditioner_client() -> "Client":
|
| 215 |
+
from gradio_client import Client
|
| 216 |
+
|
| 217 |
+
return Client(CONDITIONER_SPACE)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _client_for(ip_token: str | None):
|
| 221 |
+
"""The anonymous client is cached; a caller-token one is per-request (it bills *their* ZeroGPU quota)."""
|
| 222 |
+
if not ip_token:
|
| 223 |
+
return _conditioner_client()
|
| 224 |
+
from gradio_client import Client
|
| 225 |
+
|
| 226 |
+
return Client(CONDITIONER_SPACE, headers={"x-ip-token": ip_token})
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def encode_remote(prompt: str, canvas: str, num_frames: int, ip_token: str | None):
|
| 230 |
+
"""Ask the conditioner Space for ``prompt_embeds`` + ``text_token_tags`` and the resolved geometry.
|
| 231 |
+
|
| 232 |
+
The conditioner reads Qwen3-VL at hidden layer 50 with the prompt verbatim — exactly ``dmad_h3``'s
|
| 233 |
+
``encode_prompt`` — and returns one safetensors file carrying both tensors with ``height`` / ``width`` /
|
| 234 |
+
``num_frames`` in its metadata header. Both spaces pin the same canvas so the geometry never diverges.
|
| 235 |
+
"""
|
| 236 |
+
from safetensors import safe_open
|
| 237 |
+
|
| 238 |
+
def call(client):
|
| 239 |
+
return client.predict(
|
| 240 |
+
prompt=prompt,
|
| 241 |
+
image_path=None,
|
| 242 |
+
last_image_path=None,
|
| 243 |
+
canvas=canvas,
|
| 244 |
+
num_frames=num_frames,
|
| 245 |
+
rewrite_prompt=False,
|
| 246 |
+
api_name="/encode",
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
try:
|
| 250 |
+
path, plan = call(_client_for(ip_token))
|
| 251 |
+
except Exception as first: # noqa: BLE001
|
| 252 |
+
print(f"[dmad] retrying with a fresh conditioner client after: {first}", flush=True)
|
| 253 |
+
_conditioner_client.cache_clear()
|
| 254 |
+
path, plan = call(_client_for(ip_token))
|
| 255 |
+
|
| 256 |
+
with safe_open(path, framework="pt") as handle:
|
| 257 |
+
metadata = handle.metadata()
|
| 258 |
+
prompt_embeds = handle.get_tensor("prompt_embeds")
|
| 259 |
+
text_token_tags = handle.get_tensor("text_token_tags")
|
| 260 |
+
return prompt_embeds, text_token_tags, metadata, plan
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
# ── The paper's sampler, verbatim from dmad_h3 ────────────────────────────────
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _build_layout(text_token_tags, shape, patch_size, device):
|
| 267 |
+
"""`dmad_h3.packing.build_packed_sequence` — padless ``[text | stereo audio | video]`` row layout."""
|
| 268 |
+
from dmad_h3.packing import build_packed_sequence
|
| 269 |
+
|
| 270 |
+
layout = build_packed_sequence(
|
| 271 |
+
text_token_tags,
|
| 272 |
+
shape["latent_frames"],
|
| 273 |
+
shape["latent_height"],
|
| 274 |
+
shape["latent_width"],
|
| 275 |
+
shape["audio_latents"],
|
| 276 |
+
patch_size,
|
| 277 |
+
)
|
| 278 |
+
return layout.to(device)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _draw_init_noise(shape, geometry, seed, device):
|
| 282 |
+
"""`dmad_h3.sampling.draw_init_noise` — video latent first, then audio rows, from one CPU generator."""
|
| 283 |
+
import torch
|
| 284 |
+
|
| 285 |
+
from diffusers.modular_pipelines.minimax_h3.before_denoise import patchify_video_latents
|
| 286 |
+
|
| 287 |
+
g = torch.Generator(device="cpu").manual_seed(int(seed))
|
| 288 |
+
noise_v = torch.randn(
|
| 289 |
+
(1, geometry["video_channels"], shape["latent_frames"], shape["latent_height"], shape["latent_width"]),
|
| 290 |
+
generator=g,
|
| 291 |
+
dtype=torch.float32,
|
| 292 |
+
)
|
| 293 |
+
noise_a = torch.randn((shape["audio_latents"] * 2, geometry["audio_channels"]), generator=g, dtype=torch.float32)
|
| 294 |
+
xt = (patchify_video_latents(noise_v.to(device), geometry["patch_size"])[None].float(), noise_a.to(device)[None].float())
|
| 295 |
+
return xt, g
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def vae_scale(vae) -> int:
|
| 299 |
+
"""The product of the video VAE's spatial downsample factors (the latent spatial scale)."""
|
| 300 |
+
import numpy as np
|
| 301 |
+
|
| 302 |
+
return int(np.prod(vae.config.spatial_downsample_factors))
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def geometry_named(shape, geometry):
|
| 306 |
+
"""Adapt the geometry dict to `decode_rows`' `H3Geometry` interface (attribute-style access)."""
|
| 307 |
+
from dmad_h3.model import H3Geometry
|
| 308 |
+
|
| 309 |
+
return H3Geometry(
|
| 310 |
+
patch_size=geometry["patch_size"],
|
| 311 |
+
video_latent_channels=geometry["video_channels"],
|
| 312 |
+
audio_latent_channels=geometry["audio_channels"],
|
| 313 |
+
vae_spatial_scale_factor=geometry["spatial_scale"],
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def get_duration(prompt_embeds, text_token_tags, height, width, num_frames, seed, *args, **kwargs):
|
| 318 |
+
"""Estimated GPU seconds for ``_generate``: placement allowance + 4 steps + decode + margin.
|
| 319 |
+
|
| 320 |
+
Placeholder until first measurement: the placement of 72 GiB costs ~10 s once, then 4 student
|
| 321 |
+
evaluations at ~10.5 s/step + both VAE decodes at 1344x768 x 124 frames.
|
| 322 |
+
"""
|
| 323 |
+
return int(os.environ.get("DMAD_GPU_DURATION", "240"))
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
@spaces.GPU(duration=get_duration, size=GPU_SIZE)
|
| 327 |
+
def _generate(prompt_embeds, text_token_tags, height, width, num_frames, seed):
|
| 328 |
+
"""Denoise + decode on GPU time: the 4-step re-noise rollout, then both VAE decodes."""
|
| 329 |
+
import torch
|
| 330 |
+
|
| 331 |
+
from dmad_h3.packing import build_row_timesteps, video_latent_num_frames
|
| 332 |
+
from dmad_h3.sampling import audio_latent_num_frames, decode_rows
|
| 333 |
+
|
| 334 |
+
# Placement: the first GPU call moves the 72 GiB onto the card once, then every call runs resident.
|
| 335 |
+
PIPE["transformer"].to("cuda")
|
| 336 |
+
PIPE["vae"].to("cuda")
|
| 337 |
+
PIPE["audio_vae"].to("cuda")
|
| 338 |
+
|
| 339 |
+
transformer = PIPE["transformer"]
|
| 340 |
+
patch_size = tuple(int(p) for p in transformer.config.patch_size)
|
| 341 |
+
geometry = {
|
| 342 |
+
"patch_size": patch_size,
|
| 343 |
+
"video_channels": int(transformer.config.in_channels),
|
| 344 |
+
"audio_channels": int(transformer.config.audio_in_channels),
|
| 345 |
+
"spatial_scale": vae_scale(PIPE["vae"]),
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
latent_frames = video_latent_num_frames(num_frames)
|
| 349 |
+
shape = {
|
| 350 |
+
"num_frames": int(num_frames),
|
| 351 |
+
"latent_frames": latent_frames,
|
| 352 |
+
"latent_height": height // geometry["spatial_scale"],
|
| 353 |
+
"latent_width": width // geometry["spatial_scale"],
|
| 354 |
+
"audio_latents": audio_latent_num_frames(num_frames),
|
| 355 |
+
}
|
| 356 |
+
video_sigmas = sigma_grid(NUM_STEPS, VIDEO_SHIFT)
|
| 357 |
+
audio_sigmas = sigma_grid(NUM_STEPS, AUDIO_SHIFT)
|
| 358 |
+
|
| 359 |
+
layout = _build_layout(text_token_tags, shape, patch_size, "cuda")
|
| 360 |
+
xt, g = _draw_init_noise(shape, geometry, seed, "cuda")
|
| 361 |
+
|
| 362 |
+
x0 = None
|
| 363 |
+
for step in range(NUM_STEPS):
|
| 364 |
+
v_s = video_sigmas[step].to("cuda")
|
| 365 |
+
a_s = audio_sigmas[step].to("cuda")
|
| 366 |
+
ts, ti = build_row_timesteps(layout, v_s, a_s)
|
| 367 |
+
vel = transformer(
|
| 368 |
+
hidden_states=xt[0],
|
| 369 |
+
audio_hidden_states=xt[1],
|
| 370 |
+
encoder_hidden_states=prompt_embeds.to("cuda"),
|
| 371 |
+
timestep=ts.to("cuda"),
|
| 372 |
+
timestep_indices=ti.to("cuda"),
|
| 373 |
+
token_tags=layout.token_tags,
|
| 374 |
+
position_ids=layout.position_ids,
|
| 375 |
+
video_indices=layout.video_indices,
|
| 376 |
+
audio_indices=layout.audio_indices,
|
| 377 |
+
text_indices=layout.text_indices,
|
| 378 |
+
return_dict=False,
|
| 379 |
+
)
|
| 380 |
+
x0 = (xt[0] + v_s * vel[0].float(), xt[1] + a_s * vel[1].float())
|
| 381 |
+
nv = video_sigmas[step + 1].to("cuda")
|
| 382 |
+
na = audio_sigmas[step + 1].to("cuda")
|
| 383 |
+
# The DMD-style multistep rule the students were trained with (the sampler of all results in the paper).
|
| 384 |
+
ev = torch.randn(x0[0].shape, generator=g, dtype=torch.float32).to("cuda")
|
| 385 |
+
ea = torch.randn(x0[1].shape, generator=g, dtype=torch.float32).to("cuda")
|
| 386 |
+
xt = ((1.0 - nv) * x0[0] + nv * ev, (1.0 - na) * x0[1] + na * ea)
|
| 387 |
+
|
| 388 |
+
# Latents are kept in bf16 before decoding, as in the pipeline that produced the paper's videos.
|
| 389 |
+
video_rows = x0[0].to(torch.bfloat16).float().cpu()
|
| 390 |
+
audio_rows = x0[1].to(torch.bfloat16).float().cpu()
|
| 391 |
+
frames, wav = decode_rows(PIPE["vae"], PIPE["audio_vae"], video_rows, audio_rows, shape, geometry_named(shape, geometry))
|
| 392 |
+
return frames, wav
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
# ── Inference entry point ────────────────────────────────────────────────────
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def generate(
|
| 399 |
+
prompt,
|
| 400 |
+
seed=SEED,
|
| 401 |
+
canvas=DEFAULT_CANVAS,
|
| 402 |
+
progress=gr.Progress(track_tqdm=True),
|
| 403 |
+
):
|
| 404 |
+
"""Generate an audio-video clip (1344x768, ~5.2 s, 24 fps, stereo 32 kHz) from a text prompt.
|
| 405 |
+
|
| 406 |
+
Runs the released 4-step DMAD student of MiniMax-H3 with the paper's re-noise sampler; seed 42 + the
|
| 407 |
+
`lora_critic` checkpoint reproduces the repo's flagship `dmad_sweater` showcase video for its prompt.
|
| 408 |
+
"""
|
| 409 |
+
if LOAD_ERROR:
|
| 410 |
+
raise gr.Error(LOAD_ERROR.replace("**", "").replace("`", ""))
|
| 411 |
+
if PIPE is None:
|
| 412 |
+
raise gr.Error("The model is still loading — watch the Space logs and retry shortly.")
|
| 413 |
+
if not prompt or not prompt.strip():
|
| 414 |
+
raise gr.Error("A prompt is required.")
|
| 415 |
+
|
| 416 |
+
progress(0.0, desc="Encoding the prompt (Qwen3-VL in the conditioner Space) ...")
|
| 417 |
+
conditioned = time.time()
|
| 418 |
+
prompt_embeds, text_token_tags, metadata, plan = encode_remote(
|
| 419 |
+
prompt,
|
| 420 |
+
canvas,
|
| 421 |
+
NUM_FRAMES,
|
| 422 |
+
ip_token=_caller_ip_token(),
|
| 423 |
+
)
|
| 424 |
+
condition_seconds = time.time() - conditioned
|
| 425 |
+
height = int(metadata["height"])
|
| 426 |
+
width = int(metadata["width"])
|
| 427 |
+
num_frames = int(metadata["num_frames"])
|
| 428 |
+
|
| 429 |
+
progress(0.05, desc=f"Denoising in {NUM_STEPS} steps ({width}x{height}, {num_frames} frames) ...")
|
| 430 |
+
started = time.time()
|
| 431 |
+
frames, wav = _generate(prompt_embeds, text_token_tags, height, width, num_frames, seed)
|
| 432 |
+
generate_seconds = time.time() - started
|
| 433 |
+
|
| 434 |
+
progress(0.95, desc="Decoding and muxing the mp4 ...")
|
| 435 |
+
from dmad_h3.sampling import write_mp4
|
| 436 |
+
|
| 437 |
+
path = os.path.join(OUTPUT_DIR, f"dmad-{int(time.time() * 1000)}.mp4")
|
| 438 |
+
write_mp4(frames, wav, path)
|
| 439 |
+
report = (
|
| 440 |
+
f"{width}x{height} · {num_frames} frames ({num_frames / FPS:.2f}s) · {NUM_STEPS} steps (re-noise rule, "
|
| 441 |
+
f"video shift {VIDEO_SHIFT:g}, audio shift {AUDIO_SHIFT:g}) · conditioner {condition_seconds:.0f}s · "
|
| 442 |
+
f"denoise + decode {generate_seconds:.0f}s · seed {int(seed)}"
|
| 443 |
+
)
|
| 444 |
+
print(f"[dmad] {report}", flush=True)
|
| 445 |
+
return path, report
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
INTRO = """# DMAD: Distribution Matching as Adversarial Distillation — 4-step MiniMax-H3
|
| 449 |
+
|
| 450 |
+
<div align="center">
|
| 451 |
+
<a href="https://arxiv.org/abs/2610.02188" target="_blank" rel="noopener"><strong>[ paper ]</strong></a>
|
| 452 |
+
<a href="https://yzmblog.github.io/projects/DMAD/" target="_blank" rel="noopener"><strong>[ project ]</strong></a>
|
| 453 |
+
<a href="https://github.com/Yzmblog/DMAD" target="_blank" rel="noopener"><strong>[ code ]</strong></a>
|
| 454 |
+
<a href="https://huggingface.co/ZhengmingYu/DMAD" target="_blank" rel="noopener"><strong>[ weights ]</strong></a>
|
| 455 |
+
</div>
|
| 456 |
+
|
| 457 |
+
**DMAD** distills a 50-step teacher into few-step students by matching the *distribution* of student samples to the
|
| 458 |
+
teacher's — no data, no extra inference cost. This Space serves the released **4-step MiniMax-H3 student** (33B
|
| 459 |
+
text-to-audio-video): one rank-128 LoRA turns the teacher into a **4-step** generator of 1344x768 video with a
|
| 460 |
+
synchronized stereo soundtrack, sampled with the paper's re-noise rule. A prompt describes the scene *and* its
|
| 461 |
+
soundscape — narration goes in quotes, music gets described, ambient sound too."""
|
| 462 |
+
|
| 463 |
+
EXAMPLE_PROMPTS = [
|
| 464 |
+
"A sweet anime girl in a 'DMAD' sweater makes a heart gesture with her hands. The main subject is a young anime girl with fair skin, large, sparkling blue eyes, and long, flowing pastel pink hair that frames her face. She is wearing a slightly oversized, cozy, cream-colored knitted sweater. Across the chest area of her sweater, the text \"DMAD\" is clearly and neatly printed in a clean, black sans-serif font. Her expression is cheerful and endearing. Initially, the girl stands facing the camera with a gentle smile, her hands positioned in front of her chest, slightly apart. Then, she smoothly brings her hands together, touching her thumbs to form the bottom point of a heart and curving her index and middle fingers to create the top arches. As the heart shape is completed, her smile widens, and she gives a playful wink with her right eye. She is situated in the center of a softly lit room. The background is blurred with a shallow depth of field, suggesting a clean, minimalist interior with a warm, gentle, and comfortable feel. Sunlight filters in from a window off-screen, casting soft highlights on her hair and shoulders, all rendered in a soft, painterly anime style. Medium close-up shot. The camera is at an eye-level angle with the main subject. The camera zooms in slowly, emphasizing her facial expression and hand gesture. The lighting is soft and diffused, creating a warm and inviting mood. The visual style is a high-quality Japanese cel-shading animation, characterized by clean lines, vibrant yet soft colors, and detailed character design. This is a beautiful anime-style animation. The overall video presents a high-quality Japanese animation style. A light, cheerful piano tune with sparkling glockenspiel notes plays at a brisk, bouncy tempo, warm and tender in tone.",
|
| 465 |
+
"A polar bear is playing the violin in the snow.",
|
| 466 |
+
"A giant \"DMAD\" neon sign lights up letter by letter, reflecting on a rain-soaked cyberpunk street.",
|
| 467 |
+
"An adorable happy otter confidently stands on a surfboard wearing a yellow lifejacket, riding along turquoise tropical waters near lush tropical islands, 3D digital render art style.",
|
| 468 |
+
"An origami dragon unfolds from paper in stop-motion style, then flies over folded mountains. The camera pans with paper dust fluttering midair. Every flap and fold is sharply geometric.",
|
| 469 |
+
"An astronaut slowly floats inside a derelict International Space Station, outside is the deep cosmos and a blue Earth, cool-toned lighting, slow motion, hard sci-fi movie style.",
|
| 470 |
+
"A racing car is racing on the surface of the moon against a space backdrop, with tilt-shift zoom effect.",
|
| 471 |
+
"A robot moves through ruins. The shot cuts to a close-up of its optical scanning lens on the head, then shifts to a scanned image of the city's outline from its perspective. Graffiti on the wall reads \"HUMANITY?\".",
|
| 472 |
+
]
|
| 473 |
+
|
| 474 |
+
CSS = """
|
| 475 |
+
.main.fillable { max-width: 1100px !important; }
|
| 476 |
+
.dark .gradio-container { color: var(--body-text-color); }
|
| 477 |
+
"""
|
| 478 |
+
|
| 479 |
+
with gr.Blocks(title="DMAD — 4-step MiniMax-H3 student", theme=gr.themes.Citrus(), css=CSS) as demo:
|
| 480 |
+
gr.Markdown(INTRO)
|
| 481 |
+
|
| 482 |
+
with gr.Row(equal_height=True):
|
| 483 |
+
with gr.Column():
|
| 484 |
+
prompt = gr.Textbox(
|
| 485 |
+
label="Prompt",
|
| 486 |
+
lines=5,
|
| 487 |
+
value=EXAMPLE_PROMPTS[1],
|
| 488 |
+
placeholder="Describe the scene, shot style, and soundscape ...",
|
| 489 |
+
)
|
| 490 |
+
run = gr.Button("Generate", variant="primary", size="lg")
|
| 491 |
+
|
| 492 |
+
with gr.Accordion("Advanced", open=False):
|
| 493 |
+
seed = gr.Number(label="Seed", value=SEED, precision=0)
|
| 494 |
+
canvas = gr.Dropdown(
|
| 495 |
+
label="Canvas",
|
| 496 |
+
choices=[DEFAULT_CANVAS],
|
| 497 |
+
value=DEFAULT_CANVAS,
|
| 498 |
+
info="The students were trained at 1344x768; other canvases are not evaluated for the 4-step sampler.",
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
with gr.Column():
|
| 502 |
+
result = gr.Video(label="Video + soundtrack", autoplay=True)
|
| 503 |
+
report = gr.Markdown()
|
| 504 |
+
|
| 505 |
+
OUTPUTS = [result, report]
|
| 506 |
+
|
| 507 |
+
gr.Examples(
|
| 508 |
+
examples=[[p] for p in EXAMPLE_PROMPTS],
|
| 509 |
+
inputs=[prompt],
|
| 510 |
+
fn=generate,
|
| 511 |
+
outputs=OUTPUTS,
|
| 512 |
+
cache_examples=True,
|
| 513 |
+
cache_mode="lazy",
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
run.click(
|
| 517 |
+
generate,
|
| 518 |
+
inputs=[prompt, seed, canvas],
|
| 519 |
+
outputs=OUTPUTS,
|
| 520 |
+
api_name="generate",
|
| 521 |
+
)
|
| 522 |
+
prompt.submit(
|
| 523 |
+
generate,
|
| 524 |
+
inputs=[prompt, seed, canvas],
|
| 525 |
+
outputs=OUTPUTS,
|
| 526 |
+
api_name="generate_submit",
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
load_models()
|
| 531 |
+
|
| 532 |
+
if __name__ == "__main__":
|
| 533 |
+
demo.launch(show_error=True, mcp_server=True, allowed_paths=[OUTPUT_DIR])
|
dmad_h3/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Few-step text-to-audio-video inference with DMAD students of MiniMax-H3."""
|
| 2 |
+
|
| 3 |
+
from .lora import attach_lora, read_lora_file
|
| 4 |
+
from .model import H3Geometry, load_transformer, load_vaes
|
| 5 |
+
from .packing import build_packed_sequence, build_row_timesteps
|
| 6 |
+
from .sampling import decode_rows, latent_shape_of, rollout, sigma_grid, write_mp4
|
| 7 |
+
from .text_encoder import encode_prompt, load_conditioner, read_prompts
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
"H3Geometry",
|
| 11 |
+
"attach_lora",
|
| 12 |
+
"build_packed_sequence",
|
| 13 |
+
"build_row_timesteps",
|
| 14 |
+
"decode_rows",
|
| 15 |
+
"encode_prompt",
|
| 16 |
+
"latent_shape_of",
|
| 17 |
+
"load_conditioner",
|
| 18 |
+
"load_transformer",
|
| 19 |
+
"load_vaes",
|
| 20 |
+
"read_lora_file",
|
| 21 |
+
"read_prompts",
|
| 22 |
+
"rollout",
|
| 23 |
+
"sigma_grid",
|
| 24 |
+
"write_mp4",
|
| 25 |
+
]
|
dmad_h3/lora.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DMAD student LoRAs: reading the safetensors file and attaching it to the transformer with PEFT.
|
| 2 |
+
|
| 3 |
+
The released files use the Diffusers LoRA layout, `<module>.lora.down.weight` (A, [rank, in]) and
|
| 4 |
+
`<module>.lora.up.weight` (B, [out, rank]), with `<module>` the transformer's own module name, e.g.
|
| 5 |
+
`transformer_blocks.3.attn.to_q`; the adapter adds `(alpha / rank) * B A x`, and the released LoRAs have `alpha == rank`.
|
| 6 |
+
PEFT-style keys (`lora_A` / `lora_B`, optional `transformer.` prefix) are accepted too.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
from safetensors import safe_open
|
| 12 |
+
|
| 13 |
+
_SUFFIXES = {
|
| 14 |
+
".lora.down.weight": "A",
|
| 15 |
+
".lora.up.weight": "B",
|
| 16 |
+
".lora_A.weight": "A",
|
| 17 |
+
".lora_B.weight": "B",
|
| 18 |
+
".lora_A.default.weight": "A",
|
| 19 |
+
".lora_B.default.weight": "B",
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def read_lora_file(path):
|
| 24 |
+
"""-> (pairs, metadata): pairs maps module name -> {"A": tensor, "B": tensor}."""
|
| 25 |
+
pairs, meta = {}, {}
|
| 26 |
+
with safe_open(str(path), "pt") as f:
|
| 27 |
+
meta = dict(f.metadata() or {})
|
| 28 |
+
for key in f.keys():
|
| 29 |
+
for suffix, part in _SUFFIXES.items():
|
| 30 |
+
if key.endswith(suffix):
|
| 31 |
+
module = key[: -len(suffix)]
|
| 32 |
+
module = module[len("transformer.") :] if module.startswith("transformer.") else module
|
| 33 |
+
pairs.setdefault(module, {})[part] = f.get_tensor(key)
|
| 34 |
+
break
|
| 35 |
+
else:
|
| 36 |
+
raise ValueError(f"Unexpected tensor in the LoRA file: {key}")
|
| 37 |
+
if not pairs:
|
| 38 |
+
raise ValueError(f"No LoRA pairs found in {path}")
|
| 39 |
+
incomplete = [m for m, p in pairs.items() if set(p) != {"A", "B"}]
|
| 40 |
+
if incomplete:
|
| 41 |
+
raise ValueError(f"LoRA modules missing A or B: {incomplete[:5]}")
|
| 42 |
+
return pairs, meta
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def lora_rank_alpha(pairs, meta, alpha=None):
|
| 46 |
+
ranks = {p["A"].shape[0] for p in pairs.values()}
|
| 47 |
+
if len(ranks) != 1:
|
| 48 |
+
raise ValueError(f"Mixed LoRA ranks: {sorted(ranks)}")
|
| 49 |
+
rank = ranks.pop()
|
| 50 |
+
if alpha is None:
|
| 51 |
+
alpha = float(meta["lora_alpha"]) if "lora_alpha" in meta else float(rank)
|
| 52 |
+
return rank, float(alpha)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def attach_lora(transformer, pairs, rank, alpha):
|
| 56 |
+
"""Inject a PEFT LoRA adapter for exactly the modules in `pairs` and load the weights (no fusion)."""
|
| 57 |
+
from peft import LoraConfig, inject_adapter_in_model
|
| 58 |
+
from peft.utils import set_peft_model_state_dict
|
| 59 |
+
|
| 60 |
+
config = LoraConfig(r=rank, lora_alpha=alpha, init_lora_weights="gaussian", target_modules=sorted(pairs))
|
| 61 |
+
try:
|
| 62 |
+
transformer = inject_adapter_in_model(config, transformer, adapter_name="default")
|
| 63 |
+
except TypeError:
|
| 64 |
+
transformer = inject_adapter_in_model(config, transformer)
|
| 65 |
+
state = {}
|
| 66 |
+
for module, p in pairs.items():
|
| 67 |
+
state[f"{module}.lora_A.weight"] = p["A"]
|
| 68 |
+
state[f"{module}.lora_B.weight"] = p["B"]
|
| 69 |
+
result = set_peft_model_state_dict(transformer, state)
|
| 70 |
+
if result and result.unexpected_keys:
|
| 71 |
+
raise RuntimeError(f"unexpected LoRA keys: {result.unexpected_keys[:5]}")
|
| 72 |
+
loaded = {n for n, _ in transformer.named_parameters() if re.search(r"\.lora_[AB]\.", n)}
|
| 73 |
+
if len(loaded) != 2 * len(pairs):
|
| 74 |
+
raise RuntimeError(f"expected {2 * len(pairs)} LoRA parameters after injection, found {len(loaded)}")
|
| 75 |
+
return transformer
|
| 76 |
+
|
dmad_h3/model.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Loading the MiniMax-H3 components (Diffusers classes) and the latent geometry read from their configs."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass(frozen=True)
|
| 12 |
+
class H3Geometry:
|
| 13 |
+
"""Latent layout constants of a MiniMax-H3 checkpoint, read from `transformer/config.json` and `vae/config.json`."""
|
| 14 |
+
|
| 15 |
+
patch_size: tuple[int, int, int]
|
| 16 |
+
video_latent_channels: int
|
| 17 |
+
audio_latent_channels: int
|
| 18 |
+
vae_spatial_scale_factor: int
|
| 19 |
+
|
| 20 |
+
@classmethod
|
| 21 |
+
def from_model_dir(cls, model_dir):
|
| 22 |
+
root = Path(model_dir).expanduser().resolve()
|
| 23 |
+
transformer_cfg = json.load(open(resolve_transformer_dir(root) / "config.json"))
|
| 24 |
+
vae_cfg = json.load(open(root / "vae" / "config.json"))
|
| 25 |
+
return cls(
|
| 26 |
+
patch_size=tuple(int(p) for p in transformer_cfg["patch_size"]),
|
| 27 |
+
video_latent_channels=int(transformer_cfg["in_channels"]),
|
| 28 |
+
audio_latent_channels=int(transformer_cfg["audio_in_channels"]),
|
| 29 |
+
vae_spatial_scale_factor=int(math.prod(vae_cfg["spatial_downsample_factors"])),
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def resolve_transformer_dir(path):
|
| 34 |
+
"""Accept the model root (with `transformer/`) or the transformer directory itself."""
|
| 35 |
+
path = Path(path).expanduser().resolve()
|
| 36 |
+
if (path / "transformer" / "config.json").is_file():
|
| 37 |
+
path = path / "transformer"
|
| 38 |
+
elif not (path / "config.json").is_file():
|
| 39 |
+
raise FileNotFoundError(f"No MiniMax-H3 transformer config below {path}")
|
| 40 |
+
config = json.load(open(path / "config.json"))
|
| 41 |
+
if config.get("_class_name") != "MiniMaxH3Transformer3DModel":
|
| 42 |
+
raise ValueError(f"{path} is not a Diffusers MiniMaxH3Transformer3DModel checkpoint")
|
| 43 |
+
return path
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def load_transformer(path, dtype=torch.bfloat16):
|
| 47 |
+
"""The Diffusers MiniMax-H3 transformer on CPU."""
|
| 48 |
+
from diffusers import MiniMaxH3Transformer3DModel
|
| 49 |
+
|
| 50 |
+
transformer = MiniMaxH3Transformer3DModel.from_pretrained(
|
| 51 |
+
str(resolve_transformer_dir(path)), torch_dtype=dtype, local_files_only=True, low_cpu_mem_usage=True
|
| 52 |
+
)
|
| 53 |
+
transformer.requires_grad_(False)
|
| 54 |
+
return transformer
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def load_vaes(model_dir, device):
|
| 58 |
+
"""The video and audio VAEs in float32 on `device`."""
|
| 59 |
+
from diffusers import AutoencoderKLMiniMaxH3, AutoencoderKLMiniMaxH3Audio
|
| 60 |
+
|
| 61 |
+
root = Path(model_dir).expanduser().resolve()
|
| 62 |
+
vae = AutoencoderKLMiniMaxH3.from_pretrained(str(root / "vae"), local_files_only=True).eval().to(device)
|
| 63 |
+
audio_vae = AutoencoderKLMiniMaxH3Audio.from_pretrained(str(root / "audio_vae"), local_files_only=True).eval().to(device)
|
| 64 |
+
return vae, audio_vae
|
dmad_h3/packing.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""T2AV packed-sequence geometry of MiniMax-H3 (text | stereo audio | video rows), as used for training the students."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
VIDEO_TAG = 0
|
| 9 |
+
TEXT_TAG = 1
|
| 10 |
+
AUDIO_TAG = 2
|
| 11 |
+
FPS = 24
|
| 12 |
+
AUDIO_LATENTS_PER_SECOND = 40
|
| 13 |
+
AUDIO_CHANNELS = 2
|
| 14 |
+
FRAMES_PER_CHUNK = 17
|
| 15 |
+
LATENTS_PER_CHUNK = 5
|
| 16 |
+
_ROPE_FRAME_RESCALE = 5.0 / 3.0
|
| 17 |
+
_ROPE_FRAMES_PER_LATENT = (1, 4, 4, 4, 4)
|
| 18 |
+
_ROPE_SPATIAL_SCALE = 32.0
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass(frozen=True)
|
| 22 |
+
class MiniMaxH3PackedSequence:
|
| 23 |
+
sequence_length: int
|
| 24 |
+
position_ids: torch.Tensor
|
| 25 |
+
token_tags: torch.Tensor
|
| 26 |
+
video_indices: torch.Tensor
|
| 27 |
+
audio_indices: torch.Tensor
|
| 28 |
+
text_indices: torch.Tensor
|
| 29 |
+
num_condition_video_rows: int = 0
|
| 30 |
+
num_condition_audio_rows: int = 0
|
| 31 |
+
|
| 32 |
+
def to(self, device):
|
| 33 |
+
return MiniMaxH3PackedSequence(
|
| 34 |
+
sequence_length=self.sequence_length,
|
| 35 |
+
position_ids=self.position_ids.to(device),
|
| 36 |
+
token_tags=self.token_tags.to(device),
|
| 37 |
+
video_indices=self.video_indices.to(device),
|
| 38 |
+
audio_indices=self.audio_indices.to(device),
|
| 39 |
+
text_indices=self.text_indices.to(device),
|
| 40 |
+
num_condition_video_rows=self.num_condition_video_rows,
|
| 41 |
+
num_condition_audio_rows=self.num_condition_audio_rows,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def video_latent_num_frames(num_frames: int) -> int:
|
| 46 |
+
if num_frames % FRAMES_PER_CHUNK != LATENTS_PER_CHUNK:
|
| 47 |
+
raise ValueError(f"MiniMax-H3 num_frames must be 17*n+5, got {num_frames}.")
|
| 48 |
+
return (num_frames - LATENTS_PER_CHUNK) // FRAMES_PER_CHUNK * LATENTS_PER_CHUNK + 2
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def audio_latent_num_frames(num_frames: int) -> int:
|
| 52 |
+
return int(round(num_frames / FPS * AUDIO_LATENTS_PER_SECOND))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _spatial_grid(dim: int, patch: int, sqrt_area: float) -> torch.Tensor:
|
| 56 |
+
ratio = dim / sqrt_area
|
| 57 |
+
left = (1.0 - ratio) / 2.0
|
| 58 |
+
values = np.linspace(left, left + ratio, dim // patch, endpoint=False) * _ROPE_SPATIAL_SCALE
|
| 59 |
+
return torch.from_numpy(values).to(torch.float64)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _temporal_grid(num_frames: int, origin: float) -> torch.Tensor:
|
| 63 |
+
spans = torch.tensor(
|
| 64 |
+
[_ROPE_FRAME_RESCALE * _ROPE_FRAMES_PER_LATENT[i % 5] for i in range(num_frames)],
|
| 65 |
+
dtype=torch.float64,
|
| 66 |
+
)
|
| 67 |
+
return origin + torch.cat((torch.zeros(1, dtype=torch.float64), spans[:-1].cumsum(0)))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def build_packed_sequence(
|
| 71 |
+
text_token_tags: torch.Tensor,
|
| 72 |
+
num_latent_frames: int,
|
| 73 |
+
latent_height: int,
|
| 74 |
+
latent_width: int,
|
| 75 |
+
num_audio_latents: int,
|
| 76 |
+
patch_size: tuple[int, int, int] = (1, 2, 2),
|
| 77 |
+
) -> MiniMaxH3PackedSequence:
|
| 78 |
+
"""Build the padless T2AV layout ``[text | stereo audio | video]``."""
|
| 79 |
+
patch_t, patch_h, patch_w = patch_size
|
| 80 |
+
if patch_t != 1:
|
| 81 |
+
raise ValueError(f"MiniMax-H3 T2AV expects temporal patch size 1, got {patch_size}.")
|
| 82 |
+
if latent_height % patch_h or latent_width % patch_w:
|
| 83 |
+
raise ValueError(f"Latent canvas {latent_height}x{latent_width} is not divisible by patch {patch_size}.")
|
| 84 |
+
text_token_tags = text_token_tags.to(device="cpu", dtype=torch.long).flatten()
|
| 85 |
+
num_text = int(text_token_tags.numel())
|
| 86 |
+
rows_per_frame = (latent_height // patch_h) * (latent_width // patch_w)
|
| 87 |
+
num_audio_rows = num_audio_latents * AUDIO_CHANNELS
|
| 88 |
+
num_video_rows = num_latent_frames * rows_per_frame
|
| 89 |
+
audio_start = num_text
|
| 90 |
+
video_start = audio_start + num_audio_rows
|
| 91 |
+
sequence_length = video_start + num_video_rows
|
| 92 |
+
|
| 93 |
+
position_ids = torch.zeros(sequence_length, 3, dtype=torch.float64)
|
| 94 |
+
position_ids[:num_text, 0] = torch.arange(num_text, dtype=torch.float64)
|
| 95 |
+
sqrt_area = float(np.sqrt(latent_height * latent_width))
|
| 96 |
+
height_grid = _spatial_grid(latent_height, patch_h, sqrt_area)
|
| 97 |
+
width_grid = _spatial_grid(latent_width, patch_w, sqrt_area)
|
| 98 |
+
frame_grid = torch.stack([axis.reshape(-1) for axis in torch.meshgrid(height_grid, width_grid, indexing="ij")], dim=-1)
|
| 99 |
+
|
| 100 |
+
audio_time = float(num_text) + torch.arange(num_audio_latents, dtype=torch.float64)
|
| 101 |
+
position_ids[audio_start:video_start, 0] = audio_time.repeat(AUDIO_CHANNELS)
|
| 102 |
+
position_ids[audio_start:video_start, 2] = torch.cat(
|
| 103 |
+
(
|
| 104 |
+
torch.full((num_audio_latents,), float(width_grid[0]), dtype=torch.float64),
|
| 105 |
+
torch.full((num_audio_latents,), float(width_grid[-1]), dtype=torch.float64),
|
| 106 |
+
)
|
| 107 |
+
)
|
| 108 |
+
video_positions = torch.empty(num_latent_frames, rows_per_frame, 3, dtype=torch.float64)
|
| 109 |
+
video_positions[:, :, 0] = _temporal_grid(num_latent_frames, float(num_text))[:, None]
|
| 110 |
+
video_positions[:, :, 1:] = frame_grid[None]
|
| 111 |
+
position_ids[video_start:] = video_positions.reshape(-1, 3)
|
| 112 |
+
|
| 113 |
+
text_indices = torch.arange(num_text, dtype=torch.long)
|
| 114 |
+
audio_indices = torch.arange(audio_start, video_start, dtype=torch.long)
|
| 115 |
+
video_indices = torch.arange(video_start, sequence_length, dtype=torch.long)
|
| 116 |
+
token_tags = torch.empty(sequence_length, dtype=torch.long)
|
| 117 |
+
token_tags[text_indices] = text_token_tags
|
| 118 |
+
token_tags[audio_indices] = AUDIO_TAG
|
| 119 |
+
token_tags[video_indices] = VIDEO_TAG
|
| 120 |
+
return MiniMaxH3PackedSequence(
|
| 121 |
+
sequence_length,
|
| 122 |
+
position_ids,
|
| 123 |
+
token_tags,
|
| 124 |
+
video_indices,
|
| 125 |
+
audio_indices,
|
| 126 |
+
text_indices,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def build_row_timesteps(
|
| 131 |
+
layout: MiniMaxH3PackedSequence,
|
| 132 |
+
video_sigma: float | torch.Tensor,
|
| 133 |
+
audio_sigma: float | torch.Tensor,
|
| 134 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 135 |
+
"""Convert modality sigmas to H3's clean-ward ``t=1-sigma`` rows."""
|
| 136 |
+
# Keep the subtraction in float32. The published scheduler materializes
|
| 137 |
+
# ``timesteps = 1 - sigmas`` as a tensor before converting values to
|
| 138 |
+
# Python floats; doing the subtraction in Python differs by one ulp.
|
| 139 |
+
video_t = float((1.0 - torch.as_tensor(video_sigma, dtype=torch.float32)).item())
|
| 140 |
+
audio_t = float((1.0 - torch.as_tensor(audio_sigma, dtype=torch.float32)).item())
|
| 141 |
+
row_timesteps = torch.full((layout.sequence_length,), video_t, dtype=torch.float32)
|
| 142 |
+
row_timesteps[layout.audio_indices] = audio_t
|
| 143 |
+
return torch.unique(row_timesteps, sorted=True, return_inverse=True)
|
dmad_h3/sampling.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Few-step sampling, VAE decoding and mp4 muxing for DMAD students of MiniMax-H3."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
+
import tempfile
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from .packing import audio_latent_num_frames, build_row_timesteps, video_latent_num_frames
|
| 11 |
+
|
| 12 |
+
VIDEO_FPS = 24
|
| 13 |
+
AUDIO_SAMPLE_RATE = 32000
|
| 14 |
+
# The H3 video VAE works in ImageNet-normalized pixel space.
|
| 15 |
+
PIXEL_MEAN = (0.485, 0.456, 0.406)
|
| 16 |
+
PIXEL_STD = (0.229, 0.224, 0.225)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def shift_sigma(sigma, shift):
|
| 20 |
+
return shift * sigma / (1.0 + (shift - 1.0) * sigma)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def sigma_grid(steps, shift):
|
| 24 |
+
"""Shifted linear grid from 1 to 0 with `steps` model evaluations (steps + 1 points)."""
|
| 25 |
+
return shift_sigma(torch.linspace(1.0, 0.0, steps + 1, dtype=torch.float32), shift)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def latent_shape_of(height, width, num_frames, geometry):
|
| 29 |
+
latent_frames = video_latent_num_frames(num_frames)
|
| 30 |
+
latent_height = height // geometry.vae_spatial_scale_factor
|
| 31 |
+
latent_width = width // geometry.vae_spatial_scale_factor
|
| 32 |
+
patch_t, patch_h, patch_w = geometry.patch_size
|
| 33 |
+
video_rows = latent_frames * (latent_height // patch_h) * (latent_width // patch_w)
|
| 34 |
+
video_dim = geometry.video_latent_channels * patch_t * patch_h * patch_w
|
| 35 |
+
audio_latents = audio_latent_num_frames(num_frames)
|
| 36 |
+
return {
|
| 37 |
+
"num_frames": num_frames,
|
| 38 |
+
"latent_frames": latent_frames,
|
| 39 |
+
"latent_height": latent_height,
|
| 40 |
+
"latent_width": latent_width,
|
| 41 |
+
"audio_latents": audio_latents,
|
| 42 |
+
"video_tokens": (1, video_rows, video_dim),
|
| 43 |
+
"audio_tokens": (1, audio_latents * 2, geometry.audio_latent_channels),
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def draw_init_noise(shape, geometry, seed, device):
|
| 48 |
+
"""Initial noise from one CPU generator: video latent first, then audio rows. The same generator
|
| 49 |
+
is returned and later supplies the fresh noise of the re-noise step rule."""
|
| 50 |
+
from diffusers.modular_pipelines.minimax_h3.before_denoise import patchify_video_latents
|
| 51 |
+
|
| 52 |
+
g = torch.Generator(device="cpu").manual_seed(int(seed))
|
| 53 |
+
noise_v = torch.randn(
|
| 54 |
+
(1, geometry.video_latent_channels, shape["latent_frames"], shape["latent_height"], shape["latent_width"]),
|
| 55 |
+
generator=g,
|
| 56 |
+
dtype=torch.float32,
|
| 57 |
+
)
|
| 58 |
+
noise_a = torch.randn((shape["audio_latents"] * 2, geometry.audio_latent_channels), generator=g, dtype=torch.float32)
|
| 59 |
+
xt = (patchify_video_latents(noise_v.to(device), geometry.patch_size)[None].float(), noise_a.to(device)[None].float())
|
| 60 |
+
return xt, g
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@torch.no_grad()
|
| 64 |
+
def rollout(transformer, prompt_embeds, layout, shape, geometry, video_sigmas, audio_sigmas, seed, device, renoise=True):
|
| 65 |
+
"""Run len(video_sigmas) - 1 student evaluations and return the final (video_rows, audio_rows) x0 on CPU.
|
| 66 |
+
|
| 67 |
+
renoise=True : the DMD-style multistep rule (denoise, then fresh noise at the next sigma), which the students are
|
| 68 |
+
trained with and which the paper's results use.
|
| 69 |
+
renoise=False: the Euler ODE step (the rule of the official MiniMax-H3 pipeline).
|
| 70 |
+
"""
|
| 71 |
+
xt, g = draw_init_noise(shape, geometry, seed, device)
|
| 72 |
+
x0 = None
|
| 73 |
+
for step in range(len(video_sigmas) - 1):
|
| 74 |
+
v_s, a_s = video_sigmas[step].to(device), audio_sigmas[step].to(device)
|
| 75 |
+
ts, ti = build_row_timesteps(layout, v_s, a_s)
|
| 76 |
+
vel = transformer(
|
| 77 |
+
hidden_states=xt[0],
|
| 78 |
+
audio_hidden_states=xt[1],
|
| 79 |
+
encoder_hidden_states=prompt_embeds,
|
| 80 |
+
timestep=ts.to(device),
|
| 81 |
+
timestep_indices=ti.to(device),
|
| 82 |
+
token_tags=layout.token_tags,
|
| 83 |
+
position_ids=layout.position_ids,
|
| 84 |
+
video_indices=layout.video_indices,
|
| 85 |
+
audio_indices=layout.audio_indices,
|
| 86 |
+
text_indices=layout.text_indices,
|
| 87 |
+
return_dict=False,
|
| 88 |
+
)
|
| 89 |
+
x0 = (xt[0] + v_s * vel[0].float(), xt[1] + a_s * vel[1].float())
|
| 90 |
+
nv, na = video_sigmas[step + 1].to(device), audio_sigmas[step + 1].to(device)
|
| 91 |
+
if renoise:
|
| 92 |
+
ev = torch.randn(x0[0].shape, generator=g, dtype=torch.float32).to(device)
|
| 93 |
+
ea = torch.randn(x0[1].shape, generator=g, dtype=torch.float32).to(device)
|
| 94 |
+
xt = ((1.0 - nv) * x0[0] + nv * ev, (1.0 - na) * x0[1] + na * ea)
|
| 95 |
+
else:
|
| 96 |
+
rv, ra = nv / v_s, na / a_s
|
| 97 |
+
xt = (rv * xt[0].float() + (1.0 - rv) * x0[0].float(), ra * xt[1].float() + (1.0 - ra) * x0[1].float())
|
| 98 |
+
return x0[0].float().cpu(), x0[1].float().cpu()
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@torch.no_grad()
|
| 102 |
+
def decode_rows(vae, audio_vae, video_rows, audio_rows, shape, geometry):
|
| 103 |
+
"""Packed latent rows -> (uint8 frames [T, H, W, 3], float32 waveform [N, 2])."""
|
| 104 |
+
device = next(vae.parameters()).device
|
| 105 |
+
vm = torch.tensor(vae.config.latents_mean, device=device).view(1, -1, 1, 1, 1)
|
| 106 |
+
vs = torch.tensor(vae.config.latents_std, device=device).view(1, -1, 1, 1, 1)
|
| 107 |
+
am = torch.tensor(audio_vae.config.latents_mean, device=device).view(1, -1, 1)
|
| 108 |
+
as_ = torch.tensor(audio_vae.config.latents_std, device=device).view(1, -1, 1)
|
| 109 |
+
_, ph, pw = geometry.patch_size
|
| 110 |
+
video_channels, audio_channels = geometry.video_latent_channels, geometry.audio_latent_channels
|
| 111 |
+
t = shape["latent_frames"]
|
| 112 |
+
hh, ww = shape["latent_height"] // ph, shape["latent_width"] // pw
|
| 113 |
+
z = video_rows.float().to(device).reshape(t, hh, ww, video_channels, ph, pw)
|
| 114 |
+
z = z.permute(3, 0, 1, 4, 2, 5).reshape(1, video_channels, t, hh * ph, ww * pw)
|
| 115 |
+
px = vae.decode(z * vs + vm).sample
|
| 116 |
+
pm = torch.tensor(PIXEL_MEAN, device=px.device).view(3, 1, 1, 1)
|
| 117 |
+
ps = torch.tensor(PIXEL_STD, device=px.device).view(3, 1, 1, 1)
|
| 118 |
+
frames = ((px[0].float() * ps + pm).clamp(0, 1) * 255.0).round().byte().cpu().numpy().transpose(1, 2, 3, 0)
|
| 119 |
+
za = audio_rows.float().to(device).reshape(1, 2, -1, audio_channels)
|
| 120 |
+
za = za[0].permute(0, 2, 1) * as_ + am
|
| 121 |
+
wav = audio_vae.decode(za).sample[:, 0].float().clamp(-1, 1).cpu().numpy().T.astype(np.float32)
|
| 122 |
+
return frames, wav
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def write_mp4(frames, wav, out_path, sample_rate=AUDIO_SAMPLE_RATE):
|
| 126 |
+
"""Mux rgb24 frames (24 fps) and stereo float32 audio into an H.264/AAC mp4 tagged bt709."""
|
| 127 |
+
from imageio_ffmpeg import get_ffmpeg_exe
|
| 128 |
+
|
| 129 |
+
h_px, w_px = frames.shape[1], frames.shape[2]
|
| 130 |
+
out_dir = os.path.dirname(os.path.abspath(out_path))
|
| 131 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 132 |
+
with tempfile.TemporaryDirectory(dir=out_dir) as tmp:
|
| 133 |
+
vraw, araw = os.path.join(tmp, "video.raw"), os.path.join(tmp, "audio.raw")
|
| 134 |
+
with open(vraw, "wb") as f:
|
| 135 |
+
f.write(np.ascontiguousarray(frames).tobytes())
|
| 136 |
+
with open(araw, "wb") as f:
|
| 137 |
+
f.write(np.ascontiguousarray(wav, dtype=np.float32).tobytes())
|
| 138 |
+
subprocess.run(
|
| 139 |
+
[get_ffmpeg_exe(), "-y", "-hide_banner", "-loglevel", "error",
|
| 140 |
+
"-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{w_px}x{h_px}", "-r", str(VIDEO_FPS), "-i", vraw,
|
| 141 |
+
"-f", "f32le", "-ar", str(sample_rate), "-ac", "2", "-i", araw,
|
| 142 |
+
"-vf", "scale=in_range=full:out_color_matrix=bt709:out_range=tv",
|
| 143 |
+
"-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709",
|
| 144 |
+
"-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p",
|
| 145 |
+
"-c:a", "aac", "-b:a", "160k", "-shortest", out_path],
|
| 146 |
+
check=True,
|
| 147 |
+
)
|
dmad_h3/text_encoder.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prompt encoding with the MiniMax-H3 conditioner (Qwen3-VL, hidden layer 50): the prompt verbatim, no chat template."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
TEXT_ENCODER_LAYER = 50
|
| 9 |
+
TEXT_TAG = 1
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def read_prompts(path):
|
| 13 |
+
"""A UTF-8 .txt file (one prompt per line) or .jsonl (one {"prompt": ...} object per line)."""
|
| 14 |
+
with Path(path).expanduser().open("r", encoding="utf-8") as handle:
|
| 15 |
+
if str(path).endswith(".jsonl"):
|
| 16 |
+
prompts = [json.loads(line)["prompt"] for line in handle if line.strip()]
|
| 17 |
+
else:
|
| 18 |
+
prompts = [line.strip() for line in handle if line.strip()]
|
| 19 |
+
if not prompts:
|
| 20 |
+
raise RuntimeError(f"No non-empty prompts found in {path}.")
|
| 21 |
+
return prompts
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def load_conditioner(model_dir, device, dtype=torch.bfloat16):
|
| 25 |
+
from transformers import Qwen2TokenizerFast, Qwen3VLForConditionalGeneration, Qwen3VLProcessor
|
| 26 |
+
|
| 27 |
+
root = Path(model_dir).expanduser().resolve()
|
| 28 |
+
for sub in ("text_encoder", "tokenizer", "processor"):
|
| 29 |
+
if not (root / sub).exists():
|
| 30 |
+
raise FileNotFoundError(f"Missing MiniMax-H3 component: {root / sub}")
|
| 31 |
+
load_kwargs = {"dtype": dtype, "local_files_only": True}
|
| 32 |
+
if str(device) != "cpu":
|
| 33 |
+
load_kwargs["device_map"] = {"": str(device)}
|
| 34 |
+
text_encoder = Qwen3VLForConditionalGeneration.from_pretrained(str(root / "text_encoder"), **load_kwargs)
|
| 35 |
+
text_encoder.requires_grad_(False).eval()
|
| 36 |
+
tokenizer = Qwen2TokenizerFast.from_pretrained(str(root / "tokenizer"), local_files_only=True)
|
| 37 |
+
processor = Qwen3VLProcessor.from_pretrained(str(root / "processor"), local_files_only=True)
|
| 38 |
+
return text_encoder, tokenizer, processor
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@torch.inference_mode()
|
| 42 |
+
def encode_prompt(text_encoder, tokenizer, processor, prompt, device, output_dtype=torch.bfloat16):
|
| 43 |
+
"""-> {"prompt_embeds": [1, tokens, 5120] on CPU, "text_token_tags": [tokens] long}."""
|
| 44 |
+
token_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"]
|
| 45 |
+
if not token_ids:
|
| 46 |
+
raise ValueError("The tokenizer produced no tokens for a non-empty prompt.")
|
| 47 |
+
input_ids = torch.tensor([token_ids], dtype=torch.long, device=device)
|
| 48 |
+
mm_token_type_ids = torch.tensor(processor.create_mm_token_type_ids([token_ids]), dtype=torch.long, device=device)
|
| 49 |
+
outputs = text_encoder.model(
|
| 50 |
+
input_ids=input_ids,
|
| 51 |
+
attention_mask=torch.ones_like(input_ids),
|
| 52 |
+
mm_token_type_ids=mm_token_type_ids,
|
| 53 |
+
pixel_values=None,
|
| 54 |
+
image_grid_thw=None,
|
| 55 |
+
use_cache=False,
|
| 56 |
+
output_hidden_states=True,
|
| 57 |
+
)
|
| 58 |
+
prompt_embeds = outputs.hidden_states[TEXT_ENCODER_LAYER].to(dtype=output_dtype).cpu()
|
| 59 |
+
text_token_tags = torch.full((len(token_ids),), TEXT_TAG, dtype=torch.long)
|
| 60 |
+
return {"prompt_embeds": prompt_embeds, "text_token_tags": text_token_tags}
|
requirements.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `diffusers` pinned to the commit the DMAD reference implementation was built against
|
| 2 |
+
# (https://github.com/Yzmblog/DMAD: `diffusers @ git+...@35ab485bdea676dbcbc77de60d77f7acb4f390fd`, 0.40.0.dev0).
|
| 3 |
+
# That commit is on `main` and carries the full MiniMax-H3 model set the student's LoRA targets
|
| 4 |
+
# (`MiniMaxH3Transformer3DModel`, `AutoencoderKLMiniMaxH3(Audio)`, `patchify_video_latents`). Re-check
|
| 5 |
+
# `fold_lora`'s module names against the pinned head whenever this moves.
|
| 6 |
+
diffusers @ git+https://github.com/huggingface/diffusers.git@35ab485bdea676dbcbc77de60d77f7acb4f390fd
|
| 7 |
+
# `dmad_h3` (bundled, Apache-2.0, from the DMAD repo) needs only torch + numpy + safetensors at inference;
|
| 8 |
+
# the Qwen3-VL conditioner is NOT loaded here — it runs in the companion conditioner Space.
|
| 9 |
+
imageio-ffmpeg
|
| 10 |
+
accelerate
|
| 11 |
+
numpy
|
| 12 |
+
safetensors>=0.8.0
|
| 13 |
+
requests
|