MiniMax H3
Video with its own stereo audio from one denoising pass, at 768p. This is H3-Base, the part MiniMax published. The context stage their own workflow runs in front of it is not open, so results here are the base model's rather than what their API returns.
What runs
This is the whole app. The entry names the model and what serves it, and the build turns that into these files: there is nothing else to write.
"""MiniMax H3, generated from a declarative template."""
from __future__ import annotations
import base64
import os
import tempfile
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from runware_serverless import serve
MODEL = "MiniMaxAI/MiniMax-H3"
REVISION = "42ed227ee7df40d41602854ae760620d6eb651fe"
CACHE = "/weights"
FPS = 24
TOKEN_BUDGET = 262080
FRAME_BLOCK = 17
FRAME_BASE = 5
DEFAULT_FRAMES = 124
TRAINED_SHORT_EDGE = 768
TRAINED_WIDTH = 1344
# The model's own API names a canvas by its short edge and an aspect ratio, and
# this follows it, so every canvas is a multiple of 32 and none of them has to be
# refused. The patch size is 32 along height and width.
RATIOS = {"16:9": (16, 9), "9:16": (9, 16), "1:1": (1, 1), "4:3": (4, 3), "3:4": (3, 4)}
def _canvas(aspect: str, short_edge: int) -> tuple[int, int]:
wide, tall = RATIOS[aspect]
if wide >= tall:
return (short_edge * wide // tall) // 32 * 32, short_edge
return short_edge, (short_edge * tall // wide) // 32 * 32
class Request(BaseModel):
# An input this model does not read is a line the caller believed was doing
# something, so it is refused rather than dropped. Without this, pydantic
# ignores it: a width sent to a model of fixed size, or a misspelled seed,
# both come back as a result that silently answered a different request.
model_config = ConfigDict(extra="forbid")
prompt: str = Field(description="What to generate, as video with its own audio.")
frames: int = Field(
default=DEFAULT_FRAMES,
ge=124,
le=345,
description=(
"At 24 fps. The model snaps this up to the next length of the form 17n+5,"
" which its video VAE decodes in blocks, so 124 is the floor and 345 the"
" ceiling that stays inside the five to fifteen seconds it generates."
),
)
steps: int = Field(
default=50,
ge=2,
le=100,
description=(
"Denoising steps. 50 is the model's own default, and the whole request scales with"
" this, because the transformer is nearly all of it. Two is the floor rather than"
" one, because the step count includes the terminal point of the sigma grid and"
" that one drives no evaluation."
),
)
short_edge: int = Field(
default=TRAINED_SHORT_EDGE,
ge=512,
le=TRAINED_SHORT_EDGE,
multiple_of=32,
description=(
"The shorter side of the frame, which the aspect ratio turns into a canvas. The"
" largest speed lever here and the only one that changes the result: 544 runs at"
" 2.59 times the speed per step of the trained 768, measured at 124 frames in 16:9."
" 768 is the ceiling because this is H3-Base."
),
)
aspect: Literal["16:9", "9:16", "1:1", "4:3", "3:4"] = Field(
default="16:9",
description="The ratio the short edge is grown into. 16:9 is what the model trained on.",
)
seed: int | None = Field(default=None, description="Repeat a result by repeating its seed.")
@model_validator(mode="after")
def _fits_on_the_card(self) -> "Request":
# Refused here rather than discovered on the card. A clip past what one
# card holds raises out of memory inside the request, which takes the
# worker with it, so the caller gets a dead app instead of an answer.
#
# One budget covers both axes, because the cost and the peak follow the
# token count and not how it was split: 175 frames at 1344x768 and 345
# at 960x544 are within 0.3% of each other on tokens and within 0.6% on
# time per step.
width, height = _canvas(self.aspect, self.short_edge)
blocks = -(-(self.frames - FRAME_BASE) // FRAME_BLOCK)
tokens = (blocks * FRAME_BLOCK + FRAME_BASE) * (width // 32) * (height // 32)
if tokens > TOKEN_BUDGET:
raise ValueError(
f"{self.frames} frames at {width}x{height} is {tokens} transformer tokens"
f" and one card holds {TOKEN_BUDGET}. Shorten the clip or lower short_edge:"
" the two trade against each other, so the same budget buys about 10 seconds"
" at the trained canvas or about 14 at a 544 short edge."
)
return self
class Generated(BaseModel):
video: str = Field(description="The result as a base64 MP4, with its audio muxed in.")
frames: int
width: int
height: int
steps: int
seed: int | None
@serve
class GeneratedVideo:
def load(self) -> None:
if hasattr(self, "pipeline"):
return
# Imported here rather than at the top of the file. The build imports
# this file with the platform's own dependencies, so nothing above
# exists until a worker runs.
import torch
from diffusers import ModularPipeline
self.torch = torch
self.pipeline = ModularPipeline.from_pretrained(
MODEL, revision=REVISION, cache_dir=CACHE
)
from diffusers import MiniMaxH3Transformer3DModel, TorchAoConfig
from transformers import Qwen3VLForConditionalGeneration
from transformers import TorchAoConfig as TransformersTorchAoConfig
from torchao.quantization import Int8WeightOnlyConfig
def recipe() -> object:
return Int8WeightOnlyConfig(version=2)
self.pipeline.update_components(
transformer=MiniMaxH3Transformer3DModel.from_pretrained(
MODEL,
subfolder="transformer",
revision=REVISION,
cache_dir=CACHE,
dtype=torch.bfloat16,
device_map="cuda",
quantization_config=TorchAoConfig(
recipe(),
modules_to_not_convert=[
"proj_in",
"audio_proj_in",
"context_embedder",
"time_embedder",
"time_proj",
"token_refiner",
"norm_out",
"proj_out",
"audio_proj_out",
],
),
),
text_encoder=Qwen3VLForConditionalGeneration.from_pretrained(
MODEL,
subfolder="text_encoder",
revision=REVISION,
cache_dir=CACHE,
dtype=torch.bfloat16,
device_map="cuda",
quantization_config=TransformersTorchAoConfig(
recipe(),
modules_to_not_convert=[
"model.visual",
"model.language_model.embed_tokens",
"model.language_model.norm",
"lm_head",
],
),
),
)
# Every component stays on the card. A worker's host RAM is half its
# card's VRAM, 48 GiB against 96 GiB here, so offloading to the host
# runs out of memory long before the card does: the kill then comes
# from the container's cgroup as exit 137, not from torch as a CUDA
# error, which is why it reads as a platform fault rather than a
# sizing one.
self.pipeline.load_components(
workflow="fl2va", dtype=torch.bfloat16, device_map="cuda"
)
def predict(self, request: Request) -> Generated:
from diffusers.utils.export_utils import encode_video
generator = None
if request.seed is not None:
generator = self.torch.Generator().manual_seed(request.seed)
width, height = _canvas(request.aspect, request.short_edge)
results = self.pipeline(
prompt=request.prompt,
num_frames=request.frames,
num_inference_steps=request.steps,
width=width,
height=height,
generator=generator,
output=["videos", "audio", "sampling_rate"],
)
videos, audio, sampling_rate = _named(results)
# Both are indexed, because the pipeline returns a batch and the encoder
# takes one clip. Dropping the batch dimension on the audio matters more
# than it looks: the encoder treats any shape carrying a 1 as mono and
# flattens it, so a stereo [1, 2, N] becomes one interleaved channel of
# 2N and the track plays at twice the length of the picture.
clip, track = videos[0], audio[0]
with tempfile.NamedTemporaryFile(suffix=".mp4") as handle:
encode_video(
clip,
fps=FPS,
output_path=handle.name,
audio=track,
audio_sample_rate=sampling_rate,
)
handle.seek(0)
encoded = base64.b64encode(handle.read()).decode("ascii")
# What came out, not what was asked for. The model rounds the frame
# count to its own stride, so the two differ.
return Generated(
video=encoded,
frames=len(clip),
width=width,
height=height,
steps=request.steps,
seed=request.seed,
)
def _component(pipeline: object, name: str) -> object:
"""A pipeline component, whether it hangs off the pipeline or its components."""
direct = getattr(pipeline, name, None)
if direct is not None:
return direct
components = getattr(pipeline, "components", None)
if isinstance(components, dict):
return components[name]
return getattr(components, name)
def _named(results: object) -> tuple:
"""The named outputs, however the pipeline hands them back."""
if isinstance(results, dict):
return results["videos"], results["audio"], results["sampling_rate"]
if hasattr(results, "videos"):
return results.videos, results.audio, results.sampling_rate
return tuple(results)configVersion: 1
id: minimax-h3
name: MiniMax H3
source:
type: code
entry: model.py
compute:
gpuType: rtx-pro-6000
build:
requirements:
- torch==2.14.1
- torchvision==0.29.1
- diffusers==0.42.1
- transformers==5.21.0
- accelerate==1.15.0
- av==16.0.1
- torchao==0.18.0
volumes:
- /weightsDeploying
Deploy it as it is, or take the files above and deploy your own copy. Nothing you change reaches back to this page.
runware serverless deploy --from https://runware.ai/docs/serverless/examples/minimax-h3.ziprunware serverless deploy model.py \
--id minimax-h3 \
--gpu-type rtx-pro-6000 \
--requirement torch==2.14.1 \
--requirement torchvision==0.29.1 \
--requirement diffusers==0.42.1 \
--requirement transformers==5.21.0 \
--requirement accelerate==1.15.0 \
--requirement av==16.0.1 \
--requirement torchao==0.18.0 \
--volume /weightsCalling it
One request that works, against the app you just deployed. The fields are the ones the entry declares above, and anything it does not declare is refused rather than ignored.
import { createClient } from '@runware/sdk'
const client = await createClient({ apiKey: process.env.RUNWARE_API_KEY })
const task = await client.invoke({
appId: 'minimax-h3',
endpointPath: 'predict',
payload: {
request: {
prompt: 'A paper boat drifting down a rain gutter, close up'
}
}
})import asyncio
import os
from runware import Runware
async def main():
client = Runware(api_key=os.environ["RUNWARE_API_KEY"])
try:
task = await client.invoke(
"minimax-h3",
"predict",
{
"request": {
"prompt": "A paper boat drifting down a rain gutter, close up"
}
},
)
finally:
await client.close()
asyncio.run(main())curl https://api.serverless.runware.ai/v1/apps/minimax-h3/invoke-async/predict \
-H "Authorization: Bearer $RUNWARE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"taskId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"payload": {
"request": {
"prompt": "A paper boat drifting down a rain gutter, close up"
}
}
}'cat <<'EOF' | runware serverless apps invoke minimax-h3 predict -f -
{
"request": {
"prompt": "A paper boat drifting down a rain gutter, close up"
}
}
EOF{
"taskId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"payload": {
"request": {
"prompt": "A paper boat drifting down a rain gutter, close up"
}
}
}What it costs
This entry is pinned to rtx-pro-6000, which is the card it was tested on rather than the only one it runs on: --gpu-type deploys it somewhere else. You pay for that card by the second while a worker holds it, and for nothing else. Pricing covers what meters, and the rates are published per GPU-second.