[Model][Frontend] MiniMax-H3: Add latent-mask editing (#7465)
Signed-off-by: xiaoyu <1259084489@qq.com>
This commit is contained in:
1 parent
8e10c3ee07
commit
5a93ec1b4e
18 files changed
+2286
-122
No files matched your search
@@ -38,6 +38,8 @@ def minimax_h3_batched_forward_kwargs(
|
||||
t_audio: Sequence[float],
|
||||
imgvid_cond_timesteps: Sequence[float],
|
||||
audio_ref_cond_timesteps: Sequence[float],
|
||||
video_target_timesteps: Sequence[torch.Tensor | None] | None = None,
|
||||
audio_target_timesteps: Sequence[torch.Tensor | None] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build one DiT forward kwargs dict covering every request in the batch.
|
||||
|
||||
@@ -46,6 +48,16 @@ def minimax_h3_batched_forward_kwargs(
|
||||
happen to agree -- which also keeps ``video_token_layout`` (the sparse-
|
||||
attention hint) on the single-request step path.
|
||||
"""
|
||||
request_count = len(branches)
|
||||
if video_target_timesteps is None:
|
||||
video_target_timesteps = [None] * request_count
|
||||
elif len(video_target_timesteps) != request_count:
|
||||
raise ValueError(f"video_target_timesteps has {len(video_target_timesteps)} requests, expected {request_count}")
|
||||
if audio_target_timesteps is None:
|
||||
audio_target_timesteps = [None] * request_count
|
||||
elif len(audio_target_timesteps) != request_count:
|
||||
raise ValueError(f"audio_target_timesteps has {len(audio_target_timesteps)} requests, expected {request_count}")
|
||||
|
||||
if len(branches) == 1:
|
||||
return branches[0].forward_kwargs(
|
||||
video_rows=video_rows[0],
|
||||
@@ -54,6 +66,8 @@ def minimax_h3_batched_forward_kwargs(
|
||||
t_audio=t_audio[0],
|
||||
imgvid_cond_timestep=imgvid_cond_timesteps[0],
|
||||
audio_ref_cond_timestep=audio_ref_cond_timesteps[0],
|
||||
video_target_timesteps=video_target_timesteps[0],
|
||||
audio_target_timesteps=audio_target_timesteps[0],
|
||||
)
|
||||
|
||||
device = branches[0].device
|
||||
@@ -88,11 +102,15 @@ def minimax_h3_batched_forward_kwargs(
|
||||
position_id_parts.append(branch.img_position_ids_dev)
|
||||
text_embed_parts.append(branch.text_embeddings_dev)
|
||||
|
||||
timesteps[seq_offset : seq_offset + branch.seq_len] = float(t_video[index])
|
||||
timesteps[img_pos[branch.update_mask_dev]] = float(t_video[index])
|
||||
timesteps[img_pos[~branch.update_mask_dev]] = float(imgvid_cond_timesteps[index])
|
||||
timesteps[audio_pos[branch.audio_update_mask_dev]] = float(t_audio[index])
|
||||
timesteps[audio_pos[~branch.audio_update_mask_dev]] = float(audio_ref_cond_timesteps[index])
|
||||
branch.fill_timesteps(
|
||||
timesteps[seq_offset : seq_offset + branch.seq_len],
|
||||
t_video=t_video[index],
|
||||
t_audio=t_audio[index],
|
||||
imgvid_cond_timestep=imgvid_cond_timesteps[index],
|
||||
audio_ref_cond_timestep=audio_ref_cond_timesteps[index],
|
||||
video_target_timesteps=video_target_timesteps[index],
|
||||
audio_target_timesteps=audio_target_timesteps[index],
|
||||
)
|
||||
|
||||
# Empty documents are omitted because not every varlen kernel accepts
|
||||
# repeated interior boundaries.
|
||||
|
||||
@@ -23,6 +23,7 @@ from vllm_omni.diffusion.forward_context import (
|
||||
)
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
from .latent_mask import MiniMaxH3LatentEdit, minimax_h3_prepare_edit_rows
|
||||
from .scheduling_minimax_h3_euler_ancestral import (
|
||||
minimax_h3_euler_eta0_step,
|
||||
minimax_h3_rf_v_to_x0,
|
||||
@@ -185,25 +186,23 @@ class MiniMaxH3DenoiseBranch:
|
||||
t_audio: float,
|
||||
imgvid_cond_timestep: float,
|
||||
audio_ref_cond_timestep: float,
|
||||
video_target_timesteps: torch.Tensor | None = None,
|
||||
audio_target_timesteps: torch.Tensor | None = None,
|
||||
) -> dict[str, Any]:
|
||||
x = self.x_base.clone()
|
||||
x[0].index_copy_(0, self.img_pos_dev, video_rows)
|
||||
audio_x = self.audio_x_base.clone()
|
||||
audio_x[0].index_copy_(0, self.audio_pos_dev, audio_rows)
|
||||
# Packed-sequence timestep semantics: non-media rows (text and
|
||||
# padding) inherit the current video timestep. Later steps must reuse
|
||||
# the previous step's updated rows; re-initializing from zeros is only
|
||||
# valid at step 0.
|
||||
timesteps = torch.full(
|
||||
(self.seq_len,),
|
||||
float(t_video),
|
||||
dtype=torch.float32,
|
||||
device=x.device,
|
||||
timesteps = torch.empty(self.seq_len, dtype=torch.float32, device=self.device)
|
||||
self.fill_timesteps(
|
||||
timesteps,
|
||||
t_video=t_video,
|
||||
t_audio=t_audio,
|
||||
imgvid_cond_timestep=imgvid_cond_timestep,
|
||||
audio_ref_cond_timestep=audio_ref_cond_timestep,
|
||||
video_target_timesteps=video_target_timesteps,
|
||||
audio_target_timesteps=audio_target_timesteps,
|
||||
)
|
||||
timesteps[self.img_pos_dev[self.update_mask_dev]] = t_video
|
||||
timesteps[self.img_pos_dev[~self.update_mask_dev]] = imgvid_cond_timestep
|
||||
timesteps[self.audio_pos_dev[self.audio_update_mask_dev]] = t_audio
|
||||
timesteps[self.audio_pos_dev[~self.audio_update_mask_dev]] = audio_ref_cond_timestep
|
||||
unique_timesteps, inverse_indices = torch.unique(timesteps, sorted=True, return_inverse=True)
|
||||
return {
|
||||
**self.static_kwargs,
|
||||
@@ -213,6 +212,56 @@ class MiniMaxH3DenoiseBranch:
|
||||
"inverse_indices": inverse_indices,
|
||||
}
|
||||
|
||||
def fill_timesteps(
|
||||
self,
|
||||
timesteps: torch.Tensor,
|
||||
*,
|
||||
t_video: float,
|
||||
t_audio: float,
|
||||
imgvid_cond_timestep: float,
|
||||
audio_ref_cond_timestep: float,
|
||||
video_target_timesteps: torch.Tensor | None = None,
|
||||
audio_target_timesteps: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
"""Fill one request's packed row timesteps in an existing tensor."""
|
||||
if timesteps.shape != (self.seq_len,):
|
||||
raise ValueError(f"timesteps must have shape ({self.seq_len},)")
|
||||
# Packed-sequence timestep semantics: non-media rows (text and
|
||||
# padding) inherit the current video timestep. Later steps must reuse
|
||||
# the previous step's updated rows; re-initializing from zeros is only
|
||||
# valid at step 0.
|
||||
timesteps.fill_(float(t_video))
|
||||
timestep_groups = (
|
||||
(
|
||||
"video_target_timesteps",
|
||||
self.img_pos_dev,
|
||||
self.update_mask_dev,
|
||||
video_target_timesteps,
|
||||
t_video,
|
||||
imgvid_cond_timestep,
|
||||
),
|
||||
(
|
||||
"audio_target_timesteps",
|
||||
self.audio_pos_dev,
|
||||
self.audio_update_mask_dev,
|
||||
audio_target_timesteps,
|
||||
t_audio,
|
||||
audio_ref_cond_timestep,
|
||||
),
|
||||
)
|
||||
for name, positions, update_mask, target_timesteps, current_timestep, condition_timestep in timestep_groups:
|
||||
target_positions = positions[update_mask]
|
||||
if target_timesteps is None:
|
||||
timesteps[target_positions] = current_timestep
|
||||
else:
|
||||
target_timesteps = target_timesteps.to(device=self.device, dtype=torch.float32).reshape(-1)
|
||||
if target_timesteps.shape[0] != target_positions.shape[0]:
|
||||
raise ValueError(
|
||||
f"{name} rows {target_timesteps.shape[0]} != target rows {target_positions.shape[0]}"
|
||||
)
|
||||
timesteps[target_positions] = target_timesteps
|
||||
timesteps[positions[~update_mask]] = condition_timestep
|
||||
|
||||
|
||||
def minimax_h3_prepare_denoise_rows(
|
||||
*,
|
||||
@@ -273,6 +322,8 @@ def minimax_h3_denoise_loop(
|
||||
initial_audio_rows: torch.Tensor,
|
||||
keyframe_cond_rows: torch.Tensor | None,
|
||||
audio_ref_rows: torch.Tensor | None = None,
|
||||
video_edit: MiniMaxH3LatentEdit | None = None,
|
||||
audio_edit: MiniMaxH3LatentEdit | None = None,
|
||||
sigmas_video: list[float],
|
||||
sigmas_audio: list[float],
|
||||
device: torch.device,
|
||||
@@ -307,6 +358,10 @@ def minimax_h3_denoise_loop(
|
||||
)
|
||||
update = positive.update_mask_dev
|
||||
audio_update = positive.audio_update_mask_dev
|
||||
if video_edit is not None:
|
||||
video_edit = video_edit.to(device=device, dtype=torch.float32)
|
||||
if audio_edit is not None:
|
||||
audio_edit = audio_edit.to(device=device, dtype=torch.float32)
|
||||
|
||||
num_steps = len(sigmas_video) - 1
|
||||
for step in range(num_steps):
|
||||
@@ -323,35 +378,68 @@ def minimax_h3_denoise_loop(
|
||||
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))
|
||||
|
||||
model_video_rows, video_target_timesteps = minimax_h3_prepare_edit_rows(
|
||||
video_rows,
|
||||
update,
|
||||
video_edit,
|
||||
t_v,
|
||||
imgvid_cond_t,
|
||||
sigma=s_v,
|
||||
)
|
||||
model_audio_rows, audio_target_timesteps = minimax_h3_prepare_edit_rows(
|
||||
audio_rows,
|
||||
audio_update,
|
||||
audio_edit,
|
||||
t_a,
|
||||
audio_ref_cond_t,
|
||||
sigma=s_a,
|
||||
)
|
||||
|
||||
fk = positive.forward_kwargs(
|
||||
video_rows=video_rows,
|
||||
audio_rows=audio_rows,
|
||||
video_rows=model_video_rows,
|
||||
audio_rows=model_audio_rows,
|
||||
t_video=t_v,
|
||||
t_audio=t_a,
|
||||
imgvid_cond_timestep=imgvid_cond_t,
|
||||
audio_ref_cond_timestep=audio_ref_cond_t,
|
||||
video_target_timesteps=video_target_timesteps,
|
||||
audio_target_timesteps=audio_target_timesteps,
|
||||
)
|
||||
with torch.inference_mode():
|
||||
v_video, v_audio = model(**fk)
|
||||
mv_video_t = v_video.float()[update]
|
||||
mv_audio_t = v_audio.float()[audio_update]
|
||||
|
||||
x0_video = minimax_h3_rf_v_to_x0(
|
||||
video_rows[update],
|
||||
mv_video_t,
|
||||
torch.tensor(t_v, dtype=torch.float32, device=device),
|
||||
)
|
||||
if video_edit is None:
|
||||
x0_video = minimax_h3_rf_v_to_x0(
|
||||
video_rows[update],
|
||||
mv_video_t,
|
||||
torch.tensor(t_v, dtype=torch.float32, device=device),
|
||||
)
|
||||
else:
|
||||
x0_video = video_edit.x0(
|
||||
model_video_rows[update],
|
||||
mv_video_t,
|
||||
t_v,
|
||||
)
|
||||
new_target = minimax_h3_euler_eta0_step(video_rows[update], x0_video, sigma_curr=s_v, sigma_next=s_v_next)
|
||||
video_rows = video_rows.clone()
|
||||
video_rows[update] = new_target
|
||||
if cond_anchor is not None:
|
||||
video_rows[~update] = cond_anchor # per-step imgvid cond reset
|
||||
|
||||
x0_audio = minimax_h3_rf_v_to_x0(
|
||||
audio_rows[audio_update],
|
||||
mv_audio_t,
|
||||
torch.tensor(t_a, dtype=torch.float32, device=device),
|
||||
)
|
||||
if audio_edit is None:
|
||||
x0_audio = minimax_h3_rf_v_to_x0(
|
||||
audio_rows[audio_update],
|
||||
mv_audio_t,
|
||||
torch.tensor(t_a, dtype=torch.float32, device=device),
|
||||
)
|
||||
else:
|
||||
x0_audio = audio_edit.x0(
|
||||
model_audio_rows[audio_update],
|
||||
mv_audio_t,
|
||||
t_a,
|
||||
)
|
||||
new_audio = minimax_h3_euler_eta0_step(
|
||||
audio_rows[audio_update], x0_audio, sigma_curr=s_a, sigma_next=s_a_next
|
||||
)
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""MiniMax H3 latent-edit mask parsing and sampler math."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
|
||||
from .scheduling_minimax_h3_euler_ancestral import minimax_h3_rf_v_to_x0
|
||||
|
||||
_MASK_LEVELS = 256.0
|
||||
|
||||
|
||||
def _quantize(mask: torch.Tensor) -> torch.Tensor:
|
||||
"""Match ComfyUI's token-grid mask used by H3's timestep embedding."""
|
||||
return (torch.ceil(mask * _MASK_LEVELS) / _MASK_LEVELS).clamp_(0, 1)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MiniMaxH3ParsedMask:
|
||||
"""Token mask for the model and raw mask for the final x0 restore."""
|
||||
|
||||
model_mask_rows: torch.Tensor
|
||||
restore_mask_rows: torch.Tensor
|
||||
|
||||
|
||||
def minimax_h3_video_edit_masks(
|
||||
mask: torch.Tensor,
|
||||
*,
|
||||
latent_t: int,
|
||||
latent_h: int,
|
||||
latent_w: int,
|
||||
) -> MiniMaxH3ParsedMask:
|
||||
"""Map the canonical full-grid video mask to model and restore rows.
|
||||
|
||||
Full-grid masks are max-pooled over each 2x2 DiT token. Their raw four
|
||||
cells are repeated in the packed 24-channel feature order for restoration.
|
||||
"""
|
||||
latent_t, latent_h, latent_w = int(latent_t), int(latent_h), int(latent_w)
|
||||
if latent_t <= 0 or latent_h <= 0 or latent_w <= 0 or latent_h % 2 or latent_w % 2:
|
||||
raise ValueError("video latent dimensions must be positive and spatially even")
|
||||
|
||||
token_shape = (latent_t, latent_h // 2, latent_w // 2)
|
||||
full_shape = (latent_t, latent_h, latent_w)
|
||||
row_count = math.prod(token_shape)
|
||||
if mask.dtype != torch.float32 or tuple(mask.shape) != full_shape or not mask.is_contiguous():
|
||||
raise ValueError(f"canonical video mask must be contiguous FP32 with shape {full_shape}")
|
||||
cells = mask.reshape(latent_t, latent_h // 2, 2, latent_w // 2, 2).permute(0, 1, 3, 2, 4).contiguous()
|
||||
model = _quantize(cells.amax(dim=(3, 4)).reshape(-1))
|
||||
restore = cells.unsqueeze(3).expand(*cells.shape[:3], 24, 2, 2).reshape(row_count, 96).clone()
|
||||
return MiniMaxH3ParsedMask(model, restore)
|
||||
|
||||
|
||||
def minimax_h3_audio_edit_masks(mask: torch.Tensor, *, audio_t: int) -> MiniMaxH3ParsedMask:
|
||||
"""Flatten the canonical channel-major audio mask to H3 row order."""
|
||||
audio_t = int(audio_t)
|
||||
if audio_t <= 0:
|
||||
raise ValueError("audio_t must be positive")
|
||||
expected_shape = (2, audio_t)
|
||||
if mask.dtype != torch.float32 or tuple(mask.shape) != expected_shape or not mask.is_contiguous():
|
||||
raise ValueError(f"canonical audio mask must be contiguous FP32 with shape {expected_shape}")
|
||||
rows = mask.reshape(-1).clone()
|
||||
return MiniMaxH3ParsedMask(_quantize(rows), rows)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MiniMaxH3LatentEdit:
|
||||
"""Clean source, model anchor, and masks for one packed latent stream."""
|
||||
|
||||
clean_rows: torch.Tensor
|
||||
anchor_rows: torch.Tensor
|
||||
mask_rows: torch.Tensor
|
||||
restore_mask_rows: torch.Tensor
|
||||
|
||||
@classmethod
|
||||
def from_rows(
|
||||
cls,
|
||||
clean_rows: torch.Tensor,
|
||||
anchor_rows: torch.Tensor,
|
||||
mask_rows: torch.Tensor,
|
||||
restore_mask_rows: torch.Tensor,
|
||||
) -> MiniMaxH3LatentEdit:
|
||||
"""Create an edit from already-validated encoder outputs.
|
||||
|
||||
Value validation and all-generate elision belong at the encoder input
|
||||
boundary. This constructor only normalizes devices/dtypes and checks
|
||||
the cheap row-shape invariants needed by the sampler math.
|
||||
"""
|
||||
if clean_rows.ndim != 2 or anchor_rows.shape != clean_rows.shape:
|
||||
raise ValueError("clean_rows and anchor_rows must have matching [rows, width] shape")
|
||||
raw_mask = torch.as_tensor(mask_rows, dtype=torch.float32, device=clean_rows.device)
|
||||
if raw_mask.ndim != 1 or raw_mask.numel() != clean_rows.shape[0]:
|
||||
raise ValueError(f"mask_rows must have shape ({clean_rows.shape[0]},)")
|
||||
restore = torch.as_tensor(restore_mask_rows, dtype=torch.float32, device=clean_rows.device)
|
||||
valid_restore = restore.ndim == 1 and restore.shape == raw_mask.shape
|
||||
valid_restore |= restore.ndim == 2 and tuple(restore.shape) in {
|
||||
(clean_rows.shape[0], 1),
|
||||
tuple(clean_rows.shape),
|
||||
}
|
||||
if not valid_restore:
|
||||
raise ValueError("restore_mask_rows must have one scalar or one feature row per clean row")
|
||||
return cls(clean_rows, anchor_rows, raw_mask, restore)
|
||||
|
||||
def to(self, *, device: torch.device, dtype: torch.dtype = torch.float32) -> MiniMaxH3LatentEdit:
|
||||
return MiniMaxH3LatentEdit(
|
||||
self.clean_rows.to(device=device, dtype=dtype),
|
||||
self.anchor_rows.to(device=device, dtype=dtype),
|
||||
self.mask_rows.to(device=device),
|
||||
self.restore_mask_rows.to(device=device),
|
||||
)
|
||||
|
||||
def model_rows(self, state_rows: torch.Tensor) -> torch.Tensor:
|
||||
return torch.lerp(self.anchor_rows, state_rows, self.mask_rows.to(state_rows.dtype).unsqueeze(-1))
|
||||
|
||||
def target_timesteps(
|
||||
self,
|
||||
timestep: float,
|
||||
condition_timestep: float,
|
||||
*,
|
||||
sigma: float | None = None,
|
||||
) -> torch.Tensor:
|
||||
sigma = 1.0 - timestep if sigma is None else float(sigma)
|
||||
return torch.clamp(1.0 - self.mask_rows * sigma, max=condition_timestep)
|
||||
|
||||
def prepare(
|
||||
self,
|
||||
state_rows: torch.Tensor,
|
||||
timestep: float,
|
||||
condition_timestep: float,
|
||||
*,
|
||||
sigma: float,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Prepare the model rows and per-row timesteps for one denoise step."""
|
||||
return (
|
||||
self.model_rows(state_rows),
|
||||
self.target_timesteps(timestep, condition_timestep, sigma=sigma),
|
||||
)
|
||||
|
||||
def x0(self, model_rows: torch.Tensor, velocity: torch.Tensor, timestep: float) -> torch.Tensor:
|
||||
weight = self.mask_rows.to(model_rows.dtype).unsqueeze(-1)
|
||||
predicted = minimax_h3_rf_v_to_x0(
|
||||
model_rows,
|
||||
velocity.to(model_rows.dtype) * weight,
|
||||
torch.tensor(float(timestep), dtype=model_rows.dtype, device=model_rows.device),
|
||||
)
|
||||
restore = self.restore_mask_rows.to(model_rows.dtype)
|
||||
if restore.ndim == 1:
|
||||
restore = restore.unsqueeze(-1)
|
||||
return torch.lerp(self.clean_rows, predicted, restore)
|
||||
|
||||
|
||||
def minimax_h3_prepare_edit_rows(
|
||||
rows: torch.Tensor,
|
||||
update_mask: torch.Tensor,
|
||||
edit: MiniMaxH3LatentEdit | None,
|
||||
timestep: float,
|
||||
condition_timestep: float,
|
||||
*,
|
||||
sigma: float,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
"""Build one model input view without mutating the persistent sampler rows."""
|
||||
if edit is None:
|
||||
return rows, None
|
||||
model_rows = rows.clone()
|
||||
model_rows[update_mask], target_timesteps = edit.prepare(
|
||||
rows[update_mask],
|
||||
timestep,
|
||||
condition_timestep,
|
||||
sigma=sigma,
|
||||
)
|
||||
return model_rows, target_timesteps
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MiniMaxH3LatentEdit",
|
||||
"MiniMaxH3ParsedMask",
|
||||
"minimax_h3_audio_edit_masks",
|
||||
"minimax_h3_prepare_edit_rows",
|
||||
"minimax_h3_video_edit_masks",
|
||||
]
|
||||
@@ -108,6 +108,12 @@ from .denoise_loop import (
|
||||
from .encoder import MiniMaxH3Qwen3VLEncoder
|
||||
from .fasth3 import FastH3WeightFusion, resolve_fasth3_fusion
|
||||
from .fasth3_checkpoint import FastH3CheckpointSpec
|
||||
from .latent_mask import (
|
||||
MiniMaxH3LatentEdit,
|
||||
minimax_h3_audio_edit_masks,
|
||||
minimax_h3_prepare_edit_rows,
|
||||
minimax_h3_video_edit_masks,
|
||||
)
|
||||
from .lora import TurboSpec, load_minimax_h3_turbo_lora
|
||||
from .minimax_h3_transformer import (
|
||||
MiniMaxH3Attention,
|
||||
@@ -261,6 +267,12 @@ _MINIMAX_H3_DENOISE_INPUT_KEYS = (
|
||||
"audio_condition_lengths",
|
||||
"keyframe_frame_indices",
|
||||
"pad_seq_len",
|
||||
"video_edit_clean_rows",
|
||||
"video_edit_mask_rows",
|
||||
"video_edit_restore_mask_rows",
|
||||
"audio_edit_clean_rows",
|
||||
"audio_edit_mask_rows",
|
||||
"audio_edit_restore_mask_rows",
|
||||
)
|
||||
|
||||
# ``StepRequestState.extra`` keys owned by the step-execution path.
|
||||
@@ -273,6 +285,8 @@ _STEP_COND_ANCHOR = "minimax_h3_cond_anchor"
|
||||
_STEP_AUDIO_ANCHOR = "minimax_h3_audio_anchor"
|
||||
_STEP_SHAPE = "minimax_h3_shape"
|
||||
_STEP_TRANSFORMER = "minimax_h3_transformer"
|
||||
_STEP_VIDEO_EDIT = "minimax_h3_video_edit"
|
||||
_STEP_AUDIO_EDIT = "minimax_h3_audio_edit"
|
||||
|
||||
|
||||
def _minimax_h3_step_schedule(state: StepRequestState) -> dict[str, float]:
|
||||
@@ -407,6 +421,27 @@ def get_minimax_h3_post_process_func(
|
||||
return _minimax_h3_post_process
|
||||
|
||||
|
||||
def _expose_padded_audio_tail(
|
||||
source_audio_t: int,
|
||||
*,
|
||||
target_audio_t: int,
|
||||
mask_rows: torch.Tensor,
|
||||
restore_mask_rows: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Mark the encoder-padded audio tail for generation."""
|
||||
if not 0 < source_audio_t <= target_audio_t:
|
||||
raise ValueError(f"source_audio_t must be in [1, {target_audio_t}]")
|
||||
expected_shape = (2 * target_audio_t,)
|
||||
if tuple(mask_rows.shape) != expected_shape or tuple(restore_mask_rows.shape) != expected_shape:
|
||||
raise ValueError(f"audio edit masks must have shape {expected_shape}")
|
||||
model_mask = mask_rows.reshape(2, target_audio_t).clone()
|
||||
restore_mask = restore_mask_rows.reshape(2, target_audio_t).clone()
|
||||
if source_audio_t < target_audio_t:
|
||||
model_mask[:, source_audio_t:] = 1.0
|
||||
restore_mask[:, source_audio_t:] = 1.0
|
||||
return model_mask.reshape(-1), restore_mask.reshape(-1)
|
||||
|
||||
|
||||
def _resolve_minimax_h3_num_outputs(value: Any) -> int:
|
||||
if value is None:
|
||||
return 1
|
||||
@@ -1532,6 +1567,12 @@ class MiniMaxH3Pipeline(
|
||||
audio_condition_lengths: list[int] | None = None,
|
||||
keyframe_frame_indices: list[int] | None = None,
|
||||
pad_seq_len: int | None = None,
|
||||
video_edit_clean_rows: torch.Tensor | None = None,
|
||||
video_edit_mask_rows: torch.Tensor | None = None,
|
||||
video_edit_restore_mask_rows: torch.Tensor | None = None,
|
||||
audio_edit_clean_rows: torch.Tensor | None = None,
|
||||
audio_edit_mask_rows: torch.Tensor | None = None,
|
||||
audio_edit_restore_mask_rows: torch.Tensor | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build the packed layout, initial rows, anchors, and sigma schedules.
|
||||
|
||||
@@ -1640,6 +1681,41 @@ class MiniMaxH3Pipeline(
|
||||
full_audio[branch.audio_update_mask] = initial_audio
|
||||
initial_audio = full_audio
|
||||
|
||||
video_edit = None
|
||||
video_edit_values = (video_edit_clean_rows, video_edit_mask_rows, video_edit_restore_mask_rows)
|
||||
if any(value is None for value in video_edit_values) and any(value is not None for value in video_edit_values):
|
||||
raise ValueError("video edit clean, model-mask, and restore-mask rows must be provided together")
|
||||
if (
|
||||
video_edit_clean_rows is not None
|
||||
and video_edit_mask_rows is not None
|
||||
and video_edit_restore_mask_rows is not None
|
||||
):
|
||||
target_noise = initial_video[branch.update_mask].to(device=self.device, dtype=torch.float32)
|
||||
clean = video_edit_clean_rows.to(device=self.device, dtype=torch.float32)
|
||||
video_edit = MiniMaxH3LatentEdit.from_rows(
|
||||
clean,
|
||||
MINIMAX_H3_IMGVID_COND_TIMESTEP * clean + (1.0 - MINIMAX_H3_IMGVID_COND_TIMESTEP) * target_noise,
|
||||
video_edit_mask_rows,
|
||||
video_edit_restore_mask_rows,
|
||||
)
|
||||
|
||||
audio_edit = None
|
||||
audio_edit_values = (audio_edit_clean_rows, audio_edit_mask_rows, audio_edit_restore_mask_rows)
|
||||
if any(value is None for value in audio_edit_values) and any(value is not None for value in audio_edit_values):
|
||||
raise ValueError("audio edit clean, model-mask, and restore-mask rows must be provided together")
|
||||
if (
|
||||
audio_edit_clean_rows is not None
|
||||
and audio_edit_mask_rows is not None
|
||||
and audio_edit_restore_mask_rows is not None
|
||||
):
|
||||
clean = audio_edit_clean_rows.to(device=self.device, dtype=torch.float32)
|
||||
audio_edit = MiniMaxH3LatentEdit.from_rows(
|
||||
clean,
|
||||
clean,
|
||||
audio_edit_mask_rows,
|
||||
audio_edit_restore_mask_rows,
|
||||
)
|
||||
|
||||
video_sigmas = minimax_h3_time_shift_sigmas(
|
||||
num_steps=num_steps,
|
||||
shift_scale=video_shift,
|
||||
@@ -1664,6 +1740,8 @@ class MiniMaxH3Pipeline(
|
||||
),
|
||||
"sigmas_video": video_sigmas,
|
||||
"sigmas_audio": audio_sigmas,
|
||||
"video_edit": video_edit,
|
||||
"audio_edit": audio_edit,
|
||||
}
|
||||
|
||||
def _unpack_denoised_rows(
|
||||
@@ -1722,6 +1800,12 @@ class MiniMaxH3Pipeline(
|
||||
audio_condition_lengths: list[int] | None = None,
|
||||
keyframe_frame_indices: list[int] | None = None,
|
||||
pad_seq_len: int | None = None,
|
||||
video_edit_clean_rows: torch.Tensor | None = None,
|
||||
video_edit_mask_rows: torch.Tensor | None = None,
|
||||
video_edit_restore_mask_rows: torch.Tensor | None = None,
|
||||
audio_edit_clean_rows: torch.Tensor | None = None,
|
||||
audio_edit_mask_rows: torch.Tensor | None = None,
|
||||
audio_edit_restore_mask_rows: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
inputs = self._build_denoise_inputs(
|
||||
task=task,
|
||||
@@ -1746,6 +1830,12 @@ class MiniMaxH3Pipeline(
|
||||
audio_condition_lengths=audio_condition_lengths,
|
||||
keyframe_frame_indices=keyframe_frame_indices,
|
||||
pad_seq_len=pad_seq_len,
|
||||
video_edit_clean_rows=video_edit_clean_rows,
|
||||
video_edit_mask_rows=video_edit_mask_rows,
|
||||
video_edit_restore_mask_rows=video_edit_restore_mask_rows,
|
||||
audio_edit_clean_rows=audio_edit_clean_rows,
|
||||
audio_edit_mask_rows=audio_edit_mask_rows,
|
||||
audio_edit_restore_mask_rows=audio_edit_restore_mask_rows,
|
||||
)
|
||||
branch = inputs["branch"]
|
||||
transformer = self._transformer_for_task(task)
|
||||
@@ -1763,6 +1853,8 @@ class MiniMaxH3Pipeline(
|
||||
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),
|
||||
video_edit=inputs["video_edit"],
|
||||
audio_edit=inputs["audio_edit"],
|
||||
on_step=lambda step, video, audio: progress.update(),
|
||||
)
|
||||
|
||||
@@ -1997,7 +2089,14 @@ class MiniMaxH3Pipeline(
|
||||
if world_size == 1:
|
||||
assert conditioning is not None
|
||||
return conditioning
|
||||
tensor_names = ("visual_condition", "audio_condition")
|
||||
tensor_names = (
|
||||
"visual_condition",
|
||||
"audio_condition",
|
||||
"video_edit_clean_rows",
|
||||
"video_edit_mask",
|
||||
"audio_edit_clean_rows",
|
||||
"audio_edit_mask",
|
||||
)
|
||||
header = [None]
|
||||
if rank == 0:
|
||||
assert conditioning is not None
|
||||
@@ -2187,6 +2286,50 @@ class MiniMaxH3Pipeline(
|
||||
visual_shapes = list(conditioning.visual_condition_shapes) or None
|
||||
audio_lengths = list(conditioning.audio_condition_lengths) or None
|
||||
|
||||
latent_edit: dict[str, torch.Tensor | None] = {
|
||||
"video_edit_clean_rows": None,
|
||||
"video_edit_mask_rows": None,
|
||||
"video_edit_restore_mask_rows": None,
|
||||
"audio_edit_clean_rows": None,
|
||||
"audio_edit_mask_rows": None,
|
||||
"audio_edit_restore_mask_rows": None,
|
||||
}
|
||||
try:
|
||||
if conditioning.video_edit_clean_rows is not None:
|
||||
if conditioning.video_edit_mask is None:
|
||||
raise ValueError("MiniMax H3 video edit rows require a mask")
|
||||
video_mask = minimax_h3_video_edit_masks(
|
||||
conditioning.video_edit_mask,
|
||||
latent_t=conditioning.latent_t,
|
||||
latent_h=conditioning.height // 16,
|
||||
latent_w=conditioning.width // 16,
|
||||
)
|
||||
latent_edit.update(
|
||||
video_edit_clean_rows=conditioning.video_edit_clean_rows,
|
||||
video_edit_mask_rows=video_mask.model_mask_rows,
|
||||
video_edit_restore_mask_rows=video_mask.restore_mask_rows,
|
||||
)
|
||||
if conditioning.audio_edit_clean_rows is not None:
|
||||
if conditioning.audio_edit_mask is None:
|
||||
raise ValueError("MiniMax H3 audio edit rows require a mask")
|
||||
audio_mask = minimax_h3_audio_edit_masks(
|
||||
conditioning.audio_edit_mask,
|
||||
audio_t=conditioning.audio_t,
|
||||
)
|
||||
model_mask, restore_mask = _expose_padded_audio_tail(
|
||||
conditioning.audio_edit_source_t,
|
||||
target_audio_t=conditioning.audio_t,
|
||||
mask_rows=audio_mask.model_mask_rows,
|
||||
restore_mask_rows=audio_mask.restore_mask_rows,
|
||||
)
|
||||
latent_edit.update(
|
||||
audio_edit_clean_rows=conditioning.audio_edit_clean_rows,
|
||||
audio_edit_mask_rows=model_mask,
|
||||
audio_edit_restore_mask_rows=restore_mask,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise OmniClientError(str(exc)) from exc
|
||||
|
||||
base_schedule, num_steps = self._resolve_sigma_positions(task, sampling)
|
||||
quality_plan = self._quality_policy.resolve(
|
||||
quality=sampling.quality,
|
||||
@@ -2239,6 +2382,7 @@ class MiniMaxH3Pipeline(
|
||||
if extra.get("preencode_mp4", False)
|
||||
else None
|
||||
),
|
||||
**latent_edit,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
@@ -2411,6 +2555,8 @@ class MiniMaxH3Pipeline(
|
||||
_STEP_AUDIO_ANCHOR: audio_anchor,
|
||||
_STEP_SIGMAS_VIDEO: sigmas_video,
|
||||
_STEP_SIGMAS_AUDIO: sigmas_audio,
|
||||
_STEP_VIDEO_EDIT: inputs.get("video_edit"),
|
||||
_STEP_AUDIO_EDIT: inputs.get("audio_edit"),
|
||||
_STEP_SHAPE: {
|
||||
"height": context["height"],
|
||||
"width": context["width"],
|
||||
@@ -2444,12 +2590,40 @@ class MiniMaxH3Pipeline(
|
||||
batch_states = list(states if states is not None else input_batch.states)
|
||||
|
||||
branches = [state.extra[_STEP_BRANCH] for state in batch_states]
|
||||
video_rows = [state.latents for state in batch_states]
|
||||
audio_rows = [state.extra[_STEP_AUDIO_ROWS] for state in batch_states]
|
||||
schedules = [_minimax_h3_step_schedule(state) for state in batch_states]
|
||||
transformers = [state.extra[_STEP_TRANSFORMER] for state in batch_states]
|
||||
mixed_transformers = len({id(transformer) for transformer in transformers}) > 1
|
||||
|
||||
video_rows: list[torch.Tensor] = []
|
||||
audio_rows: list[torch.Tensor] = []
|
||||
video_target_timesteps: list[torch.Tensor | None] = []
|
||||
audio_target_timesteps: list[torch.Tensor | None] = []
|
||||
for state, branch, schedule in zip(batch_states, branches, schedules, strict=True):
|
||||
video_edit = state.extra.get(_STEP_VIDEO_EDIT)
|
||||
request_video, request_video_timesteps = minimax_h3_prepare_edit_rows(
|
||||
state.latents,
|
||||
branch.update_mask_dev,
|
||||
video_edit,
|
||||
schedule["t_video"],
|
||||
schedule["imgvid_cond_timestep"],
|
||||
sigma=schedule["sigma_video"],
|
||||
)
|
||||
video_target_timesteps.append(request_video_timesteps)
|
||||
video_rows.append(request_video)
|
||||
|
||||
state_audio = state.extra[_STEP_AUDIO_ROWS]
|
||||
audio_edit = state.extra.get(_STEP_AUDIO_EDIT)
|
||||
request_audio, request_audio_timesteps = minimax_h3_prepare_edit_rows(
|
||||
state_audio,
|
||||
branch.audio_update_mask_dev,
|
||||
audio_edit,
|
||||
schedule["t_audio"],
|
||||
schedule["audio_ref_cond_timestep"],
|
||||
sigma=schedule["sigma_audio"],
|
||||
)
|
||||
audio_target_timesteps.append(request_audio_timesteps)
|
||||
audio_rows.append(request_audio)
|
||||
|
||||
# Both execution modes must publish denoise progress for step-gated
|
||||
# attention features. Requests can differ in both step index and sigma
|
||||
# schedule, so a batch that is not at one single point has nothing to
|
||||
@@ -2495,6 +2669,8 @@ class MiniMaxH3Pipeline(
|
||||
t_audio=schedules[index]["t_audio"],
|
||||
imgvid_cond_timestep=schedules[index]["imgvid_cond_timestep"],
|
||||
audio_ref_cond_timestep=schedules[index]["audio_ref_cond_timestep"],
|
||||
video_target_timesteps=video_target_timesteps[index],
|
||||
audio_target_timesteps=audio_target_timesteps[index],
|
||||
)
|
||||
request_video, request_audio = transformers[index](**forward_kwargs)
|
||||
video_parts.append(request_video)
|
||||
@@ -2510,6 +2686,8 @@ class MiniMaxH3Pipeline(
|
||||
t_audio=[schedule["t_audio"] for schedule in schedules],
|
||||
imgvid_cond_timesteps=[schedule["imgvid_cond_timestep"] for schedule in schedules],
|
||||
audio_ref_cond_timesteps=[schedule["audio_ref_cond_timestep"] for schedule in schedules],
|
||||
video_target_timesteps=video_target_timesteps,
|
||||
audio_target_timesteps=audio_target_timesteps,
|
||||
)
|
||||
logger.debug(
|
||||
"MiniMax H3 denoise step: %d request(s) packed into %d rows",
|
||||
@@ -2543,11 +2721,19 @@ class MiniMaxH3Pipeline(
|
||||
audio_anchor = state.extra[_STEP_AUDIO_ANCHOR]
|
||||
device = video_rows.device
|
||||
|
||||
x0_video = minimax_h3_rf_v_to_x0(
|
||||
video_rows[update],
|
||||
noise_pred.float()[update],
|
||||
torch.tensor(schedule["t_video"], dtype=torch.float32, device=device),
|
||||
)
|
||||
video_edit = state.extra.get(_STEP_VIDEO_EDIT)
|
||||
if video_edit is None:
|
||||
x0_video = minimax_h3_rf_v_to_x0(
|
||||
video_rows[update],
|
||||
noise_pred.float()[update],
|
||||
torch.tensor(schedule["t_video"], dtype=torch.float32, device=device),
|
||||
)
|
||||
else:
|
||||
x0_video = video_edit.x0(
|
||||
video_edit.model_rows(video_rows[update]),
|
||||
noise_pred.float()[update],
|
||||
schedule["t_video"],
|
||||
)
|
||||
new_video = minimax_h3_euler_eta0_step(
|
||||
video_rows[update],
|
||||
x0_video,
|
||||
@@ -2559,11 +2745,19 @@ class MiniMaxH3Pipeline(
|
||||
if cond_anchor is not None:
|
||||
video_rows[~update] = cond_anchor # per-step imgvid cond reset
|
||||
|
||||
x0_audio = minimax_h3_rf_v_to_x0(
|
||||
audio_rows[audio_update],
|
||||
audio_noise_pred.float()[audio_update],
|
||||
torch.tensor(schedule["t_audio"], dtype=torch.float32, device=device),
|
||||
)
|
||||
audio_edit = state.extra.get(_STEP_AUDIO_EDIT)
|
||||
if audio_edit is None:
|
||||
x0_audio = minimax_h3_rf_v_to_x0(
|
||||
audio_rows[audio_update],
|
||||
audio_noise_pred.float()[audio_update],
|
||||
torch.tensor(schedule["t_audio"], dtype=torch.float32, device=device),
|
||||
)
|
||||
else:
|
||||
x0_audio = audio_edit.x0(
|
||||
audio_edit.model_rows(audio_rows[audio_update]),
|
||||
audio_noise_pred.float()[audio_update],
|
||||
schedule["t_audio"],
|
||||
)
|
||||
new_audio = minimax_h3_euler_eta0_step(
|
||||
audio_rows[audio_update],
|
||||
x0_audio,
|
||||
|
||||
Reference in new issue
Block a user