[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:
61 files changed
+2952
-366
No files matched your search
@@ -0,0 +1 @@
|
||||
"""MiniMax H3 model components."""
|
||||
@@ -0,0 +1,62 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""MiniMax H3 checkpoint resolution for the AR text-encoder stage."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import (
|
||||
download_weights_from_hf_specific,
|
||||
)
|
||||
|
||||
MINIMAX_H3_TEXT_ENCODER_DOWNLOAD_PATTERNS = {
|
||||
"fl2va": ["FL2VA/text_encoder/**"],
|
||||
"ref2va": ["Ref2VA/text_encoder/**"],
|
||||
}
|
||||
|
||||
|
||||
def resolve_minimax_h3_partition(
|
||||
model: str,
|
||||
task_type: str | None,
|
||||
*,
|
||||
auto_partition: str,
|
||||
) -> str:
|
||||
task = str(task_type or "auto").lower()
|
||||
if task not in {"auto", "combined", "t2va", "fl2va", "ref2va"}:
|
||||
raise ValueError(
|
||||
f"MiniMax-H3 task_type must be one of auto, combined, t2va, fl2va, or ref2va; got {task_type!r}"
|
||||
)
|
||||
path = Path(model)
|
||||
if task == "auto" and path.is_dir() and path.name in {"FL2VA", "Ref2VA"}:
|
||||
return path.name.lower()
|
||||
if task in {"auto", "combined"}:
|
||||
return auto_partition
|
||||
return "ref2va" if task == "ref2va" else "fl2va"
|
||||
|
||||
|
||||
def resolve_minimax_h3_model_root(
|
||||
model: str,
|
||||
revision: str | None,
|
||||
task_type: str | None,
|
||||
) -> str:
|
||||
path = Path(model)
|
||||
partition = resolve_minimax_h3_partition(model, task_type, auto_partition="fl2va")
|
||||
|
||||
if path.is_dir():
|
||||
if path.name == "text_encoder" and (path / "config.json").is_file():
|
||||
return str(path)
|
||||
if path.name in {"FL2VA", "Ref2VA"}:
|
||||
path = path.parent
|
||||
subdir = "Ref2VA" if partition == "ref2va" else "FL2VA"
|
||||
return str(path / subdir / "text_encoder")
|
||||
snapshot = download_weights_from_hf_specific(
|
||||
model_name_or_path=model,
|
||||
cache_dir=None,
|
||||
allow_patterns=MINIMAX_H3_TEXT_ENCODER_DOWNLOAD_PATTERNS[partition],
|
||||
revision=revision,
|
||||
require_all=True,
|
||||
)
|
||||
|
||||
subdir = "Ref2VA" if partition == "ref2va" else "FL2VA"
|
||||
return str(Path(snapshot) / subdir / "text_encoder")
|
||||
|
||||
|
||||
__all__ = ["resolve_minimax_h3_model_root", "resolve_minimax_h3_partition"]
|
||||
@@ -0,0 +1,51 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""MiniMax H3 text-conditioning contract."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
MINIMAX_H3_TEXT_HIDDEN_SIZE = 5120
|
||||
MINIMAX_H3_PRESENTATION_TASK_KEY = "_minimax_h3_presentation_task"
|
||||
MINIMAX_H3_CONDITION_LABELS_KEY = "_minimax_h3_condition_labels"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MiniMaxH3TextConditioning:
|
||||
"""Layer-50 Qwen3-VL hidden states and their H3 token roles."""
|
||||
|
||||
hidden_states: torch.Tensor
|
||||
token_tags: torch.Tensor
|
||||
|
||||
@classmethod
|
||||
def from_payload(
|
||||
cls,
|
||||
payload: Mapping[str, Any],
|
||||
) -> MiniMaxH3TextConditioning:
|
||||
hidden_states = payload.get("hidden_states")
|
||||
token_tags = payload.get("token_tags")
|
||||
if not isinstance(hidden_states, torch.Tensor) or not isinstance(token_tags, torch.Tensor):
|
||||
raise ValueError("MiniMax H3 conditioning requires hidden_states and token_tags tensors")
|
||||
if hidden_states.ndim != 2 or hidden_states.shape[-1] != MINIMAX_H3_TEXT_HIDDEN_SIZE:
|
||||
raise ValueError(
|
||||
"MiniMax H3 hidden_states must have shape "
|
||||
f"[tokens, {MINIMAX_H3_TEXT_HIDDEN_SIZE}], got {tuple(hidden_states.shape)}"
|
||||
)
|
||||
if token_tags.ndim != 1 or token_tags.shape[0] != hidden_states.shape[0]:
|
||||
raise ValueError(
|
||||
"MiniMax H3 token_tags must align with hidden_states, got "
|
||||
f"token_tags={tuple(token_tags.shape)} and hidden_states={tuple(hidden_states.shape)}"
|
||||
)
|
||||
if not torch.all((token_tags == 0) | (token_tags == 1)):
|
||||
raise ValueError("MiniMax H3 text-encoder token_tags must contain only 0 and 1")
|
||||
return cls(hidden_states=hidden_states, token_tags=token_tags)
|
||||
|
||||
def to_payload(self) -> dict[str, torch.Tensor]:
|
||||
return {
|
||||
"hidden_states": self.hidden_states,
|
||||
"token_tags": self.token_tags,
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Two-stage MiniMax H3 topology."""
|
||||
|
||||
from vllm_omni.config.stage_config import (
|
||||
PipelineConfig,
|
||||
StageExecutionType,
|
||||
StagePipelineConfig,
|
||||
)
|
||||
|
||||
_PROCESSOR = "vllm_omni.model_executor.stage_input_processors.minimax_h3"
|
||||
_CHECKPOINT = "vllm_omni.model_executor.models.minimax_h3.checkpoint"
|
||||
_DIFFUSION_PIPELINE = "vllm_omni.diffusion.models.minimax_h3.pipeline_minimax_h3"
|
||||
|
||||
MINIMAX_H3_PIPELINE = PipelineConfig(
|
||||
model_type="minimax_h3_disaggregated",
|
||||
default_deploy_config_name="minimax_h3_disaggregated.yaml",
|
||||
stage_cli_aliases={"text_encoder_tp_size": (0, "tensor_parallel_size")},
|
||||
model_arch="MiniMaxH3TextEncoder",
|
||||
stages=(
|
||||
StagePipelineConfig(
|
||||
stage_id=0,
|
||||
model_stage="text_encoder",
|
||||
execution_type=StageExecutionType.LLM_AR,
|
||||
input_sources=(),
|
||||
owns_tokenizer=True,
|
||||
requires_multimodal_data=True,
|
||||
model_arch="MiniMaxH3TextEncoder",
|
||||
engine_output_type="latent",
|
||||
prompt_transform_func=f"{_PROCESSOR}.prepare_text_encoder_prompt",
|
||||
sampling_constraints={
|
||||
"max_tokens": 1,
|
||||
"temperature": 0.0,
|
||||
"detokenize": False,
|
||||
},
|
||||
model_path_resolver=f"{_CHECKPOINT}.resolve_minimax_h3_model_root",
|
||||
),
|
||||
StagePipelineConfig(
|
||||
stage_id=1,
|
||||
model_stage="dit",
|
||||
execution_type=StageExecutionType.DIFFUSION,
|
||||
input_sources=(0,),
|
||||
final_output=True,
|
||||
final_output_type="video",
|
||||
requires_multimodal_data=True,
|
||||
model_arch="MiniMaxH3Pipeline",
|
||||
custom_process_input_func=f"{_PROCESSOR}.text_encoder2diffusion",
|
||||
omni_kv_config={"need_recv_cache": False},
|
||||
model_path_resolver=f"{_DIFFUSION_PIPELINE}.resolve_minimax_h3_diffusion_model_path",
|
||||
inline_diffusion=True,
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,493 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Shared MiniMax H3 media normalization and 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
|
||||
|
||||
import math
|
||||
import os
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
|
||||
from vllm_omni.errors import OmniClientError
|
||||
|
||||
VISION_START = "<|vision_start|>"
|
||||
VISION_END = "<|vision_end|>"
|
||||
IMAGE_PAD = "<|image_pad|>"
|
||||
VIDEO_PAD = "<|video_pad|>"
|
||||
|
||||
_TEXT_TAG = 1
|
||||
_VIDEO_TAG = 0
|
||||
|
||||
MINIMAX_H3_OUTPUT_SHORT_EDGE = 768
|
||||
MINIMAX_H3_OUTPUT_MAX_PIXELS = 768 * 1344
|
||||
MINIMAX_H3_REFERENCE_IMAGE_SHORT_EDGE = 2048
|
||||
MINIMAX_H3_REFERENCE_IMAGE_MULTIPLE = 32
|
||||
MINIMAX_H3_SUPPORTED_ASPECT_RATIOS = {
|
||||
"21:9": 21.0 / 9.0,
|
||||
"16:9": 16.0 / 9.0,
|
||||
"4:3": 4.0 / 3.0,
|
||||
"1:1": 1.0,
|
||||
"3:4": 3.0 / 4.0,
|
||||
"9:16": 9.0 / 16.0,
|
||||
}
|
||||
MINIMAX_H3_MAX_REFERENCE_IMAGE_BYTES = 30 * 1024 * 1024
|
||||
MINIMAX_H3_REFERENCE_IMAGE_FORMATS = frozenset({"jpeg", "png", "webp", "heic", "heif"})
|
||||
|
||||
|
||||
def _align_multiple(value: float, multiple: int = 32) -> int:
|
||||
return max(multiple, int(round(float(value) / multiple)) * multiple)
|
||||
|
||||
|
||||
def load_minimax_h3_images(value: Any) -> list[Image.Image]:
|
||||
"""Normalize one or more H3 image inputs to RGB PIL images."""
|
||||
if isinstance(value, (list, tuple)):
|
||||
if not value:
|
||||
raise OmniClientError("MiniMax H3 image input must not be empty")
|
||||
images: list[Image.Image] = []
|
||||
for item in value:
|
||||
loaded = load_minimax_h3_images(item)
|
||||
if len(loaded) != 1:
|
||||
raise OmniClientError(f"MiniMax H3 expected one image, got {len(loaded)}")
|
||||
images.extend(loaded)
|
||||
return images
|
||||
if isinstance(value, (str, os.PathLike)):
|
||||
if os.path.getsize(value) > 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 resolve_minimax_h3_aspect_ratio(
|
||||
task: str,
|
||||
value: Any,
|
||||
image: Image.Image | None,
|
||||
) -> float:
|
||||
"""Resolve H3's task-specific output aspect-ratio policy."""
|
||||
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_reference_image_shape(image: Image.Image) -> tuple[int, int]:
|
||||
"""Resize an H3 reference image to the official 2048-short-edge canvas."""
|
||||
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_minimax_h3_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)
|
||||
|
||||
|
||||
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(
|
||||
tokenizer: Any,
|
||||
*,
|
||||
prompt: str,
|
||||
image_token_counts: list[int],
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Return aligned FL2VA presentation token IDs and role IDs."""
|
||||
return _multi_image_presentation(
|
||||
tokenizer,
|
||||
prompt=prompt,
|
||||
image_token_counts=image_token_counts,
|
||||
)
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
def build_minimax_h3_presentation(
|
||||
tokenizer: Any,
|
||||
*,
|
||||
prompt: str,
|
||||
task: str,
|
||||
condition_labels: list[tuple[str, int]],
|
||||
image_grid_thw: torch.Tensor | None,
|
||||
video_grid_thw: torch.Tensor | None,
|
||||
video_timestamps: Sequence[Sequence[float]] | None,
|
||||
merge_size: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Build the token IDs and role IDs shared by fused and split H3."""
|
||||
if task == "t2va":
|
||||
ids = minimax_h3_text_only_ids(tokenizer, prompt)
|
||||
return ids, torch.ones_like(ids)
|
||||
|
||||
merge_length = int(merge_size) ** 2
|
||||
image_counts = (
|
||||
[int(grid.prod().item()) // merge_length for grid in image_grid_thw] if image_grid_thw is not None else []
|
||||
)
|
||||
if task == "fl2va":
|
||||
return minimax_h3_multi_image_presentation(
|
||||
tokenizer,
|
||||
prompt=prompt,
|
||||
image_token_counts=image_counts,
|
||||
)
|
||||
|
||||
video_counts: list[list[int]] = []
|
||||
if video_grid_thw is not None:
|
||||
for grid in video_grid_thw:
|
||||
block_count = int(grid[0].item())
|
||||
tokens_per_block = int(grid[1:].prod().item()) // merge_length
|
||||
video_counts.append([tokens_per_block] * block_count)
|
||||
timestamps = (
|
||||
[[float(value) for value in group] for group in video_timestamps] if video_timestamps is not None else []
|
||||
)
|
||||
if video_counts:
|
||||
return minimax_h3_ref2va_video_presentation(
|
||||
tokenizer,
|
||||
prompt=prompt,
|
||||
condition_labels=condition_labels,
|
||||
image_token_count=image_counts or None,
|
||||
video_block_token_counts=video_counts,
|
||||
video_block_timestamps=timestamps,
|
||||
)
|
||||
return minimax_h3_ref2va_presentation(
|
||||
tokenizer,
|
||||
prompt=prompt,
|
||||
condition_labels=condition_labels,
|
||||
image_token_count=image_counts or None,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"IMAGE_PAD",
|
||||
"MINIMAX_H3_OUTPUT_SHORT_EDGE",
|
||||
"VIDEO_PAD",
|
||||
"VISION_END",
|
||||
"VISION_START",
|
||||
"build_minimax_h3_presentation",
|
||||
"load_minimax_h3_images",
|
||||
"minimax_h3_multi_image_presentation",
|
||||
"minimax_h3_ref2va_presentation",
|
||||
"minimax_h3_ref2va_video_presentation",
|
||||
"minimax_h3_text_only_ids",
|
||||
"resolve_minimax_h3_aspect_ratio",
|
||||
"resolve_minimax_h3_output_canvas",
|
||||
"resolve_minimax_h3_reference_image_shape",
|
||||
]
|
||||
@@ -0,0 +1,668 @@
|
||||
# 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_PREPARED_REFERENCE_VIDEOS_KEY = "minimax_h3_prepared_reference_videos"
|
||||
|
||||
|
||||
def serialize_prepared_reference_videos(items: list[dict[str, Any]], artifact_dir: str) -> str:
|
||||
fields = (
|
||||
"original_path",
|
||||
"prepared_path",
|
||||
"input_has_audio",
|
||||
"width",
|
||||
"height",
|
||||
"start_time_seconds",
|
||||
"duration_seconds",
|
||||
"audio_duration_seconds",
|
||||
)
|
||||
return json.dumps(
|
||||
{
|
||||
"artifact_dir": artifact_dir,
|
||||
"videos": [{field: item[field] for field in fields} for item in items],
|
||||
},
|
||||
separators=(",", ":"),
|
||||
)
|
||||
|
||||
|
||||
def deserialize_prepared_reference_videos(value: str) -> tuple[str, list[dict[str, Any]]]:
|
||||
try:
|
||||
payload = json.loads(value)
|
||||
artifact_dir = payload["artifact_dir"]
|
||||
videos = payload["videos"]
|
||||
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
|
||||
raise ValueError("invalid MiniMax H3 prepared-reference-video descriptor") from exc
|
||||
if not isinstance(artifact_dir, str) or not isinstance(videos, list):
|
||||
raise ValueError("invalid MiniMax H3 prepared-reference-video descriptor")
|
||||
required = {
|
||||
"original_path",
|
||||
"prepared_path",
|
||||
"input_has_audio",
|
||||
"width",
|
||||
"height",
|
||||
"start_time_seconds",
|
||||
"duration_seconds",
|
||||
"audio_duration_seconds",
|
||||
}
|
||||
if any(not isinstance(item, dict) or set(item) != required for item in videos):
|
||||
raise ValueError("invalid MiniMax H3 prepared-reference-video descriptor")
|
||||
return artifact_dir, videos
|
||||
|
||||
|
||||
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 []
|
||||
frame_count_args = ["-frames:v", str(int(target_frame_count))] if target_frame_count > 0 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,
|
||||
*frame_count_args,
|
||||
"-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 if target_frame_count > 0 else duration,
|
||||
),
|
||||
}
|
||||
)
|
||||
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",
|
||||
]
|
||||
@@ -0,0 +1,311 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""MiniMax H3 text encoder on the vLLM Qwen3-VL model runner."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from typing import Any
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.models.qwen3_vl import (
|
||||
Qwen3VLDummyInputsBuilder,
|
||||
Qwen3VLForConditionalGeneration,
|
||||
Qwen3VLMultiModalProcessor,
|
||||
Qwen3VLProcessingInfo,
|
||||
)
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
|
||||
from vllm_omni.model_executor.models.minimax_h3.conditioning import (
|
||||
MINIMAX_H3_CONDITION_LABELS_KEY,
|
||||
MINIMAX_H3_PRESENTATION_TASK_KEY,
|
||||
)
|
||||
from vllm_omni.model_executor.models.minimax_h3.preprocessing import (
|
||||
IMAGE_PAD,
|
||||
VIDEO_PAD,
|
||||
VISION_END,
|
||||
VISION_START,
|
||||
build_minimax_h3_presentation,
|
||||
)
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
|
||||
|
||||
def _build_minimax_h3_presentation(
|
||||
tokenizer: Any,
|
||||
*,
|
||||
prompt: str,
|
||||
task: str,
|
||||
condition_labels: list[tuple[str, int]],
|
||||
image_grid_thw: torch.Tensor | None,
|
||||
video_grid_thw: torch.Tensor | None,
|
||||
video_timestamps: Sequence[Sequence[float]] | None,
|
||||
merge_size: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Build the same token stream consumed by the fused H3 encoder."""
|
||||
return build_minimax_h3_presentation(
|
||||
tokenizer,
|
||||
prompt=prompt,
|
||||
task=task,
|
||||
condition_labels=condition_labels,
|
||||
image_grid_thw=image_grid_thw,
|
||||
video_grid_thw=video_grid_thw,
|
||||
video_timestamps=video_timestamps,
|
||||
merge_size=merge_size,
|
||||
)
|
||||
|
||||
|
||||
class MiniMaxH3MultiModalProcessor(Qwen3VLMultiModalProcessor):
|
||||
"""Qwen3-VL media processing with H3's exact segmented presentation."""
|
||||
|
||||
@staticmethod
|
||||
def _base_processor_kwargs(
|
||||
kwargs: Mapping[str, object],
|
||||
) -> dict[str, object]:
|
||||
return {
|
||||
key: value
|
||||
for key, value in kwargs.items()
|
||||
if key
|
||||
not in {
|
||||
MINIMAX_H3_PRESENTATION_TASK_KEY,
|
||||
MINIMAX_H3_CONDITION_LABELS_KEY,
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _condition_labels(value: object) -> list[tuple[str, int]]:
|
||||
if not isinstance(value, Sequence) or isinstance(value, (str, bytes)):
|
||||
return []
|
||||
labels: list[tuple[str, int]] = []
|
||||
for item in value:
|
||||
if not isinstance(item, Sequence) or isinstance(item, (str, bytes)) or len(item) != 2:
|
||||
raise ValueError("MiniMax H3 condition labels must be (type, index) pairs")
|
||||
labels.append((str(item[0]), int(item[1])))
|
||||
return labels
|
||||
|
||||
def _cached_apply_hf_processor(self, inputs: Any, timing_ctx: Any):
|
||||
# H3 presentation IDs depend on the processed grids for every media
|
||||
# item. On a sender-cache hit, the generic processor passes only cache
|
||||
# misses to _apply_hf_processor_main, so the full presentation cannot
|
||||
# be reconstructed there. Reprocess H3 media to preserve exact IDs.
|
||||
return self._apply_hf_processor(inputs, timing_ctx)
|
||||
|
||||
def _apply_hf_processor_main(
|
||||
self,
|
||||
prompt: str | list[int],
|
||||
mm_items: Any,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
tokenization_kwargs: Mapping[str, object],
|
||||
*,
|
||||
enable_hf_prompt_update: bool,
|
||||
):
|
||||
task_value = hf_processor_mm_kwargs.get(MINIMAX_H3_PRESENTATION_TASK_KEY)
|
||||
if task_value is None:
|
||||
return super()._apply_hf_processor_main(
|
||||
prompt,
|
||||
mm_items,
|
||||
hf_processor_mm_kwargs,
|
||||
tokenization_kwargs,
|
||||
enable_hf_prompt_update=enable_hf_prompt_update,
|
||||
)
|
||||
if not isinstance(prompt, str):
|
||||
raise ValueError("MiniMax H3 presentation requires the original prompt text")
|
||||
|
||||
task = str(task_value)
|
||||
condition_labels = self._condition_labels(hf_processor_mm_kwargs.get(MINIMAX_H3_CONDITION_LABELS_KEY))
|
||||
base_kwargs = self._base_processor_kwargs(hf_processor_mm_kwargs)
|
||||
image_count = sum(kind == "image" for kind, _ in condition_labels)
|
||||
video_count = sum(kind == "video" for kind, _ in condition_labels)
|
||||
image_slot = f"{VISION_START}{IMAGE_PAD}{VISION_END}"
|
||||
hf_processor = self.info.get_hf_processor(**base_kwargs)
|
||||
video_slot = (
|
||||
VIDEO_PAD if self._expands_only_video_token(hf_processor) else f"{VISION_START}{VIDEO_PAD}{VISION_END}"
|
||||
)
|
||||
processing_prompt = image_slot * image_count + video_slot * video_count
|
||||
if not processing_prompt:
|
||||
processing_prompt = prompt
|
||||
|
||||
_, processed_data, _ = super()._apply_hf_processor_main(
|
||||
processing_prompt,
|
||||
mm_items,
|
||||
base_kwargs,
|
||||
tokenization_kwargs,
|
||||
enable_hf_prompt_update=enable_hf_prompt_update,
|
||||
)
|
||||
image_processor = self.info.get_image_processor(**base_kwargs)
|
||||
ids, _ = _build_minimax_h3_presentation(
|
||||
self.info.get_tokenizer(),
|
||||
prompt=prompt,
|
||||
task=task,
|
||||
condition_labels=condition_labels,
|
||||
image_grid_thw=processed_data.get("image_grid_thw"),
|
||||
video_grid_thw=processed_data.get("video_grid_thw"),
|
||||
video_timestamps=processed_data.get("timestamps"),
|
||||
merge_size=int(image_processor.merge_size),
|
||||
)
|
||||
return ids.tolist(), processed_data, True
|
||||
|
||||
def _get_prompt_updates(
|
||||
self,
|
||||
mm_items: Any,
|
||||
hf_processor_mm_kwargs: Mapping[str, Any],
|
||||
out_mm_kwargs: Any,
|
||||
):
|
||||
return super()._get_prompt_updates(
|
||||
mm_items,
|
||||
self._base_processor_kwargs(hf_processor_mm_kwargs),
|
||||
out_mm_kwargs,
|
||||
)
|
||||
|
||||
|
||||
class _ResidualMerge(nn.Module):
|
||||
"""Return the decoder residual stream without the final RMSNorm."""
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
residual: torch.Tensor | None,
|
||||
) -> tuple[torch.Tensor, None]:
|
||||
if residual is not None:
|
||||
hidden_states = hidden_states + residual
|
||||
return hidden_states, None
|
||||
|
||||
|
||||
@MULTIMODAL_REGISTRY.register_processor(
|
||||
MiniMaxH3MultiModalProcessor,
|
||||
info=Qwen3VLProcessingInfo,
|
||||
dummy_inputs=Qwen3VLDummyInputsBuilder,
|
||||
)
|
||||
class MiniMaxH3TextEncoder(Qwen3VLForConditionalGeneration):
|
||||
"""Qwen3-VL encoder used by MiniMax H3.
|
||||
|
||||
MiniMax H3 consumes the residual stream after decoder layer 50. The
|
||||
upstream vLLM Qwen3-VL implementation supplies the vision tower,
|
||||
multimodal processor, M-RoPE, DeepStack injection, paged attention, and
|
||||
tensor-parallel decoder layers. This class changes only the two parts of
|
||||
the contract that differ from causal generation: decoder depth and output
|
||||
normalization.
|
||||
"""
|
||||
|
||||
have_multimodal_outputs = True
|
||||
omni_pooler_payload_include_hidden = False
|
||||
requires_full_prefix_cached_hidden_states = False
|
||||
num_encoder_layers = 50
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "model"):
|
||||
if vllm_config.parallel_config.pipeline_parallel_size != 1:
|
||||
raise ValueError("MiniMax H3 text encoding supports tensor parallelism, not pipeline parallelism")
|
||||
|
||||
hf_config = copy.deepcopy(vllm_config.model_config.hf_config)
|
||||
hf_config.text_config.num_hidden_layers = self.num_encoder_layers
|
||||
# Reuse the token embedding as the unused LM head, avoiding a second
|
||||
# vocab-sized allocation in the upstream constructor. Set the flag
|
||||
# on both levels because VllmConfig.with_hf_config propagates the
|
||||
# multimodal parent value into its nested text config.
|
||||
hf_config.tie_word_embeddings = True
|
||||
hf_config.text_config.tie_word_embeddings = True
|
||||
encoder_config = vllm_config.with_hf_config(hf_config)
|
||||
super().__init__(vllm_config=encoder_config, prefix=prefix)
|
||||
|
||||
self.language_model.model.norm = _ResidualMerge()
|
||||
self._token_tags: torch.Tensor | None = None
|
||||
|
||||
def embed_input_ids(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
multimodal_embeddings=None,
|
||||
*,
|
||||
is_multimodal: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
# Qwen3-VL expands every visual block to exactly
|
||||
# vision_start + image/video tokens + vision_end. Classifying each
|
||||
# token directly makes tags independent of prefill chunk boundaries.
|
||||
visual_token = (
|
||||
(input_ids == self.config.vision_start_token_id)
|
||||
| (input_ids == self.config.vision_end_token_id)
|
||||
| (input_ids == self.config.image_token_id)
|
||||
| (input_ids == self.config.video_token_id)
|
||||
)
|
||||
token_tags = (~visual_token).long()
|
||||
self._token_tags = None
|
||||
embeddings = super().embed_input_ids(
|
||||
input_ids,
|
||||
multimodal_embeddings,
|
||||
is_multimodal=is_multimodal,
|
||||
)
|
||||
self._token_tags = token_tags
|
||||
return embeddings
|
||||
|
||||
def make_omni_output(
|
||||
self,
|
||||
model_outputs: torch.Tensor | OmniOutput,
|
||||
**_: object,
|
||||
) -> OmniOutput:
|
||||
if isinstance(model_outputs, OmniOutput):
|
||||
return model_outputs
|
||||
if self._token_tags is None:
|
||||
raise RuntimeError("token tags were not prepared before MiniMax H3 text encoding")
|
||||
token_tags = self._token_tags
|
||||
self._token_tags = None
|
||||
padding = model_outputs.shape[0] - token_tags.shape[0]
|
||||
if padding < 0:
|
||||
raise RuntimeError(
|
||||
"MiniMax H3 token tags exceed the model output length: "
|
||||
f"tags={token_tags.shape[0]}, outputs={model_outputs.shape[0]}"
|
||||
)
|
||||
if padding:
|
||||
# Multimodal embedding runs on scheduled tokens, while the AR
|
||||
# forward may use a CUDA-graph-padded token buffer. Match that
|
||||
# buffer so both conditioning tensors are recognized as
|
||||
# per-token prefix-cache entries; runner slicing removes these
|
||||
# padding rows before the stage payload is emitted.
|
||||
token_tags = torch.cat((token_tags, token_tags.new_ones(padding)))
|
||||
# Keep the stage-wire representation two-dimensional. The Omni
|
||||
# runner treats tensors with shape [tokens, features] as per-token
|
||||
# data, so they are concatenated across chunked-prefill steps and
|
||||
# reconstructed on prefix-cache hits. The Stage 1 adapter restores
|
||||
# H3's semantic [tokens] representation.
|
||||
token_tags = token_tags.unsqueeze(-1)
|
||||
return OmniOutput(
|
||||
text_hidden_states=model_outputs,
|
||||
multimodal_outputs={
|
||||
"hidden_states": {"output": model_outputs},
|
||||
"meta": {"token_role_ids": token_tags},
|
||||
},
|
||||
)
|
||||
|
||||
def compute_logits(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
**_: object,
|
||||
) -> torch.Tensor:
|
||||
"""Emit EOS immediately; the useful result is the prefill hidden state."""
|
||||
logits = hidden_states.new_full(
|
||||
(hidden_states.shape[0], self.config.text_config.vocab_size),
|
||||
torch.finfo(hidden_states.dtype).min,
|
||||
)
|
||||
logits[:, int(self._tokenizer.eos_token_id)] = 0
|
||||
return logits
|
||||
|
||||
def load_weights(
|
||||
self,
|
||||
weights: Iterable[tuple[str, torch.Tensor]],
|
||||
) -> set[str]:
|
||||
def encoder_weights():
|
||||
for name, weight in weights:
|
||||
layer_match = re.match(r"model\.language_model\.layers\.(\d+)\.", name)
|
||||
if layer_match and int(layer_match.group(1)) >= self.num_encoder_layers:
|
||||
continue
|
||||
if name == "model.language_model.norm.weight" or name.startswith("lm_head."):
|
||||
continue
|
||||
yield name, weight
|
||||
|
||||
loader = AutoWeightsLoader(self)
|
||||
return loader.load_weights(
|
||||
encoder_weights(),
|
||||
mapper=self.hf_to_vllm_mapper,
|
||||
)
|
||||
@@ -457,6 +457,11 @@ _OMNI_MODELS = {
|
||||
"qwen3_vl",
|
||||
"AuraQwen3VLForConditionalGeneration",
|
||||
),
|
||||
"MiniMaxH3TextEncoder": (
|
||||
"minimax_h3",
|
||||
"text_encoder",
|
||||
"MiniMaxH3TextEncoder",
|
||||
),
|
||||
## MiniMax-Music3 (text-to-music; AR talker -> flow-matching acoustic decoder)
|
||||
"MiniMaxMusic3TalkerForConditionalGeneration": (
|
||||
"minimax_music3",
|
||||
|
||||
Reference in new issue
Block a user