Spaces:
Restarting on Zero
Restarting on Zero
arjunyonjan commited on
Commit ·
53e7af9
0
Parent(s):
Pragya OS fork of MiniMax-H3 Turbo LoRA
Browse files- .gitattributes +35 -0
- .gitignore +2 -0
- README.md +212 -0
- app.py +445 -0
- examples/first.png +0 -0
- examples/last.png +0 -0
- h3_aoti.py +307 -0
- h3_lora.py +172 -0
- h3_split_blocks.py +147 -0
- index.html +478 -0
- packages.txt +1 -0
- requirements.txt +26 -0
- spaces_constant_binding_patch.py +202 -0
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
README.md
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Pragya H3 (private fork)
|
| 3 |
+
emoji: 🎬
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.20.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
short_description: Pragya OS fork of MiniMax H3 — dedicated ZeroGPU instance
|
| 11 |
+
suggested_hardware: zero-a10g
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# MiniMax-H3 — unquantized, split across two Spaces
|
| 15 |
+
|
| 16 |
+
Joint video **and** soundtrack out of a single denoising pass, at **bfloat16 with no quantization anywhere**.
|
| 17 |
+
|
| 18 |
+
This Space is the denoising half: the 61.73 GiB transformer and the two autoencoders. The 62.14 GiB Qwen3-VL
|
| 19 |
+
conditioner runs in
|
| 20 |
+
[`qwen3vl-conditioner`](https://huggingface.co/spaces/multimodalart/qwen3vl-conditioner), which this
|
| 21 |
+
Space calls over the gradio API for every request. The weights are the public
|
| 22 |
+
[`MiniMaxAI/MiniMax-H3`](https://huggingface.co/MiniMaxAI/MiniMax-H3) diffusers checkpoint.
|
| 23 |
+
|
| 24 |
+
## Why split
|
| 25 |
+
|
| 26 |
+
MiniMax-H3 is 195.9 GiB in bfloat16 and a ZeroGPU Space is evicted at **150 GB of storage**. An unquantized single
|
| 27 |
+
Space is therefore impossible, which is why quantized demos of it run NVFP4 or float8 weights. Cut the
|
| 28 |
+
`MiniMaxH3Blocks` sequence at its `text_encoder` step and both halves fit unquantized:
|
| 29 |
+
|
| 30 |
+
| Space | Subfolders | Download | Resident |
|
| 31 |
+
|---|---|---|---|
|
| 32 |
+
| [`qwen3vl-conditioner`](https://huggingface.co/spaces/multimodalart/qwen3vl-conditioner) | `text_encoder/` + `tokenizer/` + `processor/` | 66.7 GB | 62.15 GiB bf16 |
|
| 33 |
+
| this one | `transformer/` + `vae/` + `audio_vae/` | 77.3 GB | 61.73 GiB bf16 + 10.43 GiB float32 |
|
| 34 |
+
|
| 35 |
+
Besides the quality argument, unquantized weights are the ones AoTI can export; an NVFP4 checkpoint cannot be
|
| 36 |
+
exported at all.
|
| 37 |
+
|
| 38 |
+
## Studio frontend (gradio.Server)
|
| 39 |
+
|
| 40 |
+
The UI is a custom single-page studio (`index.html`) served by [`gradio.Server`](https://www.gradio.app/docs/gradio/server):
|
| 41 |
+
`@app.get("/")` serves the page, `@app.api(name="generate")` keeps the request on Gradio's queue (concurrency control,
|
| 42 |
+
SSE, ZeroGPU booking, `gradio_client` compatibility — the API name and signature are unchanged), and the page talks
|
| 43 |
+
to it with the `@gradio/client` JS package. `/status` and `/config` are plain FastAPI routes the page polls for
|
| 44 |
+
readiness and the canvas table. Keyframe cover-crop / canvas fitting moved server-side into `generate`, so API
|
| 45 |
+
callers get the same treatment the old upload event gave.
|
| 46 |
+
|
| 47 |
+
## 4-step Turbo LoRA
|
| 48 |
+
|
| 49 |
+
The transformer runs with [`larryvrh/MiniMax-H3-Turbo-Lora`](https://huggingface.co/larryvrh/MiniMax-H3-Turbo-Lora)
|
| 50 |
+
folded into its bf16 weights at startup (`h3_lora.py`), so the default is **6 sampling steps** instead of 28
|
| 51 |
+
card's comfort zone at the current checkpoint; 4 is the design point but softer). The larry fold mirrors the diffusers key
|
| 52 |
+
conversion exactly (fused-QKV thirds, the `SwiGLU` gate/value swap, the shared AdaLN row layout); lightx keys are
|
| 53 |
+
already diffusers-native. Both happen before the AoTI package is patched in, so compiled blocks carry the update too,
|
| 54 |
+
and the low-rank factors stay resident so switching is an in-place unfold/fold through one bf16 rounding.
|
| 55 |
+
`H3_LORA` selects the larry file (`off` skips it), `H3_LIGHTX=off` skips lightx, `H3_LORA_DEFAULT` picks which set
|
| 56 |
+
starts folded, and `H3_LORA_STRENGTH` scales the larry update (the card's sharpness/artifact dial).
|
| 57 |
+
|
| 58 |
+
## AoTI-compiled blocks
|
| 59 |
+
|
| 60 |
+
With `H3_AOTI=1` the 50 repeated transformer blocks run from a compiled package,
|
| 61 |
+
[`multimodalart/minimax-h3-aoti`](https://huggingface.co/multimodalart/minimax-h3-aoti)`:bf16/torch2.11/sm120/dynamic` — a single dynamic-sequence artifact that serves
|
| 62 |
+
every canvas, duration and prompt length. It carries no weights (it reads each block's live ones), so patching it in
|
| 63 |
+
is startup CPU work and costs no GPU time.
|
| 64 |
+
|
| 65 |
+
It removes a near-constant ~0.5 s/step — 50 blocks' worth of kernel-launch overhead plus the norm / rotary / AdaLN
|
| 66 |
+
epilogues around the matmuls — and cannot touch the matmuls themselves. So it pays best where the block is *not*
|
| 67 |
+
compute bound, i.e. on the small canvases:
|
| 68 |
+
|
| 69 |
+
| canvas (HxW) | eager s/step | AoTI s/step | faster |
|
| 70 |
+
|---|---|---|---|
|
| 71 |
+
| 768x1344 | 10.20 | 9.73 | +4.6% |
|
| 72 |
+
| 640x1152 | 6.46 | 5.88 | +9.1% |
|
| 73 |
+
| 544x960 | 4.02 | 3.58 | +11.0% |
|
| 74 |
+
|
| 75 |
+
At 72.16 GiB of weights on a 95.0 GiB card there is no offloading in the request path at all, which is why an
|
| 76 |
+
*unquantized* MiniMax-H3 is also the fastest one measured here: **10.6 s/step** against the 19–21 s/step the 4 bit
|
| 77 |
+
Space pays, where the whole cost is the traffic auto-offload has to move.
|
| 78 |
+
|
| 79 |
+
## How the split is expressed
|
| 80 |
+
|
| 81 |
+
`MiniMaxH3Blocks` is a `SequentialPipelineBlocks` whose branches are picked per request — and per `workflow=` — from
|
| 82 |
+
the inputs:
|
| 83 |
+
|
| 84 |
+
```
|
| 85 |
+
before_encode -> text_encoder -> vae_encoder -> denoise -> after_denoise -> decode
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
where `denoise` is itself `prepare_layout -> prepare_latents -> set_timesteps -> denoise`.
|
| 89 |
+
|
| 90 |
+
`h3_split_blocks.py` subclasses it with the `text_encoder` step removed. Dropping the step drops the three
|
| 91 |
+
components it declares, so `load_components` resolves `transformer` / `vae` / `audio_vae` / the two schedulers out of
|
| 92 |
+
the shared `modular_model_index.json` and never fetches the conditioner — and `prompt_embeds` and `text_token_tags`
|
| 93 |
+
become ordinary required inputs of the pipeline call:
|
| 94 |
+
|
| 95 |
+
```py
|
| 96 |
+
pipe = MiniMaxH3GeneratorBlocks().init_pipeline("MiniMaxAI/MiniMax-H3")
|
| 97 |
+
pipe.load_components(dtype=torch.bfloat16)
|
| 98 |
+
state = pipe(prompt_embeds=..., text_token_tags=..., height=768, width=1344, num_frames=124, num_inference_steps=30)
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
The wire format is exactly those two tensors — `(1, num_text_tokens, 5120)` bfloat16 and `(num_text_tokens,)` int64 —
|
| 102 |
+
carried as one safetensors file with the resolved `height` / `width` / `num_frames` in its metadata header. A
|
| 103 |
+
text-only request is 246 KB of it; one 768x1344 keyframe adds 1016 vision rows and takes it to 10.7 MB.
|
| 104 |
+
|
| 105 |
+
The keyframe `resize` step runs on **both** halves. It owns no pretrained component (PIL and arithmetic) and it puts
|
| 106 |
+
the keyframes onto the target canvas — which the conditioner needs to build its vision blocks and this Space needs to
|
| 107 |
+
encode with the video VAE. It is deterministic, and the conditioner returns the plan it resolved so this Space pins
|
| 108 |
+
the same canvas rather than re-deriving it. Two things that step no longer does, and that both halves therefore do
|
| 109 |
+
themselves: EXIF-transposing a keyframe into upright RGB, and snapping `num_frames` to `17 * n + 5` — the frame count
|
| 110 |
+
is resolved by the layout step, which lives on this side of the cut.
|
| 111 |
+
|
| 112 |
+
## Nothing is paid for with GPU time
|
| 113 |
+
|
| 114 |
+
The 77.3 GB download and the load happen at **startup**: `import spaces` at module top patches `torch.cuda` before
|
| 115 |
+
any GPU is attached, so nothing about the load needs a card. The conditioner round trip is a network call on this
|
| 116 |
+
Space's CPU. A `@spaces.GPU` call is therefore only the placement (once) and the denoise loop and the two decoders.
|
| 117 |
+
|
| 118 |
+
### The 150 GB quota, not the 95 GiB card, is what rules out startup placement
|
| 119 |
+
|
| 120 |
+
One thing does *not* happen at startup: the move onto the card. `spaces`' startup `torch.pack()` writes every
|
| 121 |
+
startup-resident CUDA tensor to a **second copy on disk** and only deletes the downloaded originals afterwards
|
| 122 |
+
(`Cleaned 62.13GB of tensor files ... after packing`, which is what keeps the conditioner half comfortable at
|
| 123 |
+
66.7 GB). Packing 77.3 GB needs 154.6 GB at once, and this Space is evicted mid-pack:
|
| 124 |
+
|
| 125 |
+
```
|
| 126 |
+
ZeroGPU tensors packing: 0%| | 0.00/77.3G
|
| 127 |
+
OSError: [Errno 28] No space left on device # os.posix_fallocate, spaces/zero/torch/packing.py
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
Unlinking the shards first does not rescue it. `.to("cuda")` under the startup patch does not release the
|
| 131 |
+
memory-mapped safetensors, so nothing is freed — and the pack's own cleanup walks those still-open mappings and
|
| 132 |
+
`lstat`s them, so a deleted blob becomes `FileNotFoundError: .../blobs/3d449... (deleted)`.
|
| 133 |
+
|
| 134 |
+
Placement therefore happens on the **first GPU call**, `PIPE.to("cuda")` at the top of the `@spaces.GPU` function:
|
| 135 |
+
about 10 s of PCIe once, then a no-op walk, and the denoise loop runs with everything resident and no offloading at
|
| 136 |
+
all. It is the same trick the 4 bit Space uses, for the same reason.
|
| 137 |
+
|
| 138 |
+
## Generation constraints
|
| 139 |
+
|
| 140 |
+
Fixed by the checkpoint: 24 fps, a 768 pixel short edge, 5 to 15 s, `num_frames` snapped up to the next `17 * n + 5`,
|
| 141 |
+
no CFG and no negative prompt (it is guidance-distilled, so every step is one forward pass).
|
| 142 |
+
|
| 143 |
+
## Measured
|
| 144 |
+
|
| 145 |
+
An `rtx-pro-6000` Job — the same silicon as the ZeroGPU pool (RTX PRO 6000 Blackwell, sm120, 95.0 GiB) — running
|
| 146 |
+
exactly this blockset over the wire format, 1344x768, 124 frames, 30 steps, bfloat16, cuDNN attention, everything
|
| 147 |
+
resident:
|
| 148 |
+
|
| 149 |
+
| | |
|
| 150 |
+
|---|---|
|
| 151 |
+
| `load_components` (77.3 GB, warm Xet) | 43 s |
|
| 152 |
+
| `.to("cuda")`, once | 10 s |
|
| 153 |
+
| resident weights | 72.16 GiB |
|
| 154 |
+
| denoise + decode | 317 s, **10.58 s/step** |
|
| 155 |
+
| peak allocated / reserved | 78.54 / 85.37 GiB |
|
| 156 |
+
| output | h264 1344x768 @ 24 fps, 5.167 s + stereo AAC @ 32 kHz |
|
| 157 |
+
|
| 158 |
+
And on this Space itself, driven over `gradio_client`. Startup is 93 s — the 77.3 GB download and the load, with
|
| 159 |
+
no placement and therefore no pack.
|
| 160 |
+
|
| 161 |
+
| Request | Conditioner | Denoise + decode | Steady | Round trip |
|
| 162 |
+
|---|---|---|---|---|
|
| 163 |
+
| text only, 18 tokens | 7 s | 339 s | 10.53 s/step | 353 s |
|
| 164 |
+
| one 768x1344 keyframe, 1034 tokens | 9 s | 370 s | 11.39 s/step | 386 s |
|
| 165 |
+
|
| 166 |
+
The keyframe costs about 8% per step rather than a placement penalty: it puts 1016 vision rows in front of the
|
| 167 |
+
prompt *and* 1016 conditioning rows in the packed sequence, and MiniMax-H3 attends over all of it every layer. The
|
| 168 |
+
one-time `PIPE.to("cuda")` is inside the first row's 339 s and does not reappear in the second.
|
| 169 |
+
|
| 170 |
+
## Space variables
|
| 171 |
+
|
| 172 |
+
| Variable | Default | Meaning |
|
| 173 |
+
|---|---|---|
|
| 174 |
+
| `H3_MODEL_REPO` | `MiniMaxAI/MiniMax-H3` | The diffusers-layout checkpoint. Public. |
|
| 175 |
+
| `H3_CONDITIONER` | `multimodalart/qwen3vl-conditioner` | The Space this one asks for embeddings. |
|
| 176 |
+
| `H3_PLACEMENT` | `lazy` | `lazy` moves all 72.16 GiB onto the card on the first GPU call and leaves it there; `offload` hands placement to `ComponentsManager.enable_auto_cpu_offload` instead. |
|
| 177 |
+
| `H3_ATTENTION` | `_native_cudnn` | cuDNN's fused kernel, 10–20% faster than the SDPA default and needs nothing installed. flash-attention 3 is sm90-only and this pool is sm120. |
|
| 178 |
+
| `H3_GPU_DURATION` | `900` | Seconds per request; the pool applies a 1.5 duration factor. |
|
| 179 |
+
| `H3_GPU_SIZE` | `xlarge` | ZeroGPU allocation size. `large` does not fit. |
|
| 180 |
+
| `H3_LORA` | `minimax_h3_turbo_4step_ema_ckpt850.safetensors` | Turbo LoRA file folded into the transformer at startup. `off` disables. |
|
| 181 |
+
| `H3_LORA_REPO` | `larryvrh/MiniMax-H3-Turbo-Lora` | Hub repo the LoRA is fetched from. |
|
| 182 |
+
| `H3_LORA_STRENGTH` | `1.0` | Scales the larry LoRA delta (sharpness/artifact trade-off). |
|
| 183 |
+
| `H3_LIGHTX` | `on` | Set to `off` to skip loading the lightx2v LoRA set. |
|
| 184 |
+
| `H3_LORA_DEFAULT` | `larry` | Which loaded LoRA set starts folded (`larry` / `lightx`). |
|
| 185 |
+
|
| 186 |
+
## Whose GPU quota pays
|
| 187 |
+
|
| 188 |
+
Two cards are booked per request — this Space's denoise loop and the conditioner's forward — and both are billed to the
|
| 189 |
+
requesting user, with nothing here arranging it: `gradio_client` attaches the caller's own `x-ip-token` to every
|
| 190 |
+
outgoing call, reading it off gradio's `LocalContext` inside the event listener (`Client.send_data` ->
|
| 191 |
+
`add_zero_gpu_headers`), and ZeroGPU charges the booking to whatever that token identifies.
|
| 192 |
+
|
| 193 |
+
A caller with no token to forward — a `gradio_client` script rather than a browser — leaves the conditioner's booking
|
| 194 |
+
attributed to this Space's pod IP and its small shared quota. An unattributed caller may book at most 120 credits at a
|
| 195 |
+
time and an `xlarge` booking costs twice its seconds, so the conditioner books the encode (45 s) and a prompt upsample
|
| 196 |
+
(60 s) as two separate calls, each within that ceiling.
|
| 197 |
+
|
| 198 |
+
## Secrets
|
| 199 |
+
|
| 200 |
+
None are required. Everything this Space downloads is public — the
|
| 201 |
+
[`MiniMaxAI/MiniMax-H3`](https://huggingface.co/MiniMaxAI/MiniMax-H3) checkpoint and the
|
| 202 |
+
[`multimodalart/minimax-h3-aoti`](https://huggingface.co/multimodalart/minimax-h3-aoti) packages — and the conditioner
|
| 203 |
+
is a public Space called on the requesting user's own ZeroGPU token, never on an org token.
|
| 204 |
+
|
| 205 |
+
## Where diffusers comes from
|
| 206 |
+
|
| 207 |
+
MiniMax-H3 is modular-only and not in a released `diffusers`, so `requirements.txt` installs it from the canonical
|
| 208 |
+
pull request, [huggingface/diffusers#14371](https://github.com/huggingface/diffusers/pull/14371), pinned to the commit
|
| 209 |
+
`665f5782` (`refs/pull/14371/head`) rather than to the moving `minimax-h3-refactor` branch.
|
| 210 |
+
|
| 211 |
+
That PR is a WIP, so it needs re-pinning whenever it updates, and `h3_split_blocks.py` — which subclasses its block
|
| 212 |
+
classes to cut the pipeline in two — has to be re-checked against the new head at the same time.
|
app.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MiniMax-H3 `t2va` / `fl2va`, split deployment — the denoising half."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import tempfile
|
| 7 |
+
import time
|
| 8 |
+
import traceback
|
| 9 |
+
from functools import cache
|
| 10 |
+
|
| 11 |
+
# Before anything that could initialize CUDA: `import spaces` patches `torch.cuda` so the 72 GiB load can happen at
|
| 12 |
+
# startup rather than on GPU time.
|
| 13 |
+
import spaces
|
| 14 |
+
from fastapi.responses import HTMLResponse
|
| 15 |
+
from gradio import Request, Server
|
| 16 |
+
from gradio.data_classes import FileData
|
| 17 |
+
|
| 18 |
+
MODEL_REPO = os.environ.get("H3_MODEL_REPO", "MiniMaxAI/MiniMax-H3")
|
| 19 |
+
CONDITIONER_SPACE = os.environ.get("H3_CONDITIONER", "multimodalart/qwen3vl-conditioner")
|
| 20 |
+
# `pack` places the transformer at startup, `lazy` moves everything on the first GPU call, `offload` hands placement to
|
| 21 |
+
# `ComponentsManager.enable_auto_cpu_offload`.
|
| 22 |
+
PLACEMENT = os.environ.get("H3_PLACEMENT", "pack").lower()
|
| 23 |
+
# cuDNN's fused attention is 10-20% faster than the SDPA default on this pool and needs nothing installed.
|
| 24 |
+
ATTENTION = os.environ.get("H3_ATTENTION", "_native_cudnn").lower()
|
| 25 |
+
GPU_SIZE = os.environ.get("H3_GPU_SIZE", "xlarge")
|
| 26 |
+
|
| 27 |
+
# Must stay identical to the conditioner's table: the *label* goes over the wire, so a canvas that half does not know
|
| 28 |
+
# is rejected there and surfaces as a failure here.
|
| 29 |
+
CANVASES = {
|
| 30 |
+
# 16:9
|
| 31 |
+
"960x544 · 16:9 fast": (544, 960),
|
| 32 |
+
"1024x576 · 16:9 fast": (576, 1024),
|
| 33 |
+
"1152x640 · 16:9": (640, 1152),
|
| 34 |
+
"1280x704 · 16:9": (704, 1280),
|
| 35 |
+
"1344x768 · 16:9 full": (768, 1344),
|
| 36 |
+
# 9:16
|
| 37 |
+
"544x960 · 9:16 fast": (960, 544),
|
| 38 |
+
"640x1152 · 9:16": (1152, 640),
|
| 39 |
+
"768x1344 · 9:16 full": (1344, 768),
|
| 40 |
+
# 1:1
|
| 41 |
+
"544x544 · 1:1 fast": (544, 544),
|
| 42 |
+
"768x768 · 1:1 full": (768, 768),
|
| 43 |
+
# 4:3 / 3:4
|
| 44 |
+
"768x576 · 4:3 fast": (576, 768),
|
| 45 |
+
"1024x768 · 4:3 full": (768, 1024),
|
| 46 |
+
"576x768 · 3:4 fast": (768, 576),
|
| 47 |
+
"768x1024 · 3:4 full": (1024, 768),
|
| 48 |
+
# 21:9
|
| 49 |
+
"1152x512 · 21:9 fast": (512, 1152),
|
| 50 |
+
"1536x672 · 21:9 full": (672, 1536),
|
| 51 |
+
}
|
| 52 |
+
DEFAULT_CANVAS = "960x544 · 16:9 fast"
|
| 53 |
+
FPS, FRAMES_PER_CHUNK, LATENTS_PER_CHUNK = 24, 17, 5
|
| 54 |
+
# It is the *snapped* frame count the ceiling has to hold for: 15 s is 360 frames, which rounds up to 362, i.e.
|
| 55 |
+
# 15.083 s, and is refused.
|
| 56 |
+
MIN_UI_DURATION, MAX_UI_DURATION = 2, 14
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def snap_frames(seconds: float) -> int:
|
| 60 |
+
"""The frame count MiniMax-H3's video VAE can decode: the next `17 * n + 5` at 24 fps."""
|
| 61 |
+
frames = max(1, round(float(seconds) * FPS))
|
| 62 |
+
while frames % FRAMES_PER_CHUNK != LATENTS_PER_CHUNK:
|
| 63 |
+
frames += 1
|
| 64 |
+
return frames
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def lower_duration_floor(seconds: float = MIN_UI_DURATION) -> None:
|
| 68 |
+
"""Let the pipeline generate below its 5 s floor. 56 frames (2.33 s) is fine on the released checkpoint."""
|
| 69 |
+
from diffusers.modular_pipelines.minimax_h3.modular_pipeline import MiniMaxH3ModularPipeline
|
| 70 |
+
|
| 71 |
+
MiniMaxH3ModularPipeline.min_duration = property(lambda self: float(seconds))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
OUTPUT_DIR = os.path.join(tempfile.gettempdir(), "h3-outputs")
|
| 75 |
+
|
| 76 |
+
PIPE = None
|
| 77 |
+
MANAGER = None
|
| 78 |
+
LOAD_ERROR: str | None = None
|
| 79 |
+
LOADED_IN: float | None = None
|
| 80 |
+
LORA_STATUS: str | None = None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def status() -> str:
|
| 84 |
+
if LOAD_ERROR:
|
| 85 |
+
return LOAD_ERROR
|
| 86 |
+
if PIPE is None:
|
| 87 |
+
return f"Loading `{MODEL_REPO}` (transformer + VAEs, 77.3 GB). Watch the Space logs."
|
| 88 |
+
import h3_aoti
|
| 89 |
+
|
| 90 |
+
return (
|
| 91 |
+
f"Ready · transformer + VAEs **bfloat16, unquantized** · placement `{PLACEMENT}` · attention `{ATTENTION}` · "
|
| 92 |
+
f"{h3_aoti.status()} · {LORA_STATUS or 'no LoRA'} · loaded in {LOADED_IN:.0f}s · "
|
| 93 |
+
f"conditioner `{CONDITIONER_SPACE}`"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def load_models() -> str | None:
|
| 98 |
+
"""Load the denoising half at startup.
|
| 99 |
+
|
| 100 |
+
`MiniMaxH3GeneratorBlocks` declares `transformer`, `vae`, `audio_vae`, the two schedulers and `video_processor`,
|
| 101 |
+
so `load_components` fetches exactly those subfolders — `text_encoder/` and `transformer_ref/` are never touched.
|
| 102 |
+
Both autoencoders carry `_keep_in_fp32_modules` over every module and stay float32: a bfloat16 audio VAE decodes
|
| 103 |
+
the soundtrack roughly 20 dB too quiet.
|
| 104 |
+
"""
|
| 105 |
+
global PIPE, MANAGER, LOAD_ERROR, LOADED_IN, LORA_STATUS
|
| 106 |
+
|
| 107 |
+
if PIPE is not None or LOAD_ERROR is not None:
|
| 108 |
+
return LOAD_ERROR
|
| 109 |
+
|
| 110 |
+
started = time.time()
|
| 111 |
+
try:
|
| 112 |
+
import torch
|
| 113 |
+
from diffusers import ComponentsManager
|
| 114 |
+
|
| 115 |
+
from h3_split_blocks import MiniMaxH3GeneratorBlocks
|
| 116 |
+
|
| 117 |
+
lower_duration_floor()
|
| 118 |
+
manager = ComponentsManager()
|
| 119 |
+
blocks = MiniMaxH3GeneratorBlocks()
|
| 120 |
+
print(f"[gen] loading {[c.name for c in blocks.expected_components]} from {MODEL_REPO} ...", flush=True)
|
| 121 |
+
pipe = blocks.init_pipeline(MODEL_REPO, components_manager=manager, collection="h3")
|
| 122 |
+
pipe.load_components(dtype=torch.bfloat16)
|
| 123 |
+
|
| 124 |
+
# Fold the 4-step Turbo LoRA into the bf16 weights before AoTI packages the blocks, so the compiled forward
|
| 125 |
+
# reads weights that already carry the update. `H3_LORA=off` disables.
|
| 126 |
+
import h3_lora
|
| 127 |
+
|
| 128 |
+
LORA_STATUS = h3_lora.apply_lora(pipe.transformer)
|
| 129 |
+
if LORA_STATUS:
|
| 130 |
+
print(f"[gen] {LORA_STATUS}", flush=True)
|
| 131 |
+
|
| 132 |
+
pipe.transformer.set_attention_backend(ATTENTION)
|
| 133 |
+
|
| 134 |
+
# Still startup, still free: an AoTI package carries no weights and opens its archive lazily inside the GPU
|
| 135 |
+
# worker. Off unless `H3_AOTI=1`.
|
| 136 |
+
import h3_aoti
|
| 137 |
+
|
| 138 |
+
h3_aoti.maybe_load(pipe.transformer)
|
| 139 |
+
|
| 140 |
+
if PLACEMENT == "pack":
|
| 141 |
+
# Scoped to the transformer. `spaces` packs every startup-resident CUDA tensor into a second on-disk copy,
|
| 142 |
+
# and packing all 77.3 GB busts the 150 GB storage quota; the 61.7 GB transformer alone fits. The ~10 GB of
|
| 143 |
+
# fp32 VAEs move on the first GPU call instead.
|
| 144 |
+
pipe.transformer.to("cuda")
|
| 145 |
+
|
| 146 |
+
if PLACEMENT == "offload":
|
| 147 |
+
manager.enable_auto_cpu_offload(device="cuda")
|
| 148 |
+
_arm_decode_hooks(pipe)
|
| 149 |
+
|
| 150 |
+
PIPE, MANAGER = pipe, manager
|
| 151 |
+
LOADED_IN = time.time() - started
|
| 152 |
+
print(f"[gen] ready in {LOADED_IN:.0f}s", flush=True)
|
| 153 |
+
except Exception as error:
|
| 154 |
+
traceback.print_exc()
|
| 155 |
+
LOAD_ERROR = f"**Loading `{MODEL_REPO}` failed** after {time.time() - started:.0f}s: `{type(error).__name__}: {error}`"
|
| 156 |
+
return LOAD_ERROR
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _arm_decode_hooks(pipe):
|
| 160 |
+
"""Make the offload hooks fire for the two VAEs.
|
| 161 |
+
|
| 162 |
+
`enable_auto_cpu_offload` wraps `forward`, and the decode blocks call `vae.decode(...)` directly, so the hook
|
| 163 |
+
never runs and the VAE is still on the host when the latents arrive on the card.
|
| 164 |
+
"""
|
| 165 |
+
for name in ("vae", "audio_vae"):
|
| 166 |
+
module = getattr(pipe, name)
|
| 167 |
+
inner = module.decode
|
| 168 |
+
|
| 169 |
+
def armed(*args, _module=module, _decode=inner, **kwargs):
|
| 170 |
+
hook = getattr(_module, "_hf_hook", None)
|
| 171 |
+
if hook is not None:
|
| 172 |
+
hook.pre_forward(_module)
|
| 173 |
+
return _decode(*args, **kwargs)
|
| 174 |
+
|
| 175 |
+
module.decode = armed
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@cache
|
| 179 |
+
def conditioner():
|
| 180 |
+
"""The other half, over the gradio API. Used only when the caller's token could not be extracted; the booking is
|
| 181 |
+
then billed to this Space's pod IP and its small shared quota."""
|
| 182 |
+
from gradio_client import Client
|
| 183 |
+
|
| 184 |
+
return Client(CONDITIONER_SPACE)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def conditioner_client(ip_token):
|
| 188 |
+
"""A conditioner client billed to the caller. `LocalContext`-based token forwarding is not reliable in Server
|
| 189 |
+
mode, so the `x-ip-token` header is extracted from the incoming request and passed explicitly (per the gradio
|
| 190 |
+
ZeroGPU docs); a per-request Client is cheap next to a 45s encode."""
|
| 191 |
+
if not ip_token:
|
| 192 |
+
return conditioner()
|
| 193 |
+
from gradio_client import Client
|
| 194 |
+
|
| 195 |
+
return Client(CONDITIONER_SPACE, headers={"x-ip-token": ip_token})
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def encode_remote(prompt, image_path, last_image_path, canvas, num_frames, rewrite_prompt=False, ip_token=None):
|
| 199 |
+
"""`/encode` on the conditioner Space: a safetensors file holding `prompt_embeds` + `text_token_tags`, with the
|
| 200 |
+
resolved `height` / `width` / `num_frames` in its metadata, plus the plan. `canvas` is the label."""
|
| 201 |
+
from gradio_client import handle_file
|
| 202 |
+
from safetensors import safe_open
|
| 203 |
+
|
| 204 |
+
path, plan = conditioner_client(ip_token).predict(
|
| 205 |
+
prompt=prompt,
|
| 206 |
+
image_path=handle_file(image_path) if image_path else None,
|
| 207 |
+
last_image_path=handle_file(last_image_path) if last_image_path else None,
|
| 208 |
+
canvas=canvas,
|
| 209 |
+
num_frames=num_frames,
|
| 210 |
+
rewrite_prompt=bool(rewrite_prompt),
|
| 211 |
+
api_name="/encode",
|
| 212 |
+
)
|
| 213 |
+
with safe_open(path, framework="pt") as handle:
|
| 214 |
+
metadata = handle.metadata()
|
| 215 |
+
return handle.get_tensor("prompt_embeds"), handle.get_tensor("text_token_tags"), metadata, plan
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# Seconds of GPU one request needs, from the packed video rows it is about to denoise: linear in the rows for the
|
| 219 |
+
# matmuls, quadratic for the attention, against the AoTI block package this Space runs.
|
| 220 |
+
_DUR_B, _DUR_C = 1.1745e-4, 3.8396e-9
|
| 221 |
+
# The two resident decoders and the mux, which scale with the output rather than with the step count.
|
| 222 |
+
_DECODE_BASE, _DECODE_PER_DEFAULT_CANVAS, _DEFAULT_CANVAS_PIXELS = 15, 15, 960 * 544 * 124
|
| 223 |
+
# `pack` mode: only the ~10 GB of VAEs move on a cold worker.
|
| 224 |
+
_PLACEMENT_ALLOWANCE, _PAD = 12, 10
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def get_duration(prompt_embeds, text_token_tags, image, last_image, height, width, num_frames, steps, seed, lora="larry", *a, **k):
|
| 228 |
+
height, width, num_frames, steps = int(height), int(width), int(num_frames), int(steps)
|
| 229 |
+
latent_frames = (num_frames - LATENTS_PER_CHUNK) // FRAMES_PER_CHUNK * LATENTS_PER_CHUNK + 2
|
| 230 |
+
patches = (height // 32) * (width // 32)
|
| 231 |
+
rows = latent_frames * patches + (int(image is not None) + int(last_image is not None)) * patches
|
| 232 |
+
denoise = steps * (_DUR_B * rows + _DUR_C * rows**2)
|
| 233 |
+
decode = _DECODE_BASE + _DECODE_PER_DEFAULT_CANVAS * (height * width * num_frames) / _DEFAULT_CANVAS_PIXELS
|
| 234 |
+
return max(60, int(denoise + decode) + _PLACEMENT_ALLOWANCE + _PAD)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
@spaces.GPU(duration=get_duration, size=GPU_SIZE)
|
| 238 |
+
def _generate(prompt_embeds, text_token_tags, image, last_image, height, width, num_frames, steps, seed, lora="larry"):
|
| 239 |
+
"""The only thing on GPU time: the packed-sequence denoise loop and the two decoders.
|
| 240 |
+
|
| 241 |
+
Only the three generated outputs come back — a `@spaces.GPU` return crosses a process boundary by pickling, and
|
| 242 |
+
the full `PipelineState` still holds the packed latents, the rotary grid and the row indices on the card.
|
| 243 |
+
"""
|
| 244 |
+
import torch
|
| 245 |
+
|
| 246 |
+
import h3_lora
|
| 247 |
+
|
| 248 |
+
# Fold the requested LoRA in place (a no-op when the state already matches). AoTI blocks read the same
|
| 249 |
+
# live storage, so the compiled forward carries the switch too.
|
| 250 |
+
active_lora = h3_lora.set_active(PIPE.transformer, lora)
|
| 251 |
+
|
| 252 |
+
if PLACEMENT == "lazy":
|
| 253 |
+
PIPE.to("cuda")
|
| 254 |
+
elif PLACEMENT == "pack":
|
| 255 |
+
PIPE.vae.to("cuda")
|
| 256 |
+
PIPE.audio_vae.to("cuda")
|
| 257 |
+
|
| 258 |
+
state = PIPE(
|
| 259 |
+
prompt_embeds=prompt_embeds.to("cuda"),
|
| 260 |
+
text_token_tags=text_token_tags,
|
| 261 |
+
image=image,
|
| 262 |
+
last_image=last_image,
|
| 263 |
+
height=height,
|
| 264 |
+
width=width,
|
| 265 |
+
num_frames=num_frames,
|
| 266 |
+
num_inference_steps=int(steps),
|
| 267 |
+
generator=torch.Generator("cpu").manual_seed(int(seed)),
|
| 268 |
+
)
|
| 269 |
+
return state.get("videos")[0], state.get("audio")[0].cpu(), state.get("sampling_rate"), active_lora
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _fit_keyframe(image_path, current_canvas):
|
| 273 |
+
"""Cover-crop an uploaded keyframe to the closest supported aspect ratio and pick that ratio's smallest
|
| 274 |
+
(fastest) canvas, unless the caller already picked a matching ratio. Returns `(image_path, canvas_label)`."""
|
| 275 |
+
from PIL import Image as _Image
|
| 276 |
+
|
| 277 |
+
img = _Image.open(image_path)
|
| 278 |
+
aspect = img.width / img.height
|
| 279 |
+
fastest = {}
|
| 280 |
+
for label, (h, w) in CANVASES.items():
|
| 281 |
+
r = w / h
|
| 282 |
+
if r not in fastest or w * h < fastest[r][1][0] * fastest[r][1][1]:
|
| 283 |
+
fastest[r] = (label, (h, w))
|
| 284 |
+
ratio = min(fastest, key=lambda r: abs(r - aspect))
|
| 285 |
+
label, (h, w) = fastest[ratio]
|
| 286 |
+
|
| 287 |
+
cur_h, cur_w = CANVASES[current_canvas]
|
| 288 |
+
if abs(cur_w / cur_h - aspect) <= abs(ratio - aspect):
|
| 289 |
+
label = current_canvas
|
| 290 |
+
h, w = cur_h, cur_w
|
| 291 |
+
|
| 292 |
+
target = w / h
|
| 293 |
+
if abs(img.width / img.height - target) > 1e-3:
|
| 294 |
+
if img.width / img.height > target:
|
| 295 |
+
new_w = int(img.height * target)
|
| 296 |
+
left = (img.width - new_w) // 2
|
| 297 |
+
img = img.crop((left, 0, left + new_w, img.height))
|
| 298 |
+
else:
|
| 299 |
+
new_h = int(img.width / target)
|
| 300 |
+
top = (img.height - new_h) // 2
|
| 301 |
+
img = img.crop((0, top, img.width, top + new_h))
|
| 302 |
+
img.save(image_path)
|
| 303 |
+
return image_path, label
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def _resolve_lora(lora, use_lora) -> str:
|
| 307 |
+
"""`lora` (`larry` / `lightx` / `off`) wins; the legacy `use_lora` bool maps onto `larry` / `off`."""
|
| 308 |
+
if isinstance(lora, str) and lora in ("larry", "lightx", "off"):
|
| 309 |
+
return lora
|
| 310 |
+
return "larry" if use_lora else "off"
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def generate(prompt, image_path=None, last_image_path=None, canvas=DEFAULT_CANVAS, duration=5, steps=6, seed=42, upsample=False, use_lora=True, lora="", ip_token=None):
|
| 314 |
+
"""One request. `upsample`/`use_lora` keep their defaults so a positional API client that predates them is unaffected."""
|
| 315 |
+
if LOAD_ERROR:
|
| 316 |
+
raise Exception(LOAD_ERROR)
|
| 317 |
+
if PIPE is None:
|
| 318 |
+
raise Exception("The denoiser is still loading.")
|
| 319 |
+
if not prompt or not prompt.strip():
|
| 320 |
+
raise Exception("MiniMax-H3 always takes a prompt, keyframes or not.")
|
| 321 |
+
|
| 322 |
+
from PIL import Image, ImageOps
|
| 323 |
+
|
| 324 |
+
from diffusers.utils import encode_video
|
| 325 |
+
|
| 326 |
+
lora = _resolve_lora(lora, use_lora)
|
| 327 |
+
|
| 328 |
+
# Server mode: keyframes arrive as FileData dicts, and the cover-crop / canvas-fit that used to be an upload
|
| 329 |
+
# event in the Blocks UI runs here instead, so API callers get the same treatment.
|
| 330 |
+
first = image_path["path"] if isinstance(image_path, dict) else image_path
|
| 331 |
+
last = last_image_path["path"] if isinstance(last_image_path, dict) else last_image_path
|
| 332 |
+
if first:
|
| 333 |
+
first, canvas = _fit_keyframe(first, canvas)
|
| 334 |
+
if last:
|
| 335 |
+
last, canvas = _fit_keyframe(last, canvas)
|
| 336 |
+
|
| 337 |
+
num_frames = snap_frames(duration)
|
| 338 |
+
|
| 339 |
+
conditioned = time.time()
|
| 340 |
+
prompt_embeds, text_token_tags, metadata, plan = encode_remote(
|
| 341 |
+
prompt, first, last, canvas, num_frames, rewrite_prompt=upsample, ip_token=ip_token
|
| 342 |
+
)
|
| 343 |
+
condition_seconds = time.time() - conditioned
|
| 344 |
+
height, width, num_frames = (int(metadata[key]) for key in ("height", "width", "num_frames"))
|
| 345 |
+
refined = plan.get("refined_prompt") or ""
|
| 346 |
+
|
| 347 |
+
def keyframe(path):
|
| 348 |
+
# The conditioning latents encoded here have to be of the image the conditioner looked at, which it prepares
|
| 349 |
+
# exactly this way.
|
| 350 |
+
return ImageOps.exif_transpose(Image.open(path)).convert("RGB") if path else None
|
| 351 |
+
|
| 352 |
+
started = time.time()
|
| 353 |
+
frames, audio, sampling_rate, active_lora = _generate(
|
| 354 |
+
prompt_embeds,
|
| 355 |
+
text_token_tags,
|
| 356 |
+
keyframe(first),
|
| 357 |
+
keyframe(last),
|
| 358 |
+
height,
|
| 359 |
+
width,
|
| 360 |
+
num_frames,
|
| 361 |
+
steps,
|
| 362 |
+
seed,
|
| 363 |
+
lora,
|
| 364 |
+
)
|
| 365 |
+
generate_seconds = time.time() - started
|
| 366 |
+
|
| 367 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 368 |
+
path = os.path.join(OUTPUT_DIR, f"h3-{int(time.time() * 1000)}.mp4")
|
| 369 |
+
encode_video(frames, fps=FPS, output_path=path, audio=audio, audio_sample_rate=sampling_rate)
|
| 370 |
+
|
| 371 |
+
report = (
|
| 372 |
+
f"{width}x{height} · {num_frames} frames ({num_frames / FPS:.3f} s) · {int(steps)} steps · "
|
| 373 |
+
f"conditioner {condition_seconds:.0f}s ({plan['num_text_tokens']} tokens"
|
| 374 |
+
f"{', upsampled' if refined else ''}) · "
|
| 375 |
+
f"denoise + decode {generate_seconds:.0f}s ({generate_seconds / int(steps):.1f} s/step) · "
|
| 376 |
+
f"turbo LoRA {active_lora} · seed {int(seed)}"
|
| 377 |
+
)
|
| 378 |
+
print(f"[gen] {report}", flush=True)
|
| 379 |
+
return FileData(path=path), report, refined
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
# ======================================================================
|
| 384 |
+
# Server mode: Gradio's API engine (queue, SSE, concurrency, ZeroGPU,
|
| 385 |
+
# gradio_client) under a fully custom studio frontend (index.html).
|
| 386 |
+
# ======================================================================
|
| 387 |
+
app = Server(title="MiniMax-H3 Studio")
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
@app.api(name="generate")
|
| 391 |
+
def _generate_api(prompt: str, image_path: FileData | None = None, last_image_path: FileData | None = None,
|
| 392 |
+
canvas: str = DEFAULT_CANVAS, duration: float = 5, steps: int = 6, seed: float = 42,
|
| 393 |
+
upsample: bool = False, use_lora: bool = True, lora: str = "", request: Request = None) -> tuple[FileData, str, str]:
|
| 394 |
+
"""Generate a video with a synchronized soundtrack. Returns (video, report, refined prompt).
|
| 395 |
+
|
| 396 |
+
`lora` selects the turbo LoRA: `larry` (default), `lightx`, or `off`. The legacy `use_lora` bool still works
|
| 397 |
+
when `lora` is empty.
|
| 398 |
+
"""
|
| 399 |
+
# `request` is injected by the event system, not an API input; its x-ip-token bills the conditioner to the caller.
|
| 400 |
+
ip_token = request.headers.get("x-ip-token") if request is not None else None
|
| 401 |
+
return generate(prompt, image_path, last_image_path, canvas, duration, steps, seed, upsample, use_lora, lora, ip_token=ip_token)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
@app.get("/status")
|
| 405 |
+
def studio_status():
|
| 406 |
+
"""Polled by the frontend: is the denoiser ready, and the human-readable status line."""
|
| 407 |
+
return {"ready": PIPE is not None and LOAD_ERROR is None, "status": status()}
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
# NB: not `/config` — Gradio's own client-discovery route lives there and shadowing it breaks `@gradio/client`.
|
| 411 |
+
@app.get("/studio-config")
|
| 412 |
+
def studio_config():
|
| 413 |
+
"""The canvas table and slider ranges, so the frontend never hardcodes a label the backend would reject."""
|
| 414 |
+
import h3_lora
|
| 415 |
+
|
| 416 |
+
state = getattr(PIPE.transformer, "_lora_state", None) if PIPE is not None else None
|
| 417 |
+
sets = state["sets"] if state else {}
|
| 418 |
+
return {
|
| 419 |
+
"canvases": list(CANVASES),
|
| 420 |
+
"default_canvas": DEFAULT_CANVAS,
|
| 421 |
+
"min_duration": MIN_UI_DURATION,
|
| 422 |
+
"max_duration": MAX_UI_DURATION,
|
| 423 |
+
# The LoRA dropdown: value -> {label, suggested steps}.
|
| 424 |
+
"loras": {
|
| 425 |
+
**{
|
| 426 |
+
name: {"label": spec["label"], "steps": {"larry": 6, "lightx": 4}.get(name, 6)}
|
| 427 |
+
for name, spec in sets.items()
|
| 428 |
+
},
|
| 429 |
+
"off": {"label": "off (base model)", "steps": 28},
|
| 430 |
+
},
|
| 431 |
+
"default_lora": state["active"] if state else "off",
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
@app.get("/", response_class=HTMLResponse)
|
| 436 |
+
def homepage():
|
| 437 |
+
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "index.html"), encoding="utf-8") as f:
|
| 438 |
+
return f.read()
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
load_models()
|
| 442 |
+
|
| 443 |
+
if __name__ == "__main__":
|
| 444 |
+
# allowed_paths: the /gradio_api/file= route only serves whitelisted directories.
|
| 445 |
+
app.launch(show_error=True, allowed_paths=[OUTPUT_DIR])
|
examples/first.png
ADDED
|
examples/last.png
ADDED
|
h3_aoti.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ZeroGPU AoTI for MiniMax-H3: one compiled `MiniMaxH3TransformerBlock` package, reused by all 50 blocks.
|
| 2 |
+
|
| 3 |
+
Shared byte-identically by every MiniMax-H3 Space. A Space only calls `maybe_load()`; the rest is the build path.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
AOTI = os.environ.get("H3_AOTI", "0") == "1"
|
| 12 |
+
AOTI_REPO = os.environ.get("H3_AOTI_REPO", "multimodalart/minimax-h3-aoti")
|
| 13 |
+
AOTI_REPO_TYPE = os.environ.get("H3_AOTI_REPO_TYPE", "model")
|
| 14 |
+
# A package is valid for exactly one `<width>/torch<X.Y>/sm<cc>/<shape>`, and a mismatched one segfaults rather than
|
| 15 |
+
# raising, so `maybe_load` refuses anything but this key.
|
| 16 |
+
AOTI_KEY = os.environ.get("H3_AOTI_KEY", "bf16/torch2.11/sm120/dynamic")
|
| 17 |
+
# `dynamic` is the sequence dimension: `build_packed_sequence` pads nothing, so `S` moves with the prompt as well as
|
| 18 |
+
# the canvas and a static package would serve one prompt length.
|
| 19 |
+
AOTI_SHAPE = os.environ.get("H3_AOTI_SHAPE", "dynamic")
|
| 20 |
+
AOTI_DURATION = int(os.environ.get("H3_AOTI_DURATION", "1500"))
|
| 21 |
+
|
| 22 |
+
# Where a step spends its time. `MiniMaxH3TokenRefinerBlock` is also repeated but runs a handful of text rows.
|
| 23 |
+
BLOCK_CONTAINER = "transformer_blocks"
|
| 24 |
+
|
| 25 |
+
# Height of the AdaLN table baked into the package. `temb` grows from 1 row (step 0, both streams at one noise level)
|
| 26 |
+
# to 2 (from step 1, sigmas diverged), and the block gathers from `3 * rows`, so the row count is part of the compiled
|
| 27 |
+
# shape and is pinned by padding on both sides of the compile. Must match the package's `H3_AOTI_TEMB_ROWS`.
|
| 28 |
+
TEMB_ROWS = int(os.environ.get("H3_AOTI_TEMB_ROWS", "4"))
|
| 29 |
+
|
| 30 |
+
_LOADED: set[int] = set()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def pad_temb(temb, rows: int = TEMB_ROWS):
|
| 34 |
+
"""Grow `temb` to exactly `rows` timestep rows by repeating its last one."""
|
| 35 |
+
present = temb.shape[0]
|
| 36 |
+
if present == rows:
|
| 37 |
+
return temb
|
| 38 |
+
if present > rows:
|
| 39 |
+
raise RuntimeError(
|
| 40 |
+
f"{present} distinct timesteps, but this AoTI package holds at most {rows}. "
|
| 41 |
+
f"Recompile with H3_AOTI_TEMB_ROWS>={present}."
|
| 42 |
+
)
|
| 43 |
+
import torch
|
| 44 |
+
|
| 45 |
+
return torch.cat([temb, temb[-1:].expand(rows - present, *temb.shape[1:])], dim=0)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def width() -> str:
|
| 49 |
+
"""Which transformer these artifacts belong to: `bf16`, `fp8`, `nvfp4`, ..."""
|
| 50 |
+
if explicit := os.environ.get("H3_WIDTH"):
|
| 51 |
+
return explicit.lower()
|
| 52 |
+
try:
|
| 53 |
+
import h3_core
|
| 54 |
+
|
| 55 |
+
return h3_core.WIDTH
|
| 56 |
+
except Exception:
|
| 57 |
+
return "bf16"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def artifact_key() -> str | None:
|
| 61 |
+
"""`<width>/torch<X.Y>/sm<cc>/<shape>` of the card this process is on, or `None` when there is no CUDA."""
|
| 62 |
+
try:
|
| 63 |
+
import torch
|
| 64 |
+
|
| 65 |
+
torch_version = ".".join(torch.__version__.split(".")[:2])
|
| 66 |
+
major, minor = torch.cuda.get_device_capability()
|
| 67 |
+
except Exception:
|
| 68 |
+
return None
|
| 69 |
+
return f"{width()}/torch{torch_version}/sm{major}{minor}/{AOTI_SHAPE}"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def status() -> str:
|
| 73 |
+
return (
|
| 74 |
+
f"AoTI **on** · `{AOTI_REPO}` ({AOTI_REPO_TYPE}) · shape `{AOTI_SHAPE}`"
|
| 75 |
+
if AOTI
|
| 76 |
+
else "AoTI **off** (`H3_AOTI=1` to load compiled blocks)"
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def patch_blocks(transformer, package_dir) -> None:
|
| 81 |
+
"""Point all 50 blocks at the one compiled package, binding each block's own weights on its first call.
|
| 82 |
+
|
| 83 |
+
`spaces.aoti_load_from_package_dir` with two changes. Weights are read on the first forward rather than at patch
|
| 84 |
+
time, because this runs at startup and `Module.to` later rebinds `param.data` to fresh CUDA tensors. And `temb` is
|
| 85 |
+
padded to the height the package was exported with — see `TEMB_ROWS`.
|
| 86 |
+
"""
|
| 87 |
+
from spaces.zero.torch.aoti import LazyAOTIModel, _shallow_clone_module
|
| 88 |
+
from torch._functorch._aot_autograd.subclass_parametrization import unwrap_tensor_subclass_parameters
|
| 89 |
+
|
| 90 |
+
# `LazyAOTIModel` binds constants by name and silently keeps what it cannot match, which is a SIGSEGV rather than
|
| 91 |
+
# an error. The patch resolves anonymous names through the compile side's sidecar and raises if it still cannot.
|
| 92 |
+
try:
|
| 93 |
+
from spaces_constant_binding_patch import apply_spaces_constant_binding_patch
|
| 94 |
+
|
| 95 |
+
apply_spaces_constant_binding_patch()
|
| 96 |
+
except ImportError:
|
| 97 |
+
print("[h3-aoti] spaces_constant_binding_patch.py is missing; an unbindable constant would segfault", flush=True)
|
| 98 |
+
|
| 99 |
+
model = LazyAOTIModel(Path(package_dir) / "submodules" / BLOCK_CONTAINER / "package.pt2")
|
| 100 |
+
|
| 101 |
+
for block in getattr(transformer, BLOCK_CONTAINER):
|
| 102 |
+
bound: dict = {}
|
| 103 |
+
|
| 104 |
+
def forward(hidden_states, temb, *rest, _block=block, _bound=bound):
|
| 105 |
+
first = not _bound
|
| 106 |
+
if first:
|
| 107 |
+
clone = _shallow_clone_module(_block)
|
| 108 |
+
unwrap_tensor_subclass_parameters(clone)
|
| 109 |
+
_bound["weights"] = clone.state_dict()
|
| 110 |
+
return model(_bound["weights"], first, hidden_states, pad_temb(temb), *rest)
|
| 111 |
+
|
| 112 |
+
block.forward = forward
|
| 113 |
+
print(f"[h3-aoti] {len(getattr(transformer, BLOCK_CONTAINER))} blocks patched (temb padded to {TEMB_ROWS})", flush=True)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def maybe_load(transformer) -> None:
|
| 117 |
+
"""Patch the block stack with its compiled package, or leave it eager. Safe to call at **startup**.
|
| 118 |
+
|
| 119 |
+
Off unless `H3_AOTI=1`, and anything that does not line up — another card, another torch, no `spaces` AoTI
|
| 120 |
+
helpers, no published package — falls back to eager with one line rather than raising or segfaulting. Nothing here
|
| 121 |
+
touches a GPU: the download is CPU work and the `.pt2` is not opened until the first forward.
|
| 122 |
+
"""
|
| 123 |
+
if not AOTI or id(transformer) in _LOADED:
|
| 124 |
+
return
|
| 125 |
+
|
| 126 |
+
key = artifact_key()
|
| 127 |
+
if key is None:
|
| 128 |
+
print("[h3-aoti] no CUDA device visible; running eager", flush=True)
|
| 129 |
+
return
|
| 130 |
+
if key != AOTI_KEY:
|
| 131 |
+
print(f"[h3-aoti] this card wants `{key}`, only `{AOTI_KEY}` is published; running eager", flush=True)
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
from huggingface_hub import snapshot_download
|
| 136 |
+
from spaces.zero.torch.aoti import LazyAOTIModel # noqa: F401
|
| 137 |
+
except Exception as error:
|
| 138 |
+
print(f"[h3-aoti] no AoTI loader here ({type(error).__name__}: {error}); running eager", flush=True)
|
| 139 |
+
return
|
| 140 |
+
|
| 141 |
+
print(f"[h3-aoti] loading {AOTI_REPO}:{key} ...", flush=True)
|
| 142 |
+
try:
|
| 143 |
+
local = snapshot_download(repo_id=AOTI_REPO, repo_type=AOTI_REPO_TYPE, allow_patterns=f"{key}/package/*")
|
| 144 |
+
except Exception as error:
|
| 145 |
+
print(f"[h3-aoti] {AOTI_REPO}:{key} unreachable ({type(error).__name__}: {error}); running eager", flush=True)
|
| 146 |
+
return
|
| 147 |
+
package_dir = Path(local) / key / "package"
|
| 148 |
+
if not package_dir.is_dir():
|
| 149 |
+
print(f"[h3-aoti] no package at `{AOTI_REPO}:{key}/package`; running eager", flush=True)
|
| 150 |
+
return
|
| 151 |
+
|
| 152 |
+
patch_blocks(transformer, package_dir)
|
| 153 |
+
_LOADED.add(id(transformer))
|
| 154 |
+
print(f"[h3-aoti] compiled blocks in place (temb padded to {TEMB_ROWS} rows)", flush=True)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def export_block(pipe, height: int, width: int, num_frames: int, prompt: str):
|
| 158 |
+
"""Capture one block call out of a real request and export it with a dynamic sequence dimension.
|
| 159 |
+
|
| 160 |
+
Runs on the GPU, after the transformer has been quantized and moved there: a package compiled for one
|
| 161 |
+
quantization mode is meaningless for another.
|
| 162 |
+
"""
|
| 163 |
+
import torch
|
| 164 |
+
import spaces
|
| 165 |
+
|
| 166 |
+
import h3_core as h3
|
| 167 |
+
|
| 168 |
+
transformer = h3.transformer_of(pipe)
|
| 169 |
+
blocks = getattr(transformer, BLOCK_CONTAINER)
|
| 170 |
+
|
| 171 |
+
# Keep the widest `temb` over a short real run rather than `spaces.aoti_capture`'s first call, which is the
|
| 172 |
+
# 1-row one — see `TEMB_ROWS`.
|
| 173 |
+
original_forward = blocks[0].forward
|
| 174 |
+
widest = {"args": (), "kwargs": {}, "rows": -1}
|
| 175 |
+
seen = []
|
| 176 |
+
|
| 177 |
+
def recording(*args, **kwargs):
|
| 178 |
+
rows = int(args[1].shape[0]) if len(args) > 1 and hasattr(args[1], "shape") else -1
|
| 179 |
+
seen.append(rows)
|
| 180 |
+
if rows > widest["rows"]:
|
| 181 |
+
widest.update(args=args, kwargs=kwargs, rows=rows)
|
| 182 |
+
return original_forward(*args, **kwargs)
|
| 183 |
+
|
| 184 |
+
blocks[0].forward = recording
|
| 185 |
+
try:
|
| 186 |
+
pipe(
|
| 187 |
+
prompt=prompt,
|
| 188 |
+
height=height,
|
| 189 |
+
width=width,
|
| 190 |
+
num_frames=num_frames,
|
| 191 |
+
num_inference_steps=int(os.environ.get("H3_AOTI_CAPTURE_STEPS", "4")),
|
| 192 |
+
generator=torch.Generator("cpu").manual_seed(42),
|
| 193 |
+
)
|
| 194 |
+
finally:
|
| 195 |
+
blocks[0].forward = original_forward
|
| 196 |
+
call = type("Captured", (), widest)
|
| 197 |
+
if not call.args:
|
| 198 |
+
raise RuntimeError("Nothing was captured — the transformer block was never called.")
|
| 199 |
+
print(f"[h3-aoti] temb rows seen: {sorted(set(seen))}; exporting with {TEMB_ROWS} (padded)", flush=True)
|
| 200 |
+
|
| 201 |
+
# `block(hidden_states, temb, adaln_indices, rotary_emb, attention_mask)`, `attention_mask` being `None` for the
|
| 202 |
+
# padless sequences these pipelines build. Only the sequence is dynamic: `torch.export` specializes size-1
|
| 203 |
+
# dimensions unconditionally, so a `Dim` on `temb`'s rows cannot be expressed at all.
|
| 204 |
+
if AOTI_SHAPE == "dynamic":
|
| 205 |
+
sequence = torch.export.Dim("sequence", min=2048, max=262144)
|
| 206 |
+
dynamic_shapes = ({1: sequence}, None, {0: sequence}, ({0: sequence}, {0: sequence}), None)
|
| 207 |
+
dynamic_shapes = dynamic_shapes[: len(call.args)]
|
| 208 |
+
else:
|
| 209 |
+
dynamic_shapes = None
|
| 210 |
+
|
| 211 |
+
args = (call.args[0], pad_temb(call.args[1]), *call.args[2:])
|
| 212 |
+
|
| 213 |
+
# Export the **live** block, non-strict. A shallow clone under non-strict tracing lifts every weight twice — once
|
| 214 |
+
# named, once as an anonymous `CONSTANT_TENSOR` aliasing it — and the loader binds by name, so the compiled block
|
| 215 |
+
# dereferences constants nobody set. The clone is only for flattening tensor-subclass parameters, which inductor's
|
| 216 |
+
# constant handling cannot wrap back into a `Parameter`, and it needs `strict=True`.
|
| 217 |
+
from spaces.zero.torch.aoti import _shallow_clone_module
|
| 218 |
+
from torch._functorch._aot_autograd.subclass_parametrization import unwrap_tensor_subclass_parameters
|
| 219 |
+
|
| 220 |
+
subclassed = sorted({type(p).__name__ for p in blocks[0].parameters()} - {"Parameter"})
|
| 221 |
+
if subclassed:
|
| 222 |
+
block = _shallow_clone_module(blocks[0])
|
| 223 |
+
unwrap_tensor_subclass_parameters(block)
|
| 224 |
+
strict = True
|
| 225 |
+
print(f"[h3-aoti] tensor-subclass parameters {subclassed}: exporting a flattened clone, strict=True", flush=True)
|
| 226 |
+
else:
|
| 227 |
+
block = blocks[0]
|
| 228 |
+
strict = False
|
| 229 |
+
print("[h3-aoti] plain parameters: exporting the live block, non-strict", flush=True)
|
| 230 |
+
|
| 231 |
+
# `torch.export` only gives a lifted tensor a real FQN when it is a registered parameter or buffer; a plain
|
| 232 |
+
# attribute becomes an anonymous constant the loader can never match. Only ever on the clone, since this
|
| 233 |
+
# re-registers attributes and the live block is what the eager path runs.
|
| 234 |
+
if block is not blocks[0]:
|
| 235 |
+
try:
|
| 236 |
+
from spaces_constant_binding_patch import register_loose_tensors
|
| 237 |
+
|
| 238 |
+
if loose := register_loose_tensors(block):
|
| 239 |
+
print(f"[h3-aoti] re-registered {len(loose)} loose tensors as buffers: {loose[:6]}", flush=True)
|
| 240 |
+
except ImportError:
|
| 241 |
+
pass
|
| 242 |
+
|
| 243 |
+
print(f"[h3-aoti] exporting {type(blocks[0]).__name__}, shapes={AOTI_SHAPE}, strict={strict} ...", flush=True)
|
| 244 |
+
try:
|
| 245 |
+
exported = torch.export.export(block, args, call.kwargs or None, dynamic_shapes=dynamic_shapes, strict=strict)
|
| 246 |
+
except Exception as error:
|
| 247 |
+
if not strict:
|
| 248 |
+
raise
|
| 249 |
+
print(f"[h3-aoti] strict export failed ({type(error).__name__}: {error}); retrying non-strict", flush=True)
|
| 250 |
+
exported = torch.export.export(block, args, call.kwargs or None, dynamic_shapes=dynamic_shapes)
|
| 251 |
+
|
| 252 |
+
anonymous = [
|
| 253 |
+
spec.target for spec in exported.graph_signature.input_specs if spec.kind.name == "CONSTANT_TENSOR"
|
| 254 |
+
]
|
| 255 |
+
if anonymous:
|
| 256 |
+
print(
|
| 257 |
+
f"[h3-aoti] WARNING {len(anonymous)} constants lifted anonymously: {anonymous[:6]}. The loader binds by "
|
| 258 |
+
f"name, so `compile_and_save` writes the alias sidecar and `patch_blocks` raises rather than segfaulting.",
|
| 259 |
+
flush=True,
|
| 260 |
+
)
|
| 261 |
+
return exported
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def compile_and_save(exported_program, destination: str | os.PathLike[str]) -> Path:
|
| 265 |
+
"""Inductor-compile the exported block into `<destination>/package/submodules/transformer_blocks/package.pt2`.
|
| 266 |
+
|
| 267 |
+
That layout is what `aoti_load_from_package_dir` walks, resolving the submodule name to the transformer's
|
| 268 |
+
`transformer_blocks` `ModuleList` and patching every block in it with this one package.
|
| 269 |
+
"""
|
| 270 |
+
import spaces
|
| 271 |
+
|
| 272 |
+
package_dir = Path(destination) / "package"
|
| 273 |
+
print("[h3-aoti] inductor compile (minutes) ...", flush=True)
|
| 274 |
+
spaces.aoti_compile_and_save(package_dir, exported_program, submodule=BLOCK_CONTAINER)
|
| 275 |
+
|
| 276 |
+
# The compiled artifact drops a constant's FQN when the export lifted it anonymously; the `ExportedProgram` still
|
| 277 |
+
# has the real names, so record the mapping for the loader while it is available.
|
| 278 |
+
try:
|
| 279 |
+
from spaces_constant_binding_patch import write_constant_aliases
|
| 280 |
+
|
| 281 |
+
if sidecar := write_constant_aliases(package_dir, exported_program, submodule=BLOCK_CONTAINER):
|
| 282 |
+
print(f"[h3-aoti] constant alias sidecar written: {sidecar.name}", flush=True)
|
| 283 |
+
except ImportError:
|
| 284 |
+
pass
|
| 285 |
+
|
| 286 |
+
files = sorted(str(path.relative_to(package_dir)) for path in package_dir.rglob("*") if path.is_file())
|
| 287 |
+
print(f"[h3-aoti] package written: {files}", flush=True)
|
| 288 |
+
return package_dir
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def upload(package_dir: str | os.PathLike[str], key: str) -> str:
|
| 292 |
+
"""Push the package under its `<width>/torch<X.Y>/sm<cc>/<shape>` key. CPU work — never inside GPU time."""
|
| 293 |
+
from huggingface_hub import HfApi
|
| 294 |
+
|
| 295 |
+
token = os.environ.get("HF_TOKEN")
|
| 296 |
+
if not token:
|
| 297 |
+
raise RuntimeError("`HF_TOKEN` is needed to push the AoTI package.")
|
| 298 |
+
api = HfApi(token=token)
|
| 299 |
+
api.create_repo(repo_id=AOTI_REPO, repo_type=AOTI_REPO_TYPE, private=False, exist_ok=True)
|
| 300 |
+
api.upload_folder(
|
| 301 |
+
folder_path=str(package_dir),
|
| 302 |
+
path_in_repo=f"{key}/package",
|
| 303 |
+
repo_id=AOTI_REPO,
|
| 304 |
+
repo_type=AOTI_REPO_TYPE,
|
| 305 |
+
commit_message=f"AoTI package for {key}",
|
| 306 |
+
)
|
| 307 |
+
return f"https://huggingface.co/{'datasets/' if AOTI_REPO_TYPE == 'dataset' else ''}{AOTI_REPO}/tree/main/{key}"
|
h3_lora.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Turbo LoRA support for the diffusers MiniMax-H3 transformer: two 4-step LoRAs, one fold mechanism.
|
| 2 |
+
|
| 3 |
+
Both LoRAs are applied by folding `scale * (lora_B @ lora_A)` into the bf16 weights rather than as runtime wrappers,
|
| 4 |
+
because the AoTI block package (`h3_aoti`) reads each block's live weights and a wrapper module would be invisible
|
| 5 |
+
to it. Deltas are computed in float32 and round once on the way back into bf16. The low-rank factors of every loaded
|
| 6 |
+
LoRA stay resident, so the active one can be switched per request (`set_active`) — unfold the old, fold the new, in
|
| 7 |
+
place, through one bf16 rounding.
|
| 8 |
+
|
| 9 |
+
The two supported LoRAs ship in different layouts:
|
| 10 |
+
|
| 11 |
+
* `larry` (`larryvrh/MiniMax-H3-Turbo-Lora`) targets the *reference* (ComfyUI) module tree — `blocks.N.attn.qkv_proj`,
|
| 12 |
+
`blocks.N.mlp.fc1`, `token_refiner.blocks.N`, `final_layer.adaln_proj.linear` — with `alpha == rank` (scale 1).
|
| 13 |
+
Each delta gets the same transform the base weights got in the diffusers conversion
|
| 14 |
+
(`scripts/convert_minimax_h3_to_diffusers.py`, huggingface/diffusers#14371): fused-QKV row thirds onto
|
| 15 |
+
`attn.to_q/k/v`, the `SwiGLU` gate/value swap onto `ff.net.0.proj`, `fc2` -> `ff.net.2`,
|
| 16 |
+
`blocks.` -> `transformer_blocks.`, `token_refiner.blocks.` -> `token_refiner.refiner_blocks.`,
|
| 17 |
+
`final_layer.adaln_proj.linear` -> `norm_out.linear`. The row transforms are applied to `lora_B` directly
|
| 18 |
+
(rows of `B @ A` are rows of `B`), so no full delta is ever materialized at load.
|
| 19 |
+
|
| 20 |
+
* `lightx` (`lightx2v/Minimax-h3-Turbo`) is a PEFT checkpoint against the diffusers tree itself —
|
| 21 |
+
`transformer_blocks.N.attn.to_q.lora_A.default.weight` and friends — rank 128, `alpha == 8`, so the fold scale is
|
| 22 |
+
`8 / 128 = 0.0625` (matching `set_adapters(weights=1.0)` in their inference script). Keys map name-for-name.
|
| 23 |
+
|
| 24 |
+
`H3_LORA` selects the larry file (`off` skips loading it), `H3_LIGHTX=off` skips lightx, `H3_LORA_DEFAULT` picks
|
| 25 |
+
which set starts folded, and `H3_LORA_STRENGTH` is the larry card's sharpness/artifact dial.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
from __future__ import annotations
|
| 29 |
+
|
| 30 |
+
import os
|
| 31 |
+
|
| 32 |
+
import torch
|
| 33 |
+
|
| 34 |
+
LARRY_REPO = os.environ.get("H3_LORA_REPO", "larryvrh/MiniMax-H3-Turbo-Lora")
|
| 35 |
+
# The recommended default per the model card: ckpt850 EMA (final checkpoint of the round, sharp at 4 steps).
|
| 36 |
+
LARRY_FILE = os.environ.get("H3_LORA", "minimax_h3_turbo_4step_ema_ckpt850.safetensors")
|
| 37 |
+
LIGHTX_REPO = os.environ.get("H3_LIGHTX_REPO", "lightx2v/Minimax-h3-Turbo")
|
| 38 |
+
LIGHTX_FILE = os.environ.get("H3_LIGHTX_FILE", "minimax_h3_fl2v_turbo_4step_v0.1.safetensors")
|
| 39 |
+
LIGHTX_ALPHA = 8
|
| 40 |
+
# The card's sharpness/artifact dial for the larry LoRA: >1 against blurry ghosting/smear, <1 against grain.
|
| 41 |
+
LARRY_STRENGTH = float(os.environ.get("H3_LORA_STRENGTH", "1.0"))
|
| 42 |
+
DEFAULT_LORA = os.environ.get("H3_LORA_DEFAULT", "larry")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _larry_targets(name: str, b: torch.Tensor, inner_dim: int) -> list[tuple[str, torch.Tensor]]:
|
| 46 |
+
"""Map one reference-tree base name and its `lora_B` onto diffusers parameter key + row-transformed B."""
|
| 47 |
+
if name.startswith("token_refiner.blocks."):
|
| 48 |
+
target = name.replace("token_refiner.blocks.", "token_refiner.refiner_blocks.", 1)
|
| 49 |
+
elif name.startswith("blocks."):
|
| 50 |
+
target = name.replace("blocks.", "transformer_blocks.", 1)
|
| 51 |
+
else:
|
| 52 |
+
target = name
|
| 53 |
+
target = target.replace("final_layer.adaln_proj.linear", "norm_out.linear")
|
| 54 |
+
|
| 55 |
+
if target.endswith(".attn.qkv_proj"):
|
| 56 |
+
prefix = target.removesuffix("qkv_proj")
|
| 57 |
+
return [
|
| 58 |
+
(f"{prefix}to_{kind}.weight", part.contiguous())
|
| 59 |
+
for kind, part in zip(("q", "k", "v"), b.split(inner_dim, dim=0))
|
| 60 |
+
]
|
| 61 |
+
if target.endswith(".mlp.fc1"):
|
| 62 |
+
gate, value = b.chunk(2, dim=0)
|
| 63 |
+
return [(target.replace(".mlp.fc1", ".ff.net.0.proj") + ".weight", torch.cat([value, gate]).contiguous())]
|
| 64 |
+
if target.endswith(".mlp.fc2"):
|
| 65 |
+
return [(target.replace(".mlp.fc2", ".ff.net.2") + ".weight", b)]
|
| 66 |
+
if target.endswith(".attn.out_proj"):
|
| 67 |
+
return [(target.replace(".attn.out_proj", ".attn.to_out.0") + ".weight", b)]
|
| 68 |
+
# `adaln_proj.linear` (block-level and the final `norm_out.linear`): identical row layout on both sides.
|
| 69 |
+
return [(target + ".weight", b)]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _load_larry(inner_dim: int) -> dict:
|
| 73 |
+
from huggingface_hub import hf_hub_download
|
| 74 |
+
from safetensors.torch import load_file
|
| 75 |
+
|
| 76 |
+
lora = load_file(hf_hub_download(LARRY_REPO, LARRY_FILE))
|
| 77 |
+
bases = sorted({key.rsplit(".lora_", 1)[0] for key in lora})
|
| 78 |
+
entries = []
|
| 79 |
+
for name in bases:
|
| 80 |
+
a = lora[f"{name}.lora_A.weight"]
|
| 81 |
+
b = lora[f"{name}.lora_B.weight"]
|
| 82 |
+
entries.extend((key, a, b_part) for key, b_part in _larry_targets(name, b, inner_dim))
|
| 83 |
+
return {
|
| 84 |
+
"label": f"{LARRY_REPO}/{LARRY_FILE}",
|
| 85 |
+
"scale": LARRY_STRENGTH, # alpha == rank, so the base scale is 1
|
| 86 |
+
"entries": entries,
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _load_lightx() -> dict:
|
| 91 |
+
from huggingface_hub import hf_hub_download
|
| 92 |
+
from safetensors.torch import load_file
|
| 93 |
+
|
| 94 |
+
lora = load_file(hf_hub_download(LIGHTX_REPO, LIGHTX_FILE))
|
| 95 |
+
suffix_a, suffix_b = ".lora_A.default.weight", ".lora_B.default.weight"
|
| 96 |
+
bases = sorted({key[: -len(suffix_a)] for key in lora if key.endswith(suffix_a)})
|
| 97 |
+
ranks = {lora[f"{name}{suffix_a}"].shape[0] for name in bases}
|
| 98 |
+
if len(ranks) != 1:
|
| 99 |
+
raise ValueError(f"Mixed LoRA ranks in {LIGHTX_FILE}: {sorted(ranks)}")
|
| 100 |
+
entries = [(f"{name}.weight", lora[f"{name}{suffix_a}"], lora[f"{name}{suffix_b}"]) for name in bases]
|
| 101 |
+
return {
|
| 102 |
+
"label": f"{LIGHTX_REPO}/{LIGHTX_FILE}",
|
| 103 |
+
"scale": LIGHTX_ALPHA / ranks.pop(),
|
| 104 |
+
"entries": entries,
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _apply(entries, params, sign: float) -> None:
|
| 109 |
+
for key, a, b in entries:
|
| 110 |
+
param = params.get(key)
|
| 111 |
+
if param is None:
|
| 112 |
+
raise KeyError(f"LoRA target `{key}` not found in the transformer")
|
| 113 |
+
delta = sign * (b.to(torch.float32) @ a.to(torch.float32))
|
| 114 |
+
param.data = (param.data.float() + delta.to(param.device)).to(param.dtype)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def available() -> list[str]:
|
| 118 |
+
"""The LoRA sets that were loaded at startup, plus `off`."""
|
| 119 |
+
state = getattr(_PIPE_TRANSFORMER, "_lora_state", None) if _PIPE_TRANSFORMER is not None else None
|
| 120 |
+
return sorted(state["sets"]) + ["off"] if state else ["off"]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
_PIPE_TRANSFORMER = None
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def apply_lora(transformer) -> str | None:
|
| 127 |
+
"""Load every enabled LoRA set, fold the default one into `transformer`, and stash the factors for per-request
|
| 128 |
+
switching. Returns a status line, or `None` when everything is disabled."""
|
| 129 |
+
global _PIPE_TRANSFORMER
|
| 130 |
+
_PIPE_TRANSFORMER = transformer
|
| 131 |
+
|
| 132 |
+
inner_dim = transformer.config.num_attention_heads * transformer.config.attention_head_dim
|
| 133 |
+
sets = {}
|
| 134 |
+
if LARRY_FILE.lower() not in ("", "off", "none"):
|
| 135 |
+
sets["larry"] = _load_larry(inner_dim)
|
| 136 |
+
if os.environ.get("H3_LIGHTX", "on").lower() not in ("", "off", "none"):
|
| 137 |
+
sets["lightx"] = _load_lightx()
|
| 138 |
+
if not sets:
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
active = DEFAULT_LORA if DEFAULT_LORA in sets else sorted(sets)[0]
|
| 142 |
+
params = dict(transformer.named_parameters())
|
| 143 |
+
_apply(sets[active]["entries"], params, sets[active]["scale"])
|
| 144 |
+
transformer._lora_state = {"active": active, "sets": sets}
|
| 145 |
+
return (
|
| 146 |
+
f"LoRAs loaded: "
|
| 147 |
+
+ ", ".join(f"`{name}` ({spec['label']}, {len(spec['entries'])} weights)" for name, spec in sets.items())
|
| 148 |
+
+ f" · active `{active}`"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def set_active(transformer, name: str) -> str:
|
| 153 |
+
"""Switch the folded LoRA in place. No-op when the state already matches. Returns the active set."""
|
| 154 |
+
state = getattr(transformer, "_lora_state", None)
|
| 155 |
+
if state is None:
|
| 156 |
+
return "off"
|
| 157 |
+
name = name if name in state["sets"] else "off"
|
| 158 |
+
if state["active"] == name:
|
| 159 |
+
return name
|
| 160 |
+
params = dict(transformer.named_parameters())
|
| 161 |
+
if state["active"] != "off":
|
| 162 |
+
old = state["sets"][state["active"]]
|
| 163 |
+
_apply(old["entries"], params, -old["scale"])
|
| 164 |
+
if name != "off":
|
| 165 |
+
_apply(state["sets"][name]["entries"], params, state["sets"][name]["scale"])
|
| 166 |
+
state["active"] = name
|
| 167 |
+
return name
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def set_enabled(transformer, enabled: bool) -> bool:
|
| 171 |
+
"""Backwards-compatible boolean toggle over the default set."""
|
| 172 |
+
return set_active(transformer, DEFAULT_LORA if enabled else "off") != "off"
|
h3_split_blocks.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The halves of a **split** MiniMax-H3 deployment, for both of its checkpoint partitions.
|
| 2 |
+
|
| 3 |
+
MiniMax-H3 is 195.9 GiB in bfloat16 and a ZeroGPU Space is evicted at 150 GB of storage, so `MiniMaxH3Blocks` is cut
|
| 4 |
+
at its `text_encoder` step: the 62.14 GiB Qwen3-VL runs in the conditioner Space, everything else in a generator
|
| 5 |
+
Space, and `prompt_embeds` + `text_token_tags` is the whole wire format between them.
|
| 6 |
+
|
| 7 |
+
`resize` / `setup` run on **both** sides: they own no pretrained component, and each half needs the canvas and the
|
| 8 |
+
prepared keyframes or normalized references. Both conditioner halves also return the resolved `height` / `width` /
|
| 9 |
+
`num_frames`, which the generating half pins rather than re-deriving.
|
| 10 |
+
|
| 11 |
+
Two things the blocks leave to the caller: a keyframe reaches them EXIF-transposed and in RGB, and the `t2va` / `fl2va`
|
| 12 |
+
frame count is aligned to `17 * n + 5` before the call, since that arithmetic lives on the denoising side of the cut.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from diffusers.modular_pipelines.minimax_h3.before_encoder import MiniMaxH3Ref2VASetupStep
|
| 16 |
+
from diffusers.modular_pipelines.minimax_h3.decoders import MiniMaxH3AfterDenoiseStep
|
| 17 |
+
from diffusers.modular_pipelines.minimax_h3.encoders import (
|
| 18 |
+
MiniMaxH3Ref2VAReferenceEncoderStep,
|
| 19 |
+
MiniMaxH3Ref2VATextEncoderStep,
|
| 20 |
+
MiniMaxH3TextEncoderStep,
|
| 21 |
+
)
|
| 22 |
+
from diffusers.modular_pipelines.minimax_h3.modular_blocks_minimax_h3 import (
|
| 23 |
+
MiniMaxH3AutoKeyframeVaeEncoderStep,
|
| 24 |
+
MiniMaxH3AutoResizeStep,
|
| 25 |
+
MiniMaxH3CoreDenoiseStep,
|
| 26 |
+
MiniMaxH3DecodeStep,
|
| 27 |
+
MiniMaxH3Ref2VACoreDenoiseStep,
|
| 28 |
+
_generation_outputs,
|
| 29 |
+
)
|
| 30 |
+
from diffusers.modular_pipelines.modular_pipeline import SequentialPipelineBlocks
|
| 31 |
+
from diffusers.modular_pipelines.modular_pipeline_utils import OutputParam
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _wire_outputs(num_frames: bool = True) -> list[OutputParam]:
|
| 35 |
+
"""The wire format of the split. `num_frames` is declared by the `ref2va` half alone, whose setup resolves one."""
|
| 36 |
+
return [
|
| 37 |
+
OutputParam.template("prompt_embeds"),
|
| 38 |
+
OutputParam("text_token_tags", description="The per-row modality tag of every row of `prompt_embeds`."),
|
| 39 |
+
OutputParam("height", type_hint=int, description="Resolved height of the generated video in pixels."),
|
| 40 |
+
OutputParam("width", type_hint=int, description="Resolved width of the generated video in pixels."),
|
| 41 |
+
*(
|
| 42 |
+
[OutputParam("num_frames", type_hint=int, description="Resolved number of frames, of the form 17 * n + 5.")]
|
| 43 |
+
if num_frames
|
| 44 |
+
else []
|
| 45 |
+
),
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class MiniMaxH3ConditionerBlocks(SequentialPipelineBlocks):
|
| 50 |
+
"""The conditioner half of a split MiniMax-H3: the keyframes on the canvas plus the Qwen3-VL read at layer 50."""
|
| 51 |
+
|
| 52 |
+
model_name = "minimax-h3"
|
| 53 |
+
block_classes = [MiniMaxH3AutoResizeStep, MiniMaxH3TextEncoderStep]
|
| 54 |
+
block_names = ["resize", "text_encoder"]
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def description(self):
|
| 58 |
+
return (
|
| 59 |
+
"The conditioner half of a split MiniMax-H3 deployment: puts the keyframes onto the target canvas and "
|
| 60 |
+
"encodes MiniMax-H3's presentation of the request into the `prompt_embeds` / `text_token_tags` pair the "
|
| 61 |
+
"denoising half consumes. The frame count is the caller's to align."
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
@property
|
| 65 |
+
def outputs(self):
|
| 66 |
+
return _wire_outputs(num_frames=False)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class MiniMaxH3GeneratorBlocks(SequentialPipelineBlocks):
|
| 70 |
+
"""The denoising half of a split MiniMax-H3: `MiniMaxH3Blocks` with its `text_encoder` step removed."""
|
| 71 |
+
|
| 72 |
+
model_name = "minimax-h3"
|
| 73 |
+
block_classes = [
|
| 74 |
+
MiniMaxH3AutoResizeStep,
|
| 75 |
+
MiniMaxH3AutoKeyframeVaeEncoderStep,
|
| 76 |
+
MiniMaxH3CoreDenoiseStep,
|
| 77 |
+
MiniMaxH3AfterDenoiseStep,
|
| 78 |
+
MiniMaxH3DecodeStep,
|
| 79 |
+
]
|
| 80 |
+
block_names = ["resize", "vae_encoder", "denoise", "after_denoise", "decode"]
|
| 81 |
+
|
| 82 |
+
@property
|
| 83 |
+
def description(self):
|
| 84 |
+
return (
|
| 85 |
+
"The denoising half of a split MiniMax-H3 deployment: the `t2va` / `fl2va` branch of `MiniMaxH3Blocks` "
|
| 86 |
+
"without its text-encoder step, so `prompt_embeds` and `text_token_tags` come in as inputs and the "
|
| 87 |
+
"62.14 GiB Qwen3-VL conditioner is never loaded here."
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def outputs(self):
|
| 92 |
+
return _generation_outputs()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class MiniMaxH3Ref2VAConditionerBlocks(SequentialPipelineBlocks):
|
| 96 |
+
"""The conditioner half of a split `ref2va`: the resolved plan plus the Qwen3-VL read at its 50th layer.
|
| 97 |
+
|
| 98 |
+
Component for component this is `MiniMaxH3ConditionerBlocks`, so one conditioner Space serves both partitions.
|
| 99 |
+
What differs is the presentation: `ref2va` prepends a label per reference and a vision block per image and per
|
| 100 |
+
merged video frame pair, so the references themselves have to reach this half.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
model_name = "minimax-h3"
|
| 104 |
+
block_classes = [MiniMaxH3Ref2VASetupStep, MiniMaxH3Ref2VATextEncoderStep]
|
| 105 |
+
block_names = ["setup", "text_encoder"]
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def description(self):
|
| 109 |
+
return (
|
| 110 |
+
"The conditioner half of a split MiniMax-H3 `ref2va` deployment: resolves the request plan (canvas, frame "
|
| 111 |
+
"count, references normalized onto MiniMax-H3's own rates and resolutions) and encodes MiniMax-H3's "
|
| 112 |
+
"presentation of it into the `prompt_embeds` / `text_token_tags` pair the denoising half consumes."
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
@property
|
| 116 |
+
def outputs(self):
|
| 117 |
+
return _wire_outputs()
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class MiniMaxH3Ref2VAGeneratorBlocks(SequentialPipelineBlocks):
|
| 121 |
+
"""The denoising half of a split `ref2va`: the `ref2va` branch with its `text_encoder` step removed.
|
| 122 |
+
|
| 123 |
+
`reference_encoder` stays here, next to the two autoencoders it runs: its output shapes are where every reference
|
| 124 |
+
block's geometry in the packed layout comes from.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
model_name = "minimax-h3"
|
| 128 |
+
block_classes = [
|
| 129 |
+
MiniMaxH3Ref2VASetupStep,
|
| 130 |
+
MiniMaxH3Ref2VAReferenceEncoderStep,
|
| 131 |
+
MiniMaxH3Ref2VACoreDenoiseStep,
|
| 132 |
+
MiniMaxH3AfterDenoiseStep,
|
| 133 |
+
MiniMaxH3DecodeStep,
|
| 134 |
+
]
|
| 135 |
+
block_names = ["setup", "reference_encoder", "denoise", "after_denoise", "decode"]
|
| 136 |
+
|
| 137 |
+
@property
|
| 138 |
+
def description(self):
|
| 139 |
+
return (
|
| 140 |
+
"The denoising half of a split MiniMax-H3 `ref2va` deployment: the `ref2va` branch of `MiniMaxH3Blocks` "
|
| 141 |
+
"without its text-encoder step, so `prompt_embeds` and `text_token_tags` come in as inputs and the "
|
| 142 |
+
"62.14 GiB Qwen3-VL conditioner is never loaded here. The transformer is the `transformer_ref` partition."
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def outputs(self):
|
| 147 |
+
return _generation_outputs()
|
index.html
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>MiniMax-H3 Studio</title>
|
| 7 |
+
<style>
|
| 8 |
+
:root {
|
| 9 |
+
--bg: #0b0d10;
|
| 10 |
+
--panel: #12151a;
|
| 11 |
+
--panel-2: #171b21;
|
| 12 |
+
--edge: #23282f;
|
| 13 |
+
--edge-hi: #31383f;
|
| 14 |
+
--text: #e8eaed;
|
| 15 |
+
--dim: #9aa3ad;
|
| 16 |
+
--faint: #5c6670;
|
| 17 |
+
--accent: #f59e0b;
|
| 18 |
+
--accent-dim: #92610a;
|
| 19 |
+
--go: #22c55e;
|
| 20 |
+
--err: #ef4444;
|
| 21 |
+
--mono: "SF Mono", ui-monospace, Menlo, Consolas, monospace;
|
| 22 |
+
}
|
| 23 |
+
* { margin: 0; box-sizing: border-box; }
|
| 24 |
+
body {
|
| 25 |
+
background: var(--bg); color: var(--text);
|
| 26 |
+
font: 14px/1.5 -apple-system, "Segoe UI", Inter, Roboto, sans-serif;
|
| 27 |
+
height: 100vh; display: flex; flex-direction: column; overflow: hidden;
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
/* ---- top bar ---- */
|
| 31 |
+
header {
|
| 32 |
+
display: flex; align-items: center; gap: 14px;
|
| 33 |
+
padding: 0 18px; height: 52px; flex: none;
|
| 34 |
+
background: var(--panel); border-bottom: 1px solid var(--edge);
|
| 35 |
+
}
|
| 36 |
+
.logo { font-weight: 700; letter-spacing: .4px; font-size: 15px; }
|
| 37 |
+
.logo b { color: var(--accent); }
|
| 38 |
+
.logo span { color: var(--faint); font-weight: 400; margin-left: 8px; font-size: 12px; }
|
| 39 |
+
header .links { margin-left: auto; display: flex; gap: 14px; align-items: center; }
|
| 40 |
+
header a { color: var(--dim); text-decoration: none; font-size: 12px; }
|
| 41 |
+
header a:hover { color: var(--text); }
|
| 42 |
+
#status-pill {
|
| 43 |
+
display: flex; align-items: center; gap: 7px;
|
| 44 |
+
font: 11px var(--mono); color: var(--dim);
|
| 45 |
+
border: 1px solid var(--edge); border-radius: 99px; padding: 4px 12px;
|
| 46 |
+
max-width: 46vw; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
| 47 |
+
}
|
| 48 |
+
#status-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); flex: none; animation: pulse 1.2s infinite; }
|
| 49 |
+
#status-pill.ready #status-dot { background: var(--go); animation: none; }
|
| 50 |
+
#status-pill.error #status-dot { background: var(--err); animation: none; }
|
| 51 |
+
@keyframes pulse { 50% { opacity: .35; } }
|
| 52 |
+
|
| 53 |
+
main { flex: 1; display: flex; min-height: 0; }
|
| 54 |
+
|
| 55 |
+
/* ---- control deck ---- */
|
| 56 |
+
aside {
|
| 57 |
+
width: 340px; flex: none; overflow-y: auto;
|
| 58 |
+
background: var(--panel); border-right: 1px solid var(--edge);
|
| 59 |
+
padding: 16px; display: flex; flex-direction: column; gap: 14px;
|
| 60 |
+
}
|
| 61 |
+
.deck-label {
|
| 62 |
+
font: 10px var(--mono); letter-spacing: 1.5px; color: var(--faint);
|
| 63 |
+
text-transform: uppercase; margin-bottom: 6px;
|
| 64 |
+
}
|
| 65 |
+
textarea, select, input[type=number] {
|
| 66 |
+
width: 100%; background: var(--panel-2); color: var(--text);
|
| 67 |
+
border: 1px solid var(--edge); border-radius: 8px;
|
| 68 |
+
padding: 10px 12px; font: 13px/1.5 inherit; resize: vertical;
|
| 69 |
+
}
|
| 70 |
+
textarea:focus, select:focus, input:focus { outline: none; border-color: var(--accent-dim); }
|
| 71 |
+
textarea { min-height: 96px; }
|
| 72 |
+
|
| 73 |
+
.dropzone {
|
| 74 |
+
border: 1.5px dashed var(--edge-hi); border-radius: 8px;
|
| 75 |
+
min-height: 74px; display: flex; align-items: center; justify-content: center;
|
| 76 |
+
color: var(--faint); font-size: 12px; cursor: pointer; position: relative;
|
| 77 |
+
overflow: hidden; text-align: center; padding: 6px; transition: border-color .15s;
|
| 78 |
+
}
|
| 79 |
+
.dropzone:hover, .dropzone.drag { border-color: var(--accent); color: var(--dim); }
|
| 80 |
+
.dropzone img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
|
| 81 |
+
.dropzone .clear {
|
| 82 |
+
position: absolute; top: 4px; right: 6px; z-index: 2; color: #fff;
|
| 83 |
+
background: rgba(0,0,0,.6); border-radius: 4px; padding: 0 6px; font-size: 14px; display: none;
|
| 84 |
+
}
|
| 85 |
+
.dropzone.filled .clear { display: block; }
|
| 86 |
+
.frames-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
| 87 |
+
|
| 88 |
+
.check { display: flex; align-items: center; gap: 8px; color: var(--dim); font-size: 13px; cursor: pointer; }
|
| 89 |
+
.check input { accent-color: var(--accent); }
|
| 90 |
+
|
| 91 |
+
details { border: 1px solid var(--edge); border-radius: 8px; background: var(--panel-2); }
|
| 92 |
+
summary {
|
| 93 |
+
padding: 9px 12px; cursor: pointer; font: 11px var(--mono);
|
| 94 |
+
letter-spacing: 1px; color: var(--dim); text-transform: uppercase; user-select: none;
|
| 95 |
+
}
|
| 96 |
+
details .body { padding: 4px 12px 12px; display: flex; flex-direction: column; gap: 12px; }
|
| 97 |
+
.slider-row { display: flex; justify-content: space-between; font-size: 12px; color: var(--dim); margin-bottom: 2px; }
|
| 98 |
+
.slider-row output { font-family: var(--mono); color: var(--text); }
|
| 99 |
+
input[type=range] { width: 100%; accent-color: var(--accent); }
|
| 100 |
+
|
| 101 |
+
#run {
|
| 102 |
+
margin-top: auto; border: none; border-radius: 8px; padding: 13px;
|
| 103 |
+
background: var(--accent); color: #111; font: 700 14px inherit;
|
| 104 |
+
letter-spacing: .5px; cursor: pointer; transition: filter .15s, opacity .15s;
|
| 105 |
+
}
|
| 106 |
+
#run:hover:not(:disabled) { filter: brightness(1.1); }
|
| 107 |
+
#run:disabled { opacity: .45; cursor: not-allowed; }
|
| 108 |
+
|
| 109 |
+
/* ---- stage ---- */
|
| 110 |
+
section.stage { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
| 111 |
+
.monitor-wrap {
|
| 112 |
+
flex: 1; display: flex; align-items: center; justify-content: center;
|
| 113 |
+
padding: 22px; min-height: 0;
|
| 114 |
+
background: radial-gradient(ellipse at 50% 40%, #10141a 0%, var(--bg) 75%);
|
| 115 |
+
}
|
| 116 |
+
.monitor {
|
| 117 |
+
position: relative; max-width: 100%; max-height: 100%;
|
| 118 |
+
border: 1px solid var(--edge-hi); border-radius: 10px; overflow: hidden;
|
| 119 |
+
background: #000; box-shadow: 0 24px 70px rgba(0,0,0,.55);
|
| 120 |
+
display: flex; align-items: center; justify-content: center;
|
| 121 |
+
}
|
| 122 |
+
.monitor video { display: block; max-width: 100%; max-height: calc(100vh - 220px); }
|
| 123 |
+
.monitor .placeholder {
|
| 124 |
+
position: absolute; inset: 0; display: flex; flex-direction: column;
|
| 125 |
+
align-items: center; justify-content: center; gap: 10px; color: var(--faint);
|
| 126 |
+
font: 12px var(--mono); letter-spacing: 1px; text-align: center; padding: 20px;
|
| 127 |
+
}
|
| 128 |
+
.monitor .placeholder .rec { width: 46px; height: 46px; border: 1.5px solid var(--edge-hi); border-radius: 50%;
|
| 129 |
+
display: flex; align-items: center; justify-content: center; }
|
| 130 |
+
.monitor .placeholder .rec::after { content: ""; width: 14px; height: 14px; border-radius: 50%; background: var(--edge-hi); }
|
| 131 |
+
.monitor.hidden-video video { display: none; }
|
| 132 |
+
|
| 133 |
+
/* ---- transport / report bar ---- */
|
| 134 |
+
.transport {
|
| 135 |
+
flex: none; border-top: 1px solid var(--edge); background: var(--panel);
|
| 136 |
+
padding: 10px 18px; display: flex; align-items: center; gap: 16px;
|
| 137 |
+
font: 12px var(--mono); color: var(--dim); min-height: 44px;
|
| 138 |
+
}
|
| 139 |
+
#job-state { color: var(--accent); }
|
| 140 |
+
#job-state.done { color: var(--go); }
|
| 141 |
+
#job-state.failed { color: var(--err); }
|
| 142 |
+
#report { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1; }
|
| 143 |
+
#elapsed { color: var(--faint); flex: none; }
|
| 144 |
+
|
| 145 |
+
#bar-track {
|
| 146 |
+
flex: none; width: 180px; height: 6px; border-radius: 3px;
|
| 147 |
+
background: var(--edge); overflow: hidden; position: relative;
|
| 148 |
+
}
|
| 149 |
+
#bar { height: 100%; width: 0%; border-radius: 3px; background: var(--accent); transition: width .4s linear; }
|
| 150 |
+
#bar.indeterminate { width: 40%; animation: slide 1.2s ease-in-out infinite; }
|
| 151 |
+
@keyframes slide { 0% { margin-left: -40%; } 100% { margin-left: 100%; } }
|
| 152 |
+
|
| 153 |
+
#refined-bar {
|
| 154 |
+
flex: none; display: none; border-top: 1px solid var(--edge);
|
| 155 |
+
background: var(--panel-2); padding: 10px 18px; font-size: 12px; color: var(--dim);
|
| 156 |
+
max-height: 110px; overflow-y: auto;
|
| 157 |
+
}
|
| 158 |
+
#refined-bar b { color: var(--faint); font: 10px var(--mono); letter-spacing: 1px; text-transform: uppercase; display: block; margin-bottom: 4px; }
|
| 159 |
+
|
| 160 |
+
.examples { display: flex; flex-direction: column; gap: 6px; }
|
| 161 |
+
.examples button {
|
| 162 |
+
text-align: left; background: var(--panel-2); border: 1px solid var(--edge);
|
| 163 |
+
color: var(--dim); border-radius: 6px; padding: 7px 10px; font-size: 12px; cursor: pointer;
|
| 164 |
+
}
|
| 165 |
+
.examples button:hover { color: var(--text); border-color: var(--edge-hi); }
|
| 166 |
+
|
| 167 |
+
@media (max-width: 860px) {
|
| 168 |
+
body { height: 100dvh; overflow: hidden; }
|
| 169 |
+
main { flex-direction: column; overflow-y: auto; -webkit-overflow-scrolling: touch; }
|
| 170 |
+
|
| 171 |
+
/* Stage first, controls below: the monitor is what a phone user came for. */
|
| 172 |
+
section.stage { order: -1; flex: none; }
|
| 173 |
+
.monitor-wrap { padding: 12px; }
|
| 174 |
+
.monitor video { max-height: 38vh; }
|
| 175 |
+
.monitor .placeholder { position: static; padding: 42px 16px; }
|
| 176 |
+
|
| 177 |
+
aside {
|
| 178 |
+
width: 100%; flex: none; overflow: visible;
|
| 179 |
+
border-right: none; border-top: 1px solid var(--edge);
|
| 180 |
+
padding: 14px 14px 90px; /* room for the sticky run button */
|
| 181 |
+
}
|
| 182 |
+
#run {
|
| 183 |
+
position: sticky; bottom: 12px; z-index: 5;
|
| 184 |
+
padding: 15px; font-size: 15px;
|
| 185 |
+
box-shadow: 0 8px 24px rgba(0,0,0,.5);
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
/* Touch targets + kill iOS auto-zoom on focus (needs >=16px). */
|
| 189 |
+
textarea, select, input[type=number] { font-size: 16px; }
|
| 190 |
+
.dropzone { min-height: 92px; }
|
| 191 |
+
.check { padding: 6px 0; }
|
| 192 |
+
summary { padding: 12px; }
|
| 193 |
+
input[type=range] { height: 28px; }
|
| 194 |
+
|
| 195 |
+
header { padding: 0 12px; gap: 10px; }
|
| 196 |
+
.logo span { display: none; }
|
| 197 |
+
#status-pill { max-width: 38vw; padding: 4px 9px; }
|
| 198 |
+
header .links a { display: none; }
|
| 199 |
+
header .links #status-pill { display: flex; }
|
| 200 |
+
|
| 201 |
+
.transport { flex-wrap: wrap; gap: 8px 12px; padding: 10px 12px; }
|
| 202 |
+
#bar-track { flex: 1 1 100%; order: -1; width: auto; height: 5px; }
|
| 203 |
+
#report { white-space: normal; flex: 1 1 60%; font-size: 11px; }
|
| 204 |
+
#refined-bar { max-height: 80px; }
|
| 205 |
+
}
|
| 206 |
+
@media (max-width: 400px) {
|
| 207 |
+
.frames-row { grid-template-columns: 1fr; }
|
| 208 |
+
}
|
| 209 |
+
</style>
|
| 210 |
+
</head>
|
| 211 |
+
<body>
|
| 212 |
+
|
| 213 |
+
<header>
|
| 214 |
+
<div class="logo">MiniMax-<b>H3</b> Studio<span>video + synchronized soundtrack · 4-step turbo</span></div>
|
| 215 |
+
<div class="links">
|
| 216 |
+
<div id="status-pill"><span id="status-dot"></span><span id="status-text">connecting…</span></div>
|
| 217 |
+
<a href="https://huggingface.co/MiniMaxAI/MiniMax-H3" target="_blank" rel="noopener">model</a>
|
| 218 |
+
<a href="https://huggingface.co/larryvrh/MiniMax-H3-Turbo-Lora" target="_blank" rel="noopener">turbo lora</a>
|
| 219 |
+
</div>
|
| 220 |
+
</header>
|
| 221 |
+
|
| 222 |
+
<main>
|
| 223 |
+
<aside>
|
| 224 |
+
<div>
|
| 225 |
+
<div class="deck-label">Prompt</div>
|
| 226 |
+
<textarea id="prompt" spellcheck="false">A red fox trotting through a snowy pine forest at dawn, snow crunching underfoot</textarea>
|
| 227 |
+
</div>
|
| 228 |
+
<div>
|
| 229 |
+
<div class="deck-label">Turbo LoRA</div>
|
| 230 |
+
<select id="lora"></select>
|
| 231 |
+
</div>
|
| 232 |
+
<label class="check"><input type="checkbox" id="upsample"> Upsample prompt</label>
|
| 233 |
+
|
| 234 |
+
<div>
|
| 235 |
+
<div class="deck-label">Keyframes (optional)</div>
|
| 236 |
+
<div class="frames-row">
|
| 237 |
+
<div class="dropzone" id="dz-first">First frame<span class="clear">×</span></div>
|
| 238 |
+
<div class="dropzone" id="dz-last">Last frame<span class="clear">×</span></div>
|
| 239 |
+
</div>
|
| 240 |
+
</div>
|
| 241 |
+
|
| 242 |
+
<details open>
|
| 243 |
+
<summary>Shot settings</summary>
|
| 244 |
+
<div class="body">
|
| 245 |
+
<div>
|
| 246 |
+
<div class="deck-label">Canvas</div>
|
| 247 |
+
<select id="canvas"></select>
|
| 248 |
+
</div>
|
| 249 |
+
<div>
|
| 250 |
+
<div class="slider-row"><span>Duration</span><output id="duration-out">5 s</output></div>
|
| 251 |
+
<input type="range" id="duration" min="2" max="14" step="1" value="5">
|
| 252 |
+
</div>
|
| 253 |
+
<div>
|
| 254 |
+
<div class="slider-row"><span>Steps</span><output id="steps-out">6</output></div>
|
| 255 |
+
<input type="range" id="steps" min="2" max="40" step="1" value="6">
|
| 256 |
+
</div>
|
| 257 |
+
<div>
|
| 258 |
+
<div class="deck-label">Seed</div>
|
| 259 |
+
<input type="number" id="seed" value="42" step="1">
|
| 260 |
+
</div>
|
| 261 |
+
</div>
|
| 262 |
+
</details>
|
| 263 |
+
|
| 264 |
+
<div>
|
| 265 |
+
<div class="deck-label">Examples</div>
|
| 266 |
+
<div class="examples" id="examples"></div>
|
| 267 |
+
</div>
|
| 268 |
+
|
| 269 |
+
<button id="run">▶ Generate</button>
|
| 270 |
+
</aside>
|
| 271 |
+
|
| 272 |
+
<section class="stage">
|
| 273 |
+
<div class="monitor-wrap">
|
| 274 |
+
<div class="monitor hidden-video" id="monitor">
|
| 275 |
+
<video id="video" controls playsinline></video>
|
| 276 |
+
<div class="placeholder" id="placeholder">
|
| 277 |
+
<div class="rec"></div>
|
| 278 |
+
<div>STANDBY — CUT A PROMPT AND ROLL</div>
|
| 279 |
+
</div>
|
| 280 |
+
</div>
|
| 281 |
+
</div>
|
| 282 |
+
<div id="refined-bar"><b>Upsampled prompt</b><span id="refined"></span></div>
|
| 283 |
+
<div class="transport">
|
| 284 |
+
<span id="job-state">IDLE</span>
|
| 285 |
+
<div id="bar-track"><div id="bar"></div></div>
|
| 286 |
+
<span id="report"></span>
|
| 287 |
+
<span id="elapsed"></span>
|
| 288 |
+
</div>
|
| 289 |
+
</section>
|
| 290 |
+
</main>
|
| 291 |
+
|
| 292 |
+
<input type="file" id="file-first" accept="image/*" hidden>
|
| 293 |
+
<input type="file" id="file-last" accept="image/*" hidden>
|
| 294 |
+
|
| 295 |
+
<script type="module">
|
| 296 |
+
// @gradio/client is REQUIRED here (not plain fetch): it forwards the HF iframe auth headers that ZeroGPU
|
| 297 |
+
// quota handling depends on — without them every booking lands on the pod IP's shared quota.
|
| 298 |
+
import { Client, handle_file } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
|
| 299 |
+
|
| 300 |
+
const $ = (id) => document.getElementById(id);
|
| 301 |
+
const state = { first: null, last: null, busy: false, timer: null };
|
| 302 |
+
|
| 303 |
+
/* ---- config + status ---- */
|
| 304 |
+
fetch("/studio-config").then(r => r.json()).then(cfg => {
|
| 305 |
+
const sel = $("canvas");
|
| 306 |
+
for (const label of cfg.canvases) {
|
| 307 |
+
const o = document.createElement("option");
|
| 308 |
+
o.value = o.textContent = label;
|
| 309 |
+
if (label === cfg.default_canvas) o.selected = true;
|
| 310 |
+
sel.appendChild(o);
|
| 311 |
+
}
|
| 312 |
+
$("duration").min = cfg.min_duration; $("duration").max = cfg.max_duration;
|
| 313 |
+
|
| 314 |
+
const loraSel = $("lora");
|
| 315 |
+
for (const [value, spec] of Object.entries(cfg.loras || { larry: { label: "larry", steps: 6 } })) {
|
| 316 |
+
const o = document.createElement("option");
|
| 317 |
+
o.value = value;
|
| 318 |
+
o.textContent = value === "off" ? "off (base model)" : value;
|
| 319 |
+
o.title = spec.label;
|
| 320 |
+
if (value === cfg.default_lora) o.selected = true;
|
| 321 |
+
loraSel.appendChild(o);
|
| 322 |
+
}
|
| 323 |
+
// Each LoRA has a design point: suggest it on switch (the slider stays free).
|
| 324 |
+
loraSel.addEventListener("change", () => {
|
| 325 |
+
const spec = (cfg.loras || {})[loraSel.value];
|
| 326 |
+
if (spec && spec.steps) { $("steps").value = spec.steps; $("steps-out").textContent = spec.steps; }
|
| 327 |
+
});
|
| 328 |
+
});
|
| 329 |
+
|
| 330 |
+
async function pollStatus() {
|
| 331 |
+
try {
|
| 332 |
+
const s = await (await fetch("/status")).json();
|
| 333 |
+
const pill = $("status-pill");
|
| 334 |
+
$("status-text").textContent = s.status.replace(/[*`]/g, "");
|
| 335 |
+
pill.classList.toggle("ready", s.ready);
|
| 336 |
+
pill.classList.toggle("error", !s.ready && /failed/i.test(s.status));
|
| 337 |
+
if (s.ready) return;
|
| 338 |
+
} catch (e) { /* still booting */ }
|
| 339 |
+
setTimeout(pollStatus, 5000);
|
| 340 |
+
}
|
| 341 |
+
pollStatus();
|
| 342 |
+
|
| 343 |
+
/* ---- sliders ---- */
|
| 344 |
+
const bind = (id, fmt) => $(id).addEventListener("input", e => $(id + "-out").textContent = fmt(e.target.value));
|
| 345 |
+
bind("duration", v => v + " s");
|
| 346 |
+
bind("steps", v => v);
|
| 347 |
+
|
| 348 |
+
/* ---- dropzones ---- */
|
| 349 |
+
function wireDropzone(dzId, inputId, key) {
|
| 350 |
+
const dz = $(dzId), input = $(inputId);
|
| 351 |
+
const set = (file) => {
|
| 352 |
+
if (!file) return;
|
| 353 |
+
state[key] = file;
|
| 354 |
+
const img = document.createElement("img");
|
| 355 |
+
img.src = URL.createObjectURL(file);
|
| 356 |
+
dz.appendChild(img);
|
| 357 |
+
dz.classList.add("filled");
|
| 358 |
+
};
|
| 359 |
+
dz.addEventListener("click", (e) => {
|
| 360 |
+
if (e.target.classList.contains("clear")) {
|
| 361 |
+
state[key] = null; dz.classList.remove("filled");
|
| 362 |
+
dz.querySelector("img")?.remove(); input.value = "";
|
| 363 |
+
} else input.click();
|
| 364 |
+
});
|
| 365 |
+
input.addEventListener("change", () => set(input.files[0]));
|
| 366 |
+
dz.addEventListener("dragover", e => { e.preventDefault(); dz.classList.add("drag"); });
|
| 367 |
+
dz.addEventListener("dragleave", () => dz.classList.remove("drag"));
|
| 368 |
+
dz.addEventListener("drop", e => { e.preventDefault(); dz.classList.remove("drag"); set(e.dataTransfer.files[0]); });
|
| 369 |
+
}
|
| 370 |
+
wireDropzone("dz-first", "file-first", "first");
|
| 371 |
+
wireDropzone("dz-last", "file-last", "last");
|
| 372 |
+
|
| 373 |
+
/* ---- examples ---- */
|
| 374 |
+
const EXAMPLES = [
|
| 375 |
+
["A red fox trotting through a snowy pine forest at dawn, snow crunching underfoot", "1344x768 · 16:9 full"],
|
| 376 |
+
["A busy night market, neon signs reflecting in puddles, sizzling street food", "768x1344 · 9:16 full"],
|
| 377 |
+
["A cellist playing a slow melody in an empty concert hall", "768x768 · 1:1 full"],
|
| 378 |
+
["Waves crashing against basalt cliffs at golden hour, gulls crying overhead", "1152x640 · 16:9"],
|
| 379 |
+
];
|
| 380 |
+
for (const [p, c] of EXAMPLES) {
|
| 381 |
+
const b = document.createElement("button");
|
| 382 |
+
b.textContent = p.length > 60 ? p.slice(0, 60) + "…" : p;
|
| 383 |
+
b.title = p;
|
| 384 |
+
b.onclick = () => { $("prompt").value = p; $("canvas").value = c; };
|
| 385 |
+
$("examples").appendChild(b);
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
/* ---- generate ---- */
|
| 389 |
+
const client = await Client.connect(window.location.origin, { events: ["data", "status"] });
|
| 390 |
+
|
| 391 |
+
function setJob(label, cls) {
|
| 392 |
+
const el = $("job-state");
|
| 393 |
+
el.textContent = label; el.className = cls || "";
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
function setBar(pct) {
|
| 397 |
+
const bar = $("bar");
|
| 398 |
+
if (pct === null) { bar.className = "indeterminate"; return; }
|
| 399 |
+
bar.className = "";
|
| 400 |
+
bar.style.width = Math.max(0, Math.min(100, pct)) + "%";
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
$("run").addEventListener("click", async () => {
|
| 404 |
+
if (state.busy) return;
|
| 405 |
+
const prompt = $("prompt").value.trim();
|
| 406 |
+
if (!prompt) { setJob("FAILED", "failed"); $("report").textContent = "a prompt is required"; return; }
|
| 407 |
+
|
| 408 |
+
state.busy = true;
|
| 409 |
+
$("run").disabled = true;
|
| 410 |
+
$("refined-bar").style.display = "none";
|
| 411 |
+
$("report").textContent = "";
|
| 412 |
+
setJob("ROLLING", "");
|
| 413 |
+
const t0 = Date.now();
|
| 414 |
+
state.timer = setInterval(() => $("elapsed").textContent = ((Date.now() - t0) / 1000).toFixed(0) + "s", 500);
|
| 415 |
+
|
| 416 |
+
try {
|
| 417 |
+
const submission = client.submit("/generate", {
|
| 418 |
+
prompt,
|
| 419 |
+
image_path: state.first ? handle_file(state.first) : null,
|
| 420 |
+
last_image_path: state.last ? handle_file(state.last) : null,
|
| 421 |
+
canvas: $("canvas").value,
|
| 422 |
+
duration: Number($("duration").value),
|
| 423 |
+
steps: Number($("steps").value),
|
| 424 |
+
seed: Number($("seed").value),
|
| 425 |
+
upsample: $("upsample").checked,
|
| 426 |
+
lora: $("lora").value,
|
| 427 |
+
});
|
| 428 |
+
let data = null;
|
| 429 |
+
for await (const msg of submission) {
|
| 430 |
+
if (msg.type === "status") {
|
| 431 |
+
if (msg.stage === "pending") {
|
| 432 |
+
setJob(msg.position != null ? `QUEUED #${msg.position + 1}` : "QUEUED");
|
| 433 |
+
setBar(null);
|
| 434 |
+
} else if (msg.stage === "generating") {
|
| 435 |
+
setJob("ROLLING");
|
| 436 |
+
// ETA comes from the queue's booking estimate; blend it with our own elapsed timer.
|
| 437 |
+
if (msg.eta != null && msg.eta > 0) {
|
| 438 |
+
const elapsed = (Date.now() - t0) / 1000;
|
| 439 |
+
setBar(100 * elapsed / (elapsed + msg.eta));
|
| 440 |
+
} else setBar(null);
|
| 441 |
+
} else if (msg.stage === "error") {
|
| 442 |
+
throw new Error(msg.message || "generation failed");
|
| 443 |
+
}
|
| 444 |
+
} else if (msg.type === "data") {
|
| 445 |
+
data = msg.data;
|
| 446 |
+
}
|
| 447 |
+
}
|
| 448 |
+
if (!data) throw new Error("the backend returned no data");
|
| 449 |
+
// Server mode returns the tuple as ONE Api output: unwrap [[video, report, refined]] too.
|
| 450 |
+
if (data.length === 1 && Array.isArray(data[0])) data = data[0];
|
| 451 |
+
const [video, report, refined] = data;
|
| 452 |
+
// FileData may carry only `path`; resolve those through Gradio's file route.
|
| 453 |
+
const videoUrl = (video && (video.url || (video.path && `/gradio_api/file=${video.path}`)))
|
| 454 |
+
|| (typeof video === "string" && `/gradio_api/file=${video}`);
|
| 455 |
+
if (!videoUrl) throw new Error("the backend returned no video reference");
|
| 456 |
+
$("video").src = videoUrl;
|
| 457 |
+
$("monitor").classList.remove("hidden-video");
|
| 458 |
+
$("placeholder").style.display = "none";
|
| 459 |
+
$("report").textContent = report;
|
| 460 |
+
if (refined) {
|
| 461 |
+
$("refined").textContent = refined;
|
| 462 |
+
$("refined-bar").style.display = "block";
|
| 463 |
+
}
|
| 464 |
+
setJob("DONE", "done");
|
| 465 |
+
setBar(100);
|
| 466 |
+
} catch (e) {
|
| 467 |
+
setJob("FAILED", "failed");
|
| 468 |
+
setBar(0);
|
| 469 |
+
$("report").textContent = (e && e.message) ? e.message.slice(0, 300) : String(e);
|
| 470 |
+
} finally {
|
| 471 |
+
clearInterval(state.timer);
|
| 472 |
+
state.busy = false;
|
| 473 |
+
$("run").disabled = false;
|
| 474 |
+
}
|
| 475 |
+
});
|
| 476 |
+
</script>
|
| 477 |
+
</body>
|
| 478 |
+
</html>
|
packages.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
ffmpeg
|
requirements.txt
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `diffusers` is installed from the canonical MiniMax-H3 pull request,
|
| 2 |
+
# https://github.com/huggingface/diffusers/pull/14371 ("Minimax h3 follow up (review & refactor)"), pinned to a
|
| 3 |
+
# **commit** rather than to its `minimax-h3-refactor` branch: the PR is a WIP and its head moves, and this Space's
|
| 4 |
+
# blocks subclass its block classes. Re-pin — and re-check `h3_split_blocks.py` against the block names of the new
|
| 5 |
+
# head — whenever the PR updates.
|
| 6 |
+
#
|
| 7 |
+
# 665f578278365ea4a3318cb8c9b66ce6c01204b9 = refs/pull/14371/head at the time of this deploy
|
| 8 |
+
--extra-index-url https://download.pytorch.org/whl/cu130
|
| 9 |
+
diffusers @ git+https://github.com/huggingface/diffusers.git@665f578278365ea4a3318cb8c9b66ce6c01204b9
|
| 10 |
+
torch==2.11.0
|
| 11 |
+
torchvision==0.26.0
|
| 12 |
+
# The Qwen3-VL processor decides the vision patch count, so a different minor changes the conditioning.
|
| 13 |
+
transformers==5.8.0
|
| 14 |
+
accelerate==1.14.0
|
| 15 |
+
# diffusers pins <2.
|
| 16 |
+
huggingface-hub==1.24.0
|
| 17 |
+
gradio==6.20.0
|
| 18 |
+
spaces==0.51.1
|
| 19 |
+
# No `kernels` pin on purpose: the Hub attention backends want `kernels>=0.12.3`, and that version breaks
|
| 20 |
+
# transformers 5.8.0 at import.
|
| 21 |
+
# PyAV muxes the generated soundtrack onto the frames (`encode_video`).
|
| 22 |
+
av
|
| 23 |
+
pillow
|
| 24 |
+
numpy
|
| 25 |
+
requests
|
| 26 |
+
safetensors>=0.8.0
|
spaces_constant_binding_patch.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bind AoTI constants that `torch.export` lifted anonymously.
|
| 2 |
+
|
| 3 |
+
`spaces.zero.torch.aoti.LazyAOTIModel` binds a package's constants by intersecting the module's `state_dict()` with
|
| 4 |
+
`compiled_model.get_constant_fqns()`, and keeps whatever it cannot match. `torch.export` only gives a lifted tensor a
|
| 5 |
+
real FQN when it was a registered parameter or buffer; anything else is named `_tensor_constant<N>`, which no
|
| 6 |
+
`state_dict()` can contain, so the compiled model runs against constants nobody set — a SIGSEGV rather than an error.
|
| 7 |
+
|
| 8 |
+
`write_constant_aliases` records the real names on the compile side; `apply_spaces_constant_binding_patch` uses that
|
| 9 |
+
sidecar on the load side, falls back to matching by dtype+shape, and raises if the binding is still not total.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import io
|
| 15 |
+
import json
|
| 16 |
+
import re
|
| 17 |
+
import zipfile
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
ALIASES_FILENAME = "constant_aliases.json"
|
| 23 |
+
|
| 24 |
+
_DTYPES = {
|
| 25 |
+
"float32": torch.float32, "float64": torch.float64, "float16": torch.float16,
|
| 26 |
+
"bfloat16": torch.bfloat16, "float8_e4m3fn": torch.float8_e4m3fn,
|
| 27 |
+
"float8_e5m2": torch.float8_e5m2, "float8_e4m3fnuz": torch.float8_e4m3fnuz,
|
| 28 |
+
"float8_e5m2fnuz": torch.float8_e5m2fnuz, "int8": torch.int8, "uint8": torch.uint8,
|
| 29 |
+
"int16": torch.int16, "int32": torch.int32, "int64": torch.int64, "bool": torch.bool,
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# --------------------------------------------------------------------------- compile side
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def register_loose_tensors(module: torch.nn.Module, prefix: str = "") -> list[str]:
|
| 37 |
+
"""Re-register plain tensor attributes as buffers so `torch.export` gives them real FQNs.
|
| 38 |
+
|
| 39 |
+
Run on the shallow clone, right before `torch.export.export`. Returns the names it re-registered.
|
| 40 |
+
"""
|
| 41 |
+
registered = []
|
| 42 |
+
for name, value in list(vars(module).items()):
|
| 43 |
+
if not isinstance(value, torch.Tensor) or name.startswith("_"):
|
| 44 |
+
continue
|
| 45 |
+
if name in module._parameters or name in module._buffers:
|
| 46 |
+
continue
|
| 47 |
+
object.__delattr__(module, name)
|
| 48 |
+
module.register_buffer(name, value, persistent=True)
|
| 49 |
+
registered.append(f"{prefix}{name}")
|
| 50 |
+
for child_name, child in module.named_children():
|
| 51 |
+
registered += register_loose_tensors(child, f"{prefix}{child_name}.")
|
| 52 |
+
return registered
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def constant_aliases_from_exported_program(exported_program) -> dict[str, str]:
|
| 56 |
+
"""`{'_tensor_constant<N>': '<real dotted fqn>'}` for every anonymously lifted constant.
|
| 57 |
+
|
| 58 |
+
AOT Inductor numbers its slots in the order the `CONSTANT_TENSOR` inputs appear in the graph signature, which
|
| 59 |
+
still carries each one's real FQN.
|
| 60 |
+
"""
|
| 61 |
+
targets = [
|
| 62 |
+
spec.target
|
| 63 |
+
for spec in exported_program.graph_signature.input_specs
|
| 64 |
+
if spec.kind.name == "CONSTANT_TENSOR"
|
| 65 |
+
]
|
| 66 |
+
return {f"_tensor_constant{index}": target for index, target in enumerate(targets)}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def write_constant_aliases(package_dir, exported_program, submodule: str | None = None) -> Path | None:
|
| 70 |
+
"""Drop the alias sidecar next to the `package.pt2` `aoti_compile_and_save` just wrote."""
|
| 71 |
+
aliases = constant_aliases_from_exported_program(exported_program)
|
| 72 |
+
if not aliases:
|
| 73 |
+
return None
|
| 74 |
+
subdir = Path(package_dir) / ("submodules/" + submodule if submodule else "root")
|
| 75 |
+
path = subdir / ALIASES_FILENAME
|
| 76 |
+
path.write_text(json.dumps(aliases, indent=2))
|
| 77 |
+
return path
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# --------------------------------------------------------------------------- load side
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _package_constants_info(archive_file) -> list[dict]:
|
| 84 |
+
"""Read `constants_info_` (dtype, shape, in slot order) out of a `.pt2`'s wrapper source."""
|
| 85 |
+
if isinstance(archive_file, (str, Path)):
|
| 86 |
+
handle: object = str(archive_file)
|
| 87 |
+
else:
|
| 88 |
+
position = archive_file.tell()
|
| 89 |
+
archive_file.seek(0)
|
| 90 |
+
handle = io.BytesIO(archive_file.read())
|
| 91 |
+
archive_file.seek(position)
|
| 92 |
+
with zipfile.ZipFile(handle) as archive: # pyright: ignore[reportArgumentType]
|
| 93 |
+
names = [n for n in archive.namelist() if n.endswith(".wrapper.cpp")]
|
| 94 |
+
if not names:
|
| 95 |
+
return []
|
| 96 |
+
source = archive.read(names[0]).decode()
|
| 97 |
+
info: dict[int, dict] = {}
|
| 98 |
+
for match in re.finditer(r"constants_info_\[(\d+)\]\.(\w+) = ([^;]+);", source):
|
| 99 |
+
index, field, value = int(match.group(1)), match.group(2), match.group(3).strip()
|
| 100 |
+
entry = info.setdefault(index, {})
|
| 101 |
+
if field == "dtype":
|
| 102 |
+
entry["dtype"] = _DTYPES.get(value.replace("cached_torch_dtype_", ""))
|
| 103 |
+
elif field == "shape":
|
| 104 |
+
entry["shape"] = tuple(int(x) for x in re.findall(r"-?\d+", value))
|
| 105 |
+
elif field in ("name", "original_fqn"):
|
| 106 |
+
entry[field] = value.strip('"')
|
| 107 |
+
return [info[index] for index in sorted(info)]
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def resolve_constant_map(
|
| 111 |
+
archive_file,
|
| 112 |
+
constant_fqns,
|
| 113 |
+
weights: dict[str, torch.Tensor],
|
| 114 |
+
aliases=None,
|
| 115 |
+
allow_shape_fallback: bool = False,
|
| 116 |
+
):
|
| 117 |
+
"""Map every compiled constant FQN onto one of `weights`, or report what is left over."""
|
| 118 |
+
constant_map = {name: weights[name] for name in constant_fqns if name in weights}
|
| 119 |
+
missing = [name for name in constant_fqns if name not in constant_map]
|
| 120 |
+
if not missing:
|
| 121 |
+
return constant_map, []
|
| 122 |
+
|
| 123 |
+
aliases = aliases or {}
|
| 124 |
+
for name in list(missing):
|
| 125 |
+
target = aliases.get(name)
|
| 126 |
+
if target is not None and target in weights:
|
| 127 |
+
constant_map[name] = weights[target]
|
| 128 |
+
missing.remove(name)
|
| 129 |
+
if not missing or not allow_shape_fallback:
|
| 130 |
+
return constant_map, missing
|
| 131 |
+
|
| 132 |
+
# Match by dtype+shape against the unclaimed `state_dict()` entries, preserving each side's own order inside a
|
| 133 |
+
# (dtype, shape) group. `get_constant_fqns()` returns slots lexicographically (`_tensor_constant10` before
|
| 134 |
+
# `_tensor_constant2`), so the package's own `constants_info_` index is the only correct order to walk them in.
|
| 135 |
+
info = _package_constants_info(archive_file)
|
| 136 |
+
by_name = {entry.get("name"): entry for entry in info}
|
| 137 |
+
slot_index = {entry.get("name"): index for index, entry in enumerate(info)}
|
| 138 |
+
taken = {id(tensor) for tensor in constant_map.values()}
|
| 139 |
+
buckets: dict[tuple, list[torch.Tensor]] = {}
|
| 140 |
+
for tensor in weights.values():
|
| 141 |
+
if id(tensor) not in taken:
|
| 142 |
+
buckets.setdefault((tensor.dtype, tuple(tensor.shape)), []).append(tensor)
|
| 143 |
+
for name in sorted(list(missing), key=lambda n: slot_index.get(n, 1 << 30)):
|
| 144 |
+
entry = by_name.get(name)
|
| 145 |
+
if entry is None or entry.get("dtype") is None:
|
| 146 |
+
continue
|
| 147 |
+
bucket = buckets.get((entry["dtype"], entry["shape"]))
|
| 148 |
+
if bucket:
|
| 149 |
+
constant_map[name] = bucket.pop(0)
|
| 150 |
+
missing.remove(name)
|
| 151 |
+
return constant_map, missing
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def apply_spaces_constant_binding_patch(strict: bool = True, allow_shape_fallback: bool = False):
|
| 155 |
+
"""Make `spaces`' AoTI loader bind anonymous constants, and fail loudly if it still cannot.
|
| 156 |
+
|
| 157 |
+
Call once, before any `spaces.aoti_*` loading. Idempotent.
|
| 158 |
+
"""
|
| 159 |
+
from spaces.zero.torch import aoti as spaces_aoti
|
| 160 |
+
|
| 161 |
+
if getattr(spaces_aoti.LazyAOTIModel, "_constant_binding_patched", False):
|
| 162 |
+
return
|
| 163 |
+
|
| 164 |
+
original_call = spaces_aoti.LazyAOTIModel.__call__
|
| 165 |
+
|
| 166 |
+
def patched_call(self, weights, check_full_update, *args, **kwargs):
|
| 167 |
+
compiled_model = self.compiled_model.get()
|
| 168 |
+
if compiled_model is None:
|
| 169 |
+
with spaces_aoti._register_aoti_cleanup():
|
| 170 |
+
compiled_model = torch._inductor.aoti_load_package(self.archive_file)
|
| 171 |
+
self.compiled_model.set(compiled_model)
|
| 172 |
+
loaded = self.loaded_weights.get()
|
| 173 |
+
if loaded is None or loaded is not weights:
|
| 174 |
+
fqns = compiled_model.get_constant_fqns()
|
| 175 |
+
aliases = getattr(self, "_constant_aliases", None)
|
| 176 |
+
if aliases is None:
|
| 177 |
+
aliases = {}
|
| 178 |
+
if isinstance(self.archive_file, (str, Path)):
|
| 179 |
+
sidecar = Path(self.archive_file).with_name(ALIASES_FILENAME)
|
| 180 |
+
if sidecar.is_file():
|
| 181 |
+
aliases = json.loads(sidecar.read_text())
|
| 182 |
+
self._constant_aliases = aliases
|
| 183 |
+
constant_map, missing = resolve_constant_map(
|
| 184 |
+
self.archive_file, fqns, weights, aliases, allow_shape_fallback
|
| 185 |
+
)
|
| 186 |
+
if missing and strict:
|
| 187 |
+
raise RuntimeError(
|
| 188 |
+
f"{len(missing)} of {len(fqns)} AoTI constants could not be bound to the module's "
|
| 189 |
+
f"state_dict: {missing[:8]}. Anonymous `_tensor_constant*` names mean the export saw "
|
| 190 |
+
f"plain tensor attributes rather than registered parameters or buffers. Register them "
|
| 191 |
+
f"(or write a {ALIASES_FILENAME} sidecar at compile time) — binding them partially "
|
| 192 |
+
f"would leave the compiled model dereferencing unset constants."
|
| 193 |
+
)
|
| 194 |
+
compiled_model.load_constants(
|
| 195 |
+
constant_map, check_full_update=check_full_update and not missing, user_managed=True
|
| 196 |
+
)
|
| 197 |
+
self.loaded_weights.set(weights)
|
| 198 |
+
return compiled_model(*args, **kwargs)
|
| 199 |
+
|
| 200 |
+
spaces_aoti.LazyAOTIModel.__call__ = patched_call
|
| 201 |
+
spaces_aoti.LazyAOTIModel._constant_binding_patched = True
|
| 202 |
+
spaces_aoti.LazyAOTIModel._original_call = original_call
|