mrfakename commited on
Commit
bf0e5ad
·
1 Parent(s): bdb2ca7

Add optimized MiniMax-H3 NVFP4 Space

Browse files
Files changed (10) hide show
  1. README.md +129 -7
  2. app.py +451 -0
  3. examples/first.png +0 -0
  4. examples/last.png +0 -0
  5. h3_aoti.py +307 -0
  6. h3_nvfp4.py +493 -0
  7. h3_split_blocks.py +147 -0
  8. packages.txt +1 -0
  9. requirements.txt +29 -0
  10. spaces_constant_binding_patch.py +202 -0
README.md CHANGED
@@ -1,13 +1,135 @@
1
  ---
2
- title: Zero Wave2 2
3
- emoji: 📈
4
  colorFrom: purple
5
- colorTo: blue
6
  sdk: gradio
7
- sdk_version: 6.19.0
8
- python_version: '3.13'
9
  app_file: app.py
10
- pinned: false
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: MiniMax H3 Ultra
3
+ emoji:
4
  colorFrom: purple
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 6.20.0
 
8
  app_file: app.py
9
+ pinned: true
10
+ short_description: Blackwell-native NVFP4 video + synchronized audio generation
11
+ suggested_hardware: zero-a10g
12
  ---
13
 
14
+ # MiniMax-H3 Ultra pruned NVFP4 on Blackwell
15
+
16
+ Joint video and synchronized sound from MiniMax-H3, with the repeatedly executed transformer rebuilt around the
17
+ Blackwell-native ComfyUI optimization path:
18
+
19
+ - 12.5 GB pruned NVFP4 transformer instead of the 61.7 GiB BF16 inference transformer.
20
+ - 20.1B effective inference parameters instead of 33.1B; the redundant 13.04B AdaLN projection weights become a
21
+ compact sampled timestep curve.
22
+ - One fused QKV projection per attention layer.
23
+ - One fused in-place Q/K RMSNorm + partial split-half RoPE kernel.
24
+ - Native CUDA 13 NVFP4 tensor-core GEMMs through `comfy-kitchen`.
25
+ - Segment-wise in-place AdaLN modulation and gated residual accumulation.
26
+ - Video and audio output heads run only on their own rows, not the full packed sequence.
27
+ - Prompt refinement and the rotary table are cached for the request instead of recomputed at every denoising step.
28
+ - The video VAE and audio VAE remain full precision.
29
+
30
+ The source model is [`MiniMaxAI/MiniMax-H3`](https://huggingface.co/MiniMaxAI/MiniMax-H3). The pruned NVFP4
31
+ checkpoint is
32
+ [`lilcheaty/MiniMax-H3-NVFP4`](https://huggingface.co/lilcheaty/MiniMax-H3-NVFP4), derived from ComfyUI's
33
+ [`MiniMax-H3`](https://huggingface.co/Comfy-Org/MiniMax-H3) repackage.
34
+
35
+ ## Why the pruned transformer matters
36
+
37
+ MiniMax-H3's published model card notes that about 13B parameters live in AdaLN-related branches and that their
38
+ outputs can be precomputed for inference. The pruned checkpoint makes that concrete: it samples the shared timestep
39
+ embedding curve at 1025 points and linearly interpolates an 8-value coordinate for each requested timestep. Every
40
+ block's modulation projection consequently becomes `[96768, 8]` instead of `[96768, 2688]`.
41
+
42
+ | parameter group | original BF16 architecture | pruned architecture |
43
+ |---|---:|---:|
44
+ | AdaLN projections | 13.04B | 0.04B |
45
+ | MLP | 12.02B | 11.56B |
46
+ | attention | 8.02B | 7.71B |
47
+ | refiner, norms and embeddings | 0.05B | 0.80B |
48
+ | **total** | **33.12B** | **20.11B** |
49
+
50
+ The four large matrices in each of the 50 blocks—fused QKV, attention output, MLP up/gate and MLP down—are NVFP4.
51
+ The modulation curve, norms, embeddings, biases and final heads stay at higher precision.
52
+
53
+ ## Why this is faster than the old 4-bit Space
54
+
55
+ Quantization alone does not guarantee speed. The older 4-bit comparison paid for CPU offload traffic on every layer
56
+ because its runtime did not keep the transformer resident. This engine is about 12 GB, so the transformer, both VAEs,
57
+ working activations and decoder workspace fit together on the 95 GiB `xlarge` ZeroGPU worker. There is no layerwise
58
+ host-device weight traffic in the denoising loop.
59
+
60
+ ComfyUI reports about a 2× NVFP4 uplift over FP8/BF16 on Blackwell in supported workloads. The H3 checkpoint author
61
+ measured 1.90 s/iteration for pruned NVFP4 versus 2.17 s/iteration for pruned INT8 ConvRot on an RTX PRO 6000
62
+ Blackwell at 864×480, 39 frames. Those numbers are useful implementation evidence, not a promise for every canvas:
63
+ H3 attention grows quadratically with packed sequence length, so resolution, duration and keyframe vision tokens
64
+ still dominate large requests.
65
+
66
+ ## Split deployment
67
+
68
+ The full checkpoint cannot fit under a single Space's 150 GB storage ceiling. This Space remains the denoising half:
69
+
70
+ | component | where it runs | precision / format |
71
+ |---|---|---|
72
+ | Qwen3-VL layer-50 conditioner | [`qwen3vl-conditioner`](https://huggingface.co/spaces/multimodalart/qwen3vl-conditioner) | BF16 |
73
+ | H3 transformer | this Space | pruned NVFP4 + higher-precision islands |
74
+ | video VAE | this Space | full precision checkpoint policy |
75
+ | audio VAE | this Space | FP32 |
76
+
77
+ The wire format is `prompt_embeds` plus `text_token_tags` in a safetensors file. The conditioner also returns the
78
+ resolved canvas, aligned frame count and prompt plan. Keyframes are encoded again by this Space's video VAE so the
79
+ conditioning latents exactly match the pixels seen by the conditioner.
80
+
81
+ ## Kernel path
82
+
83
+ `h3_nvfp4.py` adapts the public ComfyUI H3 implementation to diffusers' packed transformer signature. It deliberately
84
+ does not install or launch the ComfyUI application. The small adapter uses only `comfy-kitchen` for:
85
+
86
+ 1. Dynamic NVFP4 activation quantization and native FP4 matrix multiplication.
87
+ 2. Fused in-place Q/K RMSNorm and three-axis split-half rotary embedding.
88
+
89
+ Attention itself stays on diffusers' `_native_cudnn` backend, which is faster than the default SDPA path on the
90
+ ZeroGPU RTX PRO 6000 pool. The MLP uses one fused QKV-style gate/up matrix, in-place SiLU×up, and the NVFP4 down
91
+ projection.
92
+
93
+ The old BF16/AoTI engine remains available with `H3_ENGINE=bf16`. It is useful as a quality/debug reference, but it is
94
+ not the default.
95
+
96
+ ## Quality trade-off
97
+
98
+ NVFP4 is approximate. The checkpoint author reports that 4-bit weights can show more mid-motion artifacts and weaker
99
+ shape retention than the larger INT8 ConvRot checkpoint on difficult 15-second clips. The comparison was not fully
100
+ controlled, so treat it as a real caution rather than a quantified quality score.
101
+
102
+ The Space keeps both VAEs full precision and leaves AdaLN, norms, embeddings and output heads out of NVFP4. For the
103
+ exact original denoiser, set `H3_ENGINE=bf16`; this restores the 61.7 GiB unquantized transformer and its AoTI option.
104
+
105
+ ## Space variables
106
+
107
+ | variable | default | meaning |
108
+ |---|---|---|
109
+ | `H3_ENGINE` | `nvfp4` | `nvfp4` ultra engine or `bf16` reference engine. |
110
+ | `H3_NVFP4_REPO` | `lilcheaty/MiniMax-H3-NVFP4` | Repository containing the pruned Comfy-format transformer. |
111
+ | `H3_NVFP4_FILE` | `minimax_h3_fl2va_pruned_nvfp4.safetensors` | FL2VA/T2VA transformer file. |
112
+ | `H3_MODEL_REPO` | `MiniMaxAI/MiniMax-H3` | Canonical schedulers and VAE checkpoint. |
113
+ | `H3_CONDITIONER` | `multimodalart/qwen3vl-conditioner` | Remote layer-50 conditioner Space. |
114
+ | `H3_PLACEMENT` | `lazy` (`nvfp4`) | Move the compact transformer and VAEs on the first GPU call, then keep them resident. |
115
+ | `H3_ATTENTION` | `_native_cudnn` | Attention backend for both the main stack and text refiner. |
116
+ | `H3_GPU_SIZE` | `xlarge` | 95 GiB Blackwell ZeroGPU allocation. |
117
+ | `H3_AOTI` | `0` | BF16 engine only: load the optional repeated-block AoTI package. |
118
+
119
+ ## Runtime requirements
120
+
121
+ - PyTorch 2.11 with CUDA 13.0.
122
+ - A Blackwell GPU (`sm120` for this Space). NVFP4 on older architectures is emulated and can be slower than BF16.
123
+ - `comfy-kitchen==0.2.26` for the native layouts and fused Q/K kernel.
124
+ - The pinned MiniMax-H3 diffusers pull request for the modular schedulers, packing and VAE decode path.
125
+
126
+ No secret is required. All model artifacts are public, and `gradio_client` forwards the requesting user's ZeroGPU
127
+ identity to the conditioner.
128
+
129
+ ## Attribution
130
+
131
+ The fused/pruned model structure follows
132
+ [`comfy/ldm/minimax/model.py`](https://github.com/Comfy-Org/ComfyUI/blob/master/comfy/ldm/minimax/model.py) from
133
+ ComfyUI (Apache-2.0). The quantized checkpoint and its conversion notes are from
134
+ [`lilcheaty/MiniMax-H3-NVFP4`](https://huggingface.co/lilcheaty/MiniMax-H3-NVFP4). MiniMax-H3 weights remain governed
135
+ by the MiniMax-H3 Community License Agreement.
app.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 model loading can happen at
12
+ # startup rather than on GPU time.
13
+ import spaces
14
+ import gradio as gr
15
+
16
+ MODEL_REPO = os.environ.get("H3_MODEL_REPO", "MiniMaxAI/MiniMax-H3")
17
+ CONDITIONER_SPACE = os.environ.get("H3_CONDITIONER", "multimodalart/qwen3vl-conditioner")
18
+ # `nvfp4` is the Blackwell-native ultra path; `bf16` preserves the original 33B diffusers transformer as a fallback.
19
+ ENGINE = os.environ.get("H3_ENGINE", "nvfp4").lower()
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", "lazy" if ENGINE == "nvfp4" else "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
+ PIPE = None
75
+ MANAGER = None
76
+ LOAD_ERROR: str | None = None
77
+ LOADED_IN: float | None = None
78
+
79
+
80
+ def status() -> str:
81
+ if LOAD_ERROR:
82
+ return LOAD_ERROR
83
+ if PIPE is None:
84
+ payload = (
85
+ "pruned NVFP4 transformer + full-precision VAEs (~28 GB)"
86
+ if ENGINE == "nvfp4"
87
+ else "BF16 transformer + VAEs (77.3 GB)"
88
+ )
89
+ return f"Loading {payload}. Watch the Space logs."
90
+ if ENGINE == "nvfp4":
91
+ import h3_nvfp4
92
+
93
+ engine_status = h3_nvfp4.status()
94
+ else:
95
+ import h3_aoti
96
+
97
+ engine_status = f"BF16, unquantized · {h3_aoti.status()}"
98
+ return (
99
+ f"Ready · **{engine_status}** · VAEs full precision · placement `{PLACEMENT}` · attention `{ATTENTION}` · "
100
+ f"loaded in {LOADED_IN:.0f}s · conditioner `{CONDITIONER_SPACE}`"
101
+ )
102
+
103
+
104
+ def load_models() -> str | None:
105
+ """Load the denoising half at startup.
106
+
107
+ `MiniMaxH3GeneratorBlocks` declares `transformer`, `vae`, `audio_vae`, the two schedulers and `video_processor`,
108
+ so `load_components` fetches exactly those subfolders — `text_encoder/` and `transformer_ref/` are never touched.
109
+ Both autoencoders carry `_keep_in_fp32_modules` over every module and stay float32: a bfloat16 audio VAE decodes
110
+ the soundtrack roughly 20 dB too quiet.
111
+ """
112
+ global PIPE, MANAGER, LOAD_ERROR, LOADED_IN
113
+
114
+ if PIPE is not None or LOAD_ERROR is not None:
115
+ return LOAD_ERROR
116
+
117
+ started = time.time()
118
+ try:
119
+ import torch
120
+ from diffusers import ComponentsManager
121
+
122
+ from h3_split_blocks import MiniMaxH3GeneratorBlocks
123
+
124
+ lower_duration_floor()
125
+ manager = ComponentsManager()
126
+ blocks = MiniMaxH3GeneratorBlocks()
127
+ print(f"[gen] loading {[c.name for c in blocks.expected_components]} from {MODEL_REPO} ...", flush=True)
128
+ pipe = blocks.init_pipeline(MODEL_REPO, components_manager=manager, collection="h3")
129
+ if ENGINE == "nvfp4":
130
+ # Do not download the 61.7 GiB BF16 transformer. The schedulers and full-precision VAEs stay canonical;
131
+ # only the repeatedly executed DiT is replaced with the pruned Blackwell-native checkpoint.
132
+ pipe.load_components(
133
+ names=["vae", "audio_vae", "scheduler", "audio_scheduler", "video_processor"],
134
+ dtype=torch.bfloat16,
135
+ )
136
+ from h3_nvfp4 import load_transformer
137
+
138
+ pipe.update_components(transformer=load_transformer())
139
+ elif ENGINE == "bf16":
140
+ pipe.load_components(dtype=torch.bfloat16)
141
+ else:
142
+ raise ValueError(f"H3_ENGINE must be `nvfp4` or `bf16`, got {ENGINE!r}")
143
+ pipe.transformer.set_attention_backend(ATTENTION)
144
+
145
+ # Still startup, still free: an AoTI package carries no weights and opens its archive lazily inside the GPU
146
+ # worker. Off unless `H3_AOTI=1`.
147
+ if ENGINE == "bf16":
148
+ import h3_aoti
149
+
150
+ h3_aoti.maybe_load(pipe.transformer)
151
+
152
+ if PLACEMENT == "pack":
153
+ # Scoped to the transformer. `spaces` packs every startup-resident CUDA tensor into a second on-disk copy,
154
+ # and packing all 77.3 GB busts the 150 GB storage quota; the 61.7 GB transformer alone fits. The ~10 GB of
155
+ # fp32 VAEs move on the first GPU call instead.
156
+ pipe.transformer.to("cuda")
157
+
158
+ if PLACEMENT == "offload":
159
+ manager.enable_auto_cpu_offload(device="cuda")
160
+ _arm_decode_hooks(pipe)
161
+
162
+ PIPE, MANAGER = pipe, manager
163
+ LOADED_IN = time.time() - started
164
+ print(f"[gen] ready in {LOADED_IN:.0f}s", flush=True)
165
+ except Exception as error:
166
+ traceback.print_exc()
167
+ LOAD_ERROR = f"**Loading `{MODEL_REPO}` failed** after {time.time() - started:.0f}s: `{type(error).__name__}: {error}`"
168
+ return LOAD_ERROR
169
+
170
+
171
+ def _arm_decode_hooks(pipe):
172
+ """Make the offload hooks fire for the two VAEs.
173
+
174
+ `enable_auto_cpu_offload` wraps `forward`, and the decode blocks call `vae.decode(...)` directly, so the hook
175
+ never runs and the VAE is still on the host when the latents arrive on the card.
176
+ """
177
+ for name in ("vae", "audio_vae"):
178
+ module = getattr(pipe, name)
179
+ inner = module.decode
180
+
181
+ def armed(*args, _module=module, _decode=inner, **kwargs):
182
+ hook = getattr(_module, "_hf_hook", None)
183
+ if hook is not None:
184
+ hook.pre_forward(_module)
185
+ return _decode(*args, **kwargs)
186
+
187
+ module.decode = armed
188
+
189
+
190
+ @cache
191
+ def conditioner():
192
+ """The other half, over the gradio API. `gradio_client` attaches the caller's own ZeroGPU token per call, so the
193
+ conditioner's booking is billed to whoever asked for the video."""
194
+ from gradio_client import Client
195
+
196
+ return Client(CONDITIONER_SPACE)
197
+
198
+
199
+ def encode_remote(prompt, image_path, last_image_path, canvas, num_frames, rewrite_prompt=False):
200
+ """`/encode` on the conditioner Space: a safetensors file holding `prompt_embeds` + `text_token_tags`, with the
201
+ resolved `height` / `width` / `num_frames` in its metadata, plus the plan. `canvas` is the label."""
202
+ from gradio_client import handle_file
203
+ from safetensors import safe_open
204
+
205
+ path, plan = conditioner().predict(
206
+ prompt=prompt,
207
+ image_path=handle_file(image_path) if image_path else None,
208
+ last_image_path=handle_file(last_image_path) if last_image_path else None,
209
+ canvas=canvas,
210
+ num_frames=num_frames,
211
+ rewrite_prompt=bool(rewrite_prompt),
212
+ api_name="/encode",
213
+ )
214
+ with safe_open(path, framework="pt") as handle:
215
+ metadata = handle.metadata()
216
+ return handle.get_tensor("prompt_embeds"), handle.get_tensor("text_token_tags"), metadata, plan
217
+
218
+
219
+ # Seconds of GPU one request needs, from the packed video rows it is about to denoise: linear in the rows for the
220
+ # matmuls, quadratic for the attention, against the AoTI block package this Space runs.
221
+ _DUR_B, _DUR_C = 1.1745e-4, 3.8396e-9
222
+ # The two resident decoders and the mux, which scale with the output rather than with the step count.
223
+ _DECODE_BASE, _DECODE_PER_DEFAULT_CANVAS, _DEFAULT_CANVAS_PIXELS = 15, 15, 960 * 544 * 124
224
+ # `pack` mode: only the ~10 GB of VAEs move on a cold worker.
225
+ _PLACEMENT_ALLOWANCE, _PAD = 12, 10
226
+
227
+
228
+ def get_duration(prompt_embeds, text_token_tags, image, last_image, height, width, num_frames, steps, seed, *a, **k):
229
+ height, width, num_frames, steps = int(height), int(width), int(num_frames), int(steps)
230
+ latent_frames = (num_frames - LATENTS_PER_CHUNK) // FRAMES_PER_CHUNK * LATENTS_PER_CHUNK + 2
231
+ patches = (height // 32) * (width // 32)
232
+ rows = latent_frames * patches + (int(image is not None) + int(last_image is not None)) * patches
233
+ denoise = steps * (_DUR_B * rows + _DUR_C * rows**2)
234
+ decode = _DECODE_BASE + _DECODE_PER_DEFAULT_CANVAS * (height * width * num_frames) / _DEFAULT_CANVAS_PIXELS
235
+ return max(60, int(denoise + decode) + _PLACEMENT_ALLOWANCE + _PAD)
236
+
237
+
238
+ @spaces.GPU(duration=get_duration, size=GPU_SIZE)
239
+ def _generate(prompt_embeds, text_token_tags, image, last_image, height, width, num_frames, steps, seed):
240
+ """The only thing on GPU time: the packed-sequence denoise loop and the two decoders.
241
+
242
+ Only the three generated outputs come back — a `@spaces.GPU` return crosses a process boundary by pickling, and
243
+ the full `PipelineState` still holds the packed latents, the rotary grid and the row indices on the card.
244
+ """
245
+ import torch
246
+
247
+ if PLACEMENT == "lazy":
248
+ PIPE.to("cuda")
249
+ elif PLACEMENT == "pack":
250
+ PIPE.vae.to("cuda")
251
+ PIPE.audio_vae.to("cuda")
252
+
253
+ begin_request = getattr(PIPE.transformer, "begin_request", None)
254
+ end_request = getattr(PIPE.transformer, "end_request", None)
255
+ if begin_request is not None:
256
+ begin_request()
257
+ try:
258
+ with torch.inference_mode():
259
+ state = PIPE(
260
+ prompt_embeds=prompt_embeds.to("cuda", non_blocking=True),
261
+ text_token_tags=text_token_tags,
262
+ image=image,
263
+ last_image=last_image,
264
+ height=height,
265
+ width=width,
266
+ num_frames=num_frames,
267
+ num_inference_steps=int(steps),
268
+ generator=torch.Generator("cpu").manual_seed(int(seed)),
269
+ )
270
+ finally:
271
+ if end_request is not None:
272
+ end_request()
273
+ return state.get("videos")[0], state.get("audio")[0].cpu(), state.get("sampling_rate")
274
+
275
+
276
+ def generate(prompt, image_path=None, last_image_path=None, canvas=DEFAULT_CANVAS, duration=5, steps=28, seed=42, upsample=False, progress=gr.Progress(track_tqdm=True)):
277
+ """One request. `upsample` is last and defaults off, so a positional API client that predates it is unaffected."""
278
+ if LOAD_ERROR:
279
+ raise gr.Error(LOAD_ERROR)
280
+ if PIPE is None:
281
+ raise gr.Error("The denoiser is still loading.")
282
+ if not prompt or not prompt.strip():
283
+ raise gr.Error("MiniMax-H3 always takes a prompt, keyframes or not.")
284
+
285
+ from PIL import Image, ImageOps
286
+
287
+ from diffusers.utils import encode_video
288
+
289
+ num_frames = snap_frames(duration)
290
+
291
+ progress(0.0, desc=f"Upsampling the prompt on {CONDITIONER_SPACE} ..." if upsample else f"Conditioning on {CONDITIONER_SPACE} ...")
292
+ conditioned = time.time()
293
+ prompt_embeds, text_token_tags, metadata, plan = encode_remote(
294
+ prompt, image_path, last_image_path, canvas, num_frames, rewrite_prompt=upsample
295
+ )
296
+ condition_seconds = time.time() - conditioned
297
+ height, width, num_frames = (int(metadata[key]) for key in ("height", "width", "num_frames"))
298
+ refined = plan.get("refined_prompt") or ""
299
+
300
+ def keyframe(path):
301
+ # The conditioning latents encoded here have to be of the image the conditioner looked at, which it prepares
302
+ # exactly this way.
303
+ return ImageOps.exif_transpose(Image.open(path)).convert("RGB") if path else None
304
+
305
+ progress(0.1, desc=f"Denoising {steps} steps at {width}x{height}, {num_frames} frames ...")
306
+ started = time.time()
307
+ frames, audio, sampling_rate = _generate(
308
+ prompt_embeds,
309
+ text_token_tags,
310
+ keyframe(image_path),
311
+ keyframe(last_image_path),
312
+ height,
313
+ width,
314
+ num_frames,
315
+ steps,
316
+ seed,
317
+ )
318
+ generate_seconds = time.time() - started
319
+
320
+ directory = os.path.join(tempfile.gettempdir(), "h3-outputs")
321
+ os.makedirs(directory, exist_ok=True)
322
+ path = os.path.join(directory, f"h3-{int(time.time() * 1000)}.mp4")
323
+ encode_video(frames, fps=FPS, output_path=path, audio=audio, audio_sample_rate=sampling_rate)
324
+
325
+ report = (
326
+ f"`{width}x{height}`, {num_frames} frames ({num_frames / FPS:.3f} s), {int(steps)} steps · "
327
+ f"conditioner {condition_seconds:.0f}s ({plan['num_text_tokens']} tokens"
328
+ f"{', upsampled' if refined else ''}) · "
329
+ f"denoise + decode {generate_seconds:.0f}s ({generate_seconds / int(steps):.1f} s/step) · seed {int(seed)}"
330
+ )
331
+ print(f"[gen] {report}", flush=True)
332
+ return path, report, refined, gr.update(visible=bool(refined))
333
+
334
+
335
+ def _fit_keyframe(image_path, current_canvas):
336
+ """Cover-crop an uploaded keyframe to the closest supported aspect ratio and select that ratio's smallest
337
+ (fastest) canvas, unless the user already picked a matching ratio."""
338
+ if not image_path:
339
+ return gr.update(), gr.update()
340
+ from PIL import Image as _Image
341
+
342
+ img = _Image.open(image_path)
343
+ aspect = img.width / img.height
344
+ fastest = {}
345
+ for label, (h, w) in CANVASES.items():
346
+ r = w / h
347
+ if r not in fastest or w * h < fastest[r][1][0] * fastest[r][1][1]:
348
+ fastest[r] = (label, (h, w))
349
+ ratio = min(fastest, key=lambda r: abs(r - aspect))
350
+ label, (h, w) = fastest[ratio]
351
+
352
+ cur_h, cur_w = CANVASES[current_canvas]
353
+ if abs(cur_w / cur_h - aspect) <= abs(ratio - aspect):
354
+ label = current_canvas
355
+ h, w = cur_h, cur_w
356
+
357
+ target = w / h
358
+ if abs(img.width / img.height - target) <= 1e-3:
359
+ return gr.update(), gr.update(value=label)
360
+ if img.width / img.height > target:
361
+ new_w = int(img.height * target)
362
+ left = (img.width - new_w) // 2
363
+ img = img.crop((left, 0, left + new_w, img.height))
364
+ else:
365
+ new_h = int(img.width / target)
366
+ top = (img.height - new_h) // 2
367
+ img = img.crop((0, top, img.width, top + new_h))
368
+ img.save(image_path)
369
+ return gr.update(value=image_path), gr.update(value=label)
370
+
371
+
372
+ load_models()
373
+
374
+ INTRO = """# MiniMax-H3 Ultra
375
+
376
+ <div align="center">
377
+ <a href="https://huggingface.co/MiniMaxAI/MiniMax-H3" target="_blank" rel="noopener"><strong>[ model ]</strong></a> &nbsp;
378
+ <a href="https://huggingface.co/lilcheaty/MiniMax-H3-NVFP4" target="_blank" rel="noopener"><strong>[ NVFP4 ]</strong></a> &nbsp;
379
+ <a href="https://www.minimax.io/blog/minimax-h3" target="_blank" rel="noopener"><strong>[ blog ]</strong></a> &nbsp;
380
+ <a href="https://huggingface.co/spaces/multimodalart/minimax-h3-reference" target="_blank" rel="noopener"><strong>[ reference to video ]</strong></a>
381
+ </div>
382
+
383
+ **MiniMax-H3 Ultra** runs the pruned Blackwell-native NVFP4 transformer with fused QKV, fused Q/K norm + RoPE,
384
+ full-precision video/audio decoders, and the original synchronized soundtrack generation.
385
+ """
386
+
387
+ CSS = """
388
+ .main.fillable {max-width: 1250px !important}
389
+ .dark .gradio-container { color: var(--body-text-color); }
390
+ """
391
+
392
+ with gr.Blocks(title="MiniMax-H3") as demo:
393
+ gr.Markdown(INTRO)
394
+
395
+ with gr.Row():
396
+ with gr.Column():
397
+ prompt = gr.Textbox(
398
+ label="Prompt",
399
+ lines=3,
400
+ value="A red fox trotting through a snowy pine forest at dawn, snow crunching underfoot",
401
+ )
402
+ upsample = gr.Checkbox(label="Upsample prompt", value=False)
403
+ with gr.Row():
404
+ image = gr.Image(label="First frame (optional)", type="filepath")
405
+ last_image = gr.Image(label="Last frame (optional)", type="filepath")
406
+ run = gr.Button("Generate", variant="primary")
407
+ with gr.Accordion("Advanced options", open=False):
408
+ canvas = gr.Dropdown(label="Canvas", choices=list(CANVASES), value=DEFAULT_CANVAS)
409
+ duration = gr.Slider(label="Duration (s)", minimum=MIN_UI_DURATION, maximum=MAX_UI_DURATION, step=1, value=5)
410
+ steps = gr.Slider(label="Steps", minimum=10, maximum=40, step=1, value=28)
411
+ seed = gr.Number(label="Seed", value=42, precision=0)
412
+
413
+ with gr.Column():
414
+ video = gr.Video(label="Video + soundtrack")
415
+ report = gr.Markdown(visible=False)
416
+ # An output, so it can be revealed only for a request that asked for a rewrite.
417
+ with gr.Accordion("Upsampled prompt", open=False, visible=False) as upsampled_panel:
418
+ upsampled = gr.Textbox(show_label=False, lines=8, interactive=False)
419
+
420
+ image.upload(_fit_keyframe, [image, canvas], [image, canvas])
421
+
422
+ gr.Examples(
423
+ examples=[
424
+ ["A red fox trotting through a snowy pine forest at dawn, snow crunching underfoot", None, None, "1344x768 · 16:9 full"],
425
+ ["A busy night market, neon signs reflecting in puddles, sizzling street food", None, None, "768x1344 · 9:16 full"],
426
+ ["A cellist playing a slow melody in an empty concert hall", None, None, "768x768 · 1:1 full"],
427
+ ["The fox looks around, then trots deeper into the forest", "examples/first.png", None, "1344x768 · 16:9 full"],
428
+ ["A slow seamless camera move from the first view to the last", "examples/first.png", "examples/last.png", "1344x768 · 16:9 full"],
429
+ ],
430
+ inputs=[prompt, image, last_image, canvas],
431
+ outputs=[video, report, upsampled, upsampled_panel],
432
+ fn=generate,
433
+ cache_examples=True,
434
+ cache_mode="lazy",
435
+ )
436
+
437
+ run.click(
438
+ generate,
439
+ [prompt, image, last_image, canvas, duration, steps, seed, upsample],
440
+ [video, report, upsampled, upsampled_panel],
441
+ api_name="generate",
442
+ )
443
+
444
+ gr.Markdown(
445
+ '<div style="text-align:center"><a href="https://x.com/realmrfakename" target="_blank" '
446
+ 'rel="noopener">@realmrfakename</a></div>'
447
+ )
448
+
449
+
450
+ if __name__ == "__main__":
451
+ demo.queue().launch(show_error=True, theme=gr.themes.Citrus(), css=CSS)
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_nvfp4.py ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Blackwell-native MiniMax-H3 transformer for the pruned ComfyUI NVFP4 checkpoint.
2
+
3
+ The public diffusers checkpoint spends 13.04B of its 33.12B parameters on per-block
4
+ AdaLN projections. ComfyUI's pruned checkpoint replaces those projections with an
5
+ interpolated 1025-point timestep curve, fuses Q/K/V, and stores the four large linear
6
+ layers in every block as NVFP4. This adapter keeps diffusers' packed-sequence contract
7
+ so the rest of the split Space (schedulers, VAEs and remote conditioner) stays unchanged.
8
+
9
+ The kernel/layout conventions follow ComfyUI's Apache-2.0 implementation:
10
+ https://github.com/Comfy-Org/ComfyUI/blob/master/comfy/ldm/minimax/model.py
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ from types import SimpleNamespace
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+
24
+ NVFP4_REPO = os.environ.get("H3_NVFP4_REPO", "lilcheaty/MiniMax-H3-NVFP4")
25
+ NVFP4_FILE = os.environ.get("H3_NVFP4_FILE", "minimax_h3_fl2va_pruned_nvfp4.safetensors")
26
+
27
+ HIDDEN = 5376
28
+ HEADS = 56
29
+ HEAD_DIM = 128
30
+ FFN = 14336
31
+ TEXT_DIM = 5120
32
+ TIME_DIM = 8
33
+ VIDEO_DIM = 24 * 1 * 2 * 2
34
+ AUDIO_DIM = 32
35
+ LAYERS = 50
36
+ REFINER_LAYERS = 2
37
+ EPS = 1e-5
38
+
39
+
40
+ def _quant_config(handle, prefix: str) -> dict | None:
41
+ key = f"{prefix}.comfy_quant"
42
+ if key not in handle.keys():
43
+ return None
44
+ return json.loads(handle.get_tensor(key).numpy().tobytes())
45
+
46
+
47
+ class H3Linear(nn.Module):
48
+ """A plain or comfy-kitchen NVFP4 linear, selected by checkpoint metadata."""
49
+
50
+ def __init__(
51
+ self,
52
+ in_features: int,
53
+ out_features: int,
54
+ bias: bool = False,
55
+ compute_dtype: torch.dtype | None = None,
56
+ ):
57
+ super().__init__()
58
+ self.in_features = in_features
59
+ self.out_features = out_features
60
+ self.compute_dtype = compute_dtype
61
+ self.register_parameter("weight", None)
62
+ self.register_parameter("bias", None)
63
+ self.register_buffer("input_scale", None)
64
+ self.register_buffer("pre_quant_scale", None)
65
+ self.quantized = False
66
+
67
+ def load(self, handle, prefix: str) -> None:
68
+ config = _quant_config(handle, prefix)
69
+ weight = handle.get_tensor(f"{prefix}.weight")
70
+
71
+ if config is None:
72
+ self.weight = nn.Parameter(
73
+ weight if self.compute_dtype is None else weight.to(self.compute_dtype), requires_grad=False
74
+ )
75
+ elif config.get("format") == "nvfp4":
76
+ from comfy_kitchen.tensor import QuantizedTensor, TensorCoreNVFP4Layout
77
+
78
+ block_scale = handle.get_tensor(f"{prefix}.weight_scale")
79
+ if block_scale.dtype == torch.uint8:
80
+ block_scale = block_scale.view(torch.float8_e4m3fn)
81
+ tensor_scale = handle.get_tensor(f"{prefix}.weight_scale_2").float()
82
+ params = TensorCoreNVFP4Layout.Params(
83
+ scale=tensor_scale,
84
+ block_scale=block_scale,
85
+ orig_dtype=torch.bfloat16,
86
+ orig_shape=(self.out_features, self.in_features),
87
+ )
88
+ quantized = QuantizedTensor(weight.to(torch.uint8), "TensorCoreNVFP4Layout", params)
89
+ self.weight = nn.Parameter(quantized, requires_grad=False)
90
+ self.quantized = True
91
+ for name in ("input_scale", "pre_quant_scale"):
92
+ key = f"{prefix}.{name}"
93
+ if key in handle.keys():
94
+ setattr(self, name, handle.get_tensor(key))
95
+ else:
96
+ raise ValueError(f"Unsupported quantization on {prefix}: {config}")
97
+
98
+ bias_key = f"{prefix}.bias"
99
+ if bias_key in handle.keys():
100
+ bias = handle.get_tensor(bias_key)
101
+ self.bias = nn.Parameter(
102
+ bias if self.compute_dtype is None else bias.to(self.compute_dtype), requires_grad=False
103
+ )
104
+
105
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
106
+ if self.pre_quant_scale is not None:
107
+ hidden_states = hidden_states * self.pre_quant_scale.to(
108
+ device=hidden_states.device, dtype=hidden_states.dtype
109
+ )
110
+ if not self.quantized:
111
+ hidden_states = hidden_states.to(self.weight.dtype)
112
+ return F.linear(
113
+ hidden_states,
114
+ self.weight,
115
+ self.bias,
116
+ )
117
+
118
+ from comfy_kitchen.tensor import QuantizedTensor
119
+
120
+ shape = hidden_states.shape
121
+ flat = hidden_states.reshape(-1, shape[-1])
122
+ scale = None if self.input_scale is None else self.input_scale.to(flat.device)
123
+ quantized_input = QuantizedTensor.from_float(flat, "TensorCoreNVFP4Layout", scale=scale)
124
+ output = F.linear(
125
+ quantized_input,
126
+ self.weight,
127
+ None if self.bias is None else self.bias.to(hidden_states.dtype),
128
+ )
129
+ return output.reshape(*shape[:-1], self.out_features)
130
+
131
+
132
+ class H3RMSNorm(nn.Module):
133
+ def __init__(self, width: int, eps: float = EPS):
134
+ super().__init__()
135
+ self.width = width
136
+ self.eps = eps
137
+ self.register_parameter("weight", None)
138
+
139
+ def load(self, handle, prefix: str) -> None:
140
+ self.weight = nn.Parameter(handle.get_tensor(f"{prefix}.weight"), requires_grad=False)
141
+
142
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
143
+ return F.rms_norm(
144
+ hidden_states,
145
+ (self.width,),
146
+ self.weight.to(device=hidden_states.device, dtype=hidden_states.dtype),
147
+ self.eps,
148
+ )
149
+
150
+
151
+ class H3Attention(nn.Module):
152
+ def __init__(self):
153
+ super().__init__()
154
+ self.qkv_proj = H3Linear(HIDDEN, 3 * HEADS * HEAD_DIM)
155
+ self.q_norm = H3RMSNorm(HEAD_DIM)
156
+ self.k_norm = H3RMSNorm(HEAD_DIM)
157
+ self.out_proj = H3Linear(HEADS * HEAD_DIM, HIDDEN)
158
+
159
+ def load(self, handle, prefix: str) -> None:
160
+ self.qkv_proj.load(handle, f"{prefix}.qkv_proj")
161
+ self.q_norm.load(handle, f"{prefix}.q_norm")
162
+ self.k_norm.load(handle, f"{prefix}.k_norm")
163
+ self.out_proj.load(handle, f"{prefix}.out_proj")
164
+
165
+ def forward(self, hidden_states, rope_table, backend: str):
166
+ import comfy_kitchen as kitchen
167
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
168
+
169
+ sequence = hidden_states.shape[0]
170
+ qkv = self.qkv_proj(hidden_states)
171
+ query, key, value = qkv.split(HEADS * HEAD_DIM, dim=-1)
172
+ query = query.view(1, sequence, HEADS, HEAD_DIM)
173
+ key = key.view(1, sequence, HEADS, HEAD_DIM)
174
+ value = value.view(1, sequence, HEADS, HEAD_DIM)
175
+
176
+ # One in-place kernel replaces Q RMSNorm, K RMSNorm and both partial RoPE applications.
177
+ kitchen.rms_rope_split_half_(
178
+ query,
179
+ key,
180
+ rope_table,
181
+ self.q_norm.weight.to(query.device),
182
+ self.k_norm.weight.to(key.device),
183
+ epsilon=self.q_norm.eps,
184
+ rot_dim=rope_table.shape[-3] * 2,
185
+ )
186
+ attended = dispatch_attention_fn(
187
+ query,
188
+ key,
189
+ value,
190
+ attn_mask=None,
191
+ dropout_p=0.0,
192
+ is_causal=False,
193
+ backend=backend,
194
+ )
195
+ return self.out_proj(attended.reshape(sequence, HEADS * HEAD_DIM))
196
+
197
+
198
+ class H3MLP(nn.Module):
199
+ def __init__(self):
200
+ super().__init__()
201
+ self.fc1 = H3Linear(HIDDEN, 2 * FFN)
202
+ self.fc2 = H3Linear(FFN, HIDDEN)
203
+
204
+ def load(self, handle, prefix: str) -> None:
205
+ self.fc1.load(handle, f"{prefix}.fc1")
206
+ self.fc2.load(handle, f"{prefix}.fc2")
207
+
208
+ def forward(self, hidden_states):
209
+ gate, up = self.fc1(hidden_states).chunk(2, dim=-1)
210
+ return self.fc2(F.silu(gate).mul_(up))
211
+
212
+
213
+ class H3RefinerBlock(nn.Module):
214
+ def __init__(self):
215
+ super().__init__()
216
+ self.norm1 = H3RMSNorm(HIDDEN)
217
+ self.attn = H3Attention()
218
+ self.norm2 = H3RMSNorm(HIDDEN)
219
+ self.mlp = H3MLP()
220
+
221
+ def load(self, handle, prefix: str) -> None:
222
+ self.norm1.load(handle, f"{prefix}.norm1")
223
+ self.attn.load(handle, f"{prefix}.attn")
224
+ self.norm2.load(handle, f"{prefix}.norm2")
225
+ self.mlp.load(handle, f"{prefix}.mlp")
226
+
227
+
228
+ class H3AdaLN(nn.Module):
229
+ def __init__(self, expand: int, modalities: int):
230
+ super().__init__()
231
+ self.expand = expand
232
+ self.modalities = modalities
233
+ # Curve checkpoints deliberately evaluate interpolation and modulation projection in FP32. Expanding the
234
+ # checkpoint's tiny FP16 [*, 8] matrices once at load avoids 51 request-step casts.
235
+ self.linear = H3Linear(
236
+ TIME_DIM, expand * HIDDEN * modalities, bias=True, compute_dtype=torch.float32
237
+ )
238
+
239
+ def load(self, handle, prefix: str) -> None:
240
+ self.linear.load(handle, f"{prefix}.linear")
241
+
242
+ def forward(self, time_embedding):
243
+ projected = self.linear(time_embedding)
244
+ projected = projected.view(-1, self.expand * HIDDEN)
245
+ return projected.chunk(self.expand, dim=-1)
246
+
247
+
248
+ class H3Block(nn.Module):
249
+ def __init__(self):
250
+ super().__init__()
251
+ self.norm1 = H3RMSNorm(HIDDEN)
252
+ self.attn = H3Attention()
253
+ self.norm2 = H3RMSNorm(HIDDEN)
254
+ self.mlp = H3MLP()
255
+ self.adaln_proj = H3AdaLN(6, 3)
256
+
257
+ def load(self, handle, prefix: str) -> None:
258
+ self.norm1.load(handle, f"{prefix}.norm1")
259
+ self.attn.load(handle, f"{prefix}.attn")
260
+ self.norm2.load(handle, f"{prefix}.norm2")
261
+ self.mlp.load(handle, f"{prefix}.mlp")
262
+ self.adaln_proj.load(handle, f"{prefix}.adaln_proj")
263
+
264
+
265
+ class H3FinalLayer(nn.Module):
266
+ def __init__(self):
267
+ super().__init__()
268
+ self.norm = H3RMSNorm(HIDDEN)
269
+ self.adaln_proj = H3AdaLN(2, 1)
270
+ self.video_out = H3Linear(HIDDEN, VIDEO_DIM, bias=True, compute_dtype=torch.float32)
271
+ self.audio_out = H3Linear(HIDDEN, AUDIO_DIM, bias=True, compute_dtype=torch.float32)
272
+
273
+ def load(self, handle, prefix: str) -> None:
274
+ self.norm.load(handle, f"{prefix}.norm")
275
+ self.adaln_proj.load(handle, f"{prefix}.adaln_proj")
276
+ self.video_out.load(handle, f"{prefix}.video_out")
277
+ self.audio_out.load(handle, f"{prefix}.audio_out")
278
+
279
+
280
+ class H3NVFP4Transformer(nn.Module):
281
+ """Diffusers-compatible H3 transformer backed by fused comfy-kitchen NVFP4 kernels."""
282
+
283
+ def __init__(self):
284
+ super().__init__()
285
+ # The modular pipeline reads these values through the diffusers component config rather than inspecting the
286
+ # module itself. Keep the public transformer contract even though this lean adapter is not a ConfigMixin.
287
+ self.config = SimpleNamespace(
288
+ patch_size=(1, 2, 2),
289
+ in_channels=24,
290
+ audio_in_channels=AUDIO_DIM,
291
+ text_dim=TEXT_DIM,
292
+ )
293
+ self.video_patch_proj = H3Linear(VIDEO_DIM, HIDDEN, bias=True, compute_dtype=torch.float32)
294
+ self.audio_patch_proj = H3Linear(AUDIO_DIM, HIDDEN, bias=True, compute_dtype=torch.float32)
295
+ self.condition_proj = H3Linear(TEXT_DIM, HIDDEN, bias=True)
296
+ self.token_refiner = nn.ModuleList([H3RefinerBlock() for _ in range(REFINER_LAYERS)])
297
+ self.token_refiner_norm = H3RMSNorm(HIDDEN)
298
+ self.blocks = nn.ModuleList([H3Block() for _ in range(LAYERS)])
299
+ self.final_layer = H3FinalLayer()
300
+ self.register_buffer("adaln_t_table", None)
301
+ self.register_buffer("rope_inv_freq", None)
302
+ self.attention_backend = "_native_cudnn"
303
+ self._text_cache = None
304
+ self._rope_cache = None
305
+ self._segment_boundaries = None
306
+
307
+ @property
308
+ def dtype(self) -> torch.dtype:
309
+ """Match ModelMixin's placement contract used by ModularPipeline.to()."""
310
+ return self.condition_proj.weight.dtype
311
+
312
+ @property
313
+ def device(self) -> torch.device:
314
+ return self.adaln_t_table.device
315
+
316
+ def load(self, path: str) -> None:
317
+ from safetensors import safe_open
318
+
319
+ with safe_open(path, framework="pt", device="cpu") as handle:
320
+ self.video_patch_proj.load(handle, "video_patch_proj")
321
+ self.audio_patch_proj.load(handle, "audio_patch_proj")
322
+ self.condition_proj.load(handle, "condition_proj")
323
+ for index, block in enumerate(self.token_refiner):
324
+ block.load(handle, f"token_refiner.blocks.{index}")
325
+ self.token_refiner_norm.load(handle, "token_refiner.final_norm")
326
+ for index, block in enumerate(self.blocks):
327
+ block.load(handle, f"blocks.{index}")
328
+ self.final_layer.load(handle, "final_layer")
329
+ self.adaln_t_table = handle.get_tensor("adaln_t_table")
330
+ self.rope_inv_freq = handle.get_tensor("rope.inv_freq")
331
+ # Every loaded tensor is already a frozen Parameter (or a buffer). Avoid mutating the quantized tensor
332
+ # subclass through a redundant requires_grad_ dispatch.
333
+ self.eval()
334
+
335
+ def set_attention_backend(self, backend: str) -> None:
336
+ self.attention_backend = backend
337
+
338
+ def begin_request(self) -> None:
339
+ self._text_cache = None
340
+ self._rope_cache = None
341
+ self._segment_boundaries = None
342
+
343
+ def end_request(self) -> None:
344
+ self.begin_request()
345
+
346
+ def _refine_text(self, text_states: torch.Tensor) -> torch.Tensor:
347
+ key = (text_states.data_ptr(), tuple(text_states.shape), text_states.device)
348
+ if self._text_cache is not None and self._text_cache[0] == key:
349
+ return self._text_cache[1]
350
+ hidden = self.condition_proj(text_states)
351
+ # Text is tiny compared with the video sequence; use the same fused QKV path with an identity RoPE omitted.
352
+ for block in self.token_refiner:
353
+ residual = hidden
354
+ normalized = block.norm1(hidden)
355
+ qkv = block.attn.qkv_proj(normalized)
356
+ query, key_states, value = qkv.split(HEADS * HEAD_DIM, dim=-1)
357
+ query = block.attn.q_norm(query.view(1, -1, HEADS, HEAD_DIM))
358
+ key_states = block.attn.k_norm(key_states.view(1, -1, HEADS, HEAD_DIM))
359
+ value = value.view(1, -1, HEADS, HEAD_DIM)
360
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
361
+
362
+ attended = dispatch_attention_fn(
363
+ query,
364
+ key_states,
365
+ value,
366
+ attn_mask=None,
367
+ dropout_p=0.0,
368
+ is_causal=False,
369
+ backend=self.attention_backend,
370
+ ).reshape(-1, HEADS * HEAD_DIM)
371
+ hidden = residual + block.attn.out_proj(attended)
372
+ hidden = hidden + block.mlp(block.norm2(hidden))
373
+ hidden = self.token_refiner_norm(hidden)
374
+ self._text_cache = (key, hidden)
375
+ return hidden
376
+
377
+ def _rope(self, position_ids: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
378
+ key = (position_ids.data_ptr(), tuple(position_ids.shape), position_ids.device, dtype)
379
+ if self._rope_cache is not None and self._rope_cache[0] == key:
380
+ return self._rope_cache[1]
381
+ positions = position_ids.to(torch.float32)
382
+ frequencies = positions.unsqueeze(-1) * self.rope_inv_freq.to(position_ids.device).view(1, 1, -1)
383
+ temporal, height, width = frequencies.unbind(dim=1)
384
+ angles = torch.cat((temporal, height, width), dim=-1)
385
+ cosine, sine = angles.cos(), angles.sin()
386
+ table = torch.stack((cosine, -sine, sine, cosine), dim=-1)
387
+ table = table.reshape(1, position_ids.shape[0], 1, angles.shape[-1], 2, 2).to(dtype)
388
+ self._rope_cache = (key, table)
389
+ return table
390
+
391
+ def _time_embedding(self, timestep: torch.Tensor) -> torch.Tensor:
392
+ table = self.adaln_t_table.to(timestep.device)
393
+ position = timestep.float().clamp(0.0, 1.0) * (table.shape[0] - 1)
394
+ lower = position.floor().long().clamp(max=table.shape[0] - 2)
395
+ return torch.lerp(table[lower], table[lower + 1], (position - lower).unsqueeze(1))
396
+
397
+ def _segments(self, indices: torch.Tensor):
398
+ if self._segment_boundaries is None:
399
+ host = indices.detach().cpu()
400
+ changes = (host[1:] != host[:-1]).nonzero().flatten().add(1).tolist()
401
+ self._segment_boundaries = [0, *changes, len(host)]
402
+ bounds = self._segment_boundaries
403
+ return [(a, b, indices[a]) for a, b in zip(bounds[:-1], bounds[1:])]
404
+
405
+ @staticmethod
406
+ def _modulate(hidden, shift, scale, segments):
407
+ for start, stop, row in segments:
408
+ hidden[start:stop].mul_(1.0 + scale[row].to(hidden.dtype)).add_(shift[row].to(hidden.dtype))
409
+ return hidden
410
+
411
+ @staticmethod
412
+ def _gate(hidden, update, gate, segments):
413
+ for start, stop, row in segments:
414
+ hidden[start:stop].addcmul_(update[start:stop], gate[row].to(hidden.dtype))
415
+ return hidden
416
+
417
+ def forward(
418
+ self,
419
+ hidden_states,
420
+ audio_hidden_states,
421
+ encoder_hidden_states,
422
+ timestep,
423
+ timestep_indices,
424
+ token_tags,
425
+ position_ids,
426
+ video_indices,
427
+ audio_indices,
428
+ text_indices,
429
+ attention_kwargs=None,
430
+ return_dict=True,
431
+ ):
432
+ from diffusers.models.transformers.transformer_minimax_h3 import MiniMaxH3TransformerOutput
433
+
434
+ if hidden_states.shape[0] != 1:
435
+ raise ValueError("The NVFP4 MiniMax-H3 engine supports batch size 1.")
436
+
437
+ text = self._refine_text(encoder_hidden_states[0].to(torch.bfloat16))
438
+ video = self.video_patch_proj(hidden_states[0].float()).to(text.dtype)
439
+ audio = self.audio_patch_proj(audio_hidden_states[0].float()).to(text.dtype)
440
+ packed = text.new_zeros((position_ids.shape[0], HIDDEN))
441
+ packed.index_copy_(0, text_indices, text)
442
+ packed.index_copy_(0, video_indices, video)
443
+ packed.index_copy_(0, audio_indices, audio)
444
+
445
+ time_embedding = self._time_embedding(timestep)
446
+ adaln_indices = timestep_indices * 3 + token_tags.clamp(min=0)
447
+ segments = self._segments(adaln_indices)
448
+ rope = self._rope(position_ids, packed.dtype)
449
+
450
+ for block in self.blocks:
451
+ shift_attn, scale_attn, gate_attn, shift_mlp, scale_mlp, gate_mlp = block.adaln_proj(time_embedding)
452
+ normalized = self._modulate(block.norm1(packed), shift_attn, scale_attn, segments)
453
+ packed = self._gate(
454
+ packed,
455
+ block.attn(normalized, rope, self.attention_backend),
456
+ gate_attn,
457
+ segments,
458
+ )
459
+ normalized = self._modulate(block.norm2(packed), shift_mlp, scale_mlp, segments)
460
+ packed = self._gate(packed, block.mlp(normalized), gate_mlp, segments)
461
+
462
+ normalized = self.final_layer.norm(packed)
463
+ shift, scale = self.final_layer.adaln_proj(time_embedding)
464
+
465
+ video_times = timestep_indices.index_select(0, video_indices)
466
+ video_hidden = normalized.index_select(0, video_indices)
467
+ video_hidden = video_hidden * (1.0 + scale.index_select(0, video_times)) + shift.index_select(0, video_times)
468
+ video_output = self.final_layer.video_out(video_hidden.float()).unsqueeze(0)
469
+
470
+ audio_times = timestep_indices.index_select(0, audio_indices)
471
+ audio_hidden = normalized.index_select(0, audio_indices)
472
+ audio_hidden = audio_hidden * (1.0 + scale.index_select(0, audio_times)) + shift.index_select(0, audio_times)
473
+ audio_output = self.final_layer.audio_out(audio_hidden.float()).unsqueeze(0)
474
+
475
+ if not return_dict:
476
+ return video_output, audio_output
477
+ return MiniMaxH3TransformerOutput(sample=video_output, audio_sample=audio_output)
478
+
479
+
480
+ def load_transformer() -> H3NVFP4Transformer:
481
+ if torch.version.cuda is None or int(torch.version.cuda.split(".")[0]) < 13:
482
+ raise RuntimeError("NVFP4 requires the CUDA 13 PyTorch build.")
483
+ from huggingface_hub import hf_hub_download
484
+
485
+ path = hf_hub_download(repo_id=NVFP4_REPO, filename=NVFP4_FILE)
486
+ transformer = H3NVFP4Transformer()
487
+ transformer.load(path)
488
+ print(f"[h3-nvfp4] loaded {NVFP4_REPO}/{NVFP4_FILE}", flush=True)
489
+ return transformer
490
+
491
+
492
+ def status() -> str:
493
+ return f"NVFP4 · pruned AdaLN curve · fused QKV/QK-norm/RoPE · `{NVFP4_REPO}`"
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()
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Blackwell-native NVFP4 GEMMs and the fused Q/K RMSNorm + split-half RoPE kernel used by h3_nvfp4.py.
20
+ # CUDA 13 is mandatory: older builds emulate this path and are slower than BF16.
21
+ comfy-kitchen==0.2.26
22
+ # No `kernels` pin on purpose: the Hub attention backends want `kernels>=0.12.3`, and that version breaks
23
+ # transformers 5.8.0 at import.
24
+ # PyAV muxes the generated soundtrack onto the frames (`encode_video`).
25
+ av
26
+ pillow
27
+ numpy
28
+ requests
29
+ 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