[Feature] Support text encoder Disaggregation for H3 (#5885)

Signed-off-by: Canlin Guo <canlinguosdu@gmail.com>
Signed-off-by: lishunyang12 <lishunyang12@163.com>
Signed-off-by: yuanwu <yuan.wu@intel.com>
Co-authored-by: lishunyang12 <lishunyang12@163.com>
Co-authored-by: yuanwu <yuan.wu@intel.com>
This commit is contained in:
authored and GitHub committed 2026-08-28 14:27:05 +08:00
1 parent ed837e350e
commit b6a4baa659
61 files changed
+2952 -366

No files matched your search

@@ -1,6 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
"""MiniMax H3 audio-video diffusion support."""
from vllm_omni.model_executor.models.minimax_h3 import reference_video
from .pipeline_minimax_h3 import (
MiniMaxH3Pipeline,
get_minimax_h3_post_process_func,
@@ -9,4 +11,5 @@ from .pipeline_minimax_h3 import (
__all__ = [
"MiniMaxH3Pipeline",
"get_minimax_h3_post_process_func",
"reference_video",
]
@@ -62,6 +62,41 @@ from vllm_omni.errors import OmniClientError, client_error_from_metadata
from vllm_omni.model_executor.model_loader.weight_utils import (
download_weights_from_hf_specific,
)
from vllm_omni.model_executor.models.minimax_h3.checkpoint import (
resolve_minimax_h3_partition,
)
from vllm_omni.model_executor.models.minimax_h3.conditioning import (
MiniMaxH3TextConditioning,
)
from vllm_omni.model_executor.models.minimax_h3.preprocessing import (
load_minimax_h3_images as _load_images,
)
from vllm_omni.model_executor.models.minimax_h3.preprocessing import (
minimax_h3_multi_image_presentation,
minimax_h3_ref2va_presentation,
minimax_h3_ref2va_video_presentation,
minimax_h3_text_only_ids,
)
from vllm_omni.model_executor.models.minimax_h3.preprocessing import (
resolve_minimax_h3_aspect_ratio as _resolve_minimax_h3_aspect_ratio,
)
from vllm_omni.model_executor.models.minimax_h3.preprocessing import (
resolve_minimax_h3_output_canvas as _resolve_output_canvas,
)
from vllm_omni.model_executor.models.minimax_h3.preprocessing import (
resolve_minimax_h3_reference_image_shape as _reference_image_shape,
)
from vllm_omni.model_executor.models.minimax_h3.reference_video import (
MINIMAX_H3_PREPARED_REFERENCE_VIDEOS_KEY,
deserialize_prepared_reference_videos,
load_audio_file,
load_video_audio,
load_video_frames,
prepare_reference_videos,
sample_reference_video_frames,
validate_reference_audio_files,
validate_reference_audio_waveforms,
)
from vllm_omni.platforms import current_omni_platform
from vllm_omni.quantization import (
resolve_component_quant_config as _resolve_component_quant_config,
@@ -97,23 +132,7 @@ from .packed_tokens import (
minimax_h3_unpack_audio_tokens,
minimax_h3_unpatchify_video_tokens,
)
from .presentation import (
minimax_h3_multi_image_presentation_ids,
minimax_h3_multi_image_presentation_token_tags,
minimax_h3_ref2va_presentation,
minimax_h3_ref2va_video_presentation,
minimax_h3_text_only_ids,
)
from .quality_policy import MINIMAX_H3_GENERIC_CACHE_KEY, MiniMaxH3QualityPolicy
from .reference_video import (
load_audio_file,
load_video_audio,
load_video_frames,
prepare_reference_videos,
sample_reference_video_frames,
validate_reference_audio_files,
validate_reference_audio_waveforms,
)
from .scheduling_minimax_h3_euler_ancestral import (
minimax_h3_euler_eta0_step,
minimax_h3_rf_v_to_x0,
@@ -169,6 +188,28 @@ MINIMAX_H3_TASK_DOWNLOAD_PATTERNS = {
"fl2va": ["FL2VA/**"],
"ref2va": ["Ref2VA/**"],
}
MINIMAX_H3_DIFFUSION_DOWNLOAD_PATTERNS = {
"fl2va": [
"FL2VA/model_index.json",
"FL2VA/transformer/**",
"FL2VA/video_vae/**",
"FL2VA/audio_vae/**",
],
"ref2va": [
"Ref2VA/model_index.json",
"Ref2VA/transformer/**",
"Ref2VA/video_vae/**",
"Ref2VA/audio_vae/**",
],
"combined": [
"FL2VA/model_index.json",
"FL2VA/transformer/**",
"FL2VA/video_vae/**",
"FL2VA/audio_vae/**",
"Ref2VA/model_index.json",
"Ref2VA/transformer/**",
],
}
def _resolve_minimax_h3_text_encoder_quant_config(
@@ -182,33 +223,27 @@ 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}")
return resolve_minimax_h3_partition(model or "", task_type, auto_partition="combined")
def _resolve_minimax_h3_model_root(
model: str,
revision: str | None,
partition: str,
*,
load_text_encoder: bool,
) -> Path:
path = Path(model)
if path.is_dir():
if path.name in {"FL2VA", "Ref2VA"} and (path / "model_index.json").is_file():
if path.name in {"FL2VA", "Ref2VA"}:
return path.parent
return path
allow_patterns = (
MINIMAX_H3_DOWNLOAD_PATTERNS if partition == "combined" else MINIMAX_H3_TASK_DOWNLOAD_PATTERNS[partition]
)
if load_text_encoder:
allow_patterns = (
MINIMAX_H3_DOWNLOAD_PATTERNS if partition == "combined" else MINIMAX_H3_TASK_DOWNLOAD_PATTERNS[partition]
)
else:
allow_patterns = MINIMAX_H3_DIFFUSION_DOWNLOAD_PATTERNS[partition]
return Path(
download_weights_from_hf_specific(
model_name_or_path=model,
@@ -287,6 +322,29 @@ def _read_base_schedule(release: Mapping[str, Any]) -> DMD2SigmaSchedule | None:
return DMD2SigmaSchedule.from_metadata(release)
def resolve_minimax_h3_diffusion_model_path(
model: str,
revision: str | None,
task_type: str | None,
) -> str:
"""Resolve a repository root or Hub ID to its startup partition."""
partition = (
"combined"
if str(task_type or "").lower() == "combined"
else resolve_minimax_h3_partition(model, task_type, auto_partition="fl2va")
)
model_root = _resolve_minimax_h3_model_root(
model,
revision,
partition,
load_text_encoder=False,
)
if partition == "combined":
return str(model_root)
subdir = "Ref2VA" if partition == "ref2va" else "FL2VA"
return str(model_root / subdir)
def _minimax_h3_post_process(output, output_type: str = "np"):
"""Convert the joint video/audio output without capturing worker state.
@@ -310,6 +368,12 @@ def _minimax_h3_post_process(output, output_type: str = "np"):
}
def _register_dlo_component_cache(cache: BoundedAllocatorCache, *components: Any) -> None:
for component in components:
if component is not None:
component.set_omni_component_cache(cache)
def get_minimax_h3_post_process_func(
od_config: OmniDiffusionConfig,
):
@@ -328,39 +392,6 @@ def _load_image(value: Any) -> Image.Image:
return images[0]
def _load_images(value: Any) -> list[Image.Image]:
if isinstance(value, (list, tuple)):
if not value:
raise OmniClientError("MiniMax H3 image input must not be empty")
return [_load_image(item) for item in value]
if isinstance(value, (str, os.PathLike)):
file_size = os.path.getsize(value)
if file_size > MINIMAX_H3_MAX_REFERENCE_IMAGE_BYTES:
raise OmniClientError("MiniMax H3 reference image exceeds the 30 MiB size limit")
with Image.open(value) as image:
image_format = str(image.format or "").lower()
if image_format and image_format not in MINIMAX_H3_REFERENCE_IMAGE_FORMATS:
raise OmniClientError(
f"MiniMax H3 reference image must use JPG, JPEG, PNG, WEBP, HEIC, or HEIF, got {image.format}"
)
return [image.convert("RGB")]
if isinstance(value, Image.Image):
return [value.convert("RGB")]
if isinstance(value, torch.Tensor):
tensor = value.detach().float().cpu()
if tensor.ndim == 4 and tensor.shape[0] == 1:
tensor = tensor[0]
if tensor.ndim != 3:
raise OmniClientError(f"image tensor must be [C,H,W], got {tuple(tensor.shape)}")
if tensor.shape[0] in (1, 3, 4):
tensor = tensor.permute(1, 2, 0)
array = tensor.numpy()
if array.max(initial=0) <= 1.0:
array = array * 255.0
return [Image.fromarray(array.clip(0, 255).astype(np.uint8)).convert("RGB")]
raise OmniClientError(f"unsupported MiniMax H3 image input {type(value)!r}")
def _load_audio(value: Any) -> tuple[torch.Tensor, int]:
if isinstance(value, (list, tuple)) and not (len(value) == 2 and isinstance(value[1], (int, np.integer))):
audios = _load_audios(value)
@@ -369,7 +400,7 @@ def _load_audio(value: Any) -> tuple[torch.Tensor, int]:
return audios[0]
if isinstance(value, (str, os.PathLike)):
return load_audio_file(str(value))
if isinstance(value, tuple) and len(value) == 2:
if isinstance(value, (list, tuple)) and len(value) == 2:
waveform, sample_rate = value
waveform = torch.as_tensor(waveform).float()
return waveform, int(sample_rate)
@@ -423,6 +454,21 @@ def _resolve_fl2va_keyframe_indices(extra: Mapping[str, Any], image_count: int)
return raw_indices
def _reuse_prepared_reference_videos(
prepared: list[dict[str, Any]] | None,
*,
expected_count: int,
) -> list[dict[str, Any]] | None:
if prepared is None:
return None
if len(prepared) != expected_count:
raise OmniClientError("MiniMax H3 prepared-reference-video count does not match the request")
for item in prepared:
if not os.path.isfile(item["prepared_path"]):
raise OmniClientError(f"MiniMax H3 prepared reference video is unavailable: {item['prepared_path']}")
return prepared
def _validate_ref2va_reference_counts(
image_count: int,
video_count: int,
@@ -443,55 +489,6 @@ def _validate_ref2va_reference_counts(
raise OmniClientError("ref2va accepts at most 12 total references")
def _resolve_minimax_h3_aspect_ratio(
task: str,
value: Any,
image: Image.Image | None,
) -> float:
"""Resolve H3's task-specific ratio policy.
T2VA must name one of the official ratios. FL2VA always follows the
first input image, even when a generic client sends ``aspect_ratio``.
Ref2VA defaults to 16:9; ``adaptive``/``auto`` are retained as aliases
for that default for compatibility with existing clients.
"""
if task == "fl2va":
if image is None:
raise OmniClientError("fl2va requires an input image to resolve its aspect ratio")
return float(image.width) / float(image.height)
if value is None:
if task == "t2va":
raise OmniClientError("t2va requires an explicit aspect_ratio")
return MINIMAX_H3_SUPPORTED_ASPECT_RATIOS["16:9"]
if isinstance(value, str):
normalized = value.strip().lower()
if normalized in {"adaptive", "auto"}:
if task == "t2va":
raise OmniClientError("t2va requires an explicit named aspect_ratio, not adaptive")
return MINIMAX_H3_SUPPORTED_ASPECT_RATIOS["16:9"]
if normalized in MINIMAX_H3_SUPPORTED_ASPECT_RATIOS:
return MINIMAX_H3_SUPPORTED_ASPECT_RATIOS[normalized]
try:
numeric_value = float(normalized)
except (TypeError, ValueError) as exc:
supported = ", ".join(MINIMAX_H3_SUPPORTED_ASPECT_RATIOS)
raise OmniClientError(f"MiniMax H3 aspect_ratio must be one of {supported}, got {value!r}") from exc
elif isinstance(value, (int, float, np.integer, np.floating)) and not isinstance(value, bool):
numeric_value = float(value)
else:
raise OmniClientError(f"MiniMax H3 aspect_ratio must be a string ratio, got {value!r}")
if not math.isfinite(numeric_value) or not any(
math.isclose(numeric_value, ratio, rel_tol=0.0, abs_tol=1e-6)
for ratio in MINIMAX_H3_SUPPORTED_ASPECT_RATIOS.values()
):
supported = ", ".join(MINIMAX_H3_SUPPORTED_ASPECT_RATIOS)
raise OmniClientError(f"MiniMax H3 aspect_ratio must be one of {supported}, got {value!r}")
return numeric_value
def _resolve_minimax_h3_num_outputs(value: Any) -> int:
if value is None:
return 1
@@ -609,49 +606,6 @@ def _broadcast_tensor(
return output
def _reference_image_shape(image: Image.Image) -> tuple[int, int]:
width, height = image.size
ratio = width / height
if not 0.4 <= ratio <= 2.5:
raise OmniClientError(f"reference image aspect ratio must be in [0.4, 2.5], got {width}x{height}")
if min(width, height) < 256 or max(width, height) > 5760:
raise OmniClientError(f"reference image dimensions must be in [256, 5760] pixels, got {width}x{height}")
scale = MINIMAX_H3_REFERENCE_IMAGE_SHORT_EDGE / min(width, height)
return (
_align_multiple(
width * scale,
MINIMAX_H3_REFERENCE_IMAGE_MULTIPLE,
),
_align_multiple(
height * scale,
MINIMAX_H3_REFERENCE_IMAGE_MULTIPLE,
),
)
def _resolve_output_canvas(aspect_ratio: float, short_edge: int) -> tuple[int, int]:
"""Resolve the official H3 ratio/area policy to a 32-pixel canvas."""
if not math.isfinite(float(aspect_ratio)) or float(aspect_ratio) <= 0:
raise OmniClientError(f"MiniMax H3 canvas aspect ratio must be positive, got {aspect_ratio!r}")
if short_edge != MINIMAX_H3_OUTPUT_SHORT_EDGE:
raise OmniClientError(f"MiniMax H3 target.short_edge must be {MINIMAX_H3_OUTPUT_SHORT_EDGE}, got {short_edge}")
if aspect_ratio >= 1.0:
width = float(short_edge) * aspect_ratio
height = float(short_edge)
else:
width = float(short_edge)
height = float(short_edge) / aspect_ratio
area = width * height
if area > MINIMAX_H3_OUTPUT_MAX_PIXELS:
scale = (MINIMAX_H3_OUTPUT_MAX_PIXELS / area) ** 0.5
width *= scale
height *= scale
return (
_align_multiple(height, 32),
_align_multiple(width, 32),
)
class _SingleRankEncoderGroup:
"""Lightweight encoder group for ``text_encoder_tp_size == 1``.
@@ -806,6 +760,7 @@ 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()
self.load_text_encoder = od_config.model_loaded["text_encoder"]
self.partition = _minimax_h3_partition_for_task(
getattr(od_config, "task_type", None),
str(od_config.model),
@@ -815,6 +770,7 @@ class MiniMaxH3Pipeline(
str(od_config.model),
od_config.revision,
self.partition,
load_text_encoder=self.load_text_encoder,
)
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"))
@@ -886,54 +842,62 @@ class MiniMaxH3Pipeline(
quant_config=transformer_quant_config,
)
self.tokenizer = Qwen2TokenizerFast.from_pretrained(
str(model_path),
subfolder="tokenizer",
local_files_only=os.path.isdir(model_path),
)
self.processor = Qwen3VLProcessor.from_pretrained(
str(model_path),
subfolder="processor",
local_files_only=os.path.isdir(model_path),
)
if self.load_text_encoder:
self.tokenizer = Qwen2TokenizerFast.from_pretrained(
str(model_path),
subfolder="tokenizer",
local_files_only=os.path.isdir(model_path),
)
self.processor = Qwen3VLProcessor.from_pretrained(
str(model_path),
subfolder="processor",
local_files_only=os.path.isdir(model_path),
)
else:
self.tokenizer = None
self.processor = None
_, rank, dit_world = _dit_rank_world()
self._dit_rank = rank
text_encoder_tp_size = int(getattr(self.parallel_config, "text_encoder_tp_size", 1))
if text_encoder_tp_size < 1:
raise ValueError(f"text_encoder_tp_size must be >= 1, got {text_encoder_tp_size}")
if text_encoder_tp_size > dit_world:
raise ValueError(
f"text_encoder_tp_size must not exceed the DiT group size ({dit_world}), got {text_encoder_tp_size}"
)
# The Qwen3-VL text model uses 64 attention heads / 8 KV heads; the
# encoder shards them across the encoder TP ranks.
if 64 % text_encoder_tp_size or 8 % text_encoder_tp_size:
raise ValueError(
"text_encoder_tp_size must divide both Qwen3-VL "
f"num_attention_heads (64) and num_key_value_heads (8), "
f"got {text_encoder_tp_size}"
)
self.text_encoder_tp_size = text_encoder_tp_size
self.text_encoder_group = self._build_text_encoder_group(text_encoder_tp_size)
load_text_encoder = rank < text_encoder_tp_size
self.text_encoder = MiniMaxH3Qwen3VLEncoder(
os.path.join(model_path, "text_encoder"),
device=self.device,
load_model=load_text_encoder,
encoder_group=self.text_encoder_group,
quant_config=_resolve_minimax_h3_text_encoder_quant_config(od_config.quantization_config),
)
if load_text_encoder:
self.weights_sources.append(
DiffusersPipelineLoader.ComponentSource(
model_or_path=str(model_path),
subfolder="text_encoder",
revision=od_config.revision,
prefix="text_encoder.",
fall_back_to_pt=False,
if self.load_text_encoder:
text_encoder_tp_size = int(getattr(self.parallel_config, "text_encoder_tp_size", 1))
if text_encoder_tp_size < 1:
raise ValueError(f"text_encoder_tp_size must be >= 1, got {text_encoder_tp_size}")
if text_encoder_tp_size > dit_world:
raise ValueError(
f"text_encoder_tp_size must not exceed the DiT group size ({dit_world}), got {text_encoder_tp_size}"
)
# The Qwen3-VL text model uses 64 attention heads / 8 KV heads.
if 64 % text_encoder_tp_size or 8 % text_encoder_tp_size:
raise ValueError(
"text_encoder_tp_size must divide both Qwen3-VL "
f"num_attention_heads (64) and num_key_value_heads (8), "
f"got {text_encoder_tp_size}"
)
self.text_encoder_tp_size = text_encoder_tp_size
self.text_encoder_group = self._build_text_encoder_group(text_encoder_tp_size)
self.text_encoder = MiniMaxH3Qwen3VLEncoder(
os.path.join(model_path, "text_encoder"),
device=self.device,
load_model=rank < text_encoder_tp_size,
encoder_group=self.text_encoder_group,
quant_config=_resolve_minimax_h3_text_encoder_quant_config(od_config.quantization_config),
)
if rank < text_encoder_tp_size:
self.weights_sources.append(
DiffusersPipelineLoader.ComponentSource(
model_or_path=str(model_path),
subfolder="text_encoder",
revision=od_config.revision,
prefix="text_encoder.",
fall_back_to_pt=False,
)
)
else:
self.text_encoder_tp_size = 0
self.text_encoder_group = None
self.text_encoder = None
self._encoder_modules = []
stage_components = bool(
od_config.enable_layerwise_offload or getattr(od_config, "enable_distributed_layerwise_offload", False)
)
@@ -954,8 +918,12 @@ class MiniMaxH3Pipeline(
self._dlo_component_cache = None
if getattr(od_config, "enable_distributed_layerwise_offload", False):
self._dlo_component_cache = BoundedAllocatorCache(self.device)
for component in (self.text_encoder, self.video_vae, self.audio_vae):
component.set_omni_component_cache(self._dlo_component_cache)
_register_dlo_component_cache(
self._dlo_component_cache,
self.text_encoder,
self.video_vae,
self.audio_vae,
)
self._quality_policy = MiniMaxH3QualityPolicy(od_config)
self._cache_dit_runtime = RequestScopedCacheDiTRuntime(self)
@@ -992,6 +960,8 @@ class MiniMaxH3Pipeline(
# path as the DiT.
for component_name in ("video_vae", "audio_vae"):
component = getattr(self, component_name)
if component is None:
continue
loaded_with_prefix.update(f"{component_name}.{name}" for name, _ in component.named_parameters())
return loaded_with_prefix
@@ -1191,12 +1161,7 @@ class MiniMaxH3Pipeline(
if task == "fl2va":
if prepared_videos:
raise OmniClientError("fl2va does not accept video conditions")
ids = minimax_h3_multi_image_presentation_ids(
self.tokenizer,
prompt=prompt,
image_token_counts=image_token_counts,
)
tags = minimax_h3_multi_image_presentation_token_tags(
ids, tags = minimax_h3_multi_image_presentation(
self.tokenizer,
prompt=prompt,
image_token_counts=image_token_counts,
@@ -1985,12 +1950,46 @@ class MiniMaxH3Pipeline(
raise OmniClientError("MiniMax H3 requires a non-empty prompt")
return prompt, multi_modal_data
@staticmethod
def _extract_text_conditioning(raw_prompt: Any) -> MiniMaxH3TextConditioning | None:
if isinstance(raw_prompt, str):
return None
additional_information = raw_prompt.get("additional_information") or {}
text_encoder_output = additional_information.get("text_encoder_output")
if text_encoder_output is None:
return None
if not isinstance(text_encoder_output, Mapping):
raise OmniClientError("text_encoder_output must be a mapping")
try:
return MiniMaxH3TextConditioning.from_payload(text_encoder_output)
except ValueError as exc:
raise OmniClientError(str(exc)) from exc
@staticmethod
def _extract_prepared_reference_videos(raw_prompt: Any) -> list[dict[str, Any]] | None:
if isinstance(raw_prompt, str):
return None
additional_information = raw_prompt.get("additional_information") or {}
meta = additional_information.get("meta") or {}
descriptor = meta.get(MINIMAX_H3_PREPARED_REFERENCE_VIDEOS_KEY)
if descriptor is None:
return None
if not isinstance(descriptor, str):
raise OmniClientError("MiniMax H3 prepared-reference-video descriptor must be a string")
try:
_, videos = deserialize_prepared_reference_videos(descriptor)
except ValueError as exc:
raise OmniClientError(str(exc)) from exc
return videos
def _prepare_request_inputs(
self,
*,
prompt: str,
multi_modal_data: dict[str, Any],
sampling: Any,
text_conditioning: MiniMaxH3TextConditioning | None = None,
prepared_reference_videos: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""Resolve the task and output shape, then run every request-level encode.
@@ -2083,12 +2082,20 @@ class MiniMaxH3Pipeline(
# before starting any subsequent collective.
prep_error: Exception | None = None
try:
prepared_videos = self._prepare_reference_videos(
raw_videos,
target_frame_count=num_frames,
workdir=workdir,
start_time_seconds=extra.get("start_time_seconds"),
)
_, rank, _ = _dit_rank_world()
if prepared_reference_videos is not None:
if rank == 0:
prepared_videos = _reuse_prepared_reference_videos(
prepared_reference_videos,
expected_count=video_count,
)
else:
prepared_videos = self._prepare_reference_videos(
raw_videos,
target_frame_count=num_frames,
workdir=workdir,
start_time_seconds=extra.get("start_time_seconds"),
)
except Exception as exc:
prep_error = exc
_broadcast_rank0_exception(prep_error)
@@ -2129,13 +2136,27 @@ class MiniMaxH3Pipeline(
audio_index += 1
condition_labels.append(("audio", audio_index))
text_embeddings, text_tags = self.encode_prompt(
task=task,
prompt=prompt,
images=prepared_images,
prepared_videos=prepared_videos,
condition_labels=condition_labels if task == "ref2va" else None,
)
if text_conditioning is not None:
text_embeddings = text_conditioning.hidden_states.to(
device=self.device,
dtype=torch.bfloat16,
)
text_tags = text_conditioning.token_tags.to(
device=self.device,
dtype=torch.long,
)
elif getattr(self, "text_encoder", None) is not None:
text_embeddings, text_tags = self.encode_prompt(
task=task,
prompt=prompt,
images=prepared_images,
prepared_videos=prepared_videos,
condition_labels=condition_labels if task == "ref2va" else None,
)
else:
raise OmniClientError(
"MiniMax H3 diffusion stage requires text_encoder_output when text_encoder is not loaded"
)
# ``prepared_videos`` is intentionally ``None`` on non-zero DiT
# ranks; the distributed video encoder broadcasts the prepared
@@ -2264,11 +2285,14 @@ class MiniMaxH3Pipeline(
def forward(self, request: DiffusionRequestBatch) -> DiffusionOutput:
if len(request.prompts) != 1:
raise OmniClientError("MiniMax H3 supports one request at a time")
prompt, multi_modal_data = self._extract_prompt(request.prompts[0])
raw_prompt = request.prompts[0]
prompt, multi_modal_data = self._extract_prompt(raw_prompt)
context = self._prepare_request_inputs(
prompt=prompt,
multi_modal_data=multi_modal_data,
sampling=request.sampling_params,
text_conditioning=self._extract_text_conditioning(raw_prompt),
prepared_reference_videos=self._extract_prepared_reference_videos(raw_prompt),
)
denoise_kwargs = self._denoise_kwargs(context)
num_outputs = context["num_outputs"]
@@ -2357,6 +2381,8 @@ class MiniMaxH3Pipeline(
prompt=prompt,
multi_modal_data=multi_modal_data,
sampling=state.sampling,
text_conditioning=self._extract_text_conditioning(state.prompt),
prepared_reference_videos=self._extract_prepared_reference_videos(state.prompt),
)
inputs = self._build_denoise_inputs(**self._denoise_kwargs(context))
@@ -1,297 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
"""MiniMax H3 Qwen presentation building.
Builds the positive presentation token stream:
- fl2va: '<Picture 1>: ' label + vision block (<|vision_start|> +
N*<|image_pad|> + <|vision_end|>) + prompt text.
- t2va: prompt text only (no vision block).
Prompt text passes through verbatim (no stripping or rewriting).
All presentation variants are emitted through the shared ``_Presentation``
accumulator so ids and AdaLN token tags cannot drift apart.
"""
from __future__ import annotations
from collections.abc import Sequence
from typing import Any
import torch
VISION_START = "<|vision_start|>"
VISION_END = "<|vision_end|>"
IMAGE_PAD = "<|image_pad|>"
VIDEO_PAD = "<|video_pad|>"
_TEXT_TAG = 1
_VIDEO_TAG = 0
def _text_ids(tokenizer: Any, text: str) -> list[int]:
return list(tokenizer(text, add_special_tokens=False)["input_ids"])
def _vision_block_ids(tokenizer: Any, pad_token: str, count: int) -> list[int]:
return (
[tokenizer.convert_tokens_to_ids(VISION_START)]
+ [tokenizer.convert_tokens_to_ids(pad_token)] * int(count)
+ [tokenizer.convert_tokens_to_ids(VISION_END)]
)
class _Presentation:
"""Accumulates aligned (ids, token_tags) presentation segments."""
def __init__(self) -> None:
self.ids: list[int] = []
self.tags: list[int] = []
def text(self, token_ids: list[int]) -> None:
self.ids += token_ids
self.tags += [_TEXT_TAG] * len(token_ids)
def vision(self, token_ids: list[int]) -> None:
self.ids += token_ids
self.tags += [_VIDEO_TAG] * len(token_ids)
def build(self) -> tuple[torch.Tensor, torch.Tensor]:
return (
torch.tensor(self.ids, dtype=torch.long),
torch.tensor(self.tags, dtype=torch.long),
)
def _timestamped_video_blocks(
presentation: _Presentation,
tokenizer: Any,
*,
counts: Sequence[int],
timestamps: Sequence[float],
context: str,
) -> None:
"""Emit per-temporal-block ``<{t:.1f} seconds>`` text + VIDEO vision."""
counts = [int(value) for value in counts]
timestamps = [float(value) for value in timestamps]
if not counts or len(counts) != len(timestamps):
raise ValueError(f"{context}video block token counts and timestamps must align")
for count, timestamp in zip(counts, timestamps):
if count <= 0:
raise ValueError(f"{context}video block token count must be positive")
presentation.text(_text_ids(tokenizer, f"<{timestamp:.1f} seconds>"))
presentation.vision(_vision_block_ids(tokenizer, VIDEO_PAD, count))
def minimax_h3_text_only_ids(tokenizer: Any, prompt: str) -> torch.Tensor:
"""t2va presentation: verbatim prompt, no special tokens."""
if not prompt:
raise ValueError("prompt must be non-empty")
return torch.tensor(_text_ids(tokenizer, prompt), dtype=torch.long)
def _multi_image_presentation(
tokenizer: Any,
*,
prompt: str,
image_token_counts: list[int],
) -> tuple[torch.Tensor, torch.Tensor]:
if not image_token_counts:
raise ValueError("image_token_counts must be non-empty")
presentation = _Presentation()
for index, count in enumerate(image_token_counts, start=1):
if int(count) <= 0:
raise ValueError("image_token_count must be positive")
presentation.text(_text_ids(tokenizer, f"<Picture {index}>: "))
presentation.vision(_vision_block_ids(tokenizer, IMAGE_PAD, count))
presentation.text(_text_ids(tokenizer, prompt))
return presentation.build()
def minimax_h3_multi_image_presentation_ids(
tokenizer: Any,
*,
prompt: str,
image_token_counts: list[int],
) -> torch.Tensor:
"""Positive fl2va presentation with one or more labeled image slots."""
ids, _ = _multi_image_presentation(tokenizer, prompt=prompt, image_token_counts=image_token_counts)
return ids
def minimax_h3_multi_image_presentation_token_tags(
tokenizer: Any,
*,
prompt: str,
image_token_counts: list[int],
) -> torch.Tensor:
"""AdaLN token tags aligned with minimax_h3_multi_image_presentation_ids."""
_, tags = _multi_image_presentation(tokenizer, prompt=prompt, image_token_counts=image_token_counts)
return tags
def minimax_h3_ref2va_presentation(
tokenizer: Any,
*,
prompt: str,
condition_labels: list[tuple[str, int]],
image_token_count: int | list[int] | None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""ref2va positive presentation:
per condition in request order — image i: ``<Picture i>: `` label followed
by the vision block; audio j: ``<Audio j>: `` label only (audio content
never enters Qwen) — then the verbatim prompt. Returns (ids, token_tags)
with the vision block tagged VIDEO(0) and everything else TEXT(1).
condition_labels: [("image", 1), ("audio", 1), ...] with 1-based ordinals
per type.
"""
return minimax_h3_ref2va_video_presentation(
tokenizer,
prompt=prompt,
condition_labels=condition_labels,
image_token_count=image_token_count,
video_block_token_counts=None,
video_block_timestamps=None,
)
def _as_int_list(value: int | Sequence[int] | None, *, name: str) -> list[int]:
if value is None:
return []
if isinstance(value, int):
return [int(value)]
if not isinstance(value, Sequence) or isinstance(value, (str, bytes)):
raise ValueError(f"{name} must be an int or a sequence of ints")
return [int(item) for item in value]
def _as_nested_int_list(
value: Sequence[int] | Sequence[Sequence[int]] | None,
*,
name: str,
) -> list[list[int]]:
if value is None:
return []
if not isinstance(value, Sequence) or isinstance(value, (str, bytes)):
raise ValueError(f"{name} must be a sequence")
if len(value) == 0:
return []
first = value[0]
if isinstance(first, Sequence) and not isinstance(first, (str, bytes)):
out: list[list[int]] = []
for group in value:
if not isinstance(group, Sequence) or isinstance(group, (str, bytes)):
raise ValueError(f"{name} must not mix nested and flat entries")
out.append([int(item) for item in group])
return out
return [[int(item) for item in value]]
def _as_nested_float_list(
value: Sequence[float] | Sequence[Sequence[float]] | None,
*,
name: str,
) -> list[list[float]]:
if value is None:
return []
if not isinstance(value, Sequence) or isinstance(value, (str, bytes)):
raise ValueError(f"{name} must be a sequence")
if len(value) == 0:
return []
first = value[0]
if isinstance(first, Sequence) and not isinstance(first, (str, bytes)):
out: list[list[float]] = []
for group in value:
if not isinstance(group, Sequence) or isinstance(group, (str, bytes)):
raise ValueError(f"{name} must not mix nested and flat entries")
out.append([float(item) for item in group])
return out
return [[float(item) for item in value]]
def minimax_h3_ref2va_video_presentation(
tokenizer: Any,
*,
prompt: str,
condition_labels: list[tuple[str, int]],
image_token_count: int | list[int] | None,
video_block_token_counts: list[int] | list[list[int]] | None,
video_block_timestamps: list[float] | list[list[float]] | None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""ref2va (optionally with video refs) positive presentation:
per condition in request order —
- image i: ``<Picture i>: `` label + one image vision block;
- audio j: ``<Audio j>: `` label only (audio content never enters Qwen);
- video k: ``<Video k>: `` label, then per temporal block a timestamp
text ``<{t:.1f} seconds>`` followed by a VIDEO vision block
(<|vision_start|> + <|video_pad|> x n + <|vision_end|>). Timestamps are
the mean of each merged frame pair (Qwen3VL temporal merge 2; odd frame
counts repeat the last frame), emitting the
``<0.2 seconds>`` ..
``<4.0 seconds>`` sequence — note Python bankers-rounding at .1f.
then the verbatim prompt. Vision blocks are tagged VIDEO(0), everything
else TEXT(1).
"""
if not prompt:
raise ValueError("prompt must be non-empty")
presentation = _Presentation()
image_token_counts = _as_int_list(image_token_count, name="image_token_count")
video_counts_by_ref = _as_nested_int_list(
video_block_token_counts,
name="video_block_token_counts",
)
video_timestamps_by_ref = _as_nested_float_list(
video_block_timestamps,
name="video_block_timestamps",
)
if len(video_counts_by_ref) != len(video_timestamps_by_ref):
raise ValueError("video block token counts and timestamps must align")
image_seen = 0
video_seen = 0
for cond_type, ordinal in condition_labels:
if cond_type == "image":
image_seen += 1
if image_seen > len(image_token_counts):
raise ValueError("image_token_count required for an image reference")
count = int(image_token_counts[image_seen - 1])
if count <= 0:
raise ValueError("image_token_count required for an image reference")
presentation.text(_text_ids(tokenizer, f"<Picture {ordinal}>: "))
presentation.vision(_vision_block_ids(tokenizer, IMAGE_PAD, count))
elif cond_type == "audio":
presentation.text(_text_ids(tokenizer, f"<Audio {ordinal}>: "))
elif cond_type == "video":
video_seen += 1
if video_seen > len(video_counts_by_ref):
raise ValueError("video reference requires block token counts and timestamps")
counts = video_counts_by_ref[video_seen - 1]
timestamps = video_timestamps_by_ref[video_seen - 1]
if not counts or not timestamps:
raise ValueError("video reference requires block token counts and timestamps")
presentation.text(_text_ids(tokenizer, f"<Video {ordinal}>: "))
_timestamped_video_blocks(
presentation,
tokenizer,
counts=counts,
timestamps=timestamps,
context="",
)
else:
raise ValueError(f"unsupported ref2va condition type {cond_type!r}")
if image_seen != len(image_token_counts):
raise ValueError("unused image_token_count entries")
if video_seen != len(video_counts_by_ref):
raise ValueError("unused video block token count entries")
presentation.text(_text_ids(tokenizer, prompt))
return presentation.build()
__all__ = [
"minimax_h3_multi_image_presentation_ids",
"minimax_h3_multi_image_presentation_token_tags",
"minimax_h3_ref2va_presentation",
"minimax_h3_ref2va_video_presentation",
"minimax_h3_text_only_ids",
]
@@ -1,621 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
"""MiniMax H3 Ref2VA reference-video preparation."""
from __future__ import annotations
import json
import math
import os
import subprocess
from pathlib import Path
from typing import Any
import numpy as np
import torch
from vllm_omni.errors import OmniClientError
MINIMAX_H3_FPS = 24.0
MINIMAX_H3_QWEN_VIDEO_SAMPLE_FPS = 2.0
MINIMAX_H3_QWEN_TEMPORAL_PATCH = 2
MINIMAX_H3_BASE_SHORT_EDGE = 768
MINIMAX_H3_MAX_PIXELS = 768 * 1344
MINIMAX_H3_CANVAS_MULTIPLE = 32
MINIMAX_H3_MIN_REFERENCE_DIMENSION = 256
MINIMAX_H3_MAX_REFERENCE_DIMENSION = 5760
MINIMAX_H3_MIN_REFERENCE_FPS = 23.976
MINIMAX_H3_MAX_REFERENCE_FPS = 60.0
MINIMAX_H3_MIN_REFERENCE_DURATION = 2.0
MINIMAX_H3_MAX_REFERENCE_DURATION = 15.0
MINIMAX_H3_MAX_REFERENCE_TOTAL_DURATION = 15.0
# ffprobe reports container durations at a finer precision than the official
# example's rounded values. Trim only this small probe-rounding excess.
MINIMAX_H3_REFERENCE_DURATION_EPSILON = 1e-2
MINIMAX_H3_MAX_VIDEO_BYTES = 50 * 1024 * 1024
MINIMAX_H3_MAX_AUDIO_BYTES = 15 * 1024 * 1024
MINIMAX_H3_VIDEO_FORMATS = frozenset({"mp4", "mov"})
MINIMAX_H3_VIDEO_CODECS = frozenset({"h264", "h265", "hevc"})
MINIMAX_H3_AUDIO_FORMATS = frozenset({"wav", "mp3"})
MINIMAX_H3_AUDIO_CODECS = frozenset({"aac", "mp3"})
def _nearest_multiple(value: float, multiple: int) -> int:
return max(multiple, int(round(float(value) / multiple)) * multiple)
def _probe_video(path: str) -> dict[str, Any]:
show_entries = (
"stream=codec_type,codec_name,width,height,r_frame_rate,nb_read_frames,nb_frames,duration,"
"sample_aspect_ratio:format=format_name,size,duration"
)
command = ["ffprobe", "-v", "error", "-show_entries", show_entries, "-of", "json", path]
result = subprocess.run(command, check=True, capture_output=True, text=True)
probe = json.loads(result.stdout)
streams = probe.get("streams") or []
video_streams = [stream for stream in streams if stream.get("codec_type") == "video"]
if not video_streams:
raise OmniClientError(f"media has no video stream: {path}")
stream = video_streams[0]
raw_count = stream.get("nb_read_frames") or stream.get("nb_frames")
if raw_count in (None, "", "N/A"):
result = subprocess.run(
["ffprobe", "-v", "error", "-count_frames", *command[3:]],
check=True,
capture_output=True,
text=True,
)
probe = json.loads(result.stdout)
streams = probe.get("streams") or []
video_streams = [stream for stream in streams if stream.get("codec_type") == "video"]
if not video_streams:
raise OmniClientError(f"media has no video stream: {path}")
stream = video_streams[0]
raw_count = stream.get("nb_read_frames") or stream.get("nb_frames")
try:
numerator, denominator = str(stream["r_frame_rate"]).split("/", 1)
fps = float(numerator) / float(denominator)
except (KeyError, TypeError, ValueError, ZeroDivisionError) as exc:
raise OmniClientError(f"cannot determine video FPS: {path}") from exc
if not math.isfinite(fps) or fps <= 0:
raise OmniClientError(f"cannot determine video FPS: {path}")
if raw_count in (None, "", "N/A"):
raise OmniClientError(f"cannot determine video frame count: {path}")
raw_duration = stream.get("duration")
if raw_duration in (None, "", "N/A"):
raw_duration = probe.get("format", {}).get("duration")
duration = float(raw_duration) if raw_duration not in (None, "", "N/A") else int(raw_count) / fps
format_info = probe.get("format") or {}
format_names = tuple(
name.strip().lower() for name in str(format_info.get("format_name", "")).split(",") if name.strip()
)
raw_size = format_info.get("size")
file_size = int(raw_size) if raw_size not in (None, "", "N/A") else os.path.getsize(path)
audio_codecs = tuple(
str(stream.get("codec_name", "")).lower()
for stream in streams
if stream.get("codec_type") == "audio" and stream.get("codec_name")
)
return {
"width": int(stream["width"]),
"height": int(stream["height"]),
"fps": fps,
"frame_count": int(raw_count),
"duration": duration,
"format_names": format_names,
"video_codec": str(stream.get("codec_name", "")).lower(),
"audio_codecs": audio_codecs,
"file_size": file_size,
}
def _validate_reference_video_metadata(meta: dict[str, Any], *, index: int, source: str) -> None:
width = int(meta["width"])
height = int(meta["height"])
if (
min(width, height) < MINIMAX_H3_MIN_REFERENCE_DIMENSION
or max(width, height) > MINIMAX_H3_MAX_REFERENCE_DIMENSION
):
raise OmniClientError(f"reference video {index} dimensions must be in [256, 5760] pixels, got {width}x{height}")
ratio = width / height
if not 0.4 <= ratio <= 2.5:
raise OmniClientError(f"reference video {index} aspect ratio must be in [0.4, 2.5], got {width}x{height}")
fps = float(meta["fps"])
if not MINIMAX_H3_MIN_REFERENCE_FPS <= fps <= MINIMAX_H3_MAX_REFERENCE_FPS:
raise OmniClientError(f"reference video {index} FPS must be in [23.976, 60], got {fps:.3f}")
duration = float(meta["duration"])
if (
not math.isfinite(duration)
or not MINIMAX_H3_MIN_REFERENCE_DURATION <= duration <= MINIMAX_H3_MAX_REFERENCE_DURATION
):
raise OmniClientError(f"reference video {index} duration must be in [2, 15] seconds, got {duration:.3f}")
raw_file_size = meta.get("file_size")
file_size = int(raw_file_size) if raw_file_size is not None else os.path.getsize(source)
if file_size > MINIMAX_H3_MAX_VIDEO_BYTES:
raise OmniClientError(f"reference video {index} exceeds the 50 MiB size limit")
format_names = set(meta.get("format_names", ()))
if not format_names.intersection(MINIMAX_H3_VIDEO_FORMATS):
formats = ", ".join(sorted(format_names)) or "unknown"
raise OmniClientError(f"reference video {index} must use an MP4 or MOV container, got {formats}")
video_codec = str(meta.get("video_codec", "")).lower()
if video_codec not in MINIMAX_H3_VIDEO_CODECS:
raise OmniClientError(f"reference video {index} must use H.264 or H.265 video, got {video_codec or 'unknown'}")
audio_codecs = tuple(str(codec).lower() for codec in meta.get("audio_codecs", ()))
invalid_audio = [codec for codec in audio_codecs if codec not in MINIMAX_H3_AUDIO_CODECS]
if invalid_audio:
raise OmniClientError(
f"reference video {index} must use AAC or MP3 audio when audio is present, got {invalid_audio[0]}"
)
def _audio_items(values: Any) -> list[Any]:
if isinstance(values, (str, os.PathLike)):
return [values]
if isinstance(values, tuple) and len(values) == 2 and isinstance(values[1], (int, np.integer)):
return [values]
if isinstance(values, (list, tuple)):
return list(values)
return [values]
def _probe_audio(path: str) -> dict[str, Any]:
result = subprocess.run(
[
"ffprobe",
"-v",
"error",
"-show_entries",
"stream=codec_type,codec_name,duration:format=format_name,size,duration",
"-of",
"json",
path,
],
check=True,
capture_output=True,
text=True,
)
probe = json.loads(result.stdout)
streams = [stream for stream in probe.get("streams", []) if stream.get("codec_type") == "audio"]
if not streams:
raise OmniClientError(f"media has no audio stream: {path}")
stream = streams[0]
raw_duration = stream.get("duration")
if raw_duration in (None, "", "N/A"):
raw_duration = (probe.get("format") or {}).get("duration")
if raw_duration in (None, "", "N/A"):
raise OmniClientError(f"cannot determine audio duration: {path}")
format_info = probe.get("format") or {}
format_names = tuple(
name.strip().lower() for name in str(format_info.get("format_name", "")).split(",") if name.strip()
)
raw_size = format_info.get("size")
file_size = int(raw_size) if raw_size not in (None, "", "N/A") else os.path.getsize(path)
return {
"duration": float(raw_duration),
"format_names": format_names,
"codec": str(stream.get("codec_name", "")).lower(),
"file_size": file_size,
}
def validate_reference_audio_files(values: Any) -> None:
"""Validate path-backed standalone audio references against the H3 spec."""
total_duration = 0.0
for index, value in enumerate(_audio_items(values)):
if not isinstance(value, (str, os.PathLike)):
continue
source = str(value)
meta = _probe_audio(source)
file_size = int(meta["file_size"])
if file_size > MINIMAX_H3_MAX_AUDIO_BYTES:
raise OmniClientError(f"reference audio {index} exceeds the 15 MiB size limit")
if not set(meta["format_names"]).intersection(MINIMAX_H3_AUDIO_FORMATS):
formats = ", ".join(meta["format_names"]) or "unknown"
raise OmniClientError(f"reference audio {index} must be WAV or MP3, got {formats}")
codec = str(meta["codec"]).lower()
if codec not in MINIMAX_H3_AUDIO_CODECS and not codec.startswith("pcm_"):
raise OmniClientError(f"reference audio {index} must use MP3 or PCM audio, got {codec or 'unknown'}")
duration = float(meta["duration"])
if (
not math.isfinite(duration)
or not MINIMAX_H3_MIN_REFERENCE_DURATION <= duration <= MINIMAX_H3_MAX_REFERENCE_DURATION
):
raise OmniClientError(f"reference audio {index} duration must be in [2, 15] seconds, got {duration:.3f}")
total_duration += duration
if total_duration > MINIMAX_H3_MAX_REFERENCE_TOTAL_DURATION:
raise OmniClientError("reference audio must be at most 15 seconds in total")
def validate_reference_audio_waveforms(values: list[tuple[torch.Tensor, int]]) -> None:
"""Validate in-memory standalone audio references using sample counts."""
total_duration = 0.0
for index, (waveform, sample_rate) in enumerate(values):
if int(sample_rate) <= 0:
raise OmniClientError(f"reference audio {index} has an invalid sample rate")
samples = int(waveform.shape[-1])
duration = samples / int(sample_rate)
if not MINIMAX_H3_MIN_REFERENCE_DURATION <= duration <= MINIMAX_H3_MAX_REFERENCE_DURATION:
raise OmniClientError(f"reference audio {index} duration must be in [2, 15] seconds, got {duration:.3f}")
total_duration += duration
if total_duration > MINIMAX_H3_MAX_REFERENCE_TOTAL_DURATION:
raise OmniClientError("reference audio must be at most 15 seconds in total")
def _reference_video_shape(width: int, height: int) -> tuple[int, int]:
if (
min(width, height) < MINIMAX_H3_MIN_REFERENCE_DIMENSION
or max(width, height) > MINIMAX_H3_MAX_REFERENCE_DIMENSION
):
raise OmniClientError(f"reference video dimensions must be in [256, 5760] pixels, got {width}x{height}")
ratio = float(width) / float(height)
if not 0.4 <= ratio <= 2.5:
raise OmniClientError(f"reference video aspect ratio must be in [0.4, 2.5], got {width}x{height}")
if ratio >= 1.0:
target_width = MINIMAX_H3_BASE_SHORT_EDGE * ratio
target_height = float(MINIMAX_H3_BASE_SHORT_EDGE)
else:
target_width = float(MINIMAX_H3_BASE_SHORT_EDGE)
target_height = MINIMAX_H3_BASE_SHORT_EDGE / ratio
area = target_width * target_height
if area > MINIMAX_H3_MAX_PIXELS:
scale = math.sqrt(MINIMAX_H3_MAX_PIXELS / area)
target_width *= scale
target_height *= scale
return (
_nearest_multiple(target_width, MINIMAX_H3_CANVAS_MULTIPLE),
_nearest_multiple(target_height, MINIMAX_H3_CANVAS_MULTIPLE),
)
def _transcode_reference_video(
source: str,
*,
target_width: int,
target_height: int,
target_frame_count: int,
workdir: str,
start_time_seconds: float = 0.0,
duration_seconds: float | None = None,
) -> str:
output = str(Path(workdir) / "prepared.mp4")
duration_args = ["-t", f"{float(duration_seconds):.6f}"] if duration_seconds is not None else []
subprocess.run(
[
"ffmpeg",
"-y",
"-loglevel",
"error",
"-ss",
f"{float(start_time_seconds):.6f}",
"-i",
source,
"-map",
"0:v:0",
"-an",
"-vf",
(f"fps={MINIMAX_H3_FPS:g},scale={target_width}:{target_height}:flags=lanczos,setsar=1"),
*duration_args,
"-frames:v",
str(int(target_frame_count)),
"-metadata:s:v:0",
"rotate=0",
# Keep the transformed RGB pixels lossless. The same prepared
# stream is decoded by Qwen3VL and the video VAE; a yuv420p
# intermediate would make the two consumers see different
# pixels from the model-card reference recipe.
"-c:v",
"libx264rgb",
"-crf",
"0",
"-preset",
"veryfast",
"-pix_fmt",
"rgb24",
output,
],
check=True,
)
return output
def prepare_reference_videos(
values: Any,
*,
target_frame_count: int,
workdir: str,
start_time_seconds: Any = None,
) -> list[dict[str, Any]]:
if isinstance(values, (str, os.PathLike)):
values = [values]
if not isinstance(values, (list, tuple)) or not values:
raise OmniClientError("MiniMax H3 Ref2VA video input must be a path or a non-empty list of paths")
if isinstance(start_time_seconds, (list, tuple)):
start_times = list(start_time_seconds)
else:
start_times = [start_time_seconds] * len(values)
if len(start_times) != len(values):
raise OmniClientError("start_time_seconds must contain one value per reference video")
prepared: list[dict[str, Any]] = []
total_duration = 0.0
for index, value in enumerate(values):
item_start = start_times[index]
if isinstance(value, dict):
item_start = value.get("start_time_seconds", item_start)
value = value.get("path", value.get("video_path", value.get("video_url")))
if not isinstance(value, (str, os.PathLike)):
raise OmniClientError(
f"MiniMax H3 Ref2VA video references require file paths, got item {index}: {type(value)!r}"
)
source = str(value)
meta = _probe_video(source)
_validate_reference_video_metadata(meta, index=index, source=source)
start = 0.0 if item_start is None else float(item_start)
if not math.isfinite(start) or start < 0 or start >= float(meta["duration"]):
raise OmniClientError(f"reference video {index} start_time_seconds is outside the source duration")
duration = float(meta["duration"]) - start
if duration < MINIMAX_H3_MIN_REFERENCE_DURATION:
raise OmniClientError(
f"reference video {index} must provide at least 2 seconds after start_time_seconds, got {duration:.3f}"
)
remaining_duration = MINIMAX_H3_MAX_REFERENCE_TOTAL_DURATION - total_duration
if duration > remaining_duration:
if duration - remaining_duration > MINIMAX_H3_REFERENCE_DURATION_EPSILON:
raise OmniClientError("reference videos must be at most 15 seconds in total")
duration = remaining_duration
if duration < MINIMAX_H3_MIN_REFERENCE_DURATION:
raise OmniClientError("reference videos must be at most 15 seconds in total")
total_duration += duration
width, height = _reference_video_shape(meta["width"], meta["height"])
item_workdir = Path(workdir) / f"video_{index}"
item_workdir.mkdir(parents=True)
prepared_path = _transcode_reference_video(
source,
target_width=width,
target_height=height,
target_frame_count=target_frame_count,
workdir=str(item_workdir),
start_time_seconds=start,
duration_seconds=duration,
)
prepared.append(
{
"original_path": source,
"prepared_path": prepared_path,
"input_has_audio": bool(meta.get("audio_codecs")),
"width": width,
"height": height,
"start_time_seconds": start,
"duration_seconds": duration,
# Reference video frames and their soundtrack are conditioned
# only for the generated temporal extent. Keep the source
# segment duration for metadata/validation, and expose the
# bounded duration separately for audio extraction.
"audio_duration_seconds": min(
duration,
float(target_frame_count) / MINIMAX_H3_FPS,
),
}
)
return prepared
def load_video_frames(path: str) -> np.ndarray:
try:
import decord
except ImportError:
meta = _probe_video(path)
return _decode_video_frames_ffmpeg(
path,
frame_count=int(meta["frame_count"]),
width=int(meta["width"]),
height=int(meta["height"]),
)
reader = decord.VideoReader(path)
if len(reader) <= 0:
raise OmniClientError(f"video has no frames: {path}")
frames = reader.get_batch(list(range(len(reader))))
return frames.asnumpy() if hasattr(frames, "asnumpy") else np.asarray(frames)
def _decode_video_frames_ffmpeg(
path: str,
*,
frame_count: int,
width: int,
height: int,
indices: list[int] | None = None,
) -> np.ndarray:
frame_count = int(frame_count)
width = int(width)
height = int(height)
if frame_count <= 0:
raise OmniClientError(f"video has no frames: {path}")
if width <= 0 or height <= 0:
raise OmniClientError(f"video has invalid dimensions {width}x{height}: {path}")
if indices is not None and (not indices or any(index < 0 or index >= frame_count for index in indices)):
raise OmniClientError(f"invalid frame indices for {path}: {indices}")
output_frame_count = frame_count if indices is None else len(indices)
command = [
"ffmpeg",
"-loglevel",
"error",
"-threads",
"0",
"-i",
path,
"-map",
"0:v:0",
"-an",
]
if indices is not None:
select = "+".join(f"eq(n\\,{index})" for index in indices)
command.extend(["-vf", f"select={select}"])
command.extend(
[
"-vsync",
"0",
"-frames:v",
str(output_frame_count),
"-f",
"rawvideo",
"-pix_fmt",
"rgb24",
"pipe:1",
]
)
result = subprocess.run(
command,
check=True,
capture_output=True,
)
frame_size = width * height * 3
expected_size = output_frame_count * frame_size
if len(result.stdout) != expected_size:
raise OmniClientError(f"decoded {len(result.stdout)} bytes from {path}, expected {expected_size}")
return np.frombuffer(result.stdout, dtype=np.uint8).reshape(
output_frame_count,
height,
width,
3,
)
def sample_reference_video_frames(prepared_path: str) -> dict[str, Any]:
meta = _probe_video(prepared_path)
ratio = MINIMAX_H3_FPS / MINIMAX_H3_QWEN_VIDEO_SAMPLE_FPS
indices: list[int] = []
cursor = 0.0
while True:
frame_index = int(round(cursor))
if frame_index >= meta["frame_count"]:
break
if not indices or frame_index > indices[-1]:
indices.append(frame_index)
cursor += ratio
if not indices:
raise OmniClientError(f"no frames sampled from {prepared_path}")
# The preparation step emits a lossless RGB stream. Decode only the sampled
# frames in one ffmpeg process so Qwen3VL sees the exact prepared pixels
# without decoding the entire high-bitrate stream into host memory.
decoded_frames = _decode_video_frames_ffmpeg(
prepared_path,
frame_count=int(meta["frame_count"]),
indices=indices,
width=meta["width"],
height=meta["height"],
)
frames = [np.asarray(frame) for frame in decoded_frames]
timestamps = [index / MINIMAX_H3_QWEN_VIDEO_SAMPLE_FPS for index in range(len(indices))]
timestamps += [timestamps[-1]] * ((-len(timestamps)) % MINIMAX_H3_QWEN_TEMPORAL_PATCH)
block_timestamps = [
(timestamps[index] + timestamps[index + MINIMAX_H3_QWEN_TEMPORAL_PATCH - 1]) / 2
for index in range(
0,
len(timestamps),
MINIMAX_H3_QWEN_TEMPORAL_PATCH,
)
]
return {
"frames": frames,
"block_timestamps": block_timestamps,
}
def _soundfile_to_waveform(path: str) -> tuple[torch.Tensor, int]:
import soundfile as sf
data, sample_rate = sf.read(path, dtype="float32", always_2d=True)
# soundfile is (samples, channels); torchaudio.load is (channels, samples).
waveform = torch.from_numpy(data).t().contiguous()
return waveform, int(sample_rate)
def load_audio_file(path: str) -> tuple[torch.Tensor, int]:
"""Load an audio file as ``(waveform[C, T] float32, sample_rate)``.
torchaudio 2.6+ routes ``load`` through TorchCodec, whose wheels do not load
on aarch64 with a CPU-only torch (they link CUDA libraries that are absent).
Fall back to soundfile; if the container is not libsndfile-readable (e.g.
mp3/m4a/mp4), demux to wav with ffmpeg first so any ffmpeg-supported input
works at its native sample rate.
"""
try:
import torchaudio
return torchaudio.load(path)
except (ImportError, RuntimeError, OSError):
pass
try:
return _soundfile_to_waveform(path)
except Exception:
import tempfile
with tempfile.TemporaryDirectory(prefix="minimax_h3_audio_") as tmpdir:
wav = str(Path(tmpdir) / "audio.wav")
subprocess.run(
[
"ffmpeg",
"-y",
"-loglevel",
"error",
"-i",
path,
"-vn",
"-f",
"wav",
wav,
],
check=True,
)
return _soundfile_to_waveform(wav)
def load_video_audio(
path: str,
*,
start_time_seconds: float = 0.0,
duration_seconds: float | None = None,
) -> tuple[torch.Tensor, int]:
import tempfile
with tempfile.TemporaryDirectory(prefix="minimax_h3_video_audio_") as tmpdir:
output = str(Path(tmpdir) / "audio.wav")
command = [
"ffmpeg",
"-y",
"-loglevel",
"error",
"-ss",
f"{float(start_time_seconds):.6f}",
"-i",
path,
"-vn",
"-ac",
"2",
"-ar",
"44100",
"-f",
"wav",
]
if duration_seconds is not None:
command.extend(["-t", f"{float(duration_seconds):.6f}"])
command.append(output)
subprocess.run(command, check=True)
return load_audio_file(output)
__all__ = [
"load_audio_file",
"load_video_audio",
"load_video_frames",
"prepare_reference_videos",
"sample_reference_video_frames",
"validate_reference_audio_files",
"validate_reference_audio_waveforms",
]