Files changed (1) hide show
  1. app.py +4 -444
app.py CHANGED
@@ -1,445 +1,5 @@
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])
 
1
+ app = FastAPI()
2
 
3
+ @app.get("/")
4
+ def greet_json():
5
+ return {"Hello": "World!"}