[2/N] Add a minimal temporal chunk callback for MiniMax-H3 (#7017)
Signed-off-by: specture724 <specture724@gmail.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ffa991b24f
commit
ecdd762ff5
6 files changed
+641
-27
No files matched your search
@@ -58,8 +58,16 @@ class SupportsChunkedVAEDecode(Protocol):
|
||||
Implementations must drain decoding before surfacing callback errors. In a
|
||||
distributed VAE, every rank invokes the method so collectives stay in
|
||||
lockstep, while ``on_chunk`` is called only on the rank that owns output.
|
||||
|
||||
``chunk_value_range`` is the closed interval the delivered floats occupy,
|
||||
which differs per checkpoint: a Wan VAE emits ``(-1.0, 1.0)`` while a
|
||||
MiniMax-H3 VAE reverts through its processor to ``(0.0, 1.0)``. A consumer
|
||||
cannot quantize chunks to pixels without it, so it is part of the
|
||||
capability rather than knowledge each consumer hard-codes per model.
|
||||
"""
|
||||
|
||||
chunk_value_range: ClassVar[tuple[float, float]]
|
||||
|
||||
def decode_with_chunks(
|
||||
self,
|
||||
z: torch.Tensor,
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Frames-only callback coordination for MiniMax-H3 VAE decoding."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
|
||||
from .temporal_chunks import decode_temporal_chunks
|
||||
|
||||
MiniMaxH3VideoChunkCallback = Callable[[torch.Tensor], None]
|
||||
|
||||
|
||||
def decode_h3_chunks(
|
||||
host,
|
||||
latent: torch.Tensor,
|
||||
callback: MiniMaxH3VideoChunkCallback | None,
|
||||
*,
|
||||
group: dist.ProcessGroup | None,
|
||||
) -> torch.Tensor:
|
||||
"""Run the local temporal loop, synchronizing callback errors across ranks."""
|
||||
streaming = callback is not None
|
||||
owner = streaming
|
||||
if group is not None:
|
||||
rank = dist.get_rank(group)
|
||||
world_size = dist.get_world_size(group)
|
||||
# Ownership is positional: every rank supplies the callback and rank 0
|
||||
# publishes. Reduce only whether the ranks agree that this decode
|
||||
# streams, so the verdict is identical everywhere -- a rank-local
|
||||
# verdict would let a peer fall through and enter the decoder
|
||||
# collectives alone, hanging the stage instead of failing it.
|
||||
census = torch.tensor([int(streaming)], dtype=torch.int64, device=latent.device)
|
||||
dist.all_reduce(census, group=group)
|
||||
supplied = int(census.item())
|
||||
if supplied not in (0, world_size):
|
||||
raise ValueError(
|
||||
"MiniMax-H3 chunk callback must be supplied on every rank of the VAE "
|
||||
f"group or on none of them; got {supplied} of {world_size}"
|
||||
)
|
||||
# No rank supplied a callback: every rank runs a plain full decode.
|
||||
streaming = supplied == world_size
|
||||
owner = streaming and rank == 0
|
||||
|
||||
error: BaseException | None = None
|
||||
|
||||
def publish(raw: torch.Tensor) -> None:
|
||||
nonlocal error
|
||||
if not owner or error is not None:
|
||||
return
|
||||
try:
|
||||
processor = getattr(host.model, "processor", None)
|
||||
decoded = raw if processor is None else processor.revert_tensor(raw)
|
||||
frames = host._normalize_decoded_frames(decoded).contiguous()
|
||||
assert callback is not None
|
||||
callback(frames)
|
||||
except BaseException as exc: # noqa: BLE001
|
||||
error = exc
|
||||
|
||||
# Peer ranks run the temporal loop without materializing a second video.
|
||||
sink = publish if owner else ((lambda _frames: None) if streaming else None)
|
||||
result = decode_temporal_chunks(
|
||||
host.model,
|
||||
host._denormalize_latent(latent),
|
||||
sink,
|
||||
)
|
||||
|
||||
if group is not None:
|
||||
failed = torch.tensor([int(rank == 0 and error is not None)], dtype=torch.int32, device=latent.device)
|
||||
dist.broadcast(failed, src=dist.get_global_rank(group, 0), group=group)
|
||||
if int(failed.item()):
|
||||
if rank == 0:
|
||||
assert error is not None
|
||||
raise error
|
||||
raise RuntimeError("MiniMax-H3 video chunk callback failed on rank zero")
|
||||
elif error is not None:
|
||||
raise error
|
||||
|
||||
if not result.numel():
|
||||
return result
|
||||
processor = getattr(host.model, "processor", None)
|
||||
decoded = result if processor is None else processor.revert_tensor(result)
|
||||
return host._normalize_decoded_frames(decoded)
|
||||
@@ -0,0 +1,122 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Small compatibility loop for the released MiniMax-H3 temporal decoder."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
def decode_temporal_chunks(
|
||||
model: nn.Module,
|
||||
latent: torch.Tensor,
|
||||
callback: Callable[[torch.Tensor], None] | None,
|
||||
) -> torch.Tensor:
|
||||
"""Decode H3 temporal clips and synchronously publish committed frames.
|
||||
|
||||
The released VAE exposes the temporal clip primitives but materializes the
|
||||
final tensor. This is the same loop with the write point replaced by a
|
||||
frames-only callback. ``callback=None`` retains the complete-output path.
|
||||
"""
|
||||
if latent.ndim != 5 or not bool(getattr(model, "use_3d_conv", False)):
|
||||
raise ValueError("MiniMax-H3 temporal chunk decode requires a rank-5 3D latent")
|
||||
|
||||
token_drop = int(model.token_drop)
|
||||
chunk_size = int(model.tokens_chunk_size)
|
||||
overlap_tokens = int(model.token_overlap)
|
||||
ratio_t = int(model.vae_ratio_t)
|
||||
pre_padding = int(model.frame_pre_padding)
|
||||
|
||||
isolated_first = bool(model.isolated_first_frame and pre_padding == 0)
|
||||
isolated_last = bool(model.isolated_last_frame)
|
||||
z_head = latent[:, :, :1] if isolated_first else None
|
||||
z_tail = latent[:, :, -1:] if isolated_last else None
|
||||
start = int(isolated_first)
|
||||
stop = int(latent.shape[2]) - int(isolated_last)
|
||||
latent = latent[:, :, start:stop]
|
||||
|
||||
pseudo_tokens = int(latent.shape[2]) + token_drop
|
||||
pad_tokens = (-pseudo_tokens) % chunk_size
|
||||
if pad_tokens:
|
||||
latent = torch.cat((latent, latent[:, :, -1:].repeat(1, 1, pad_tokens, 1, 1)), dim=2)
|
||||
num_chunks = (pseudo_tokens + pad_tokens) // chunk_size - int(token_drop > 0)
|
||||
if num_chunks <= 0:
|
||||
raise ValueError("MiniMax-H3 temporal chunk plan is empty")
|
||||
|
||||
total_frames, pad_frames, output_frames = model._decode_temporal_output_frame_plan(
|
||||
latent, z_head, z_tail, num_chunks, pad_tokens
|
||||
)
|
||||
output_frames = int(output_frames)
|
||||
if output_frames <= 0:
|
||||
raise ValueError("MiniMax-H3 temporal chunk plan has no output frames")
|
||||
|
||||
collected: list[torch.Tensor] = []
|
||||
overlap: torch.Tensor | None = None
|
||||
written = 0
|
||||
|
||||
def emit(part: torch.Tensor) -> None:
|
||||
nonlocal written
|
||||
frames = int(part.shape[2])
|
||||
if frames <= 0 or written >= output_frames:
|
||||
return
|
||||
frames = min(frames, output_frames - written)
|
||||
part = part[:, :, :frames]
|
||||
if callback is None:
|
||||
collected.append(part)
|
||||
else:
|
||||
callback(part)
|
||||
written += frames
|
||||
|
||||
chunk_frames = chunk_size * ratio_t
|
||||
split_count = int(token_drop > 0) + 1
|
||||
for index in range(num_chunks):
|
||||
begin = index * chunk_size
|
||||
end = begin + chunk_size + overlap_tokens
|
||||
clip = latent[:, :, begin:end]
|
||||
if index == 0 and z_head is not None:
|
||||
clip = torch.cat((z_head, clip), dim=2)
|
||||
if index == num_chunks - 1 and z_tail is not None:
|
||||
clip = torch.cat((clip, z_tail), dim=2)
|
||||
|
||||
decoded = model._adaptive_decode(clip)
|
||||
|
||||
# The isolated boundary latents were prepended/appended to the clip, so
|
||||
# the decoder returns their frames inside this clip's block. Publish
|
||||
# them the way the released loop does and drop their temporal block
|
||||
# before splitting, or every later frame shifts by one block.
|
||||
decoded_tail = None
|
||||
if index == 0 and z_head is not None:
|
||||
emit(decoded[:, :, ratio_t - 1 : ratio_t])
|
||||
decoded = decoded[:, :, ratio_t:]
|
||||
if index == num_chunks - 1 and z_tail is not None:
|
||||
decoded_tail = decoded[:, :, -1:]
|
||||
decoded = decoded[:, :, :-ratio_t]
|
||||
|
||||
for split in range(split_count):
|
||||
begin = split * chunk_frames
|
||||
end = min(begin + chunk_frames, int(decoded.shape[2]))
|
||||
part = decoded[:, :, begin:end]
|
||||
part = part[:, :, pre_padding:]
|
||||
if split == 0:
|
||||
if overlap is not None:
|
||||
part = model.blend(overlap, part, int(model.frame_overlap), dim=-3)
|
||||
overlap = None
|
||||
emit(part)
|
||||
else:
|
||||
overlap = part.contiguous()
|
||||
|
||||
if index == num_chunks - 1:
|
||||
if overlap is not None:
|
||||
emit(overlap)
|
||||
overlap = None
|
||||
if decoded_tail is not None:
|
||||
emit(decoded_tail)
|
||||
|
||||
if written != output_frames:
|
||||
raise RuntimeError(f"MiniMax-H3 temporal decode emitted {written}/{output_frames} frames")
|
||||
if callback is not None:
|
||||
return latent.new_empty((0,))
|
||||
return torch.cat(collected, dim=2) if collected else latent.new_empty((0,))
|
||||
@@ -9,7 +9,7 @@ import json
|
||||
from collections.abc import Iterator
|
||||
from contextlib import AbstractContextManager, contextmanager, nullcontext
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
@@ -22,11 +22,13 @@ from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor impor
|
||||
DistributedVaeMixin,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_world_group
|
||||
from vllm_omni.diffusion.models.interface import DecodedChunkConsumer
|
||||
from vllm_omni.diffusion.offloader.module_residency import (
|
||||
BoundedAllocatorCache,
|
||||
PinnedModuleStager,
|
||||
)
|
||||
|
||||
from .chunked_decode import decode_h3_chunks
|
||||
from .ops import install_h3_vae_optimizations
|
||||
from .packed_tokens import minimax_h3_patchify_video_latent
|
||||
|
||||
@@ -377,25 +379,16 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
|
||||
).float()
|
||||
return rows, shape
|
||||
|
||||
@torch.inference_mode()
|
||||
def decode_latent(self, latent: torch.Tensor) -> torch.Tensor:
|
||||
channels = int(self.config_dict["latent_channels"])
|
||||
mean = torch.tensor(
|
||||
self.config_dict["latents_mean"],
|
||||
device=latent.device,
|
||||
dtype=latent.dtype,
|
||||
).view(1, channels, 1, 1, 1)
|
||||
std = torch.tensor(
|
||||
self.config_dict["latents_std"],
|
||||
device=latent.device,
|
||||
dtype=latent.dtype,
|
||||
).view(1, channels, 1, 1, 1)
|
||||
# The checkpoint hands rank r the tiles ``range(r, num_tiles, sp_size)``
|
||||
# and then rejects an empty share inside the gather. A rank with no
|
||||
# tiles raises and leaves the collective while the others block in it
|
||||
# forever, so too few tiles hangs the whole stage rather than failing
|
||||
# it. Tile count depends only on the latent shape, so every rank takes
|
||||
# this branch together.
|
||||
def _decode_tiling_context(self, latent: torch.Tensor) -> AbstractContextManager:
|
||||
"""Pick the tiling mode a decode of ``latent`` can safely use.
|
||||
|
||||
The checkpoint hands rank r the tiles ``range(r, num_tiles, sp_size)``
|
||||
and then rejects an empty share inside the gather. A rank with no
|
||||
tiles raises and leaves the collective while the others block in it
|
||||
forever, so too few tiles hangs the whole stage rather than failing
|
||||
it. Tile count depends only on the latent shape, so every rank takes
|
||||
this branch together.
|
||||
"""
|
||||
num_tiles = self._decoder_tile_count(latent)
|
||||
if self.parallel_size > 1 and num_tiles < self.parallel_size:
|
||||
logger.warning_once(
|
||||
@@ -405,19 +398,64 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
|
||||
num_tiles,
|
||||
self.parallel_size,
|
||||
)
|
||||
tiling_context: AbstractContextManager = self._rank_local_tiling()
|
||||
else:
|
||||
tiling_context = nullcontext()
|
||||
return self._rank_local_tiling()
|
||||
return nullcontext()
|
||||
|
||||
with tiling_context:
|
||||
decoded = self.model.decode_base(latent * std + mean)
|
||||
frames = self.model.processor.revert_tensor(decoded)
|
||||
@torch.inference_mode()
|
||||
def decode_latent(self, latent: torch.Tensor) -> torch.Tensor:
|
||||
with self._decode_tiling_context(latent):
|
||||
decoded = self.model.decode_base(self._denormalize_latent(latent))
|
||||
return self._normalize_decoded_frames(self.model.processor.revert_tensor(decoded))
|
||||
|
||||
def _denormalize_latent(self, latent: torch.Tensor) -> torch.Tensor:
|
||||
channels = int(self.config_dict["latent_channels"])
|
||||
mean = torch.tensor(self.config_dict["latents_mean"], device=latent.device, dtype=latent.dtype)
|
||||
std = torch.tensor(self.config_dict["latents_std"], device=latent.device, dtype=latent.dtype)
|
||||
shape = (1, channels, 1, 1, 1)
|
||||
return latent * std.view(shape) + mean.view(shape)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_decoded_frames(decoded: torch.Tensor) -> torch.Tensor:
|
||||
"""Canonicalize remote H3 decoder output to [B,C,T,H,W]."""
|
||||
frames = decoded
|
||||
if frames.ndim == 4:
|
||||
frames = frames.unsqueeze(0).transpose(1, 2)
|
||||
if frames.ndim != 5:
|
||||
raise ValueError(f"unexpected decoded video shape {tuple(frames.shape)}")
|
||||
return frames.float()
|
||||
|
||||
# Chunks are reverted through the checkpoint's processor, which
|
||||
# denormalizes and clamps into the unit interval.
|
||||
chunk_value_range: ClassVar[tuple[float, float]] = (0.0, 1.0)
|
||||
|
||||
@torch.inference_mode()
|
||||
def decode_with_chunks(self, z: torch.Tensor, *, on_chunk: DecodedChunkConsumer) -> None:
|
||||
"""Decode temporal clips and synchronously publish frames-only chunks.
|
||||
|
||||
Implements :class:`SupportsChunkedVAEDecode`. Every rank participating
|
||||
in distributed VAE execution must invoke this method with a callback so
|
||||
the temporal collectives stay in lockstep; ``on_chunk`` is called only
|
||||
on the rank that owns output. Chunks arrive as ``[B, C, T, H, W]``
|
||||
float frames, normalized through the checkpoint's processor to match
|
||||
the complete decode path. After a callback failure, the remaining
|
||||
chunks are decoded and discarded before the exception is re-raised.
|
||||
"""
|
||||
if not callable(on_chunk):
|
||||
raise TypeError("on_chunk must be callable")
|
||||
if not callable(getattr(self.model, "_adaptive_decode", None)):
|
||||
raise RuntimeError("Loaded MiniMax-H3 VAE does not expose temporal decode primitives")
|
||||
group = None
|
||||
if self.is_distributed_enabled():
|
||||
group = self._native_parallel_state().get("sp_process_group")
|
||||
if group is None or dist.get_world_size(group) != self.parallel_size:
|
||||
raise RuntimeError("MiniMax-H3 VAE chunk decode has an invalid spatial-parallel group")
|
||||
# Native H3 tiling performs its own collectives for every temporal clip,
|
||||
# so this path needs the same too-few-tiles fallback as the complete
|
||||
# decode: without it a shape that leaves some ranks tileless hangs the
|
||||
# gather instead of decoding rank-locally.
|
||||
with self._decode_tiling_context(z):
|
||||
decode_h3_chunks(self, z, on_chunk, group=group)
|
||||
|
||||
|
||||
class MiniMaxH3AudioVAE(nn.Module):
|
||||
def __init__(
|
||||
|
||||
Reference in new issue
Block a user