MiniMax-H3-Turbo / run_ref2va.py
cg233's picture
Add Ref2VA Turbo 8-step model and standalone inference demo
48c7709 verified
Raw History Blame Contribute Delete
18 kB
from __future__ import annotations
import argparse
from contextlib import nullcontext
import json
from pathlib import Path
from types import MethodType
from huggingface_hub import snapshot_download
from safetensors import safe_open
import torch
from torch import nn
from diffusers import ComponentsManager, ModularPipeline
from diffusers.modular_pipelines.minimax_h3.references import (
MiniMaxH3AudioReference,
MiniMaxH3ImageReference,
MiniMaxH3VideoReference,
)
from diffusers.schedulers.scheduling_minimax_h3 import MiniMaxH3Scheduler, MiniMaxH3SchedulerOutput
from diffusers.utils import encode_video
from diffusers.models.modeling_utils import get_parameter_dtype
from diffusers.models.transformers.transformer_minimax_h3 import (
MiniMaxH3Transformer3DModel, MiniMaxH3TransformerOutput,
)
OFFICIAL_REPO = "MiniMaxAI/MiniMax-H3"
TURBO_REPO = "Wuli-art/MiniMax-H3-Turbo"
BASE_COMPONENTS = (
"text_encoder", "tokenizer", "processor", "vae", "audio_vae",
"scheduler", "audio_scheduler",
)
def ensure_processor_compat(processor) -> None:
if hasattr(processor, "create_mm_token_type_ids"):
return
def create_mm_token_type_ids(instance, batches):
return [[
1 if token == instance.image_token_id else
2 if token == instance.video_token_id else 0
for token in row
] for row in batches]
processor.create_mm_token_type_ids = MethodType(create_mm_token_type_ids, processor)
class _BlockTimeEmbedding(nn.Module):
def __init__(self, rows: int, modalities: int, hidden_size: int) -> None:
super().__init__()
self.register_buffer(
"weight",
torch.empty(rows, modalities, 6, hidden_size, dtype=torch.bfloat16),
)
class _OutputTimeEmbedding(nn.Module):
def __init__(self, rows: int, hidden_size: int) -> None:
super().__init__()
self.register_buffer(
"weight", torch.empty(rows, 2, hidden_size, dtype=torch.bfloat16)
)
class FixedMiniMaxH3Transformer3DModel(MiniMaxH3Transformer3DModel):
"""Official Diffusers H3 trunk with fixed video/audio time embeddings."""
_supports_gradient_checkpointing = False
_keep_in_fp32_modules = ["proj_in", "audio_proj_in", "proj_out", "audio_proj_out", "rope"]
def __init__(
self,
num_attention_heads: int = 56,
attention_head_dim: int = 128,
hidden_size: int = 5376,
num_layers: int = 50,
num_refiner_layers: int = 2,
ffn_dim: int = 14336,
in_channels: int = 24,
audio_in_channels: int = 32,
patch_size: tuple[int, int, int] = (1, 2, 2),
text_dim: int = 5120,
freq_dim: int = 256,
time_embed_hidden_dim: int = 5376,
time_embed_dim: int = 2688,
rope_freq_dim: int = 16,
rope_theta: float = 10000.0,
norm_eps: float = 1e-5,
qk_norm_eps: float = 1e-5,
final_norm_eps: float = 1e-5,
fixed_num_steps: int = 8,
fixed_audio_reference: bool = False,
fixed_reference_layouts: bool = False,
) -> None:
super().__init__(
num_attention_heads=num_attention_heads,
attention_head_dim=attention_head_dim,
hidden_size=hidden_size,
num_layers=num_layers,
num_refiner_layers=num_refiner_layers,
ffn_dim=ffn_dim,
in_channels=in_channels,
audio_in_channels=audio_in_channels,
patch_size=patch_size,
text_dim=text_dim,
freq_dim=freq_dim,
time_embed_hidden_dim=time_embed_hidden_dim,
time_embed_dim=time_embed_dim,
rope_freq_dim=rope_freq_dim,
rope_theta=rope_theta,
norm_eps=norm_eps,
qk_norm_eps=qk_norm_eps,
final_norm_eps=final_norm_eps,
)
fixed_num_steps = int(fixed_num_steps)
self.register_to_config(
fixed_num_steps=fixed_num_steps,
fixed_audio_reference=bool(fixed_audio_reference),
fixed_reference_layouts=bool(fixed_reference_layouts),
)
if fixed_reference_layouts and not fixed_audio_reference:
raise ValueError("reference layouts require audio-reference time embeddings")
hidden_size = int(self.config.hidden_size)
video_rows = (fixed_num_steps + 2) * (2 if fixed_reference_layouts else 1)
audio_rows = fixed_num_steps * (2 if fixed_reference_layouts else 1) + int(fixed_audio_reference)
self.video_time_embedding = nn.ModuleList(
[_BlockTimeEmbedding(video_rows, 2, hidden_size) for _ in self.transformer_blocks]
)
self.audio_time_embedding = nn.ModuleList(
[
_BlockTimeEmbedding(audio_rows, 1, hidden_size)
for _ in self.transformer_blocks
]
)
self.video_output_time_embedding = _OutputTimeEmbedding(video_rows, hidden_size)
self.audio_output_time_embedding = _OutputTimeEmbedding(audio_rows, hidden_size)
self.register_buffer("video_timesteps", torch.empty(fixed_num_steps, dtype=torch.float32))
self.register_buffer("audio_timesteps", torch.empty(fixed_num_steps, dtype=torch.float32))
self.register_buffer("visual_condition_timestep", torch.tensor(0.999, dtype=torch.float32))
self.time_proj = None
self.time_embedder = None
for block in self.transformer_blocks:
block.adaln_proj = None
self.norm_out.linear = None
@staticmethod
def _step(value: torch.Tensor, schedule: torch.Tensor) -> int:
error = (schedule - value.float()).abs()
index = int(error.argmin())
if float(error[index]) > 2e-6:
raise ValueError(
f"unsupported timestep {float(value):.9f}; "
f"use the checkpoint's fixed {schedule.numel()}-step schedule"
)
return index
def _row_plan(self, timestep, timestep_indices, token_tags):
row_t = timestep.index_select(0, timestep_indices).float()
is_video = token_tags == 0
is_text = token_tags == 1
is_audio = token_tags == 2
is_audio_reference = is_audio & torch.isclose(
row_t, torch.ones_like(row_t), rtol=0.0, atol=2e-6
)
if is_audio_reference.any() and not self.config.fixed_audio_reference:
raise ValueError("this checkpoint does not contain audio-reference time embeddings")
is_condition = is_video & torch.isclose(
row_t, self.visual_condition_timestep, rtol=0.0, atol=2e-6
)
probe = row_t[is_text]
if probe.numel() == 0:
probe = row_t[is_video & ~is_condition]
if probe.numel() == 0:
raise ValueError("cannot resolve the current video step")
step = self._step(probe[0], self.video_timesteps)
generated_audio = is_audio & ~is_audio_reference
if generated_audio.any() and self._step(row_t[generated_audio][0], self.audio_timesteps) != step:
raise ValueError("video and audio schedules are on different steps")
return step, is_video, is_text, generated_audio, is_condition, is_audio_reference
def forward(
self,
hidden_states: torch.Tensor,
audio_hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor,
timestep: torch.Tensor,
timestep_indices: torch.Tensor,
token_tags: torch.Tensor,
position_ids: torch.Tensor,
video_indices: torch.Tensor,
audio_indices: torch.Tensor,
text_indices: torch.Tensor,
attention_kwargs: dict | None = None,
return_dict: bool = True,
):
del attention_kwargs
rotary_emb = self.rope(position_ids)
video = self.proj_in(hidden_states.to(get_parameter_dtype(self.proj_in)))
audio = self.audio_proj_in(audio_hidden_states.to(get_parameter_dtype(self.audio_proj_in)))
text = self.context_embedder(encoder_hidden_states.to(get_parameter_dtype(self.context_embedder)))
text = self.token_refiner(text)
packed = text.new_zeros((text.shape[0], position_ids.shape[0], text.shape[-1]))
packed = packed.index_copy(1, text_indices, text)
packed = packed.index_copy(1, video_indices, video.to(text.dtype))
packed = packed.index_copy(1, audio_indices, audio.to(text.dtype))
step, is_video, is_text, is_audio, is_condition, is_audio_reference = self._row_plan(
timestep, timestep_indices, token_tags
)
use_audio_layout = bool(is_audio_reference.any()) and self.config.fixed_reference_layouts
video_offset = self.config.fixed_num_steps + 2 if use_audio_layout else 0
audio_offset = self.config.fixed_num_steps if use_audio_layout else 0
audio_reference_row = self.audio_time_embedding[0].weight.shape[0] - 1
condition_row = video_offset + self.config.fixed_num_steps + int(step == self.config.fixed_num_steps - 1)
for layer, block in enumerate(self.transformer_blocks):
table = packed.new_empty((token_tags.numel(), 6, packed.shape[-1]))
table[is_video & ~is_condition] = self.video_time_embedding[layer].weight[video_offset + step, 0]
table[is_condition] = self.video_time_embedding[layer].weight[condition_row, 0]
table[is_text] = self.video_time_embedding[layer].weight[video_offset + step, 1]
table[is_audio] = self.audio_time_embedding[layer].weight[audio_offset + step, 0]
if is_audio_reference.any():
table[is_audio_reference] = self.audio_time_embedding[layer].weight[audio_reference_row, 0]
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = table.unbind(dim=1)
residual = packed
value = block.norm1(packed)
value = value * (1.0 + scale_msa[None]) + shift_msa[None]
packed = residual + gate_msa[None] * block.attn(value, rotary_emb)
residual = packed
value = block.norm2(packed)
value = value * (1.0 + scale_mlp[None]) + shift_mlp[None]
packed = residual + gate_mlp[None] * block.ff(value)
output_table = packed.new_empty((token_tags.numel(), 2, packed.shape[-1]))
output_table[is_video & ~is_condition] = self.video_output_time_embedding.weight[video_offset + step]
output_table[is_condition] = self.video_output_time_embedding.weight[condition_row]
output_table[is_text] = self.video_output_time_embedding.weight[video_offset + step]
output_table[is_audio] = self.audio_output_time_embedding.weight[audio_offset + step]
if is_audio_reference.any():
output_table[is_audio_reference] = self.audio_output_time_embedding.weight[audio_reference_row]
shift, scale = output_table.unbind(dim=1)
packed = self.norm_out.norm(packed) * (1.0 + scale[None]) + shift[None]
packed = packed.to(get_parameter_dtype(self.proj_out))
video = self.proj_out(packed).index_select(1, video_indices)
audio = self.audio_proj_out(packed).index_select(1, audio_indices)
if not return_dict:
return video, audio
return MiniMaxH3TransformerOutput(sample=video, audio_sample=audio)
class ReferenceArgument(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
references = list(getattr(namespace, self.dest, None) or [])
references.append((option_string[2:], values))
setattr(namespace, self.dest, references)
class FixedStepMiniMaxH3Scheduler(MiniMaxH3Scheduler):
def step(self, model_output, timestep, sample, return_dict=True):
if isinstance(timestep, int) or (torch.is_tensor(timestep) and not timestep.is_floating_point()):
raise ValueError('pass a floating-point scheduler timestep')
if self._step_index is None:
self._step_index = self.index_for_timestep(timestep) if self._begin_index is None else self._begin_index
compute_dtype = torch.float32 if sample.dtype in (torch.float16, torch.bfloat16) else sample.dtype
gap = (self.sigmas[self._step_index] - self.sigmas[self._step_index + 1]).to(
device=sample.device, dtype=compute_dtype,
)
previous = sample.to(compute_dtype) + gap * model_output.to(compute_dtype)
self._step_index += 1
previous = previous.to(sample.dtype)
if not return_dict:
return (previous,)
return MiniMaxH3SchedulerOutput(prev_sample=previous)
def load_pipeline(model_path=None, components_path=OFFICIAL_REPO, device='cuda', cpu_offload=True):
component_names = list(BASE_COMPONENTS)
base_root = Path(components_path)
if not base_root.is_dir():
base_root = Path(snapshot_download(
repo_id=components_path,
allow_patterns=['model_index.json', 'modular_model_index.json']
+ [f'{name}/*' for name in component_names],
))
if model_path is None:
model_root = Path(snapshot_download(
repo_id=TURBO_REPO,
allow_patterns=['ref2va-turbo-8step/*'],
)) / 'ref2va-turbo-8step'
else:
model_root = Path(model_path)
transformer_path = model_root / 'transformer'
config = json.loads((transformer_path / 'config.json').read_text())
if config.get('fixed_num_steps') != 8 or not config.get('fixed_audio_reference') or not config.get('fixed_reference_layouts'):
raise ValueError('expected a ref2va-turbo-8step checkpoint')
manager = ComponentsManager()
if cpu_offload:
manager.enable_auto_cpu_offload(device=device, memory_reserve_margin='12GB')
pipe = ModularPipeline.from_pretrained(base_root, workflow='ref2va', components_manager=manager)
pipe.load_components(
names=component_names,
dtype={'vae': torch.float32, 'audio_vae': torch.float32, 'default': torch.bfloat16},
pretrained_model_name_or_path=str(base_root),
)
ensure_processor_compat(pipe.processor)
transformer, loading = FixedMiniMaxH3Transformer3DModel.from_pretrained(
transformer_path, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True, output_loading_info=True,
)
if any(loading.get(name) for name in ("missing_keys", "unexpected_keys", "mismatched_keys", "error_msgs")):
raise ValueError("the checkpoint does not match the Ref2VA transformer")
index = json.loads((transformer_path / 'diffusion_pytorch_model.safetensors.index.json').read_text())['weight_map']
for name in ('video_timesteps', 'audio_timesteps', 'visual_condition_timestep'):
with safe_open(transformer_path / index[name], framework='pt', device='cpu') as handle:
setattr(transformer, name, handle.get_tensor(name))
pipe.update_components(transformer_ref=transformer)
video_scheduler = FixedStepMiniMaxH3Scheduler.from_config(pipe.scheduler.config)
audio_scheduler = FixedStepMiniMaxH3Scheduler.from_config(pipe.audio_scheduler.config)
video_scheduler.set_shift(12.0)
audio_scheduler.set_shift(3.0)
pipe.update_components(scheduler=video_scheduler, audio_scheduler=audio_scheduler)
if not cpu_offload:
pipe.to(device)
return pipe
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model')
parser.add_argument('--components', default=OFFICIAL_REPO)
parser.add_argument('--prompt', required=True)
parser.add_argument('--image', '--video', '--audio', dest='references', action=ReferenceArgument)
parser.add_argument('--height', type=int)
parser.add_argument('--width', type=int)
parser.add_argument('--num-frames', type=int, default=124)
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--output', default='ref_output.mp4')
parser.add_argument('--device', default='cuda')
parser.add_argument('--no-cpu-offload', action='store_true')
parser.add_argument('--disable-cudnn', action='store_true')
arguments = parser.parse_args()
if not any(kind in ('image', 'video') for kind, path in arguments.references or []):
parser.error('provide at least one --image or --video')
if (arguments.height is None) != (arguments.width is None):
parser.error('--height and --width must be provided together')
reference_types = {
'image': MiniMaxH3ImageReference, 'video': MiniMaxH3VideoReference, 'audio': MiniMaxH3AudioReference,
}
references = [reference_types[kind].from_file(path) for kind, path in arguments.references]
pipe = load_pipeline(arguments.model, arguments.components, arguments.device, not arguments.no_cpu_offload)
request = {
'prompt': arguments.prompt,
'references': references,
'num_frames': arguments.num_frames,
'num_inference_steps': 9,
'generator': torch.Generator(device='cpu').manual_seed(arguments.seed),
'output_type': 'np',
}
if arguments.height is not None:
request.update(height=arguments.height, width=arguments.width)
calls = []
handle = pipe.transformer_ref.register_forward_pre_hook(lambda module, inputs: calls.append(1))
if arguments.disable_cudnn:
torch.backends.cuda.enable_cudnn_sdp(False)
context = torch.backends.cudnn.flags(enabled=False) if arguments.disable_cudnn else nullcontext()
try:
with context:
result = pipe(**request)
finally:
handle.remove()
if len(calls) != 8:
raise RuntimeError(f'expected 8 denoising calls, received {len(calls)}')
output = Path(arguments.output)
output.parent.mkdir(parents=True, exist_ok=True)
encode_video(
result.videos[0], fps=24, output_path=str(output),
audio=result.audio[0], audio_sample_rate=int(result.sampling_rate),
)
print(f'Wrote {output} with 8 denoising steps')
if __name__ == '__main__':
main()