Merge branch 'main' into perf/minimax-h3-lossless-hot-path
This commit is contained in:
143 files changed
+8587
-2165
No files matched your search
@@ -14,6 +14,9 @@ from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import VideoTokenLayout
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
|
||||
|
||||
from .scheduling_minimax_h3_euler_ancestral import (
|
||||
minimax_h3_euler_eta0_step,
|
||||
minimax_h3_rf_v_to_x0,
|
||||
@@ -88,6 +91,13 @@ class MiniMaxH3DenoiseBranch:
|
||||
"max_seqlen_q": text_len,
|
||||
},
|
||||
}
|
||||
# Where the video segment sits in the packed sequence. Resolved to plain
|
||||
# ints here so the attention layers never sync on it per step.
|
||||
grid = packed["latent_grid"].tolist()
|
||||
self.static_kwargs["video_token_layout"] = VideoTokenLayout(
|
||||
prefix_len=int(packed["video_row_start"]),
|
||||
latent_grid=(int(grid[0]), int(grid[1]), int(grid[2])),
|
||||
)
|
||||
|
||||
def forward_kwargs(
|
||||
self,
|
||||
@@ -140,7 +150,8 @@ def minimax_h3_denoise_loop(
|
||||
device: torch.device,
|
||||
imgvid_cond_noise_aug_for_inference: float = MINIMAX_H3_IMGVID_COND_TIMESTEP,
|
||||
audio_cond_noise_aug_for_inference: float = MINIMAX_H3_AUDIO_REF_COND_TIMESTEP,
|
||||
on_step: Callable[[int, torch.Tensor, torch.Tensor], None] | None = None,
|
||||
on_step_end: Callable[[int, torch.Tensor, torch.Tensor], None] | None = None,
|
||||
on_step_start: Callable[[int, float, float], None] | None = None,
|
||||
step_profiler: Callable[[int], AbstractContextManager] | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Run the full denoise loop; returns final (video_rows, audio_rows).
|
||||
@@ -193,8 +204,14 @@ def minimax_h3_denoise_loop(
|
||||
for step in range(num_steps):
|
||||
step_cm = step_profiler(step) if step_profiler is not None else nullcontext()
|
||||
with step_cm:
|
||||
# Publish the step index so step-gated attention features (e.g. the
|
||||
# dense warmup of RAINFUSION_ATTN) can see where we are.
|
||||
set_forward_context_denoise_step_idx(step)
|
||||
s_v, s_v_next = sigmas_video[step], sigmas_video[step + 1]
|
||||
s_a, s_a_next = sigmas_audio[step], sigmas_audio[step + 1]
|
||||
if on_step_start is not None:
|
||||
# Attention gates use the scheduler-style descending timestep.
|
||||
on_step_start(step, s_v, s_a)
|
||||
t_v, t_a = 1.0 - s_v, 1.0 - s_a
|
||||
imgvid_cond_t = max(t_v, float(imgvid_cond_noise_aug_for_inference))
|
||||
audio_ref_cond_t = max(t_a, float(audio_cond_noise_aug_for_inference))
|
||||
@@ -247,9 +264,10 @@ def minimax_h3_denoise_loop(
|
||||
audio_rows[audio_update] = new_audio
|
||||
if audio_anchor is not None:
|
||||
audio_rows[~audio_update] = audio_anchor # per-step audio ref reset
|
||||
if on_step is not None:
|
||||
on_step(step, video_rows, audio_rows)
|
||||
if on_step_end is not None:
|
||||
on_step_end(step, video_rows, audio_rows)
|
||||
|
||||
set_forward_context_denoise_step_idx(None)
|
||||
return video_rows, audio_rows
|
||||
|
||||
|
||||
|
||||
@@ -1029,16 +1029,84 @@ class MiniMaxH3Qwen3VLEncoder(nn.Module):
|
||||
def load_to_device(self) -> None:
|
||||
if not self.is_loaded:
|
||||
return
|
||||
if getattr(self, "_omni_layerwise_enabled", False):
|
||||
for name, child in self.vision.named_children():
|
||||
if name != "blocks":
|
||||
child.to(self.device_target)
|
||||
for name, child in self.text_model.named_children():
|
||||
if name != "layers":
|
||||
child.to(self.device_target)
|
||||
return
|
||||
self.vision.to(self.device_target)
|
||||
self.text_model.to(self.device_target)
|
||||
|
||||
def offload_to_cpu(self) -> None:
|
||||
if not self.is_loaded:
|
||||
return
|
||||
if getattr(self, "_omni_layerwise_enabled", False):
|
||||
for hook in self._omni_layerwise_hooks:
|
||||
hook.offload_layer()
|
||||
for name, child in self.vision.named_children():
|
||||
if name != "blocks":
|
||||
child.to("cpu")
|
||||
for name, child in self.text_model.named_children():
|
||||
if name != "layers":
|
||||
child.to("cpu")
|
||||
torch.accelerator.empty_cache()
|
||||
return
|
||||
self.vision.to("cpu")
|
||||
self.text_model.to("cpu")
|
||||
torch.accelerator.empty_cache()
|
||||
|
||||
def enable_omni_layerwise_offload(self, *, pin_memory: bool = True) -> None:
|
||||
"""Stream the TP-local Qwen vision/text blocks for low-HBM serving.
|
||||
|
||||
The encoder has its own TP process group, so these blocks must remain
|
||||
rank-local. Reusing the DiT AllGather group would concatenate
|
||||
different TP shards and corrupt the encoder weights.
|
||||
"""
|
||||
if not self.is_loaded or getattr(self, "_omni_layerwise_enabled", False):
|
||||
return
|
||||
|
||||
from vllm_omni.diffusion.offloader.layerwise_backend import apply_block_hook
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
self._omni_layerwise_hooks = []
|
||||
self._omni_layerwise_block_groups = []
|
||||
copy_stream = current_omni_platform.Stream()
|
||||
for blocks in (self.vision.blocks, self.text_model.layers):
|
||||
if len(blocks) <= 1:
|
||||
continue
|
||||
last_hook = apply_block_hook(
|
||||
blocks[-1],
|
||||
blocks[0],
|
||||
self.device_target,
|
||||
copy_stream,
|
||||
pin_memory,
|
||||
)
|
||||
hooks = [last_hook]
|
||||
for index, block in enumerate(blocks[:-1]):
|
||||
hooks.append(
|
||||
apply_block_hook(
|
||||
block,
|
||||
blocks[index + 1],
|
||||
self.device_target,
|
||||
copy_stream,
|
||||
pin_memory,
|
||||
)
|
||||
)
|
||||
for index, hook in enumerate(hooks):
|
||||
hook._prev_hook = hooks[index - 1]
|
||||
self._omni_layerwise_hooks.extend(hooks)
|
||||
self._omni_layerwise_block_groups.append(blocks)
|
||||
|
||||
self._omni_layerwise_enabled = bool(self._omni_layerwise_hooks)
|
||||
logger.info(
|
||||
"MiniMax H3 encoder layerwise offload enabled on %d blocks across %d stacks",
|
||||
sum(len(blocks) for blocks in self._omni_layerwise_block_groups),
|
||||
len(self._omni_layerwise_block_groups),
|
||||
)
|
||||
|
||||
def _encode(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
|
||||
@@ -26,13 +26,15 @@ from vllm.model_executor.layers.linear import (
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata, VideoTokenLayout
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.cache.cachedit import CacheDiTAdapterConfig
|
||||
from vllm_omni.diffusion.distributed.sp_plan import (
|
||||
SequenceParallelInput,
|
||||
SequenceParallelOutput,
|
||||
)
|
||||
from vllm_omni.diffusion.layers.norm import RMSNorm
|
||||
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.base_config import (
|
||||
@@ -132,6 +134,7 @@ _FORWARD_SUPPORTED_KWARGS = frozenset(
|
||||
"img_pos_for_infer_output_info",
|
||||
"packed_seq_params",
|
||||
"refiner_packed_seq_params",
|
||||
"video_token_layout",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -168,16 +171,11 @@ def _reorder_grouped_qkv_to_qkv(
|
||||
)
|
||||
|
||||
|
||||
def _norm(size: int, *, eps: float, dtype: torch.dtype = _BF16_DTYPE) -> nn.RMSNorm:
|
||||
def _norm(size: int, *, eps: float, dtype: torch.dtype = _BF16_DTYPE) -> RMSNorm:
|
||||
# RMSNorm uses fp32 accumulation with bf16 inputs and outputs.
|
||||
# torch.nn.RMSNorm upcasts reduced-precision inputs for the variance
|
||||
# reduction, matching that accumulation semantic.
|
||||
return nn.RMSNorm(size, eps=eps, dtype=dtype)
|
||||
|
||||
|
||||
def _rotate_half(x: torch.Tensor) -> torch.Tensor:
|
||||
x1, x2 = torch.chunk(x, 2, dim=-1)
|
||||
return torch.cat((-x2, x1), dim=-1)
|
||||
return RMSNorm(size, eps=eps, dtype=dtype)
|
||||
|
||||
|
||||
def _modulate_scale_shift(
|
||||
@@ -230,20 +228,6 @@ class MiniMaxH3Rope(nn.Module):
|
||||
return torch.cat((half, half), dim=-1) # [S, 96]
|
||||
|
||||
|
||||
def _apply_rope(x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
|
||||
"""Rotate the first rot_dim head dims; pass the rest through.
|
||||
|
||||
x: [T, heads, head_dim]; freqs: [T, rot_dim]. In the unfused path, cos/sin
|
||||
are cast to the activation dtype before the elementwise math.
|
||||
"""
|
||||
rot_dim = freqs.shape[-1]
|
||||
x_rot, x_pass = x[..., :rot_dim], x[..., rot_dim:]
|
||||
cos = torch.cos(freqs).to(x.dtype).unsqueeze(1) # [T, 1, rot_dim]
|
||||
sin = torch.sin(freqs).to(x.dtype).unsqueeze(1)
|
||||
x_rot = (x_rot * cos) + (_rotate_half(x_rot) * sin)
|
||||
return torch.cat((x_rot, x_pass), dim=-1)
|
||||
|
||||
|
||||
class MiniMaxH3TimeEmbedder(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
@@ -327,6 +311,8 @@ class MiniMaxH3Attention(nn.Module):
|
||||
quant_config: QuantizationConfig | None,
|
||||
*,
|
||||
prefix: str,
|
||||
role: str = "self",
|
||||
role_category: str | None = None,
|
||||
skip_sequence_parallel: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
@@ -349,6 +335,7 @@ class MiniMaxH3Attention(nn.Module):
|
||||
self.num_kv_heads = self.qkv_proj.num_kv_heads
|
||||
self.q_norm = _norm(arch.attention_head_dim, eps=arch.qk_norm_eps)
|
||||
self.k_norm = _norm(arch.attention_head_dim, eps=arch.qk_norm_eps)
|
||||
self.rope = RotaryEmbedding(is_neox_style=True, half_head_dim=False)
|
||||
self.out_proj = RowParallelLinear(
|
||||
inner_dim,
|
||||
arch.hidden_size,
|
||||
@@ -364,9 +351,27 @@ class MiniMaxH3Attention(nn.Module):
|
||||
head_size=self.head_dim,
|
||||
softmax_scale=self.softmax_scale,
|
||||
causal=False,
|
||||
# Packed rows reach the impl as [B, S, N, D].
|
||||
qkv_layout="BSND",
|
||||
role=role,
|
||||
role_category=role_category,
|
||||
skip_sequence_parallel=skip_sequence_parallel,
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
def _apply_rope(self, x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
|
||||
"""Rotate the first rot_dim head dims; pass the rest through.
|
||||
|
||||
x: [T, heads, head_dim]; freqs: [T, rot_dim]. In the unfused path, cos/sin
|
||||
are cast to the activation dtype before the elementwise math.
|
||||
"""
|
||||
rot_dim = freqs.shape[-1]
|
||||
x_rot, x_pass = x[..., :rot_dim], x[..., rot_dim:]
|
||||
cos = torch.cos(freqs).to(x.dtype) # [T, rot_dim]
|
||||
sin = torch.sin(freqs).to(x.dtype)
|
||||
x_rot = self.rope(x_rot, cos, sin)
|
||||
return torch.cat((x_rot, x_pass), dim=-1)
|
||||
|
||||
@torch.compiler.disable
|
||||
def _run_packed_attention(
|
||||
self,
|
||||
@@ -376,18 +381,31 @@ class MiniMaxH3Attention(nn.Module):
|
||||
*,
|
||||
cu_seqlens: torch.Tensor,
|
||||
max_seqlen: int,
|
||||
packed_total: int,
|
||||
video_layout: VideoTokenLayout | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Run packed attention as a small eager island.
|
||||
|
||||
The scalar packed-layout metadata and the CuTe FlashAttention-4 DSL
|
||||
are intentionally opaque to Dynamo. Keeping this boundary narrow lets
|
||||
regional compile fuse projections, norms, RoPE, and the surrounding
|
||||
DiT block without repeatedly graph-breaking inside the FA4 compiler.
|
||||
The scalar packed-layout metadata and backend-specific attention
|
||||
kernels are intentionally opaque to Dynamo. Keeping this boundary
|
||||
narrow lets regional compile fuse projections, norms, RoPE, and the
|
||||
surrounding DiT block without repeated graph breaks.
|
||||
"""
|
||||
used = int(cu_seqlens[1].item())
|
||||
packed_total = int(cu_seqlens[-1].item())
|
||||
# max_seqlen is already the first (real) packed document length. Do
|
||||
# not read the CUDA cu_seqlens scalars here: this function runs once
|
||||
# per layer and .item() would serialize every attention launch.
|
||||
if not 0 < max_seqlen <= packed_total:
|
||||
raise ValueError(
|
||||
f"max_seqlen must be within the packed sequence, got {max_seqlen} for length {packed_total}"
|
||||
)
|
||||
used = min(max_seqlen, packed_total)
|
||||
attn_mask = None
|
||||
if used < packed_total:
|
||||
# Ring attention can dispatch to a different implementation from the
|
||||
# configured backend, so this no-mask fast path is local-only.
|
||||
prefix_slice = (
|
||||
not getattr(self.attention, "use_ring", False) and self.attention.attn_backend.supports_prefix_kv_slicing
|
||||
)
|
||||
if used < packed_total and not prefix_slice:
|
||||
attn_mask = torch.arange(packed_total, device=q.device)[None] < used
|
||||
metadata = AttentionMetadata(
|
||||
attn_mask=attn_mask,
|
||||
@@ -396,7 +414,9 @@ class MiniMaxH3Attention(nn.Module):
|
||||
"cu_seqlens_k": cu_seqlens,
|
||||
"max_seqlen_q": max_seqlen,
|
||||
"max_seqlen_k": max_seqlen,
|
||||
"valid_kv_length": used,
|
||||
},
|
||||
video_layout=video_layout,
|
||||
)
|
||||
return self.attention(
|
||||
q.unsqueeze(0),
|
||||
@@ -412,7 +432,9 @@ class MiniMaxH3Attention(nn.Module):
|
||||
rope_freqs: torch.Tensor | None,
|
||||
cu_seqlens: torch.Tensor,
|
||||
max_seqlen: int,
|
||||
packed_total: int | None = None,
|
||||
sp_seq_lens: list[int] | None = None,
|
||||
video_layout: VideoTokenLayout | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""x: [T, hidden] packed thd rows -> [T, hidden].
|
||||
|
||||
@@ -436,8 +458,8 @@ class MiniMaxH3Attention(nn.Module):
|
||||
q = self.q_norm(q)
|
||||
k = self.k_norm(k)
|
||||
if rope_freqs is not None:
|
||||
q = _apply_rope(q, rope_freqs)
|
||||
k = _apply_rope(k, rope_freqs)
|
||||
q = self._apply_rope(q, rope_freqs)
|
||||
k = self._apply_rope(k, rope_freqs)
|
||||
|
||||
# The packed layout uses a second document for alignment padding.
|
||||
# Local/Ulysses backends unpad it, while Ring keeps aligned rows for
|
||||
@@ -448,6 +470,11 @@ class MiniMaxH3Attention(nn.Module):
|
||||
v,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
# Before Ulysses, q contains only this rank's row shard. The
|
||||
# backend receives the global sequence after all-to-all, so carry
|
||||
# its Python length explicitly instead of inferring it from q.
|
||||
packed_total=packed_total if packed_total is not None else q.shape[0],
|
||||
video_layout=video_layout,
|
||||
)
|
||||
out = out.reshape(total, self.num_heads * self.head_dim)
|
||||
out, _ = self.out_proj(out)
|
||||
@@ -558,6 +585,8 @@ class MiniMaxH3TokenRefinerBlock(nn.Module):
|
||||
arch,
|
||||
quant_config,
|
||||
prefix=f"{prefix}.attn",
|
||||
role="minimax_h3.token_refiner",
|
||||
role_category="self",
|
||||
skip_sequence_parallel=True,
|
||||
)
|
||||
self.mlp = MiniMaxH3MLP(
|
||||
@@ -627,6 +656,8 @@ class MiniMaxH3DiTBlock(nn.Module):
|
||||
super().__init__()
|
||||
self.norm1 = _norm(arch.hidden_size, eps=arch.norm_eps)
|
||||
self.norm2 = _norm(arch.hidden_size, eps=arch.norm_eps)
|
||||
# The prefix also carries the block index that block-sparse attention
|
||||
# backends match against their skip_layers selector.
|
||||
self.attn = MiniMaxH3Attention(
|
||||
arch,
|
||||
quant_config,
|
||||
@@ -655,7 +686,9 @@ class MiniMaxH3DiTBlock(nn.Module):
|
||||
rope_freqs: torch.Tensor,
|
||||
cu_seqlens: torch.Tensor,
|
||||
max_seqlen: int,
|
||||
packed_total: int,
|
||||
sp_seq_lens: list[int] | None = None,
|
||||
video_layout: VideoTokenLayout | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""x: [T, H]; t_emb: [M, t_dim]; combined_indices: [T]
|
||||
(= inverse_indices * modality_num + token_tags.clamp(min=0)).
|
||||
@@ -681,7 +714,9 @@ class MiniMaxH3DiTBlock(nn.Module):
|
||||
rope_freqs=rope_freqs,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
packed_total=packed_total,
|
||||
sp_seq_lens=sp_seq_lens,
|
||||
video_layout=video_layout,
|
||||
)
|
||||
x = _modulate_gate(residual, gate_msa, h, combined_indices, dtype=_BF16_DTYPE)
|
||||
|
||||
@@ -814,6 +849,10 @@ class MiniMaxH3DiTModel(nn.Module):
|
||||
},
|
||||
"sp_gather": SequenceParallelOutput(gather_dim=0, expected_dims=2),
|
||||
}
|
||||
# The checkpoint already stores qkv and the MLP gate/up as single tensors
|
||||
# (see the reordering in load_weights), so there are no unfused names for
|
||||
# quantization or LoRA to map onto. Address the fused layers directly, e.g.
|
||||
# ignored_layers=["blocks.0.attn.qkv_proj"].
|
||||
packed_modules_mapping = {}
|
||||
|
||||
def _validate_tp_config(self, *, arch: MiniMaxH3DiTArchConfig, tp_size: int) -> None:
|
||||
@@ -1080,6 +1119,7 @@ class MiniMaxH3DiTModel(nn.Module):
|
||||
refiner_psp = _required_kwarg(kwargs, "refiner_packed_seq_params")
|
||||
refiner_cu = self._psp_field(refiner_psp, "refiner_packed_seq_params", "cu_seqlens_q").to(torch.int32)
|
||||
refiner_max = int(self._psp_field(refiner_psp, "refiner_packed_seq_params", "max_seqlen_q"))
|
||||
video_layout = kwargs.get("video_token_layout")
|
||||
|
||||
if x.dim() != 3 or x.shape[0] != 1:
|
||||
raise ValueError(f"x must be [1, S, C], got {list(x.shape)}")
|
||||
@@ -1127,6 +1167,8 @@ class MiniMaxH3DiTModel(nn.Module):
|
||||
rope_freqs=block_rope,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
packed_total=seq_len,
|
||||
video_layout=video_layout,
|
||||
)
|
||||
hidden = self.sp_gather(hidden)
|
||||
|
||||
|
||||
@@ -236,6 +236,9 @@ def minimax_h3_packed_sequence(
|
||||
"token_tags": token_tags,
|
||||
"cu_seqlens": cu,
|
||||
"document_id": doc,
|
||||
# Extent of the video segment within the packed sequence.
|
||||
"latent_grid": torch.tensor([latent_t, ph, pw], dtype=torch.int64),
|
||||
"video_row_start": torch.tensor(video_sl.start, dtype=torch.int64),
|
||||
}
|
||||
|
||||
|
||||
@@ -554,6 +557,9 @@ def minimax_h3_packed_sequence_ref2va_blocks(
|
||||
"token_tags": token_tags,
|
||||
"cu_seqlens": cu,
|
||||
"document_id": doc,
|
||||
# Extent of the video segment within the packed sequence.
|
||||
"latent_grid": torch.tensor([latent_t, ph, pw], dtype=torch.int64),
|
||||
"video_row_start": torch.tensor(video_sl.start, dtype=torch.int64),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ import math
|
||||
import os
|
||||
import tempfile
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from contextlib import contextmanager
|
||||
from itertools import groupby
|
||||
from pathlib import Path
|
||||
from typing import Any, ClassVar
|
||||
|
||||
@@ -26,6 +28,7 @@ from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
init_world_group,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import DenoiseProgressMixin
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import (
|
||||
DiffusersPipelineLoader,
|
||||
)
|
||||
@@ -36,11 +39,15 @@ from vllm_omni.diffusion.models.interface import (
|
||||
SupportsComponentDiscovery,
|
||||
)
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
|
||||
from vllm_omni.diffusion.offloader import OffloadPlan
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import (
|
||||
DiffusionPipelineProfilerMixin,
|
||||
)
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.errors import OmniClientError
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import (
|
||||
download_weights_from_hf_specific,
|
||||
)
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
from .condition_noise import (
|
||||
@@ -104,6 +111,57 @@ MINIMAX_H3_MAX_REFERENCE_IMAGE_BYTES = 30 * 1024 * 1024
|
||||
MINIMAX_H3_REFERENCE_IMAGE_FORMATS = frozenset({"jpeg", "png", "webp", "heic", "heif"})
|
||||
MINIMAX_H3_MIN_OUTPUT_SECONDS = 4.0
|
||||
MINIMAX_H3_MAX_OUTPUT_SECONDS = 15.0
|
||||
MINIMAX_H3_DOWNLOAD_PATTERNS = [
|
||||
"FL2VA/**",
|
||||
"Ref2VA/model_index.json",
|
||||
"Ref2VA/transformer/**",
|
||||
]
|
||||
MINIMAX_H3_TASK_DOWNLOAD_PATTERNS = {
|
||||
"fl2va": ["FL2VA/**"],
|
||||
"ref2va": ["Ref2VA/**"],
|
||||
}
|
||||
|
||||
|
||||
def _minimax_h3_partition_for_task(
|
||||
task_type: str | None,
|
||||
model: str | None = None,
|
||||
) -> str:
|
||||
task = str(task_type or "auto").lower()
|
||||
if task == "auto" and model is not None:
|
||||
path = Path(model)
|
||||
if path.is_dir() and path.name in {"FL2VA", "Ref2VA"} and (path / "model_index.json").is_file():
|
||||
return path.name.lower()
|
||||
if task in {"auto", "combined"}:
|
||||
return "combined"
|
||||
if task in {"t2va", "fl2va"}:
|
||||
return "fl2va"
|
||||
if task == "ref2va":
|
||||
return "ref2va"
|
||||
raise ValueError(f"MiniMax-H3 task_type must be one of auto, t2va, fl2va, or ref2va; got {task_type!r}")
|
||||
|
||||
|
||||
def _resolve_minimax_h3_model_root(
|
||||
model: str,
|
||||
revision: str | None,
|
||||
partition: str,
|
||||
) -> Path:
|
||||
path = Path(model)
|
||||
if path.is_dir():
|
||||
if path.name in {"FL2VA", "Ref2VA"} and (path / "model_index.json").is_file():
|
||||
return path.parent
|
||||
return path
|
||||
allow_patterns = (
|
||||
MINIMAX_H3_DOWNLOAD_PATTERNS if partition == "combined" else MINIMAX_H3_TASK_DOWNLOAD_PATTERNS[partition]
|
||||
)
|
||||
return Path(
|
||||
download_weights_from_hf_specific(
|
||||
model_name_or_path=model,
|
||||
cache_dir=None,
|
||||
allow_patterns=allow_patterns,
|
||||
revision=revision,
|
||||
require_all=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _resolve_component_quant_config(quant_config, component: str):
|
||||
@@ -444,6 +502,7 @@ class _SingleRankEncoderGroup:
|
||||
|
||||
class MiniMaxH3Pipeline(
|
||||
nn.Module,
|
||||
DenoiseProgressMixin,
|
||||
ProgressBarMixin,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
SupportImageInput,
|
||||
@@ -453,9 +512,22 @@ class MiniMaxH3Pipeline(
|
||||
):
|
||||
"""CFG-distilled joint video/audio generation for MiniMax H3."""
|
||||
|
||||
_dit_modules: ClassVar[list[str]] = ["transformer"]
|
||||
_dit_modules: ClassVar[list[str]] = ["transformer", "transformers_ref"]
|
||||
_encoder_modules: ClassVar[list[str]] = ["text_encoder"]
|
||||
_vae_modules: ClassVar[list[str]] = ["video_vae", "audio_vae"]
|
||||
_offload_plan: ClassVar[OffloadPlan] = OffloadPlan(
|
||||
offload_submodules={"token_refiner": "blocks"},
|
||||
resident_dit_paths=frozenset({"transformer"}),
|
||||
encoder_block_attrs={"text_encoder": ("vision.blocks", "text_model.layers")},
|
||||
on_demand_component_paths=frozenset({"text_encoder", "video_vae", "audio_vae"}),
|
||||
)
|
||||
# H3's regular loader performs checkpoint-layout conversions (grouped QKV
|
||||
# and fused MLP). Keep it on that path until mmap can run the same loader
|
||||
# callbacks for every affected parameter.
|
||||
_supports_mmap_loading: ClassVar[bool] = False
|
||||
# TODO(offload): Re-enable after the generic rank-local mmap path can run
|
||||
# this model's grouped-QKV reorder and fused-MLP packing before TP sharding.
|
||||
# Do not bypass the regular loader until that equivalence is tested.
|
||||
_PROFILER_TARGETS: ClassVar[list[str]] = [
|
||||
"_prepare_reference_videos",
|
||||
"encode_prompt",
|
||||
@@ -479,24 +551,64 @@ class MiniMaxH3Pipeline(
|
||||
if int(self.parallel_config.cfg_parallel_size) != 1:
|
||||
raise ValueError("MiniMax-H3 is CFG-distilled and has no negative branch; cfg_parallel_size must be 1")
|
||||
self.device = get_local_device()
|
||||
model_path = str(od_config.model)
|
||||
model_index = json.loads((Path(model_path) / "model_index.json").read_text(encoding="utf-8"))
|
||||
self.partition = _minimax_h3_partition_for_task(
|
||||
getattr(od_config, "task_type", None),
|
||||
str(od_config.model),
|
||||
)
|
||||
model_root = _resolve_minimax_h3_model_root(
|
||||
str(od_config.model),
|
||||
od_config.revision,
|
||||
self.partition,
|
||||
)
|
||||
model_path = model_root / ("Ref2VA" if self.partition == "ref2va" else "FL2VA")
|
||||
model_index = json.loads((model_path / "model_index.json").read_text(encoding="utf-8"))
|
||||
release = model_index.get("_minimax_h3") or {}
|
||||
self.partition = str(release.get("partition", ""))
|
||||
self.supported_tasks = frozenset(release.get("tasks") or ())
|
||||
partition = str(release.get("partition", "")).lower()
|
||||
expected_partition = "ref2va" if self.partition == "ref2va" else "fl2va"
|
||||
if partition != expected_partition:
|
||||
raise ValueError(f"invalid MiniMax-H3 {expected_partition} partition at {model_path}")
|
||||
|
||||
supported_tasks = {str(task).lower() for task in release.get("tasks", [])}
|
||||
if not supported_tasks:
|
||||
supported_tasks = {"ref2va"} if partition == "ref2va" else {"t2va", "fl2va"}
|
||||
ref2va_model_path = None
|
||||
if self.partition == "combined":
|
||||
ref2va_model_path = model_root / "Ref2VA"
|
||||
ref2va_index_path = ref2va_model_path / "model_index.json"
|
||||
if not ref2va_index_path.is_file():
|
||||
raise ValueError(f"Ref2VA partition not found at {ref2va_model_path}")
|
||||
ref2va_index = json.loads(ref2va_index_path.read_text(encoding="utf-8"))
|
||||
ref2va_release = ref2va_index.get("_minimax_h3") or {}
|
||||
if str(ref2va_release.get("partition", "")).lower() != "ref2va":
|
||||
raise ValueError(f"invalid MiniMax-H3 ref2va partition at {ref2va_model_path}")
|
||||
supported_tasks.update(str(task).lower() for task in ref2va_release.get("tasks", ["ref2va"]))
|
||||
|
||||
self.supported_tasks = frozenset(supported_tasks)
|
||||
shifts = release.get("sigma_shift_scales") or {}
|
||||
self.default_video_shift = float(shifts.get("video", 12.0))
|
||||
self.default_audio_shift = float(shifts.get("audio", 3.0))
|
||||
|
||||
self.weights_sources = [
|
||||
DiffusersPipelineLoader.ComponentSource(
|
||||
model_or_path=model_path,
|
||||
model_or_path=str(model_path),
|
||||
subfolder="transformer",
|
||||
revision=od_config.revision,
|
||||
prefix="transformer.",
|
||||
fall_back_to_pt=False,
|
||||
)
|
||||
]
|
||||
self._dit_modules = ["transformer"]
|
||||
if ref2va_model_path is not None:
|
||||
self.weights_sources.append(
|
||||
DiffusersPipelineLoader.ComponentSource(
|
||||
model_or_path=str(ref2va_model_path),
|
||||
subfolder="transformer",
|
||||
revision=od_config.revision,
|
||||
prefix="transformers_ref.",
|
||||
fall_back_to_pt=False,
|
||||
)
|
||||
)
|
||||
self._dit_modules.append("transformers_ref")
|
||||
transformer_quant_config = _resolve_component_quant_config(
|
||||
od_config.quantization_config,
|
||||
"transformer",
|
||||
@@ -505,14 +617,19 @@ class MiniMaxH3Pipeline(
|
||||
od_config,
|
||||
quant_config=transformer_quant_config,
|
||||
)
|
||||
if ref2va_model_path is not None:
|
||||
self.transformers_ref = MiniMaxH3DiTModel(
|
||||
od_config,
|
||||
quant_config=transformer_quant_config,
|
||||
)
|
||||
|
||||
self.tokenizer = Qwen2TokenizerFast.from_pretrained(
|
||||
model_path,
|
||||
str(model_path),
|
||||
subfolder="tokenizer",
|
||||
local_files_only=os.path.isdir(model_path),
|
||||
)
|
||||
self.processor = Qwen3VLProcessor.from_pretrained(
|
||||
model_path,
|
||||
str(model_path),
|
||||
subfolder="processor",
|
||||
local_files_only=os.path.isdir(model_path),
|
||||
)
|
||||
@@ -542,13 +659,19 @@ class MiniMaxH3Pipeline(
|
||||
load_model=rank < text_encoder_tp_size,
|
||||
encoder_group=self.text_encoder_group,
|
||||
)
|
||||
stage_components = bool(
|
||||
od_config.enable_layerwise_offload or getattr(od_config, "enable_distributed_layerwise_offload", False)
|
||||
)
|
||||
component_load_device = torch.device("cpu") if stage_components else self.device
|
||||
self.video_vae = MiniMaxH3VideoVAE(
|
||||
os.path.join(model_path, "video_vae"),
|
||||
device=self.device,
|
||||
load_device=component_load_device,
|
||||
)
|
||||
self.audio_vae = MiniMaxH3AudioVAE(
|
||||
os.path.join(model_path, "audio_vae"),
|
||||
device=self.device,
|
||||
load_device=component_load_device,
|
||||
)
|
||||
# Registry-side VAE patch-parallel discovery uses ``pipeline.vae``.
|
||||
self.vae = self.video_vae
|
||||
@@ -561,16 +684,23 @@ class MiniMaxH3Pipeline(
|
||||
self,
|
||||
weights: Iterable[tuple[str, torch.Tensor]],
|
||||
) -> set[str]:
|
||||
prefix = "transformer."
|
||||
def source_prefix(item: tuple[str, torch.Tensor]) -> str:
|
||||
name, _ = item
|
||||
prefix = name.partition(".")[0] + "."
|
||||
if prefix in {"transformer.", "transformers_ref."}:
|
||||
return prefix
|
||||
raise ValueError(f"unexpected MiniMax-H3 weight {name!r}")
|
||||
|
||||
def transformer_weights():
|
||||
for name, tensor in weights:
|
||||
if name.startswith(prefix):
|
||||
yield name[len(prefix) :], tensor
|
||||
|
||||
loaded = self.transformer.load_weights(transformer_weights())
|
||||
self.transformer.post_load_weights()
|
||||
loaded_with_prefix = {prefix + name for name in loaded}
|
||||
loaded_with_prefix: set[str] = set()
|
||||
loaded_prefixes: set[str] = set()
|
||||
for prefix, grouped_weights in groupby(weights, key=source_prefix):
|
||||
if prefix in loaded_prefixes:
|
||||
raise ValueError(f"MiniMax-H3 weight source {prefix!r} is not contiguous")
|
||||
loaded_prefixes.add(prefix)
|
||||
transformer = getattr(self, prefix.removesuffix("."))
|
||||
loaded = transformer.load_weights((name[len(prefix) :], tensor) for name, tensor in grouped_weights)
|
||||
transformer.post_load_weights()
|
||||
loaded_with_prefix.update(prefix + name for name in loaded)
|
||||
# The text encoder and both VAEs load eagerly in ``__init__`` rather
|
||||
# than through ``weights_sources``. Record them for the runner's strict
|
||||
# missing-parameter check.
|
||||
@@ -579,14 +709,23 @@ class MiniMaxH3Pipeline(
|
||||
loaded_with_prefix.update(f"{component_name}.{name}" for name, _ in component.named_parameters())
|
||||
return loaded_with_prefix
|
||||
|
||||
def _transformer_for_task(self, task: str) -> MiniMaxH3DiTModel:
|
||||
if task == "ref2va" and hasattr(self, "transformers_ref"):
|
||||
return self.transformers_ref
|
||||
return self.transformer
|
||||
|
||||
def _resolve_task(
|
||||
self,
|
||||
requested: str | None,
|
||||
multi_modal_data: dict[str, Any],
|
||||
) -> str:
|
||||
if requested is None:
|
||||
# A Ref2VA-only startup has no FL2VA transformer; preserve its
|
||||
# historical implicit default even for image-only references.
|
||||
if self.partition == "ref2va":
|
||||
requested = "ref2va"
|
||||
elif multi_modal_data.get("video") is not None or multi_modal_data.get("audio") is not None:
|
||||
requested = "ref2va"
|
||||
elif multi_modal_data.get("image") is not None:
|
||||
requested = "fl2va"
|
||||
else:
|
||||
@@ -935,12 +1074,16 @@ class MiniMaxH3Pipeline(
|
||||
input_ids: torch.Tensor,
|
||||
vision_kwargs: dict[str, torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
if self.od_config.enable_cpu_offload:
|
||||
if self.od_config.enable_cpu_offload and not getattr(
|
||||
self.od_config, "enable_distributed_layerwise_offload", False
|
||||
):
|
||||
# Invoke nn.Module.__call__ so the generic model-level offloader
|
||||
# swaps the resident DiT and encoder.
|
||||
return self.text_encoder(input_ids, **vision_kwargs)
|
||||
|
||||
if self.od_config.enable_layerwise_offload:
|
||||
if self.od_config.enable_layerwise_offload or getattr(
|
||||
self.od_config, "enable_distributed_layerwise_offload", False
|
||||
):
|
||||
# Layerwise DiT offload already provides the low-residency encoder
|
||||
# phase used by the checkpoint reference.
|
||||
self.text_encoder.load_to_device()
|
||||
@@ -955,12 +1098,33 @@ class MiniMaxH3Pipeline(
|
||||
self.text_encoder.load_to_device()
|
||||
return self.text_encoder.encode_ids(input_ids, **vision_kwargs)
|
||||
|
||||
def _uses_manual_component_offload(self) -> bool:
|
||||
od_config = getattr(self, "od_config", None)
|
||||
return bool(
|
||||
getattr(od_config, "enable_layerwise_offload", False)
|
||||
or getattr(od_config, "enable_distributed_layerwise_offload", False)
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def _component_on_device(self, component: nn.Module):
|
||||
staged = self._uses_manual_component_offload()
|
||||
if staged:
|
||||
component.load_to_device()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if staged:
|
||||
component.offload_to_cpu()
|
||||
|
||||
def _encode_visual_condition(
|
||||
self,
|
||||
image: Image.Image,
|
||||
) -> torch.Tensor:
|
||||
_, rank, _ = _dit_rank_world()
|
||||
rows = self.video_vae.encode_image(image) if rank == 0 else None
|
||||
rows = None
|
||||
if rank == 0:
|
||||
with self._component_on_device(self.video_vae):
|
||||
rows = self.video_vae.encode_image(image)
|
||||
return _broadcast_tensor(
|
||||
rows,
|
||||
dtype=torch.float32,
|
||||
@@ -996,7 +1160,8 @@ class MiniMaxH3Pipeline(
|
||||
rows = None
|
||||
audio_t = 0
|
||||
if rank == 0:
|
||||
rows, audio_t = self.audio_vae.encode_waveform(*audio)
|
||||
with self._component_on_device(self.audio_vae):
|
||||
rows, audio_t = self.audio_vae.encode_waveform(*audio)
|
||||
audio_t_tensor = torch.tensor(
|
||||
[audio_t],
|
||||
dtype=torch.long,
|
||||
@@ -1042,6 +1207,15 @@ class MiniMaxH3Pipeline(
|
||||
prepared_videos: list[dict[str, Any]] | None,
|
||||
*,
|
||||
count: int,
|
||||
) -> tuple[torch.Tensor, list[tuple[int, int, int]]]:
|
||||
with self._component_on_device(self.video_vae):
|
||||
return self._encode_video_conditions_resident(prepared_videos, count=count)
|
||||
|
||||
def _encode_video_conditions_resident(
|
||||
self,
|
||||
prepared_videos: list[dict[str, Any]] | None,
|
||||
*,
|
||||
count: int,
|
||||
) -> tuple[torch.Tensor, list[tuple[int, int, int]]]:
|
||||
group, rank, world_size = _dit_rank_world()
|
||||
distributed_encode = self.video_vae.is_distributed_enabled()
|
||||
@@ -1089,6 +1263,15 @@ class MiniMaxH3Pipeline(
|
||||
prepared_videos: list[dict[str, Any]] | None,
|
||||
*,
|
||||
has_audio: list[bool],
|
||||
) -> tuple[torch.Tensor | None, list[int]]:
|
||||
with self._component_on_device(self.audio_vae):
|
||||
return self._encode_video_audio_conditions_resident(prepared_videos, has_audio=has_audio)
|
||||
|
||||
def _encode_video_audio_conditions_resident(
|
||||
self,
|
||||
prepared_videos: list[dict[str, Any]] | None,
|
||||
*,
|
||||
has_audio: list[bool],
|
||||
) -> tuple[torch.Tensor | None, list[int]]:
|
||||
_, rank, _ = _dit_rank_world()
|
||||
count = sum(has_audio)
|
||||
@@ -1156,6 +1339,17 @@ class MiniMaxH3Pipeline(
|
||||
)
|
||||
return video_rows, audio_rows
|
||||
|
||||
@contextmanager
|
||||
def _resident_dit_layers_on_device(self, *, enabled: bool = True):
|
||||
controller = getattr(self, "_dlo_residency_controller", None)
|
||||
if controller is not None and enabled:
|
||||
controller.load_resident_layers()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if controller is not None and enabled:
|
||||
controller.offload_resident_layers()
|
||||
|
||||
def diffuse(
|
||||
self,
|
||||
*,
|
||||
@@ -1277,21 +1471,31 @@ class MiniMaxH3Pipeline(
|
||||
num_steps=num_steps,
|
||||
shift_scale=audio_shift,
|
||||
)
|
||||
with self.progress_bar(total=len(video_sigmas) - 1) as progress:
|
||||
video_rows, audio_rows = minimax_h3_denoise_loop(
|
||||
model=self.transformer,
|
||||
positive=branch,
|
||||
initial_video_rows=initial_video,
|
||||
initial_audio_rows=initial_audio,
|
||||
keyframe_cond_rows=visual_anchor,
|
||||
audio_ref_rows=audio_anchor,
|
||||
sigmas_video=video_sigmas,
|
||||
sigmas_audio=audio_sigmas,
|
||||
device=self.device,
|
||||
imgvid_cond_noise_aug_for_inference=(MINIMAX_H3_IMGVID_COND_TIMESTEP),
|
||||
audio_cond_noise_aug_for_inference=(MINIMAX_H3_AUDIO_REF_COND_TIMESTEP),
|
||||
on_step=lambda step, video, audio: progress.update(),
|
||||
)
|
||||
transformer = self._transformer_for_task(task)
|
||||
# The static DLO plan keeps leading blocks resident only for the
|
||||
# primary ``transformer``. In combined mode ``transformers_ref`` is
|
||||
# fully streamed, so a Ref2VA request must not stage the inactive
|
||||
# FL2VA transformer resident blocks.
|
||||
with self._resident_dit_layers_on_device(enabled=transformer is self.transformer):
|
||||
with self.progress_bar(total=len(video_sigmas) - 1) as progress:
|
||||
video_rows, audio_rows = minimax_h3_denoise_loop(
|
||||
model=transformer,
|
||||
positive=branch,
|
||||
initial_video_rows=initial_video,
|
||||
initial_audio_rows=initial_audio,
|
||||
keyframe_cond_rows=visual_anchor,
|
||||
audio_ref_rows=audio_anchor,
|
||||
sigmas_video=video_sigmas,
|
||||
sigmas_audio=audio_sigmas,
|
||||
device=self.device,
|
||||
imgvid_cond_noise_aug_for_inference=(MINIMAX_H3_IMGVID_COND_TIMESTEP),
|
||||
audio_cond_noise_aug_for_inference=(MINIMAX_H3_AUDIO_REF_COND_TIMESTEP),
|
||||
on_step_start=lambda step, video_sigma, audio_sigma: self.record_denoise_step(
|
||||
step,
|
||||
normalized_timestep=video_sigma,
|
||||
),
|
||||
on_step_end=lambda step, video, audio: progress.update(),
|
||||
)
|
||||
|
||||
target_video = video_rows[branch.update_mask_dev]
|
||||
video_latent = minimax_h3_unpatchify_video_tokens(
|
||||
@@ -1320,14 +1524,16 @@ class MiniMaxH3Pipeline(
|
||||
height: int,
|
||||
width: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
with current_omni_platform.create_autocast_context(
|
||||
device_type=self.device.type,
|
||||
dtype=torch.float16,
|
||||
enabled=True,
|
||||
):
|
||||
video = self.video_vae.decode_latent(video_latent)
|
||||
with self._component_on_device(self.video_vae):
|
||||
with current_omni_platform.create_autocast_context(
|
||||
device_type=self.device.type,
|
||||
dtype=torch.float16,
|
||||
enabled=True,
|
||||
):
|
||||
video = self.video_vae.decode_latent(video_latent)
|
||||
video = video[..., :height, :width].contiguous()
|
||||
audio = self.audio_vae.decode_latent(audio_latent)
|
||||
with self._component_on_device(self.audio_vae):
|
||||
audio = self.audio_vae.decode_latent(audio_latent)
|
||||
return video, audio
|
||||
|
||||
@torch.no_grad()
|
||||
|
||||
@@ -19,6 +19,7 @@ from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor impor
|
||||
DistributedVaeMixin,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_dit_group
|
||||
from vllm_omni.diffusion.offloader.module_residency import PinnedModuleStager
|
||||
|
||||
from .packed_tokens import minimax_h3_patchify_video_latent
|
||||
|
||||
@@ -50,7 +51,14 @@ def _load_remote_component(
|
||||
class_reference,
|
||||
component_path,
|
||||
)
|
||||
return component_cls.from_pretrained(component_path)
|
||||
# Build on the host regardless of the ambient default device. Online
|
||||
# quantization wraps pipeline construction in a `with torch.device(<accel>)`
|
||||
# block for the DiT's quantized linears, and the checkpoint's own VAE code
|
||||
# builds constants with ops that have no accelerator kernel (BigVGAN's
|
||||
# anti-aliasing filters call torch.kaiser_window). Callers place the module
|
||||
# explicitly right after this returns, so nothing depends on the context.
|
||||
with torch.device("cpu"):
|
||||
return component_cls.from_pretrained(component_path)
|
||||
|
||||
|
||||
class _AudioVAEDeterminismContext(AbstractContextManager):
|
||||
@@ -102,8 +110,10 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
|
||||
component_path: str,
|
||||
*,
|
||||
device: torch.device,
|
||||
load_device: torch.device | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self._device_target = device
|
||||
self.config_dict = _load_component_config(component_path)
|
||||
self.remote = _load_remote_component(
|
||||
component_path,
|
||||
@@ -112,11 +122,33 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
|
||||
# Match the reference loader contract: video VAE weights stay FP32.
|
||||
# Keyframe encoding is numerically sensitive to first casting the
|
||||
# checkpoint through FP16; decode still runs under FP16 autocast.
|
||||
self.remote.eval().to(device=device, dtype=torch.float32)
|
||||
initial_device = load_device or device
|
||||
self.remote.eval().to(device=initial_device, dtype=torch.float32)
|
||||
self._stager = None
|
||||
if initial_device.type == "cpu" and device.type not in ("cpu", "meta"):
|
||||
self._stager = PinnedModuleStager(
|
||||
self.remote,
|
||||
device,
|
||||
pin_memory=True,
|
||||
)
|
||||
self.model = self.remote.model
|
||||
self.use_tiling = True
|
||||
self.use_slicing = False
|
||||
self.parallel_size = 1
|
||||
self.device_module = torch.get_device_module()
|
||||
|
||||
def load_to_device(self) -> None:
|
||||
if self._stager is not None:
|
||||
self._stager.load()
|
||||
else:
|
||||
self.remote.to(self._device_target)
|
||||
|
||||
def offload_to_cpu(self) -> None:
|
||||
if self._stager is not None:
|
||||
self._stager.offload()
|
||||
else:
|
||||
self.remote.to("cpu")
|
||||
torch.accelerator.empty_cache()
|
||||
|
||||
def set_parallel_size(
|
||||
self,
|
||||
@@ -166,13 +198,13 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
|
||||
previous_dtype = parameter.dtype
|
||||
if previous_dtype != torch.float32:
|
||||
self.to(torch.float32)
|
||||
devices = [parameter.device] if parameter.device.type == "cuda" else []
|
||||
devices = [parameter.device] if parameter.device.type != "cpu" else []
|
||||
try:
|
||||
with torch.random.fork_rng(devices=devices):
|
||||
with torch.random.fork_rng(devices=devices, device_type=parameter.device.type):
|
||||
torch.default_generator.manual_seed(MINIMAX_H3_KEYFRAME_ENCODE_SEED)
|
||||
for device in devices:
|
||||
with torch.cuda.device(device):
|
||||
torch.cuda.manual_seed(MINIMAX_H3_KEYFRAME_ENCODE_SEED)
|
||||
with self.device_module.device(device):
|
||||
self.device_module.manual_seed(MINIMAX_H3_KEYFRAME_ENCODE_SEED)
|
||||
latent = self.model.encode_images(
|
||||
image,
|
||||
use_fp16_latent=True,
|
||||
@@ -210,13 +242,13 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
|
||||
previous_dtype = parameter.dtype
|
||||
if previous_dtype != torch.float32:
|
||||
self.to(torch.float32)
|
||||
devices = [parameter.device] if parameter.device.type == "cuda" else []
|
||||
devices = [parameter.device] if parameter.device.type != "cpu" else []
|
||||
try:
|
||||
with torch.random.fork_rng(devices=devices):
|
||||
with torch.random.fork_rng(devices=devices, device_type=parameter.device.type):
|
||||
torch.default_generator.manual_seed(MINIMAX_H3_KEYFRAME_ENCODE_SEED)
|
||||
for device in devices:
|
||||
with torch.cuda.device(device):
|
||||
torch.cuda.manual_seed(MINIMAX_H3_KEYFRAME_ENCODE_SEED)
|
||||
with self.device_module.device(device):
|
||||
self.device_module.manual_seed(MINIMAX_H3_KEYFRAME_ENCODE_SEED)
|
||||
latent = self.model.encode_videos(
|
||||
frames,
|
||||
use_fp16_latent=True,
|
||||
@@ -276,8 +308,10 @@ class MiniMaxH3AudioVAE(nn.Module):
|
||||
component_path: str,
|
||||
*,
|
||||
device: torch.device,
|
||||
load_device: torch.device | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self._device_target = device
|
||||
self.config_dict = _load_component_config(component_path)
|
||||
self.remote = _load_remote_component(
|
||||
component_path,
|
||||
@@ -285,10 +319,31 @@ class MiniMaxH3AudioVAE(nn.Module):
|
||||
)
|
||||
# The checkpoint's audio VAE contract is FP32 for both reference
|
||||
# encoding and waveform decoding.
|
||||
self.remote.eval().to(device=device, dtype=torch.float32)
|
||||
initial_device = load_device or device
|
||||
self.remote.eval().to(device=initial_device, dtype=torch.float32)
|
||||
self._stager = None
|
||||
if initial_device.type == "cpu" and device.type not in ("cpu", "meta"):
|
||||
self._stager = PinnedModuleStager(
|
||||
self.remote,
|
||||
device,
|
||||
pin_memory=True,
|
||||
)
|
||||
self.model = self.remote.model
|
||||
self.sample_rate = int(self.config_dict["sample_rate"])
|
||||
|
||||
def load_to_device(self) -> None:
|
||||
if self._stager is not None:
|
||||
self._stager.load()
|
||||
else:
|
||||
self.remote.to(self._device_target)
|
||||
|
||||
def offload_to_cpu(self) -> None:
|
||||
if self._stager is not None:
|
||||
self._stager.offload()
|
||||
else:
|
||||
self.remote.to("cpu")
|
||||
torch.accelerator.empty_cache()
|
||||
|
||||
@torch.inference_mode()
|
||||
def encode_waveform(
|
||||
self,
|
||||
|
||||
Reference in new issue
Block a user