Image-Text-to-Video
Diffusers
Safetensors
text-to-video
image-to-video
video-to-video
text-to-audio-video
image-to-audio-video
image-text-to-audio-video
video-to-audio-video
audio-to-audio-video
audio-video-generation
multimodal
synchronized-audio-video
reference-to-audio-video
Instructions to use MiniMaxAI/MiniMax-H3 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use MiniMaxAI/MiniMax-H3 with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("MiniMaxAI/MiniMax-H3", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
File size: 9,520 Bytes
5d9b308 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | # SPDX-License-Identifier: Apache-2.0
# Transformer building blocks for the MiniMax H3 visual VAE ViT decoder.
import math
import os
import torch
import torch.nn as nn
from typing import Optional
from diffusers.utils import logging
from diffusers.utils.torch_utils import maybe_allow_in_graph
from .attention import Attention
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
def _env_flag(name, default="0"):
value = os.environ.get(name, default)
return str(value).strip().lower() in ("1", "true", "yes", "on")
def _env_optional_bool(name, default=""):
value = str(os.environ.get(name, default)).strip().lower()
if value in ("", "default", "auto", "none", "unset"):
return None
return value not in ("0", "false", "no", "off", "disabled")
def _vit_torch_compile_kwargs(prefix):
kwargs = {}
backend = os.environ.get(f"{prefix}_BACKEND", "inductor").strip()
mode = os.environ.get(f"{prefix}_MODE", "reduce-overhead").strip()
if backend and backend.lower() not in ("default", "none"):
kwargs["backend"] = backend
if mode and mode.lower() not in ("default", "none"):
kwargs["mode"] = mode
kwargs["fullgraph"] = _env_flag(f"{prefix}_FULLGRAPH", "0")
dynamic = _env_optional_bool(f"{prefix}_DYNAMIC")
if dynamic is not None:
kwargs["dynamic"] = dynamic
return kwargs
def _vit_norm_input(module, hidden_states):
if _env_flag("MINIMAX_H3_VAE_DECODER_VIT_FP32_NORM", "1"):
return hidden_states.float()
return hidden_states.to(getattr(module.weight, "dtype", hidden_states.dtype))
class FeedForward(nn.Module):
def __init__(
self,
dim: int,
dim_out: Optional[int] = None,
mult: int = 4,
activation_fn: str = "silu",
bias: bool = True,
use_gated: bool = True,
glu_balanced: bool = False,
):
super().__init__()
ratio = 2 / 3 if (use_gated and glu_balanced) else 1
inner_dim = round(dim * mult * ratio)
dim_out = dim_out if dim_out is not None else dim
self.use_gated = use_gated
if use_gated:
self.w1 = nn.Linear(dim, inner_dim * 2, bias=bias)
else:
self.w1 = nn.Linear(dim, inner_dim, bias=bias)
if activation_fn == "silu":
self.act_fn = nn.SiLU()
elif activation_fn == "gelu":
self.act_fn = nn.GELU()
elif activation_fn == "gelu-approximate":
self.act_fn = nn.GELU(approximate="tanh")
else:
raise ValueError(f"Unsupported activation function: {activation_fn}")
self.w2 = nn.Linear(inner_dim, dim_out, bias=bias)
self._compile_forward_enabled = _env_flag(
"MINIMAX_H3_VAE_DECODER_VIT_FF_TORCH_COMPILE", "0"
)
self._compile_forward_fatal = _env_flag(
"MINIMAX_H3_VAE_DECODER_VIT_FF_TORCH_COMPILE_FATAL", "0"
)
self._compiled_forward = None
def _forward_impl(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.w1(hidden_states)
if self.use_gated:
gate, hidden_states = hidden_states.chunk(2, dim=-1)
hidden_states = self.act_fn(gate) * hidden_states
else:
hidden_states = self.act_fn(hidden_states)
hidden_states = self.w2(hidden_states)
return hidden_states
def _get_forward_impl(self):
if not self._compile_forward_enabled:
return self._forward_impl
if self._compiled_forward is not None:
return self._compiled_forward
if not hasattr(torch, "compile"):
message = "torch.compile is unavailable; falling back to eager ViT FeedForward"
if self._compile_forward_fatal:
raise RuntimeError(message)
logger.warning(f"[ViTFeedForward] {message}")
self._compile_forward_enabled = False
return self._forward_impl
kwargs = _vit_torch_compile_kwargs("MINIMAX_H3_VAE_DECODER_VIT_FF_TORCH_COMPILE")
try:
self._compiled_forward = torch.compile(self._forward_impl, **kwargs)
logger.info(f"[ViTFeedForward] torch.compile enabled kwargs={kwargs}")
except Exception as exc:
if self._compile_forward_fatal:
raise
logger.warning(
f"[ViTFeedForward] torch.compile setup failed: {type(exc).__name__}: {exc}; "
"falling back to eager"
)
self._compile_forward_enabled = False
self._compiled_forward = None
return self._forward_impl
return self._compiled_forward
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
forward_impl = self._get_forward_impl()
try:
return forward_impl(hidden_states)
except Exception as exc:
if (
self._compile_forward_enabled
and self._compiled_forward is not None
and forward_impl is self._compiled_forward
and not self._compile_forward_fatal
):
logger.warning(
f"[ViTFeedForward] compiled forward failed: {type(exc).__name__}: {exc}; "
"disabling compile and retrying eager"
)
self._compile_forward_enabled = False
self._compiled_forward = None
return self._forward_impl(hidden_states)
raise
class RotaryEmbeddingND(nn.Module):
def __init__(self, dim, rotary_base=10000, n_dim=3, use_angle=False):
super().__init__()
self.dim = dim
self.n_dim = n_dim
if dim % (2 * n_dim) != 0:
raise ValueError(
f"head_dim {dim} must be divisible by 2 * n_dim {2 * n_dim}"
)
if use_angle:
self.angle_scale = 2.0 * math.pi
else:
self.angle_scale = 1.0
inv_freq = 1 / rotary_base ** torch.arange(
0, 1, 2 * n_dim / dim, dtype=torch.float32
)
self.register_buffer("inv_freq", inv_freq, persistent=False)
def forward(self, img_ids):
B, N, D = img_ids.shape
if D != self.n_dim:
raise ValueError(f"Expected {self.n_dim} dimensions, got {D}")
with torch.autocast("cuda", enabled=False):
angles = (
self.angle_scale
* img_ids[:, :, :, None]
* self.inv_freq.to(img_ids.device)[None, None, None, :]
)
angles = angles.flatten(2, 3)
angles = angles.tile(2)
angles = angles.unsqueeze(2)
cos = torch.cos(angles)
sin = torch.sin(angles)
return cos.to(dtype=img_ids.dtype), sin.to(dtype=img_ids.dtype)
@maybe_allow_in_graph
class TransformerBlock(nn.Module):
def __init__(
self,
heads: int,
dim_head: int,
embed_dim: Optional[int] = None,
ffn_glu_balanced: bool = False,
norm_type: str = "layer_norm",
norm_affine: bool = True,
qk_norm_type: str = "rms_norm",
qk_norm_affine: bool = False,
ffn_activation_fn: str = "silu",
ffn_use_gated: bool = True,
use_scale: bool = True,
bias: bool = True,
eps: float = 1e-5,
**kwargs,
):
super().__init__()
dim = embed_dim if embed_dim is not None else dim_head * heads
self.use_scale = use_scale
if norm_type == "layer_norm":
norm_class = nn.LayerNorm
elif norm_type == "rms_norm":
norm_class = nn.RMSNorm
else:
raise ValueError(f"unknown norm_type {norm_type}")
self.norm1 = norm_class(
dim,
elementwise_affine=norm_affine,
eps=eps,
)
self.attn = Attention(
heads=heads,
dim_head=dim_head,
embed_dim=dim,
qk_norm_type=qk_norm_type,
qk_norm_affine=qk_norm_affine,
bias=bias,
eps=eps,
**kwargs,
)
if use_scale:
self.scale1 = nn.Parameter(torch.zeros(dim))
self.norm2 = norm_class(
dim,
elementwise_affine=norm_affine,
eps=eps,
)
self.ff = FeedForward(
dim=dim,
activation_fn=ffn_activation_fn,
bias=bias,
use_gated=ffn_use_gated,
glu_balanced=ffn_glu_balanced,
)
if use_scale:
self.scale2 = nn.Parameter(torch.zeros(dim))
def forward(
self,
hidden_states: torch.FloatTensor,
rotary_pos_emb: Optional[torch.FloatTensor] = None,
pack_info: dict = {},
):
norm_hidden_states = self.norm1(_vit_norm_input(self.norm1, hidden_states)).to(hidden_states.dtype)
attn_output = self.attn(norm_hidden_states, rotary_pos_emb, pack_info)
if self.use_scale:
hidden_states = hidden_states + attn_output * self.scale1
else:
hidden_states = hidden_states + attn_output
norm_hidden_states = self.norm2(_vit_norm_input(self.norm2, hidden_states)).to(hidden_states.dtype)
ff_output = self.ff(norm_hidden_states)
if self.use_scale:
hidden_states = hidden_states + ff_output * self.scale2
else:
hidden_states = hidden_states + ff_output
return hidden_states
|