Merge remote-tracking branch 'origin/main' into qwen-image-2.1

# Conflicts:
#	vllm_omni/diffusion/executor/multiproc_executor.py
#	vllm_omni/diffusion/offloader/sequential_backend.py
This commit is contained in:
Isotr0py committed 2026-09-21 07:32:04 +00:00
commit 9174554e40
1332 files changed
+160051 -60504

No files matched your search

@@ -0,0 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from vllm_omni.diffusion.models.anima.pipeline_anima import AnimaPipeline
__all__ = [
"AnimaPipeline",
]
@@ -0,0 +1,321 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from collections.abc import Iterable
from types import SimpleNamespace
from typing import Any
import torch
import torch.nn as nn
import torch.nn.functional as F
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.layer import Attention
ANIMA_TEXT_CONDITIONER_CONFIG = {
"source_dim": 1024,
"target_dim": 1024,
"model_dim": 1024,
"num_layers": 6,
"num_attention_heads": 16,
"mlp_ratio": 4.0,
"target_vocab_size": 32128,
"use_self_attention": True,
"use_layer_norm": False,
"min_sequence_length": 512,
}
def _rotate_half(hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states_1 = hidden_states[..., : hidden_states.shape[-1] // 2]
hidden_states_2 = hidden_states[..., hidden_states.shape[-1] // 2 :]
return torch.cat((-hidden_states_2, hidden_states_1), dim=-1)
def _apply_rotary_pos_emb(
hidden_states: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
unsqueeze_dim: int = 1,
) -> torch.Tensor:
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
return (hidden_states * cos) + (_rotate_half(hidden_states) * sin)
class AnimaRotaryEmbedding(nn.Module):
def __init__(self, head_dim: int, rope_theta: float = 10000.0) -> None:
super().__init__()
inv_freq = 1.0 / (
rope_theta ** (torch.arange(0, head_dim, 2, dtype=torch.int64).to(dtype=torch.float32) / head_dim)
)
self.register_buffer("inv_freq", inv_freq, persistent=False)
def forward(self, hidden_states: torch.Tensor, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
inv_freq_expanded = inv_freq_expanded.to(hidden_states.device)
position_ids_expanded = position_ids[:, None, :].float()
freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos()
sin = emb.sin()
return cos.to(dtype=hidden_states.dtype), sin.to(dtype=hidden_states.dtype)
class AnimaTextConditionerAttention(nn.Module):
def __init__(
self,
query_dim: int,
context_dim: int,
num_attention_heads: int,
attention_head_dim: int,
prefix: str = "",
) -> None:
super().__init__()
inner_dim = num_attention_heads * attention_head_dim
self.num_attention_heads = num_attention_heads
self.attention_head_dim = attention_head_dim
self.q_proj = nn.Linear(query_dim, inner_dim, bias=False)
self.q_norm = nn.RMSNorm(attention_head_dim, eps=1e-6)
self.k_proj = nn.Linear(context_dim, inner_dim, bias=False)
self.k_norm = nn.RMSNorm(attention_head_dim, eps=1e-6)
self.v_proj = nn.Linear(context_dim, inner_dim, bias=False)
self.o_proj = nn.Linear(inner_dim, query_dim, bias=False)
self.attn = Attention(
num_heads=num_attention_heads,
head_size=attention_head_dim,
softmax_scale=1.0 / (attention_head_dim**0.5),
causal=False,
num_kv_heads=num_attention_heads,
prefix=prefix,
)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
encoder_hidden_states: torch.Tensor | None = None,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
encoder_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> torch.Tensor:
encoder_hidden_states = hidden_states if encoder_hidden_states is None else encoder_hidden_states
input_shape = hidden_states.shape[:-1]
encoder_input_shape = encoder_hidden_states.shape[:-1]
query = self.q_proj(hidden_states)
key = self.k_proj(encoder_hidden_states)
value = self.v_proj(encoder_hidden_states)
query = query.view(*input_shape, self.num_attention_heads, self.attention_head_dim)
key = key.view(*encoder_input_shape, self.num_attention_heads, self.attention_head_dim)
value = value.view(*encoder_input_shape, self.num_attention_heads, self.attention_head_dim)
query = self.q_norm(query)
key = self.k_norm(key)
if position_embeddings is not None:
if encoder_position_embeddings is None:
raise ValueError("encoder_position_embeddings is required with rotary embeddings.")
cos, sin = position_embeddings
query = _apply_rotary_pos_emb(query, cos, sin, unsqueeze_dim=2)
cos, sin = encoder_position_embeddings
key = _apply_rotary_pos_emb(key, cos, sin, unsqueeze_dim=2)
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
hidden_states = self.attn(query, key, value, attn_metadata=attn_metadata)
hidden_states = hidden_states.flatten(2, 3).contiguous()
return self.o_proj(hidden_states)
class AnimaTextConditionerBlock(nn.Module):
def __init__(
self,
source_dim: int,
model_dim: int,
num_attention_heads: int = 16,
mlp_ratio: float = 4.0,
use_self_attention: bool = True,
use_layer_norm: bool = False,
prefix: str = "",
) -> None:
super().__init__()
self.use_self_attention = use_self_attention
norm_cls = nn.LayerNorm if use_layer_norm else nn.RMSNorm
norm_kwargs = {} if use_layer_norm else {"eps": 1e-6}
if use_self_attention:
self.norm_self_attn = norm_cls(model_dim, **norm_kwargs)
self.self_attn = AnimaTextConditionerAttention(
query_dim=model_dim,
context_dim=model_dim,
num_attention_heads=num_attention_heads,
attention_head_dim=model_dim // num_attention_heads,
prefix=f"{prefix}.self_attn" if prefix else "self_attn",
)
self.norm_cross_attn = norm_cls(model_dim, **norm_kwargs)
self.cross_attn = AnimaTextConditionerAttention(
query_dim=model_dim,
context_dim=source_dim,
num_attention_heads=num_attention_heads,
attention_head_dim=model_dim // num_attention_heads,
prefix=f"{prefix}.cross_attn" if prefix else "cross_attn",
)
self.norm_mlp = norm_cls(model_dim, **norm_kwargs)
self.mlp = nn.Sequential(
nn.Linear(model_dim, int(model_dim * mlp_ratio)),
nn.GELU(),
nn.Linear(int(model_dim * mlp_ratio), model_dim),
)
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor,
target_attention_mask: torch.Tensor | None = None,
source_attention_mask: torch.Tensor | None = None,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
source_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> torch.Tensor:
if self.use_self_attention:
norm_hidden_states = self.norm_self_attn(hidden_states)
attn_hidden_states = self.self_attn(
norm_hidden_states,
attention_mask=target_attention_mask,
position_embeddings=position_embeddings,
encoder_position_embeddings=position_embeddings,
)
hidden_states = hidden_states + attn_hidden_states
norm_hidden_states = self.norm_cross_attn(hidden_states)
attn_hidden_states = self.cross_attn(
norm_hidden_states,
attention_mask=source_attention_mask,
encoder_hidden_states=encoder_hidden_states,
position_embeddings=position_embeddings,
encoder_position_embeddings=source_position_embeddings,
)
hidden_states = hidden_states + attn_hidden_states
hidden_states = hidden_states + self.mlp(self.norm_mlp(hidden_states))
return hidden_states
def is_conditioner_block_module(name: str, module: nn.Module) -> bool:
return "blocks" in name and name.split(".")[-1].isdigit()
class AnimaTextConditioner(nn.Module):
_repeated_blocks = ["AnimaTextConditionerBlock"]
_hsdp_shard_conditions = [is_conditioner_block_module]
def __init__(
self,
source_dim: int = 1024,
target_dim: int = 1024,
model_dim: int = 1024,
num_layers: int = 6,
num_attention_heads: int = 16,
mlp_ratio: float = 4.0,
target_vocab_size: int = 32128,
use_self_attention: bool = True,
use_layer_norm: bool = False,
min_sequence_length: int = 512,
**kwargs: Any,
) -> None:
super().__init__()
self.config = SimpleNamespace(
source_dim=source_dim,
target_dim=target_dim,
model_dim=model_dim,
num_layers=num_layers,
num_attention_heads=num_attention_heads,
mlp_ratio=mlp_ratio,
target_vocab_size=target_vocab_size,
use_self_attention=use_self_attention,
use_layer_norm=use_layer_norm,
min_sequence_length=min_sequence_length,
extra_config=kwargs,
)
self.embed = nn.Embedding(target_vocab_size, target_dim)
self.in_proj = nn.Linear(target_dim, model_dim) if model_dim != target_dim else nn.Identity()
self.rotary_emb = AnimaRotaryEmbedding(model_dim // num_attention_heads)
self.blocks = nn.ModuleList(
[
AnimaTextConditionerBlock(
source_dim=source_dim,
model_dim=model_dim,
num_attention_heads=num_attention_heads,
mlp_ratio=mlp_ratio,
use_self_attention=use_self_attention,
use_layer_norm=use_layer_norm,
prefix=f"blocks.{i}",
)
for i in range(num_layers)
]
)
self.out_proj = nn.Linear(model_dim, target_dim)
self.norm = nn.RMSNorm(target_dim, eps=1e-6)
self.gradient_checkpointing = False
@property
def dtype(self) -> torch.dtype:
return next(self.parameters()).dtype
@staticmethod
def _prepare_attention_mask(attention_mask: torch.Tensor | None) -> torch.Tensor | None:
if attention_mask is None:
return None
return attention_mask.to(torch.bool)
def forward(
self,
source_hidden_states: torch.Tensor,
target_input_ids: torch.Tensor,
target_attention_mask: torch.Tensor | None = None,
source_attention_mask: torch.Tensor | None = None,
) -> torch.Tensor:
target_attention_mask = self._prepare_attention_mask(target_attention_mask)
source_attention_mask = self._prepare_attention_mask(source_attention_mask)
hidden_states = self.embed(target_input_ids).to(dtype=source_hidden_states.dtype)
hidden_states = self.in_proj(hidden_states)
position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
source_position_ids = torch.arange(source_hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
position_embeddings = self.rotary_emb(hidden_states, position_ids)
source_position_embeddings = self.rotary_emb(hidden_states, source_position_ids)
for block in self.blocks:
hidden_states = block(
hidden_states,
source_hidden_states,
target_attention_mask=target_attention_mask,
source_attention_mask=source_attention_mask,
position_embeddings=position_embeddings,
source_position_embeddings=source_position_embeddings,
)
hidden_states = self.norm(self.out_proj(hidden_states))
if target_attention_mask is not None:
hidden_states = hidden_states * target_attention_mask.to(hidden_states).unsqueeze(-1)
if hidden_states.shape[1] < self.config.min_sequence_length:
hidden_states = F.pad(hidden_states, (0, 0, 0, self.config.min_sequence_length - hidden_states.shape[1]))
return hidden_states
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
params = dict(self.named_parameters())
loaded = set()
for name, tensor in weights:
if name not in params:
continue
param = params[name]
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, tensor)
loaded.add(name)
return loaded
@@ -0,0 +1,705 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from collections.abc import Iterable
from types import SimpleNamespace
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from diffusers.models.embeddings import Timesteps, apply_rotary_emb
from diffusers.models.modeling_outputs import Transformer2DModelOutput
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.distributed.hsdp_utils import is_transformer_block_module
ANIMA_TRANSFORMER_CONFIG = {
"in_channels": 16,
"out_channels": 16,
"num_attention_heads": 16,
"attention_head_dim": 128,
"num_layers": 28,
"mlp_ratio": 4.0,
"text_embed_dim": 1024,
"adaln_lora_dim": 256,
"max_size": (128, 240, 240),
"patch_size": (1, 2, 2),
"rope_scale": (1.0, 4.0, 4.0),
"concat_padding_mask": True,
"extra_pos_embed_type": None,
}
# NOTE: We import and use diffusers' `apply_rotary_emb` instead of a custom native implementation
# to prevent numerical drift in bfloat16. Diffusers upcasts queries, keys, and rotary frequency
# tensors to float32 before computing the rotation, and casts back to bfloat16 at the end.
# Performing the entire computation in bfloat16 accumulates precision errors across the 28
# transformer blocks, which is heavily amplified by Classifier-Free Guidance (CFG).
class CosmosPatchEmbed(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
patch_size: tuple[int, int, int],
bias: bool = True,
) -> None:
super().__init__()
self.patch_size = patch_size
self.proj = nn.Linear(in_channels * patch_size[0] * patch_size[1] * patch_size[2], out_channels, bias=bias)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
batch_size, num_channels, num_frames, height, width = hidden_states.shape
p_t, p_h, p_w = self.patch_size
hidden_states = hidden_states.reshape(
batch_size,
num_channels,
num_frames // p_t,
p_t,
height // p_h,
p_h,
width // p_w,
p_w,
)
hidden_states = hidden_states.permute(0, 2, 4, 6, 1, 3, 5, 7).flatten(4, 7)
return self.proj(hidden_states)
class CosmosTimestepEmbedding(nn.Module):
def __init__(self, in_features: int, out_features: int) -> None:
super().__init__()
self.linear_1 = nn.Linear(in_features, out_features, bias=False)
self.activation = nn.SiLU()
self.linear_2 = nn.Linear(out_features, 3 * out_features, bias=False)
def forward(self, timesteps: torch.Tensor) -> torch.Tensor:
emb = self.linear_1(timesteps)
emb = self.activation(emb)
return self.linear_2(emb)
class CosmosEmbedding(nn.Module):
def __init__(self, embedding_dim: int, condition_dim: int) -> None:
super().__init__()
self.time_proj = Timesteps(embedding_dim, flip_sin_to_cos=True, downscale_freq_shift=0.0)
self.t_embedder = CosmosTimestepEmbedding(embedding_dim, condition_dim)
self.norm = nn.RMSNorm(embedding_dim, eps=1e-6)
def forward(self, hidden_states: torch.Tensor, timestep: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
timesteps_proj = self.time_proj(timestep).type_as(hidden_states)
temb = self.t_embedder(timesteps_proj)
embedded_timestep = self.norm(timesteps_proj)
return temb, embedded_timestep
class CosmosAdaLayerNorm(nn.Module):
def __init__(self, in_features: int, hidden_features: int) -> None:
super().__init__()
self.embedding_dim = in_features
self.activation = nn.SiLU()
self.norm = nn.LayerNorm(in_features, elementwise_affine=False, eps=1e-6)
self.linear_1 = nn.Linear(in_features, hidden_features, bias=False)
self.linear_2 = nn.Linear(hidden_features, 2 * in_features, bias=False)
def forward(
self,
hidden_states: torch.Tensor,
embedded_timestep: torch.Tensor,
temb: torch.Tensor | None = None,
) -> torch.Tensor:
embedded_timestep = self.activation(embedded_timestep)
embedded_timestep = self.linear_1(embedded_timestep)
embedded_timestep = self.linear_2(embedded_timestep)
if temb is not None:
embedded_timestep = embedded_timestep + temb[..., : 2 * self.embedding_dim]
shift, scale = embedded_timestep.chunk(2, dim=-1)
hidden_states = self.norm(hidden_states)
if embedded_timestep.ndim == 2:
shift, scale = (x.unsqueeze(1) for x in (shift, scale))
return hidden_states * (1 + scale) + shift
class CosmosAdaLayerNormZero(nn.Module):
def __init__(self, in_features: int, hidden_features: int | None = None) -> None:
super().__init__()
self.norm = nn.LayerNorm(in_features, elementwise_affine=False, eps=1e-6)
self.activation = nn.SiLU()
self.linear_1 = (
nn.Identity() if hidden_features is None else nn.Linear(in_features, hidden_features, bias=False)
)
self.linear_2 = nn.Linear(hidden_features or in_features, 3 * in_features, bias=False)
def forward(
self,
hidden_states: torch.Tensor,
embedded_timestep: torch.Tensor,
temb: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
embedded_timestep = self.activation(embedded_timestep)
embedded_timestep = self.linear_1(embedded_timestep)
embedded_timestep = self.linear_2(embedded_timestep)
if temb is not None:
embedded_timestep = embedded_timestep + temb
shift, scale, gate = embedded_timestep.chunk(3, dim=-1)
hidden_states = self.norm(hidden_states)
if embedded_timestep.ndim == 2:
shift, scale, gate = (x.unsqueeze(1) for x in (shift, scale, gate))
hidden_states = hidden_states * (1 + scale) + shift
return hidden_states, gate
class CosmosGELU(nn.Module):
def __init__(self, dim: int, inner_dim: int, bias: bool = False) -> None:
super().__init__()
self.proj = nn.Linear(dim, inner_dim, bias=bias)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
return F.gelu(self.proj(hidden_states))
class CosmosFeedForward(nn.Module):
def __init__(self, dim: int, mult: float = 4.0, bias: bool = False) -> None:
super().__init__()
inner_dim = int(dim * mult)
self.net = nn.ModuleList(
[
CosmosGELU(dim, inner_dim, bias=bias),
nn.Identity(),
nn.Linear(inner_dim, dim, bias=bias),
]
)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
for module in self.net:
hidden_states = module(hidden_states)
return hidden_states
class CosmosAttention(nn.Module):
def __init__(
self,
query_dim: int,
cross_attention_dim: int | None = None,
heads: int = 8,
dim_head: int = 64,
out_bias: bool = False,
img_context: bool = False,
prefix: str = "",
) -> None:
super().__init__()
inner_dim = heads * dim_head
cross_attention_dim = query_dim if cross_attention_dim is None else cross_attention_dim
self.heads = heads
self.dim_head = dim_head
self.out_dim = inner_dim
self.query_dim = query_dim
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
self.to_k = nn.Linear(cross_attention_dim, inner_dim, bias=False)
self.to_v = nn.Linear(cross_attention_dim, inner_dim, bias=False)
self.norm_q = nn.RMSNorm(dim_head, eps=1e-6)
self.norm_k = nn.RMSNorm(dim_head, eps=1e-6)
self.to_out = nn.ModuleList([nn.Linear(inner_dim, query_dim, bias=out_bias), nn.Identity()])
self.attn = Attention(
num_heads=heads,
head_size=dim_head,
softmax_scale=1.0 / (dim_head**0.5),
causal=False,
num_kv_heads=heads,
prefix=prefix,
)
self.img_context = img_context
if img_context:
self.q_img = nn.Linear(query_dim, inner_dim, bias=False)
self.k_img = nn.Linear(query_dim, inner_dim, bias=False)
self.v_img = nn.Linear(query_dim, inner_dim, bias=False)
self.q_img_norm = nn.RMSNorm(dim_head, eps=1e-6)
self.k_img_norm = nn.RMSNorm(dim_head, eps=1e-6)
self.img_attn = Attention(
num_heads=heads,
head_size=dim_head,
softmax_scale=1.0 / (dim_head**0.5),
causal=False,
num_kv_heads=heads,
prefix=f"{prefix}.img_attn" if prefix else "img_attn",
)
def _attention(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor | None = None,
attention_mask: torch.Tensor | None = None,
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> torch.Tensor:
encoder_hidden_states = hidden_states if encoder_hidden_states is None else encoder_hidden_states
batch_size, seq_len, _ = hidden_states.shape
encoder_seq_len = encoder_hidden_states.shape[1]
query = self.to_q(hidden_states).view(batch_size, seq_len, self.heads, self.dim_head)
key = self.to_k(encoder_hidden_states).view(batch_size, encoder_seq_len, self.heads, self.dim_head)
value = self.to_v(encoder_hidden_states).view(batch_size, encoder_seq_len, self.heads, self.dim_head)
query = self.norm_q(query)
key = self.norm_k(key)
if image_rotary_emb is not None:
# We use diffusers' apply_rotary_emb to leverage its internal float32 rotation upcasting
# logic, resolving the bfloat16 cumulative precision drift vs. the reference pipeline.
query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
hidden_states = self.attn(query, key, value, attn_metadata=attn_metadata)
return hidden_states.flatten(2, 3).type_as(query)
def _image_attention(
self,
hidden_states: torch.Tensor,
img_context: torch.Tensor,
attention_mask: torch.Tensor | None = None,
) -> torch.Tensor:
batch_size, seq_len, _ = hidden_states.shape
img_seq_len = img_context.shape[1]
query = self.q_img(hidden_states).view(batch_size, seq_len, self.heads, self.dim_head)
key = self.k_img(img_context).view(batch_size, img_seq_len, self.heads, self.dim_head)
value = self.v_img(img_context).view(batch_size, img_seq_len, self.heads, self.dim_head)
query = self.q_img_norm(query)
key = self.k_img_norm(key)
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
hidden_states = self.img_attn(query, key, value, attn_metadata=attn_metadata)
return hidden_states.flatten(2, 3).type_as(query)
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor | tuple[torch.Tensor, torch.Tensor | None] | None = None,
attention_mask: torch.Tensor | tuple[torch.Tensor | None, torch.Tensor | None] | None = None,
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> torch.Tensor:
if self.img_context:
if not isinstance(encoder_hidden_states, tuple):
raise ValueError("Expected encoder_hidden_states as (text_context, img_context).")
text_context, img_context = encoder_hidden_states
text_mask, img_mask = attention_mask if attention_mask is not None else (None, None)
query_states = hidden_states
hidden_states = self._attention(query_states, text_context, text_mask, image_rotary_emb)
if img_context is not None:
hidden_states = hidden_states + self._image_attention(query_states, img_context, img_mask)
else:
hidden_states = self._attention(hidden_states, encoder_hidden_states, attention_mask, image_rotary_emb)
hidden_states = self.to_out[0](hidden_states)
return self.to_out[1](hidden_states)
class CosmosTransformerBlock(nn.Module):
def __init__(
self,
num_attention_heads: int,
attention_head_dim: int,
cross_attention_dim: int,
mlp_ratio: float = 4.0,
adaln_lora_dim: int = 256,
out_bias: bool = False,
img_context: bool = False,
before_proj: bool = False,
after_proj: bool = False,
prefix: str = "",
) -> None:
super().__init__()
hidden_size = num_attention_heads * attention_head_dim
self.norm1 = CosmosAdaLayerNormZero(in_features=hidden_size, hidden_features=adaln_lora_dim)
self.img_context = img_context
self.attn1 = CosmosAttention(
query_dim=hidden_size,
cross_attention_dim=None,
heads=num_attention_heads,
dim_head=attention_head_dim,
out_bias=out_bias,
prefix=f"{prefix}.attn1" if prefix else "attn1",
)
self.norm2 = CosmosAdaLayerNormZero(in_features=hidden_size, hidden_features=adaln_lora_dim)
self.attn2 = CosmosAttention(
query_dim=hidden_size,
cross_attention_dim=cross_attention_dim,
heads=num_attention_heads,
dim_head=attention_head_dim,
out_bias=out_bias,
img_context=img_context,
prefix=f"{prefix}.attn2" if prefix else "attn2",
)
self.norm3 = CosmosAdaLayerNormZero(in_features=hidden_size, hidden_features=adaln_lora_dim)
self.ff = CosmosFeedForward(hidden_size, mult=mlp_ratio, bias=out_bias)
self.before_proj = nn.Linear(hidden_size, hidden_size) if before_proj else None
self.after_proj = nn.Linear(hidden_size, hidden_size) if after_proj else None
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor | tuple[torch.Tensor, torch.Tensor | None],
embedded_timestep: torch.Tensor,
temb: torch.Tensor | None = None,
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
extra_pos_emb: torch.Tensor | None = None,
attention_mask: torch.Tensor | tuple[torch.Tensor | None, torch.Tensor | None] | None = None,
controlnet_residual: torch.Tensor | None = None,
latents: torch.Tensor | None = None,
block_idx: int | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
if self.before_proj is not None:
hidden_states = self.before_proj(hidden_states) + latents
if extra_pos_emb is not None:
hidden_states = hidden_states + extra_pos_emb
norm_hidden_states, gate = self.norm1(hidden_states, embedded_timestep, temb)
attn_output = self.attn1(norm_hidden_states, image_rotary_emb=image_rotary_emb)
hidden_states = hidden_states + gate * attn_output
norm_hidden_states, gate = self.norm2(hidden_states, embedded_timestep, temb)
attn_output = self.attn2(
norm_hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
)
hidden_states = hidden_states + gate * attn_output
norm_hidden_states, gate = self.norm3(hidden_states, embedded_timestep, temb)
ff_output = self.ff(norm_hidden_states)
hidden_states = hidden_states + gate * ff_output
if controlnet_residual is not None:
if self.after_proj is not None:
raise ValueError("controlnet_residual is incompatible with after_proj.")
hidden_states = hidden_states + controlnet_residual
if self.after_proj is not None:
return hidden_states, self.after_proj(hidden_states)
return hidden_states
class CosmosRotaryPosEmbed(nn.Module):
def __init__(
self,
hidden_size: int,
max_size: tuple[int, int, int] = (128, 240, 240),
patch_size: tuple[int, int, int] = (1, 2, 2),
base_fps: int = 24,
rope_scale: tuple[float, float, float] = (2.0, 1.0, 1.0),
) -> None:
super().__init__()
self.max_size = [size // patch for size, patch in zip(max_size, patch_size)]
self.patch_size = patch_size
self.base_fps = base_fps
self.dim_h = hidden_size // 6 * 2
self.dim_w = hidden_size // 6 * 2
self.dim_t = hidden_size - self.dim_h - self.dim_w
self.h_ntk_factor = rope_scale[1] ** (self.dim_h / (self.dim_h - 2))
self.w_ntk_factor = rope_scale[2] ** (self.dim_w / (self.dim_w - 2))
self.t_ntk_factor = rope_scale[0] ** (self.dim_t / (self.dim_t - 2))
def forward(self, hidden_states: torch.Tensor, fps: float | None = None) -> tuple[torch.Tensor, torch.Tensor]:
_, _, num_frames, height, width = hidden_states.shape
pe_size = [num_frames // self.patch_size[0], height // self.patch_size[1], width // self.patch_size[2]]
device = hidden_states.device
h_theta = 10000.0 * self.h_ntk_factor
w_theta = 10000.0 * self.w_ntk_factor
t_theta = 10000.0 * self.t_ntk_factor
seq = torch.arange(max(self.max_size), device=device, dtype=torch.float32)
dim_h_range = torch.arange(0, self.dim_h, 2, device=device, dtype=torch.float32)[: self.dim_h // 2] / self.dim_h
dim_w_range = torch.arange(0, self.dim_w, 2, device=device, dtype=torch.float32)[: self.dim_w // 2] / self.dim_w
dim_t_range = torch.arange(0, self.dim_t, 2, device=device, dtype=torch.float32)[: self.dim_t // 2] / self.dim_t
h_spatial_freqs = 1.0 / (h_theta**dim_h_range)
w_spatial_freqs = 1.0 / (w_theta**dim_w_range)
temporal_freqs = 1.0 / (t_theta**dim_t_range)
emb_h = torch.outer(seq[: pe_size[1]], h_spatial_freqs)[None, :, None, :].repeat(pe_size[0], 1, pe_size[2], 1)
emb_w = torch.outer(seq[: pe_size[2]], w_spatial_freqs)[None, None, :, :].repeat(pe_size[0], pe_size[1], 1, 1)
if fps is None:
emb_t = torch.outer(seq[: pe_size[0]], temporal_freqs)
else:
emb_t = torch.outer(seq[: pe_size[0]] / fps * self.base_fps, temporal_freqs)
emb_t = emb_t[:, None, None, :].repeat(1, pe_size[1], pe_size[2], 1)
freqs = torch.cat([emb_t, emb_h, emb_w] * 2, dim=-1).flatten(0, 2).float()
return torch.cos(freqs), torch.sin(freqs)
class CosmosLearnablePositionalEmbed(nn.Module):
def __init__(
self,
hidden_size: int,
max_size: tuple[int, int, int],
patch_size: tuple[int, int, int],
eps: float = 1e-6,
) -> None:
super().__init__()
self.max_size = [size // patch for size, patch in zip(max_size, patch_size)]
self.patch_size = patch_size
self.eps = eps
self.pos_emb_t = nn.Parameter(torch.zeros(self.max_size[0], hidden_size))
self.pos_emb_h = nn.Parameter(torch.zeros(self.max_size[1], hidden_size))
self.pos_emb_w = nn.Parameter(torch.zeros(self.max_size[2], hidden_size))
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
batch_size, _, num_frames, height, width = hidden_states.shape
pe_size = [num_frames // self.patch_size[0], height // self.patch_size[1], width // self.patch_size[2]]
emb_t = self.pos_emb_t[: pe_size[0]][None, :, None, None, :].repeat(batch_size, 1, pe_size[1], pe_size[2], 1)
emb_h = self.pos_emb_h[: pe_size[1]][None, None, :, None, :].repeat(batch_size, pe_size[0], 1, pe_size[2], 1)
emb_w = self.pos_emb_w[: pe_size[2]][None, None, None, :, :].repeat(batch_size, pe_size[0], pe_size[1], 1, 1)
emb = (emb_t + emb_h + emb_w).flatten(1, 3)
norm = torch.linalg.vector_norm(emb, dim=-1, keepdim=True, dtype=torch.float32)
norm = torch.add(self.eps, norm, alpha=np.sqrt(norm.numel() / emb.numel()))
return (emb / norm).type_as(hidden_states)
class AnimaTransformer3DModel(nn.Module):
_repeated_blocks = ["CosmosTransformerBlock"]
_hsdp_shard_conditions = [is_transformer_block_module]
def __init__(
self,
in_channels: int = 16,
out_channels: int = 16,
num_attention_heads: int = 32,
attention_head_dim: int = 128,
num_layers: int = 28,
mlp_ratio: float = 4.0,
text_embed_dim: int = 1024,
adaln_lora_dim: int = 256,
max_size: tuple[int, int, int] = (128, 240, 240),
patch_size: tuple[int, int, int] = (1, 2, 2),
rope_scale: tuple[float, float, float] = (2.0, 1.0, 1.0),
concat_padding_mask: bool = True,
extra_pos_embed_type: str | None = "learnable",
use_crossattn_projection: bool = False,
crossattn_proj_in_channels: int = 1024,
encoder_hidden_states_channels: int = 1024,
controlnet_block_every_n: int | None = None,
img_context_dim_in: int | None = None,
img_context_num_tokens: int = 256,
img_context_dim_out: int = 2048,
**kwargs: Any,
) -> None:
super().__init__()
hidden_size = num_attention_heads * attention_head_dim
self.config = SimpleNamespace(
in_channels=in_channels,
out_channels=out_channels,
num_attention_heads=num_attention_heads,
attention_head_dim=attention_head_dim,
num_layers=num_layers,
mlp_ratio=mlp_ratio,
text_embed_dim=text_embed_dim,
adaln_lora_dim=adaln_lora_dim,
max_size=max_size,
patch_size=patch_size,
rope_scale=rope_scale,
concat_padding_mask=concat_padding_mask,
extra_pos_embed_type=extra_pos_embed_type,
use_crossattn_projection=use_crossattn_projection,
crossattn_proj_in_channels=crossattn_proj_in_channels,
encoder_hidden_states_channels=encoder_hidden_states_channels,
controlnet_block_every_n=controlnet_block_every_n,
img_context_dim_in=img_context_dim_in,
img_context_num_tokens=img_context_num_tokens,
img_context_dim_out=img_context_dim_out,
extra_config=kwargs,
)
patch_embed_in_channels = in_channels + 1 if concat_padding_mask else in_channels
self.patch_embed = CosmosPatchEmbed(patch_embed_in_channels, hidden_size, patch_size, bias=False)
self.rope = CosmosRotaryPosEmbed(
hidden_size=attention_head_dim,
max_size=max_size,
patch_size=patch_size,
rope_scale=rope_scale,
)
self.learnable_pos_embed: CosmosLearnablePositionalEmbed | None = None
if extra_pos_embed_type == "learnable":
self.learnable_pos_embed = CosmosLearnablePositionalEmbed(
hidden_size=hidden_size,
max_size=max_size,
patch_size=patch_size,
)
self.time_embed = CosmosEmbedding(hidden_size, hidden_size)
self.transformer_blocks = nn.ModuleList(
[
CosmosTransformerBlock(
num_attention_heads=num_attention_heads,
attention_head_dim=attention_head_dim,
cross_attention_dim=text_embed_dim,
mlp_ratio=mlp_ratio,
adaln_lora_dim=adaln_lora_dim,
out_bias=False,
img_context=img_context_dim_in is not None and img_context_dim_in > 0,
prefix=f"transformer_blocks.{i}",
)
for i in range(num_layers)
]
)
self.norm_out = CosmosAdaLayerNorm(hidden_size, adaln_lora_dim)
self.proj_out = nn.Linear(hidden_size, patch_size[0] * patch_size[1] * patch_size[2] * out_channels, bias=False)
self.crossattn_proj: nn.Module | None = None
if use_crossattn_projection:
self.crossattn_proj = nn.Sequential(
nn.Linear(crossattn_proj_in_channels, encoder_hidden_states_channels, bias=True),
nn.GELU(),
)
self.img_context_proj: nn.Module | None = None
if img_context_dim_in:
self.img_context_proj = nn.Sequential(
nn.Linear(img_context_dim_in, img_context_dim_out, bias=True),
nn.GELU(),
)
self.gradient_checkpointing = False
@property
def dtype(self) -> torch.dtype:
return next(self.parameters()).dtype
def forward(
self,
hidden_states: torch.Tensor,
timestep: torch.Tensor,
encoder_hidden_states: torch.Tensor | tuple[torch.Tensor, torch.Tensor | None],
block_controlnet_hidden_states: list[torch.Tensor] | None = None,
attention_mask: torch.Tensor | tuple[torch.Tensor | None, torch.Tensor | None] | None = None,
fps: float | None = None,
condition_mask: torch.Tensor | None = None,
padding_mask: torch.Tensor | None = None,
return_dict: bool = True,
) -> Transformer2DModelOutput | tuple[torch.Tensor]:
batch_size, _, num_frames, height, width = hidden_states.shape
if condition_mask is not None:
hidden_states = torch.cat([hidden_states, condition_mask], dim=1)
if self.config.concat_padding_mask:
if padding_mask is None:
raise ValueError("padding_mask is required when concat_padding_mask=True.")
padding_mask_resized = F.interpolate(
padding_mask,
size=list(hidden_states.shape[-2:]),
mode="nearest",
)
hidden_states = torch.cat(
[hidden_states, padding_mask_resized.unsqueeze(2).repeat(batch_size, 1, num_frames, 1, 1)],
dim=1,
)
if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim != 2:
attention_mask = attention_mask.squeeze(1).squeeze(1)
image_rotary_emb = self.rope(hidden_states, fps=fps)
extra_pos_emb = self.learnable_pos_embed(hidden_states) if self.learnable_pos_embed is not None else None
p_t, p_h, p_w = self.config.patch_size
post_patch_num_frames = num_frames // p_t
post_patch_height = height // p_h
post_patch_width = width // p_w
hidden_states = self.patch_embed(hidden_states)
hidden_states = hidden_states.flatten(1, 3)
if timestep.ndim == 1:
temb, embedded_timestep = self.time_embed(hidden_states, timestep)
elif timestep.ndim == 5:
if timestep.shape != (batch_size, 1, num_frames, 1, 1):
raise ValueError(f"Expected timestep shape [B, 1, T, 1, 1], got {timestep.shape}.")
timestep = timestep.flatten()
temb, embedded_timestep = self.time_embed(hidden_states, timestep)
temb, embedded_timestep = (
x.view(batch_size, post_patch_num_frames, 1, 1, -1)
.expand(-1, -1, post_patch_height, post_patch_width, -1)
.flatten(1, 3)
for x in (temb, embedded_timestep)
)
else:
raise ValueError(f"Expected timestep shape [B, 1, T, 1, 1] or [T], got {timestep.shape}.")
text_context, img_context = (
encoder_hidden_states if isinstance(encoder_hidden_states, tuple) else (encoder_hidden_states, None)
)
if self.config.use_crossattn_projection:
if self.crossattn_proj is None:
raise ValueError("crossattn_proj is required when use_crossattn_projection=True.")
text_context = self.crossattn_proj(text_context)
if img_context is not None and self.config.img_context_dim_in:
if self.img_context_proj is None:
raise ValueError("img_context_proj is required when img_context_dim_in is set.")
img_context = self.img_context_proj(img_context)
processed_encoder_hidden_states = (
(text_context, img_context) if isinstance(encoder_hidden_states, tuple) else text_context
)
controlnet_block_index_map = {}
if block_controlnet_hidden_states is not None:
n_blocks = len(self.transformer_blocks)
controlnet_block_index_map = {
block_idx: block_controlnet_hidden_states[idx]
for idx, block_idx in list(enumerate(range(0, n_blocks, self.config.controlnet_block_every_n)))
}
for block_idx, block in enumerate(self.transformer_blocks):
hidden_states = block(
hidden_states,
processed_encoder_hidden_states,
embedded_timestep,
temb,
image_rotary_emb,
extra_pos_emb,
attention_mask,
controlnet_block_index_map.get(block_idx),
)
hidden_states = self.norm_out(hidden_states, embedded_timestep, temb)
hidden_states = self.proj_out(hidden_states)
hidden_states = hidden_states.unflatten(2, (p_h, p_w, p_t, -1))
hidden_states = hidden_states.unflatten(1, (post_patch_num_frames, post_patch_height, post_patch_width))
hidden_states = hidden_states.permute(0, 7, 1, 6, 2, 4, 3, 5)
hidden_states = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
if not return_dict:
return (hidden_states,)
return Transformer2DModelOutput(sample=hidden_states)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
params = dict(self.named_parameters())
loaded = set()
for name, tensor in weights:
if name not in params:
continue
param = params[name]
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, tensor)
loaded.add(name)
return loaded
@@ -0,0 +1,795 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import inspect
import json
import logging
import os
from collections.abc import Callable, Iterable
from pathlib import Path
from typing import Any, cast
import numpy as np
import torch
from diffusers.image_processor import VaeImageProcessor
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
from diffusers.utils.torch_utils import randn_tensor
from safetensors.torch import load_file
from torch import nn
from transformers import AutoTokenizer, Qwen3Model, T5TokenizerFast
from vllm_omni.diffusion.config import set_current_diffusion_config
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_qwenimage import DistributedAutoencoderKLQwenImage
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.models.anima.anima_text_conditioner import (
ANIMA_TEXT_CONDITIONER_CONFIG,
AnimaTextConditioner,
)
from vllm_omni.diffusion.models.anima.anima_transformer import ANIMA_TRANSFORMER_CONFIG, AnimaTransformer3DModel
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
from vllm_omni.diffusion.offloader.config import OffloadStrategy, resolve_offload_strategy
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
from vllm_omni.diffusion.utils.size_utils import normalize_min_aligned_size
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
logger = logging.getLogger(__name__)
ANIMA_VAE_SCALE_FACTOR = 8
def retrieve_timesteps(
scheduler: Any,
num_inference_steps: int | None = None,
device: str | torch.device | None = None,
timesteps: list[int] | None = None,
sigmas: list[float] | None = None,
**kwargs: Any,
) -> tuple[torch.Tensor, int]:
if timesteps is not None and sigmas is not None:
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
if timesteps is not None:
if "timesteps" not in inspect.signature(scheduler.set_timesteps).parameters:
raise ValueError(
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
f" timestep schedules. Please check whether you are using the correct scheduler."
)
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
scheduler_timesteps = scheduler.timesteps
num_inference_steps = len(scheduler_timesteps)
elif sigmas is not None:
if "sigmas" not in inspect.signature(scheduler.set_timesteps).parameters:
raise ValueError(
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
f" sigmas schedules. Please check whether you are using the correct scheduler."
)
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
scheduler_timesteps = scheduler.timesteps
num_inference_steps = len(scheduler_timesteps)
else:
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
scheduler_timesteps = scheduler.timesteps
if num_inference_steps is None:
num_inference_steps = len(scheduler_timesteps)
return cast(torch.Tensor, scheduler_timesteps), num_inference_steps
_ANIMA_ORIGINAL_TRANSFORMER_RENAMES = {
"t_embedder.1": "time_embed.t_embedder",
"t_embedding_norm": "time_embed.norm",
"blocks": "transformer_blocks",
"adaln_modulation_self_attn.1": "norm1.linear_1",
"adaln_modulation_self_attn.2": "norm1.linear_2",
"adaln_modulation_cross_attn.1": "norm2.linear_1",
"adaln_modulation_cross_attn.2": "norm2.linear_2",
"adaln_modulation_mlp.1": "norm3.linear_1",
"adaln_modulation_mlp.2": "norm3.linear_2",
"self_attn": "attn1",
"cross_attn": "attn2",
"q_proj": "to_q",
"k_proj": "to_k",
"v_proj": "to_v",
"output_proj": "to_out.0",
"q_norm": "norm_q",
"k_norm": "norm_k",
"mlp.layer1": "ff.net.0.proj",
"mlp.layer2": "ff.net.2",
"x_embedder.proj.1": "patch_embed.proj",
"final_layer.adaln_modulation.1": "norm_out.linear_1",
"final_layer.adaln_modulation.2": "norm_out.linear_2",
"final_layer.linear": "proj_out",
}
_ANIMA_ORIGINAL_TRANSFORMER_DROP_KEYS = (
"accum_video_sample_counter",
"accum_image_sample_counter",
"accum_iteration",
"accum_train_in_hours",
"pos_embedder.seq",
"pos_embedder.dim_spatial_range",
"pos_embedder.dim_temporal_range",
"_extra_state",
)
def _anima_vae_scale_factor_from_vae(vae: Any) -> int:
vae_config = getattr(vae, "config", None)
spatial_compression_ratio = getattr(vae_config, "spatial_compression_ratio", None)
if spatial_compression_ratio is not None:
return int(spatial_compression_ratio)
temporal_downsample = getattr(vae, "temperal_downsample", None)
if temporal_downsample is not None:
return int(2 ** len(temporal_downsample))
return ANIMA_VAE_SCALE_FACTOR
def get_anima_post_process_func(od_config: OmniDiffusionConfig) -> Callable[[torch.Tensor], Any]:
image_processor = VaeImageProcessor(vae_scale_factor=ANIMA_VAE_SCALE_FACTOR)
def post_process_func(images: torch.Tensor) -> Any:
return image_processor.postprocess(images)
return post_process_func
class AnimaPipeline(nn.Module, DiffusionPipelineProfilerMixin, ProgressBarMixin):
"""Native Anima model path.
The Anima transformer checkpoint is distributed as a single safetensors
file. This loader builds the native pipeline components and runs the denoise
transformer/text-conditioner directly.
"""
supports_step_execution = False
def __init__(self, *, od_config: OmniDiffusionConfig, device: torch.device | str | None = None) -> None:
super().__init__()
self.od_config = od_config
self.parallel_config = od_config.parallel_config
self.device = device or get_local_device()
self.weights_sources: list[str] = []
self._raise_unsupported_features()
self._interrupt = False
self._guidance_scale = 1.0
self._num_timesteps = 0
self._current_timestep = None
self._profiler_initialized = False
def _raise_unsupported_features(self) -> None:
pc = self.od_config.parallel_config
if pc.cfg_parallel_size > 1:
raise NotImplementedError("AnimaPipeline does not yet support CFG parallel. Validate native CFG first.")
if pc.sequence_parallel_size is not None and pc.sequence_parallel_size > 1:
raise NotImplementedError("AnimaPipeline does not yet support sequence parallelism. Add an _sp_plan first.")
if pc.tensor_parallel_size > 1:
raise NotImplementedError("AnimaPipeline does not yet support tensor parallelism. Port TP linears first.")
if pc.use_hsdp:
raise NotImplementedError("AnimaPipeline does not yet support HSDP. Validate sharding after native load.")
if self.od_config.cache_backend not in ("none", None):
raise NotImplementedError("AnimaPipeline does not yet support TeaCache or Cache-DiT.")
if self.od_config.quantization_config is not None:
raise NotImplementedError("AnimaPipeline does not yet support quantized checkpoints.")
if resolve_offload_strategy(self.od_config) is not OffloadStrategy.NONE:
raise NotImplementedError("AnimaPipeline does not yet support CPU offload.")
@staticmethod
def _sub_state_dict(state_dict: dict[str, torch.Tensor], prefix: str) -> dict[str, torch.Tensor]:
return {key.removeprefix(prefix): value for key, value in state_dict.items() if key.startswith(prefix)}
@staticmethod
def _convert_original_transformer_state_dict(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
if "patch_embed.proj.weight" in state_dict:
return state_dict
# The raw Anima checkpoint uses the original training names for a
# Cosmos-style denoiser. Convert those keys to the local
# AnimaTransformer3DModel module names before strict loading.
converted_state_dict = {}
for key, value in state_dict.items():
new_key = key.removeprefix("net.")
if any(drop_key in new_key for drop_key in _ANIMA_ORIGINAL_TRANSFORMER_DROP_KEYS):
continue
for old_key, new_name in _ANIMA_ORIGINAL_TRANSFORMER_RENAMES.items():
new_key = new_key.replace(old_key, new_name)
if new_key in converted_state_dict:
raise ValueError(f"Duplicate converted Anima transformer key: {new_key}")
converted_state_dict[new_key] = value
return converted_state_dict
@staticmethod
def _split_single_file_state_dict(
state_dict: dict[str, torch.Tensor],
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
transformer_state_dict = AnimaPipeline._sub_state_dict(state_dict, "transformer.")
text_conditioner_state_dict = AnimaPipeline._sub_state_dict(state_dict, "text_conditioner.")
if transformer_state_dict and text_conditioner_state_dict:
return transformer_state_dict, text_conditioner_state_dict
text_conditioner_state_dict = AnimaPipeline._sub_state_dict(state_dict, "net.llm_adapter.")
if text_conditioner_state_dict:
transformer_state_dict = {
key: value for key, value in state_dict.items() if not key.startswith("net.llm_adapter.")
}
return transformer_state_dict, text_conditioner_state_dict
raise ValueError(
"Anima native loader could not find text-conditioner weights. Expected either "
"`text_conditioner.*` Diffusers keys or `net.llm_adapter.*` original Anima keys."
)
def _load_native_denoiser_components(
self,
state_dict: dict[str, torch.Tensor] | None = None,
) -> tuple[AnimaTransformer3DModel, AnimaTextConditioner]:
if state_dict is None:
model_path = self.od_config.model
if not isinstance(model_path, str) or not os.path.isfile(model_path):
raise ValueError(f"AnimaPipeline currently requires a local file path, got: {model_path}")
state_dict = load_file(model_path, device="cpu")
transformer_state_dict, text_conditioner_state_dict = self._split_single_file_state_dict(state_dict)
del state_dict
transformer_state_dict = self._convert_original_transformer_state_dict(transformer_state_dict)
config_path = Path(self.od_config.model).with_suffix(".json")
config = json.loads(config_path.read_text()) if config_path.is_file() else {}
text_conditioner_config = {**ANIMA_TEXT_CONDITIONER_CONFIG, **config.get("text_conditioner", {})}
transformer_config = {**ANIMA_TRANSFORMER_CONFIG, **config.get("transformer", {})}
native_text_conditioner = AnimaTextConditioner(**cast(dict[str, Any], text_conditioner_config))
native_text_conditioner.load_state_dict(text_conditioner_state_dict, strict=True)
native_text_conditioner.to(device=self.device, dtype=self.od_config.dtype)
del text_conditioner_state_dict
native_transformer = AnimaTransformer3DModel(**cast(dict[str, Any], transformer_config))
native_transformer.load_state_dict(transformer_state_dict, strict=True)
native_transformer.to(device=self.device, dtype=self.od_config.dtype)
del transformer_state_dict
return native_transformer, native_text_conditioner
def _component_path(self, name: str, default_model: str) -> str:
custom_args = self.od_config.custom_pipeline_args or {}
return str(custom_args.get(f"{name}_model", custom_args.get(f"{name}_path", default_model)))
@staticmethod
def _from_pretrained_kwargs(model: str, subfolder: str | None = None) -> dict[str, Any]:
kwargs: dict[str, Any] = {"local_files_only": os.path.exists(model)}
if subfolder is not None and os.path.isdir(os.path.join(model, subfolder)):
kwargs["subfolder"] = subfolder
return kwargs
def _load_outer_components(self) -> tuple[Any, Any, Any, Any, Any]:
custom_args = self.od_config.custom_pipeline_args or {}
components_model_value = custom_args.get("components_model", custom_args.get("components_path"))
if components_model_value is None:
if not isinstance(self.od_config.model, str):
raise ValueError("AnimaPipeline requires `model` or `components_model` to load outer components.")
checkpoint_dir = os.path.dirname(os.path.abspath(self.od_config.model))
components_model = checkpoint_dir if os.path.isdir(checkpoint_dir) else self.od_config.model
else:
components_model = str(components_model_value)
text_encoder_model = self._component_path("text_encoder", components_model)
vae_model = self._component_path("vae", components_model)
tokenizer_model = self._component_path("tokenizer", components_model)
t5_tokenizer_model = self._component_path("t5_tokenizer", components_model)
text_encoder = Qwen3Model.from_pretrained(
text_encoder_model,
torch_dtype=self.od_config.dtype,
**self._from_pretrained_kwargs(text_encoder_model, "text_encoder"),
).to(self.device)
vae = DistributedAutoencoderKLQwenImage.from_pretrained(
vae_model,
torch_dtype=self.od_config.dtype,
**self._from_pretrained_kwargs(vae_model, "vae"),
).to(self.device)
tokenizer = AutoTokenizer.from_pretrained(
tokenizer_model,
**self._from_pretrained_kwargs(tokenizer_model, "tokenizer"),
)
t5_tokenizer = T5TokenizerFast.from_pretrained(
t5_tokenizer_model,
**self._from_pretrained_kwargs(t5_tokenizer_model, "t5_tokenizer"),
)
scheduler_model = self._component_path("scheduler", components_model)
has_scheduler_config = os.path.isfile(os.path.join(scheduler_model, "scheduler_config.json")) or os.path.isdir(
os.path.join(scheduler_model, "scheduler")
)
if has_scheduler_config:
scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
scheduler_model,
**self._from_pretrained_kwargs(scheduler_model, "scheduler"),
)
else:
scheduler = FlowMatchEulerDiscreteScheduler(shift=3.0)
return text_encoder, tokenizer, t5_tokenizer, vae, scheduler
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]] | None = None) -> set[str]:
logger.info("Loading Anima transformer/text-conditioner directly from single-file checkpoint.")
state_dict = dict(weights) if weights is not None else None
loaded = set(state_dict.keys()) if state_dict is not None else set()
if not state_dict:
state_dict = None
with set_current_diffusion_config(self.od_config):
native_transformer, native_text_conditioner = self._load_native_denoiser_components(state_dict)
text_encoder, tokenizer, t5_tokenizer, vae, scheduler = self._load_outer_components()
self.transformer = native_transformer
self.text_conditioner = native_text_conditioner
self.text_encoder = text_encoder
self.tokenizer = tokenizer
self.t5_tokenizer = t5_tokenizer
self.vae = vae
self.scheduler = scheduler
self.vae_scale_factor = _anima_vae_scale_factor_from_vae(self.vae)
self._setup_profiler()
return loaded
def _setup_profiler(self) -> None:
if self._profiler_initialized:
return
self.setup_diffusion_pipeline_profiler(
profiler_targets=["vae.decode", "diffuse", "text_encoder.forward"],
enable_diffusion_pipeline_profiler=self.od_config.enable_diffusion_pipeline_profiler,
)
self._profiler_initialized = True
def _extract_prompts(self, prompts: list[Any]) -> tuple[str | list[str] | None, str | list[str] | None]:
"""Extract prompt and negative_prompt from OmniPromptType list."""
prompt = [p if isinstance(p, str) else (p.get("prompt") or "") for p in prompts] or None
if all(isinstance(p, str) or p.get("negative_prompt") is None for p in prompts):
negative_prompt = None
elif prompts:
negative_prompt = ["" if isinstance(p, str) else (p.get("negative_prompt") or "") for p in prompts]
else:
negative_prompt = None
return prompt, negative_prompt
def _get_qwen_prompt_embeds(
self,
prompt: str | list[str],
max_sequence_length: int,
device: torch.device,
dtype: torch.dtype,
) -> tuple[torch.Tensor, torch.Tensor]:
prompt = [prompt] if isinstance(prompt, str) else prompt
text_inputs = self.tokenizer(
prompt,
padding="longest",
max_length=max_sequence_length,
truncation=True,
return_tensors="pt",
)
text_input_ids = text_inputs.input_ids.to(device)
prompt_attention_mask = text_inputs.attention_mask.to(device)
if text_input_ids.shape[-1] == 0:
text_input_ids = text_input_ids.new_zeros((text_input_ids.shape[0], 1))
prompt_attention_mask = prompt_attention_mask.new_zeros((prompt_attention_mask.shape[0], 1))
prompt_embeds = self.text_encoder(
input_ids=text_input_ids,
attention_mask=prompt_attention_mask,
output_hidden_states=False,
).last_hidden_state
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
prompt_embeds = prompt_embeds * prompt_attention_mask.to(prompt_embeds).unsqueeze(-1)
return prompt_embeds, prompt_attention_mask
def _get_t5_prompt_ids(
self,
prompt: str | list[str],
max_sequence_length: int,
device: torch.device,
) -> tuple[torch.Tensor, torch.Tensor]:
prompt = [prompt] if isinstance(prompt, str) else prompt
text_inputs = self.t5_tokenizer(
prompt,
padding="longest",
max_length=max_sequence_length,
truncation=True,
return_tensors="pt",
)
return text_inputs.input_ids.to(device), text_inputs.attention_mask.to(device)
def encode_prompt(
self,
prompt: str | list[str],
negative_prompt: str | list[str] | None = None,
prepare_unconditional_embeds: bool = True,
max_sequence_length: int = 512,
device: torch.device | None = None,
dtype: torch.dtype | None = None,
) -> dict[str, torch.Tensor | None]:
device = device or self.device
dtype = dtype or self.text_encoder.dtype
prompt = [prompt] if isinstance(prompt, str) else prompt
batch_size = len(prompt)
prompt_embeds, prompt_attention_mask = self._get_qwen_prompt_embeds(
prompt=prompt,
max_sequence_length=max_sequence_length,
device=device,
dtype=dtype,
)
t5_input_ids, t5_attention_mask = self._get_t5_prompt_ids(
prompt=prompt,
max_sequence_length=max_sequence_length,
device=device,
)
negative_prompt_embeds = None
negative_prompt_attention_mask = None
negative_t5_input_ids = None
negative_t5_attention_mask = None
if prepare_unconditional_embeds:
if negative_prompt is None:
negative_prompt = ""
if isinstance(negative_prompt, str):
negative_prompt = [negative_prompt] * batch_size
elif len(negative_prompt) != batch_size:
raise ValueError(
f"`negative_prompt` length ({len(negative_prompt)}) must match prompt batch size ({batch_size})."
)
negative_prompt_embeds, negative_prompt_attention_mask = self._get_qwen_prompt_embeds(
prompt=negative_prompt,
max_sequence_length=max_sequence_length,
device=device,
dtype=dtype,
)
negative_t5_input_ids, negative_t5_attention_mask = self._get_t5_prompt_ids(
prompt=negative_prompt,
max_sequence_length=max_sequence_length,
device=device,
)
return {
"qwen_prompt_embeds": prompt_embeds,
"qwen_attention_mask": prompt_attention_mask,
"t5_input_ids": t5_input_ids,
"t5_attention_mask": t5_attention_mask,
"negative_qwen_prompt_embeds": negative_prompt_embeds,
"negative_qwen_attention_mask": negative_prompt_attention_mask,
"negative_t5_input_ids": negative_t5_input_ids,
"negative_t5_attention_mask": negative_t5_attention_mask,
}
def condition_prompt_embeds(
self,
qwen_prompt_embeds: torch.Tensor,
qwen_attention_mask: torch.Tensor,
t5_input_ids: torch.Tensor,
t5_attention_mask: torch.Tensor,
device: torch.device | None = None,
conditioning_dtype: torch.dtype | None = None,
output_dtype: torch.dtype | None = None,
) -> torch.Tensor:
device = device or self.device
conditioning_dtype = conditioning_dtype or self.text_conditioner.dtype
output_dtype = output_dtype or self.transformer.dtype
prompt_embeds = self.text_conditioner(
source_hidden_states=qwen_prompt_embeds.to(device=device, dtype=conditioning_dtype),
target_input_ids=t5_input_ids.to(device),
target_attention_mask=t5_attention_mask.to(device),
source_attention_mask=qwen_attention_mask.to(device),
)
return prompt_embeds.to(dtype=output_dtype, device=device)
def prepare_latents(
self,
batch_size: int,
num_channels_latents: int,
height: int,
width: int,
dtype: torch.dtype | None = None,
device: torch.device | None = None,
generator: torch.Generator | list[torch.Generator] | None = None,
latents: torch.Tensor | None = None,
) -> torch.Tensor:
device = device or self.device
dtype = dtype or self.transformer.dtype
if latents is not None:
return latents.to(device=device, dtype=dtype)
latent_height = height // self.vae_scale_factor
latent_width = width // self.vae_scale_factor
shape = (batch_size, num_channels_latents, 1, latent_height, latent_width)
if isinstance(generator, list) and len(generator) != batch_size:
raise ValueError(
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
)
# Draw latents in float32 then cast
latents = randn_tensor(shape, generator=generator, device=device, dtype=torch.float32)
sigma_max = (
getattr(self.scheduler.config, "sigma_max", 1.0)
if hasattr(self, "scheduler") and hasattr(self.scheduler, "config")
else 1.0
)
return latents.to(dtype=dtype) * sigma_max
def prepare_timesteps(
self,
num_inference_steps: int,
sigmas: list[float] | None = None,
device: torch.device | None = None,
) -> tuple[torch.Tensor, int]:
device = device or self.device
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
return retrieve_timesteps(
self.scheduler,
device=device,
sigmas=sigmas,
)
def diffuse(
self,
prompt_embeds: torch.Tensor,
negative_prompt_embeds: torch.Tensor | None,
latents: torch.Tensor,
padding_mask: torch.Tensor,
timesteps: torch.Tensor,
do_true_cfg: bool,
true_cfg_scale: float,
) -> torch.Tensor:
self.scheduler.set_begin_index(0)
with self.progress_bar(total=len(timesteps)) as pbar:
for i, t in enumerate(timesteps):
if self.interrupt:
continue
self._current_timestep = t
# Broadcast timestep to match batch size
timestep = t.expand(latents.shape[0]).to(dtype=self.transformer.dtype, device=latents.device)
timestep = timestep / 1000.0 # normalize to 0..1 range
# Predict noise
latent_model_input = latents.to(self.transformer.dtype)
# Positive pass
noise_pred = self.transformer(
hidden_states=latent_model_input,
timestep=timestep,
encoder_hidden_states=prompt_embeds,
padding_mask=padding_mask,
return_dict=False,
)[0]
# Negative / uncond pass
if do_true_cfg and negative_prompt_embeds is not None:
noise_pred_uncond = self.transformer(
hidden_states=latent_model_input,
timestep=timestep,
encoder_hidden_states=negative_prompt_embeds,
padding_mask=padding_mask,
return_dict=False,
)[0]
noise_pred = noise_pred_uncond + true_cfg_scale * (noise_pred - noise_pred_uncond)
# Scheduler step
latents_dtype = latents.dtype
latents = self.scheduler.step(noise_pred.to(latents_dtype), t, latents, return_dict=False)[0]
if latents.dtype != latents_dtype:
latents = latents.to(latents_dtype)
pbar.update()
return latents
def decode_latents(
self,
latents: torch.Tensor,
output_type: str = "pil",
) -> DiffusionOutput:
"""Decode final latents."""
if output_type == "latent":
return DiffusionOutput(
output=latents,
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
)
latents = latents.to(self.vae.dtype)
latents_mean = (
torch.tensor(self.vae.config.latents_mean)
.view(1, self.vae.config.z_dim, 1, 1, 1)
.to(latents.device, latents.dtype)
)
latents_std = (
torch.tensor(self.vae.config.latents_std)
.view(1, self.vae.config.z_dim, 1, 1, 1)
.to(latents.device, latents.dtype)
)
latents = latents * latents_std + latents_mean
image = self.vae.decode(latents, return_dict=False)[0][:, :, 0]
return DiffusionOutput(
output=image,
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
)
def forward(
self,
req: DiffusionRequestBatch,
prompt: str | list[str] | None = None,
negative_prompt: str | list[str] | None = None,
true_cfg_scale: float = 4.0,
height: int | None = None,
width: int | None = None,
num_inference_steps: int = 50,
sigmas: list[float] | None = None,
guidance_scale: float = 4.0,
num_images_per_prompt: int = 1,
generator: torch.Generator | list[torch.Generator] | None = None,
latents: torch.Tensor | None = None,
output_type: str | None = "pil",
max_sequence_length: int = 512,
) -> list[DiffusionOutput]:
if req.num_reqs != 1:
raise ValueError("AnimaPipeline supports one request per forward.")
extracted_prompt, negative_prompt = self._extract_prompts(req.prompts)
prompt = extracted_prompt or prompt
if prompt is None:
prompt = ""
height = req.sampling_params.height or height or 1024
width = req.sampling_params.width or width or 1024
height, width = normalize_min_aligned_size(height, width, self.vae_scale_factor * 2)
if height is None or width is None:
raise ValueError("AnimaPipeline requires resolved height and width.")
height = int(height)
width = int(width)
if req.sampling_params.output_type is not None:
output_type = req.sampling_params.output_type
output_type = output_type or "pil"
num_inference_steps = req.sampling_params.num_inference_steps or num_inference_steps
sigmas = req.sampling_params.sigmas or sigmas
max_sequence_length = req.sampling_params.max_sequence_length or max_sequence_length
generator = req.sampling_params.generator or generator
if req.sampling_params.guidance_scale_provided:
guidance_scale = req.sampling_params.guidance_scale
if req.sampling_params.true_cfg_scale is None:
true_cfg_scale = guidance_scale
if req.sampling_params.true_cfg_scale is not None:
true_cfg_scale = req.sampling_params.true_cfg_scale
num_images_per_prompt = (
req.sampling_params.num_outputs_per_prompt
if req.sampling_params.num_outputs_per_prompt > 0
else num_images_per_prompt
)
self._guidance_scale = guidance_scale
self._interrupt = False
if isinstance(prompt, str):
batch_size = 1
else:
batch_size = len(prompt)
do_true_cfg = guidance_scale > 1.0
# Encode prompts
enc_out = self.encode_prompt(
prompt=prompt,
negative_prompt=negative_prompt,
prepare_unconditional_embeds=do_true_cfg,
max_sequence_length=max_sequence_length,
device=self.device,
dtype=self.text_encoder.dtype,
)
qwen_prompt_embeds = enc_out["qwen_prompt_embeds"]
qwen_attention_mask = enc_out["qwen_attention_mask"]
t5_input_ids = enc_out["t5_input_ids"]
t5_attention_mask = enc_out["t5_attention_mask"]
if (
qwen_prompt_embeds is None
or qwen_attention_mask is None
or t5_input_ids is None
or t5_attention_mask is None
):
raise ValueError("Anima prompt encoding did not produce all required positive embeddings.")
# Condition prompt embeds
prompt_embeds = self.condition_prompt_embeds(
qwen_prompt_embeds=qwen_prompt_embeds,
qwen_attention_mask=qwen_attention_mask,
t5_input_ids=t5_input_ids,
t5_attention_mask=t5_attention_mask,
device=self.device,
)
negative_prompt_embeds = None
negative_qwen_prompt_embeds = enc_out["negative_qwen_prompt_embeds"]
if do_true_cfg and negative_qwen_prompt_embeds is not None:
negative_qwen_attention_mask = enc_out["negative_qwen_attention_mask"]
negative_t5_input_ids = enc_out["negative_t5_input_ids"]
negative_t5_attention_mask = enc_out["negative_t5_attention_mask"]
if (
negative_qwen_attention_mask is None
or negative_t5_input_ids is None
or negative_t5_attention_mask is None
):
raise ValueError("Anima prompt encoding did not produce all required negative embeddings.")
negative_prompt_embeds = self.condition_prompt_embeds(
qwen_prompt_embeds=negative_qwen_prompt_embeds,
qwen_attention_mask=negative_qwen_attention_mask,
t5_input_ids=negative_t5_input_ids,
t5_attention_mask=negative_t5_attention_mask,
device=self.device,
)
# Repeat for num_images_per_prompt
_, seq_len, _ = prompt_embeds.shape
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
if negative_prompt_embeds is not None:
_, seq_len, _ = negative_prompt_embeds.shape
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
# Prepare latents
latents = self.prepare_latents(
batch_size=batch_size * num_images_per_prompt,
num_channels_latents=16, # Cosmos/Anima has 16 channels
height=height,
width=width,
dtype=torch.float32,
device=self.device,
generator=generator,
latents=latents,
)
# Prepare padding mask
padding_mask = latents.new_zeros(1, 1, height, width, dtype=self.transformer.dtype)
# Prepare timesteps
timesteps, num_inference_steps = self.prepare_timesteps(
num_inference_steps=num_inference_steps,
sigmas=sigmas,
device=self.device,
)
self._num_timesteps = len(timesteps)
# Denoise loop
latents = self.diffuse(
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
latents=latents,
padding_mask=padding_mask,
timesteps=timesteps,
do_true_cfg=do_true_cfg,
true_cfg_scale=true_cfg_scale,
)
self._current_timestep = None
return [self.decode_latents(latents, output_type=output_type)]
@property
def guidance_scale(self) -> float:
return self._guidance_scale
@property
def num_timesteps(self) -> int:
return self._num_timesteps
@property
def current_timestep(self) -> torch.Tensor | None:
return self._current_timestep
@property
def interrupt(self) -> bool:
return self._interrupt
@@ -0,0 +1,16 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""AuK diffusion-stage components: the flow transformer, the codec, the pipeline."""
from vllm_omni.diffusion.models.auk.auk_transformer import AuKTransformer, dit_state_dict, sample_latents
from vllm_omni.diffusion.models.auk.auk_vae import AuKVAE
from vllm_omni.diffusion.models.auk.pipeline_auk import AuKPipeline, get_auk_post_process_func
__all__ = [
"AuKPipeline",
"AuKTransformer",
"AuKVAE",
"dit_state_dict",
"get_auk_post_process_func",
"sample_latents",
]
@@ -0,0 +1,677 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""The AuK audio DiT as a self-contained inference module.
Two phases. ``num_layers`` double-stream blocks attend jointly over text and
audio while keeping each stream's residual separate, then
``num_single_layers`` single-stream blocks run over the concatenated
``[text | ref audio | target audio]`` sequence. Only the target-audio slice is
projected back to latent space, so the module predicts a flow-matching
velocity for the target frames and :func:`sample_latents` integrates it.
Parameter names and shapes match the AuK reference backbone, so a released
checkpoint loads with ``load_state_dict(strict=True)`` once the
``transformer.`` prefix is stripped (see :func:`dit_state_dict`).
Deliberate differences from the reference, all inference-only:
* ``x_transformers`` and ``torchdiffeq`` are gone. Rotary embeddings are
computed here (interleaved GPT-J pairs, no xpos scaling) and the ODE is an
explicit Euler loop.
* Dropout, activation checkpointing, the ``flash_attn`` backend switch and the
zero-init of the modulation layers are training concerns and are dropped.
* The timestep sinusoid is cast to the time MLP's weight dtype rather than to
the timestep's own dtype, so an fp32 timestep works against half-precision
weights outside autocast.
* ``attn_mask_enabled`` defaults to ``True``, the value the released config
sets, rather than the reference's ``False``.
"""
import math
from collections.abc import Iterable, Mapping
import torch
import torch.nn.functional as F
from torch import nn
__all__ = ["AuKTransformer", "dit_state_dict", "sample_latents"]
def _sdpa(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: torch.Tensor | None) -> torch.Tensor:
"""The single attention call site, so the backend can be swapped in one place.
``q``/``k``/``v`` are ``[B, H, N, D]``. ``mask`` is a boolean key-padding
mask ``[B, K]`` in which ``True`` marks a valid key; it is broadcast to
``[B, H, Q, K]`` only when given.
"""
attn_mask = None
if mask is not None:
attn_mask = mask[:, None, None, :].expand(q.shape[0], q.shape[1], q.shape[-2], k.shape[-2])
return F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=0.0, is_causal=False)
def _rotate_half(x: torch.Tensor) -> torch.Tensor:
"""Rotate interleaved GPT-J pairs: ``(x1, x2) -> (-x2, x1)``."""
pairs = x.reshape(*x.shape[:-1], -1, 2)
x1, x2 = pairs.unbind(dim=-1)
return torch.stack((-x2, x1), dim=-1).flatten(-2)
def _apply_rope(x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
"""Apply rotary frequencies ``[1, 1, N, D]`` to ``x`` ``[B, H, N, D]`` in fp32."""
out_dtype = x.dtype
x32 = x.float()
out = x32 * freqs.cos() + _rotate_half(x32) * freqs.sin()
return out.to(out_dtype)
class Rotary(nn.Module):
"""Rotary position frequencies for one stream, evaluated in fp32.
The frequencies live in a buffer so that a released checkpoint's own copy
of them loads with ``strict=True``. They are recomputed whenever the
module has been cast below fp32: rounding either the frequencies or the
integer positions to bf16 wrecks the phase at long positions.
"""
def __init__(self, dim: int, base: float = 10000.0) -> None:
super().__init__()
if dim % 2 != 0:
raise ValueError(f"rotary dim must be even, got {dim}")
self.dim = dim
self.base = base
self.register_buffer("inv_freq", self._frequencies(torch.device("cpu")))
def _frequencies(self, device: torch.device) -> torch.Tensor:
exponents = torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim
return 1.0 / (self.base**exponents)
def forward(self, seq_len: int) -> torch.Tensor:
"""Return frequencies ``[1, 1, seq_len, dim]`` for positions ``0..seq_len-1``."""
inv_freq = self.inv_freq
if inv_freq.dtype != torch.float32:
inv_freq = self._frequencies(inv_freq.device)
pos = torch.arange(seq_len, device=inv_freq.device, dtype=torch.float32)
freqs = torch.outer(pos, inv_freq)
return torch.stack((freqs, freqs), dim=-1).flatten(-2)[None, None]
class TimeEmbedding(nn.Module):
"""Sinusoidal timestep features followed by a two-layer MLP."""
def __init__(self, dim: int, freq_embed_dim: int = 256) -> None:
super().__init__()
self.freq_embed_dim = freq_embed_dim
self.time_mlp = nn.Sequential(nn.Linear(freq_embed_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
def forward(self, timestep: torch.Tensor, scale: float = 1000.0) -> torch.Tensor:
half = self.freq_embed_dim // 2
decay = math.log(10000) / (half - 1)
freqs = torch.exp(torch.arange(half, device=timestep.device, dtype=torch.float32) * -decay)
angles = scale * timestep.unsqueeze(1) * freqs.unsqueeze(0)
hidden = torch.cat((angles.sin(), angles.cos()), dim=-1)
return self.time_mlp(hidden.to(self.time_mlp[0].weight.dtype))
class ConvPosEmbedding(nn.Module):
"""Depthwise-grouped conv stack that adds local position information."""
def __init__(self, dim: int, kernel_size: int = 31, groups: int = 16) -> None:
super().__init__()
if kernel_size % 2 == 0:
raise ValueError(f"kernel_size must be odd, got {kernel_size}")
padding = kernel_size // 2
self.conv1d = nn.Sequential(
nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=padding),
nn.Mish(),
nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=padding),
nn.Mish(),
)
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
keep = None if mask is None else mask.unsqueeze(1)
x = x.transpose(1, 2)
if keep is not None:
x = x.masked_fill(~keep, 0.0)
for layer in self.conv1d:
x = layer(x)
# Re-zero padding after each convolution so it cannot bleed into
# valid frames through the kernel window.
if keep is not None and isinstance(layer, nn.Conv1d):
x = x.masked_fill(~keep, 0.0)
return x.transpose(1, 2)
class AudioEmbedding(nn.Module):
"""Project audio latents to model width and add conv position information."""
def __init__(self, latent_dim: int, dim: int) -> None:
super().__init__()
self.linear = nn.Linear(latent_dim, dim)
self.conv_pos_embed = ConvPosEmbedding(dim)
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
x = self.linear(x)
return self.conv_pos_embed(x, mask=mask) + x
class AdaLayerNorm(nn.Module):
"""Timestep-conditioned modulation for a block: six chunks from one projection."""
def __init__(self, dim: int) -> None:
super().__init__()
self.silu = nn.SiLU()
self.linear = nn.Linear(dim, dim * 6)
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
def forward(
self, x: torch.Tensor, emb: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.linear(self.silu(emb)).chunk(6, dim=1)
x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
class AdaLayerNormFinal(nn.Module):
"""Timestep-conditioned modulation before the output projection."""
def __init__(self, dim: int) -> None:
super().__init__()
self.silu = nn.SiLU()
self.linear = nn.Linear(dim, dim * 2)
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
scale, shift = self.linear(self.silu(emb)).chunk(2, dim=1)
return self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
class FeedForward(nn.Module):
"""SwiGLU feed-forward with the gate projection fused into ``linear_in``."""
def __init__(self, dim: int, mult: float = 4.0) -> None:
super().__init__()
inner_dim = int(dim * mult)
self.linear_in = nn.Linear(dim, inner_dim * 2, bias=False)
self.linear_out = nn.Linear(inner_dim, dim, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
gate, up = self.linear_in(x).chunk(2, dim=-1)
return self.linear_out(F.silu(gate) * up)
class Attention(nn.Module):
"""Self-attention with per-head QK RMSNorm and rotary positions.
``to_out`` stays a ``ModuleList`` because the released checkpoints name the
output projection ``to_out.0``; the reference's trailing dropout carries no
parameters and is dropped.
"""
def __init__(self, dim: int, heads: int, dim_head: int, attn_mask_enabled: bool = True) -> None:
super().__init__()
self.heads = heads
self.dim_head = dim_head
self.attn_mask_enabled = attn_mask_enabled
inner_dim = heads * dim_head
self.to_qkv = nn.Linear(dim, 3 * inner_dim)
self.q_norm = nn.RMSNorm(dim_head, elementwise_affine=True)
self.k_norm = nn.RMSNorm(dim_head, elementwise_affine=True)
self.to_out = nn.ModuleList([nn.Linear(inner_dim, dim)])
def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
return x.transpose(1, 2).reshape(x.shape[0], -1, self.heads * self.dim_head)
def _qkv(
self,
packed: torch.Tensor,
q_norm: nn.Module,
k_norm: nn.Module,
rope: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Split a packed QKV projection into heads, RMSNorm Q/K, then rotate."""
q, k, v = (t.view(t.shape[0], -1, self.heads, self.dim_head).transpose(1, 2) for t in packed.chunk(3, dim=-1))
q = q_norm(q)
k = k_norm(k)
if rope is not None:
q = _apply_rope(q, rope)
k = _apply_rope(k, rope)
return q, k, v
def _project(self, x: torch.Tensor, rope: torch.Tensor | None) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
return self._qkv(self.to_qkv(x), self.q_norm, self.k_norm, rope)
def forward(
self, x: torch.Tensor, mask: torch.Tensor | None = None, rope: torch.Tensor | None = None
) -> torch.Tensor:
q, k, v = self._project(x, rope)
attn_mask = mask if self.attn_mask_enabled else None
out = self._merge_heads(_sdpa(q, k, v, attn_mask).to(q.dtype))
out = self.to_out[0](out)
if mask is not None:
out = out.masked_fill(~mask.unsqueeze(-1), 0.0)
return out
class JointAttention(Attention):
"""Attention over the audio and text streams jointly, with separate projections."""
def __init__(self, dim: int, heads: int, dim_head: int, context_dim: int, attn_mask_enabled: bool = True) -> None:
super().__init__(dim, heads, dim_head, attn_mask_enabled)
inner_dim = heads * dim_head
self.to_qkv_c = nn.Linear(context_dim, 3 * inner_dim)
self.c_q_norm = nn.RMSNorm(dim_head, elementwise_affine=True)
self.c_k_norm = nn.RMSNorm(dim_head, elementwise_affine=True)
self.to_out_c = nn.Linear(inner_dim, context_dim)
def _project_context(self, c: torch.Tensor, c_rope: torch.Tensor | None) -> tuple[torch.Tensor, ...]:
return self._qkv(self.to_qkv_c(c), self.c_q_norm, self.c_k_norm, c_rope)
def forward( # type: ignore[override] # joint attention takes the context stream too
self,
x: torch.Tensor,
c: torch.Tensor,
mask: torch.Tensor | None = None,
rope: torch.Tensor | None = None,
c_rope: torch.Tensor | None = None,
c_mask: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
audio_len = x.shape[1]
q, k, v = self._project(x, rope)
c_q, c_k, c_v = self._project_context(c, c_rope)
q = torch.cat([q, c_q], dim=2)
k = torch.cat([k, c_k], dim=2)
v = torch.cat([v, c_v], dim=2)
joint_mask = None
if self.attn_mask_enabled and mask is not None:
if c_mask is not None:
joint_mask = torch.cat([mask, c_mask], dim=1)
else:
joint_mask = F.pad(mask, (0, c.shape[1]), value=True)
out = self._merge_heads(_sdpa(q, k, v, joint_mask).to(q.dtype))
x_out = self.to_out[0](out[:, :audio_len])
c_out = self.to_out_c(out[:, audio_len:])
if mask is not None:
x_out = x_out.masked_fill(~mask.unsqueeze(-1), 0.0)
if c_mask is not None:
c_out = c_out.masked_fill(~c_mask.unsqueeze(-1), 0.0)
return x_out, c_out
class DoubleBlock(nn.Module):
"""MM-DiT block: joint attention, separate modulation and feed-forward per stream."""
def __init__(self, dim: int, heads: int, dim_head: int, ff_mult: float, attn_mask_enabled: bool) -> None:
super().__init__()
self.attn_norm_c = AdaLayerNorm(dim)
self.attn_norm_x = AdaLayerNorm(dim)
self.attn = JointAttention(
dim=dim, heads=heads, dim_head=dim_head, context_dim=dim, attn_mask_enabled=attn_mask_enabled
)
self.ff_norm_c = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
self.ff_c = FeedForward(dim=dim, mult=ff_mult)
self.ff_norm_x = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
self.ff_x = FeedForward(dim=dim, mult=ff_mult)
def forward(
self,
x: torch.Tensor,
c: torch.Tensor,
t: torch.Tensor,
mask: torch.Tensor | None,
rope: torch.Tensor,
c_rope: torch.Tensor,
c_mask: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor]:
norm_c, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.attn_norm_c(c, t)
norm_x, x_gate_msa, x_shift_mlp, x_scale_mlp, x_gate_mlp = self.attn_norm_x(x, t)
x_attn, c_attn = self.attn(x=norm_x, c=norm_c, mask=mask, rope=rope, c_rope=c_rope, c_mask=c_mask)
c = c + c_gate_msa[:, None] * c_attn
norm_c = self.ff_norm_c(c) * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
c = c + c_gate_mlp[:, None] * self.ff_c(norm_c)
x = x + x_gate_msa[:, None] * x_attn
norm_x = self.ff_norm_x(x) * (1 + x_scale_mlp[:, None]) + x_shift_mlp[:, None]
x = x + x_gate_mlp[:, None] * self.ff_x(norm_x)
return c, x
class SingleBlock(nn.Module):
"""DiT block over the concatenated text and audio sequence."""
def __init__(self, dim: int, heads: int, dim_head: int, ff_mult: float, attn_mask_enabled: bool) -> None:
super().__init__()
self.attn_norm = AdaLayerNorm(dim)
self.attn = Attention(dim=dim, heads=heads, dim_head=dim_head, attn_mask_enabled=attn_mask_enabled)
self.ff_norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
self.ff = FeedForward(dim=dim, mult=ff_mult)
def forward(self, x: torch.Tensor, t: torch.Tensor, mask: torch.Tensor | None, rope: torch.Tensor) -> torch.Tensor:
norm, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.attn_norm(x, t)
x = x + gate_msa[:, None] * self.attn(x=norm, mask=mask, rope=rope)
norm = self.ff_norm(x) * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
return x + gate_mlp[:, None] * self.ff(norm)
class AuKTransformer(nn.Module):
"""Flow-matching velocity predictor for AuK audio latents.
Args:
dim: Model width.
heads: Attention heads.
dim_head: Per-head width.
ff_mult: Feed-forward expansion factor.
latent_dim: Audio VAE latent channels, the input and output width.
text_hidden_dim: Width of the pre-encoded text hidden states.
num_layers: Double-stream (joint attention) block count.
num_single_layers: Single-stream block count.
attn_mask_enabled: Apply padding masks inside attention. When ``False``
attention runs unmasked, though padded outputs are still zeroed,
which is what the reference does with the flag off.
"""
def __init__(
self,
*,
dim: int,
heads: int,
dim_head: int,
ff_mult: float,
latent_dim: int,
text_hidden_dim: int,
num_layers: int,
num_single_layers: int,
attn_mask_enabled: bool = True,
) -> None:
super().__init__()
self.dim = dim
self.latent_dim = latent_dim
self.text_cond: torch.Tensor | None = None
self.text_uncond: torch.Tensor | None = None
self.time_embed = TimeEmbedding(dim)
self.txt_norm = nn.RMSNorm(dim, elementwise_affine=True)
self.txt_proj = nn.Linear(text_hidden_dim, dim)
self.audio_embed = AudioEmbedding(latent_dim, dim)
self.rotary_embed = Rotary(dim_head)
self.transformer_blocks = nn.ModuleList(
[
DoubleBlock(
dim=dim, heads=heads, dim_head=dim_head, ff_mult=ff_mult, attn_mask_enabled=attn_mask_enabled
)
for _ in range(num_layers)
]
)
self.single_transformer_blocks = nn.ModuleList(
[
SingleBlock(
dim=dim, heads=heads, dim_head=dim_head, ff_mult=ff_mult, attn_mask_enabled=attn_mask_enabled
)
for _ in range(num_single_layers)
]
)
self.norm_out = AdaLayerNormFinal(dim)
self.proj_out = nn.Linear(dim, latent_dim)
def project_text(self, text: torch.Tensor) -> torch.Tensor:
"""Project LLM hidden states ``[B, nt, text_hidden_dim]`` to model width."""
return self.txt_norm(self.txt_proj(text))
def clear_cache(self) -> None:
"""Drop the cached text projection. Call this when the conditioning changes."""
self.text_cond = None
self.text_uncond = None
def _embed_audio(
self,
x: torch.Tensor,
ref: torch.Tensor | None,
drop_audio_cond: bool,
mask: torch.Tensor | None,
ref_mask: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor | None, int]:
"""Embed the target latents, prepending the reference prompt when present.
Returns the ``[ref | target]`` sequence, its padding mask and the
reference length, which the caller uses to slice the target back out.
"""
if ref is not None and ref.shape[1] == 0:
ref = None
target = self.audio_embed(x, mask=mask)
if ref is None:
return target, mask, 0
if drop_audio_cond:
ref = torch.zeros_like(ref)
prompt = self.audio_embed(ref, mask=ref_mask)
audio = torch.cat([prompt, target], dim=1)
prompt_len = prompt.shape[1]
audio_mask = None
if mask is not None or ref_mask is not None:
if mask is None:
mask = x.new_ones(x.shape[:2], dtype=torch.bool)
if ref_mask is None:
ref_mask = ref.new_ones(ref.shape[:2], dtype=torch.bool)
audio_mask = torch.cat([ref_mask, mask], dim=1)
return audio, audio_mask, prompt_len
def forward(
self,
x: torch.Tensor,
text: torch.Tensor,
time: torch.Tensor,
*,
mask: torch.Tensor | None = None,
c_mask: torch.Tensor | None = None,
ref: torch.Tensor | None = None,
ref_mask: torch.Tensor | None = None,
drop_audio_cond: bool = False,
drop_text: bool = False,
cfg_infer: bool = False,
cache: bool = False,
) -> torch.Tensor:
"""Predict the flow-matching velocity for the target frames of ``x``.
Args:
x: Noised target latents ``[B, n, latent_dim]``.
text: Pre-encoded text hidden states ``[B, nt, text_hidden_dim]``.
time: Flow-matching timestep, a scalar or ``[B]``.
mask: Target padding mask ``[B, n]``, ``True`` where valid.
c_mask: Text padding mask ``[B, nt]``. Inferred from all-zero text
rows when omitted.
ref: Reference prompt latents ``[B, np, latent_dim]``, prepended to
the audio sequence. A zero-length ``ref`` counts as absent.
ref_mask: Reference padding mask ``[B, np]``.
drop_audio_cond: Zero the reference prompt, for the CFG uncond branch.
drop_text: Zero the projected text, for the CFG uncond branch.
cfg_infer: Run the cond and uncond branches as one batch of ``2B``,
cond first. ``drop_audio_cond`` and ``drop_text`` are then
driven per branch and ignored.
cache: Reuse the projected text across calls, for an ODE loop over
fixed conditioning. Only the ``cfg_infer`` path caches, as in
the reference. Call :meth:`clear_cache` when the text changes.
Returns:
Velocity ``[B, n, latent_dim]``, or ``[2B, n, latent_dim]`` under
``cfg_infer``.
"""
batch = x.shape[0]
if time.ndim == 0:
time = time.repeat(batch)
t = self.time_embed(time)
if c_mask is None:
# Padding rows are all-zero in the text encoder's output.
c_mask = text.abs().sum(-1) > 0
if cfg_infer:
if cache and self.text_cond is not None:
c_cond, c_uncond = self.text_cond, self.text_uncond
else:
c_cond = self.project_text(text)
# The uncond branch drops the text, which is exactly a zeroed projection.
c_uncond = torch.zeros_like(c_cond)
if cache:
self.text_cond, self.text_uncond = c_cond, c_uncond
x_cond, mask_cond, prompt_len = self._embed_audio(x, ref, False, mask, ref_mask)
x_uncond, mask_uncond, _ = self._embed_audio(x, ref, True, mask, ref_mask)
x = torch.cat((x_cond, x_uncond), dim=0)
c = torch.cat((c_cond, c_uncond), dim=0)
t = torch.cat((t, t), dim=0)
c_mask = torch.cat((c_mask, c_mask), dim=0)
audio_mask = None
if mask_cond is not None and mask_uncond is not None:
audio_mask = torch.cat((mask_cond, mask_uncond), dim=0)
else:
c = self.project_text(text)
if drop_text:
c = torch.zeros_like(c)
x, audio_mask, prompt_len = self._embed_audio(x, ref, drop_audio_cond, mask, ref_mask)
seq_len = x.shape[1]
text_len = c.shape[1]
rope_audio = self.rotary_embed(seq_len)
rope_text = self.rotary_embed(text_len)
for block in self.transformer_blocks:
c, x = block(x, c, t, mask=audio_mask, rope=rope_audio, c_rope=rope_text, c_mask=c_mask)
x = torch.cat([c, x], dim=1)
rope = self.rotary_embed(text_len + seq_len)
single_mask = None if audio_mask is None else torch.cat([c_mask, audio_mask], dim=1)
for block in self.single_transformer_blocks:
x = block(x, t, mask=single_mask, rope=rope)
x = x[:, text_len + prompt_len :]
return self.proj_out(self.norm_out(x, t))
def dit_state_dict(
checkpoint: Mapping[str, torch.Tensor] | Iterable[tuple[str, torch.Tensor]],
prefix: str = "transformer.",
) -> dict[str, torch.Tensor]:
"""Select the DiT tensors out of a full AuK checkpoint and strip ``prefix``.
Released checkpoints wrap the backbone under ``transformer.`` alongside the
text-encoder layer-fusion parameters, which this module does not own.
"""
items = checkpoint.items() if isinstance(checkpoint, Mapping) else checkpoint
return {name[len(prefix) :]: tensor for name, tensor in items if name.startswith(prefix)}
@torch.no_grad()
def sample_latents(
dit: AuKTransformer,
*,
text: torch.Tensor,
c_mask: torch.Tensor | None,
ref: torch.Tensor,
ref_mask: torch.Tensor | None,
gen_frames: int,
nfe: int = 32,
cfg_strength: float = 1.0,
sway_sampling_coef: float | None = None,
t_grid: list[float] | None = None,
seed: int | None = None,
generator: torch.Generator | None = None,
latent_dim: int | None = None,
device: torch.device | str | None = None,
dtype: torch.dtype | None = None,
) -> torch.Tensor:
"""Integrate the flow from noise to audio latents with explicit Euler steps.
Single-request only: the batch dimension carries the CFG branches, not
separate prompts, so no target padding mask is needed.
Args:
dit: The velocity model.
text: Pre-encoded text hidden states ``[1, nt, text_hidden_dim]``.
c_mask: Text padding mask ``[1, nt]``.
ref: Reference prompt latents ``[1, np, latent_dim]``.
ref_mask: Reference padding mask ``[1, np]``.
gen_frames: Target latent frames to generate.
nfe: Euler steps, ignored when ``t_grid`` is given.
cfg_strength: Classifier-free guidance weight. Below ``1e-5`` the
uncond branch is skipped entirely.
sway_sampling_coef: Reshapes the uniform time grid towards ``t=0``.
t_grid: Explicit timesteps, overriding ``nfe`` and the sway reshape.
seed: Seeds the global RNG before drawing the noise. Ignored when
``generator`` is given.
generator: Draws the initial noise from its own RNG, leaving the global
one untouched.
latent_dim: Latent channels; defaults to the model's.
device: Device for the noise; defaults to the reference's.
dtype: Dtype for the noise and the Euler accumulator; defaults to the
reference's, which is the reference implementation's rule. Pass
``torch.float32`` explicitly when serving half-precision weights.
Drawing the noise at bf16 instead of fp32 moves a 32-step CFG
trajectory by 0.025 relative MSE, roughly 17 times what bf16
weights themselves cost, because the draw consumes the generator
differently and starts the ODE somewhere else. Keeping it fp32
costs a few tens of KB and no measurable time.
Returns:
The target latents at ``t=1``, ``[1, gen_frames, latent_dim]``.
"""
device = torch.device(device) if device is not None else ref.device
dtype = dtype if dtype is not None else ref.dtype
latent_dim = latent_dim if latent_dim is not None else dit.latent_dim
if generator is None:
if seed is not None:
torch.manual_seed(seed)
x = torch.randn(gen_frames, latent_dim, device=device, dtype=dtype).unsqueeze(0)
else:
x = (
torch.randn(gen_frames, latent_dim, generator=generator, device=generator.device, dtype=dtype)
.to(device)
.unsqueeze(0)
)
if t_grid is not None:
t = torch.tensor(t_grid, device=device, dtype=torch.float32)
else:
t = torch.linspace(0, 1, nfe + 1, device=device, dtype=torch.float32)
if sway_sampling_coef is not None:
t = t + sway_sampling_coef * (torch.cos(math.pi / 2 * t) - 1 + t)
guided = cfg_strength >= 1e-5
if t.numel() < 2 or not bool(torch.all(t[1:] > t[:-1])):
raise ValueError(
f"AuK sampling needs a strictly increasing time grid with at least two points; got {t.tolist()}"
)
try:
for i in range(t.shape[0] - 1):
if guided:
pred = dit(
x,
text,
t[i],
c_mask=c_mask,
ref=ref,
ref_mask=ref_mask,
cfg_infer=True,
cache=True,
)
v_cond, v_uncond = pred.chunk(2, dim=0)
v = v_cond + (v_cond - v_uncond) * cfg_strength
else:
v = dit(x, text, t[i], c_mask=c_mask, ref=ref, ref_mask=ref_mask)
x = x + (t[i + 1] - t[i]) * v
finally:
# The cached text projections belong to this request only; a failed
# step must not leak them into the next one.
dit.clear_cache()
return x
+505
View File
@@ -0,0 +1,505 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
#
# Adapted from the AuK reference release (MIT), which in turn adapts NVIDIA
# BigVGAN (MIT), jik876/hifi-gan (MIT), junjun3518/alias-free-torch
# (Apache-2.0), EdwardDixon/snake (MIT) and adefossez/julius (MIT).
"""BigVGAN-flow VAE for AuK: 24 kHz mono waveform <-> 50 Hz, 64-channel latents.
Inference only. The reference module also carries a residual coupling flow, a KL
term and a discriminator; all three are training-only, so the released
``flow.*`` tensors are skipped (see :meth:`AuKVAE.load_weights`).
Parameter and buffer names follow the reference release, so the published
``vae.safetensors`` loads without a key map. That is also why the convolutions
are built with the legacy ``weight_norm`` parametrization (``weight_g`` /
``weight_v``): :meth:`remove_weight_norm` folds them into plain weights once
the checkpoint is in.
"""
from __future__ import annotations
import inspect
import math
import warnings
from pathlib import Path
import torch
import torch.nn.functional as F
from safetensors.torch import load_file
from torch import nn
from torch.nn.utils import remove_weight_norm as _fold_weight_norm
from torch.nn.utils import weight_norm as _apply_weight_norm
from vllm.logger import init_logger
logger = init_logger(__name__)
__all__ = ["AuKVAE"]
# Checkpoint prefix owned by the training-only coupling flow.
TRAINING_ONLY_PREFIX = "flow."
def _weight_norm(module: nn.Module) -> nn.Module:
"""Legacy ``weight_g``/``weight_v`` split, which is how the release stores these tensors."""
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message=".*weight_norm.*deprecated.*", category=FutureWarning)
return _apply_weight_norm(module)
def _same_padding(kernel_size: int, dilation: int = 1) -> int:
return int((kernel_size * dilation - dilation) / 2)
def _kaiser_sinc_filter(cutoff: float, half_width: float, kernel_size: int) -> torch.Tensor:
"""Kaiser-windowed sinc low-pass, returned as a ``[1, 1, kernel_size]`` conv kernel."""
half_size = kernel_size // 2
attenuation = 2.285 * (half_size - 1) * math.pi * (4 * half_width) + 7.95
if attenuation > 50.0:
beta = 0.1102 * (attenuation - 8.7)
elif attenuation >= 21.0:
beta = 0.5842 * (attenuation - 21.0) ** 0.4 + 0.07886 * (attenuation - 21.0)
else:
beta = 0.0
window = torch.kaiser_window(kernel_size, beta=beta, periodic=False)
if kernel_size % 2 == 0:
time = torch.arange(-half_size, half_size) + 0.5
else:
time = torch.arange(kernel_size) - half_size
if cutoff == 0:
return torch.zeros_like(time).view(1, 1, kernel_size)
taps = 2 * cutoff * window * torch.sinc(2 * cutoff * time)
# Normalize to unit sum so a constant input passes through unscaled.
return (taps / taps.sum()).view(1, 1, kernel_size)
class Conv(nn.Conv1d):
"""1-D convolution over ``[B, C, T]``; ``causal`` swaps centred padding for a left pad."""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int = 1,
stride: int = 1,
dilation: int = 1,
bias: bool = True,
causal: bool = False,
) -> None:
super().__init__(
in_channels,
out_channels,
kernel_size,
stride=stride,
padding=0 if causal else _same_padding(kernel_size, dilation),
dilation=dilation,
bias=bias,
)
self.causal = causal
self.left_padding = dilation * (kernel_size - 1) if causal else 0
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.causal:
x = F.pad(x, (self.left_padding, 0))
return super().forward(x)
class ConvTranspose(nn.ConvTranspose1d):
"""Transposed 1-D convolution; ``causal`` drops the trailing ``stride`` samples instead of padding."""
def __init__(
self, in_channels: int, out_channels: int, kernel_size: int, stride: int, causal: bool = False
) -> None:
if causal and kernel_size != 2 * stride:
raise ValueError(f"causal ConvTranspose needs kernel_size == 2 * stride, got {kernel_size} and {stride}")
super().__init__(
in_channels,
out_channels,
kernel_size,
stride=stride,
padding=0 if causal else (kernel_size - stride) // 2,
)
self.causal = causal
self.trim = stride
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = super().forward(x)
return x[:, :, : -self.trim] if self.causal else x
class NormConv(nn.Module):
"""Weight-normalized conv held under ``layer``; the attribute name is load-bearing for the checkpoint."""
def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 1, stride: int = 1) -> None:
super().__init__()
self.layer = _weight_norm(
nn.Conv1d(in_channels, out_channels, kernel_size, stride=stride, padding=(kernel_size - 1) // 2)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.layer(x)
class ResStack(nn.Module):
"""Stack of dilated residual conv pairs. The leaky slope is torch's 0.01 default, as upstream."""
def __init__(self, channels: int, kernel_size: int = 3, base: int = 3, nums: int = 4) -> None:
super().__init__()
self.layers = nn.ModuleList(
[
nn.Sequential(
nn.LeakyReLU(),
_weight_norm(nn.Conv1d(channels, channels, kernel_size, dilation=base**i, padding=base**i)),
nn.LeakyReLU(),
_weight_norm(nn.Conv1d(channels, channels, kernel_size, dilation=1, padding=1)),
)
for i in range(nums)
]
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
for layer in self.layers:
x = x + layer(x)
return x
class Encoder(nn.Module):
"""Strided conv encoder over ``[B, 1, T]``, emitting ``[B, 2 * latent_dim, T / hop]`` mean/log-std pairs."""
def __init__(
self,
latent_dim: int,
channels: tuple[int, ...],
down_sample_factors: tuple[int, ...],
in_channels: int = 1,
proj_kernel_size: int = 3,
stack_kernel_size: int = 3,
stack_dilation_base: int = 2,
stacks: int = 6,
) -> None:
super().__init__()
layers: list[nn.Module] = [
NormConv(in_channels, channels[0], kernel_size=proj_kernel_size),
nn.LeakyReLU(0.2, True),
]
for in_c, out_c, factor in zip(channels[:-1], channels[1:], down_sample_factors, strict=True):
layers += [
NormConv(in_c, out_c, kernel_size=factor * 2, stride=factor),
ResStack(out_c, stack_kernel_size, stack_dilation_base, stacks),
nn.LeakyReLU(0.2, True),
]
layers.append(NormConv(channels[-1], latent_dim * 2, kernel_size=proj_kernel_size))
self.generator = nn.Sequential(*layers)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.generator(x)
class SnakeBeta(nn.Module):
"""``x + sin^2(alpha * x) / beta`` with per-channel learned alpha and beta (log-scale in AuK)."""
def __init__(self, channels: int, alpha_logscale: bool = False) -> None:
super().__init__()
self.alpha_logscale = alpha_logscale
init = torch.zeros(channels) if alpha_logscale else torch.ones(channels)
self.alpha = nn.Parameter(init.clone())
self.beta = nn.Parameter(init.clone())
self.eps = 1e-9
def forward(self, x: torch.Tensor) -> torch.Tensor:
alpha = self.alpha.unsqueeze(0).unsqueeze(-1)
beta = self.beta.unsqueeze(0).unsqueeze(-1)
if self.alpha_logscale:
alpha = torch.exp(alpha)
beta = torch.exp(beta)
return x + (1.0 / (beta + self.eps)) * torch.sin(x * alpha).pow(2)
class LowPass(nn.Module):
"""Fixed FIR low-pass with replicate padding, applied per channel."""
def __init__(
self,
cutoff: float = 0.5,
half_width: float = 0.6,
stride: int = 1,
kernel_size: int = 12,
causal: bool = False,
) -> None:
super().__init__()
if not 0.0 <= cutoff <= 0.5:
raise ValueError(f"cutoff must lie in [0, 0.5], got {cutoff}")
if causal:
self.pad_left, self.pad_right = kernel_size - 1, 0
else:
even = kernel_size % 2 == 0
self.pad_left = kernel_size // 2 - int(even)
self.pad_right = kernel_size // 2
self.stride = stride
self.register_buffer("filter", _kaiser_sinc_filter(cutoff, half_width, kernel_size))
def forward(self, x: torch.Tensor) -> torch.Tensor:
channels = x.size(1)
x = F.pad(x, (self.pad_left, self.pad_right), mode="replicate")
return F.conv1d(x, self.filter.expand(channels, -1, -1), stride=self.stride, groups=channels)
class Upsample(nn.Module):
"""Band-limited interpolation by ``ratio``. Always non-causal, matching how AuK builds it."""
def __init__(self, ratio: int = 2, kernel_size: int = 12) -> None:
super().__init__()
self.ratio = ratio
self.pad = kernel_size // ratio - 1
self.pad_left = self.pad * ratio + (kernel_size - ratio) // 2
self.pad_right = self.pad * ratio + (kernel_size - ratio + 1) // 2
self.register_buffer("filter", _kaiser_sinc_filter(0.5 / ratio, 0.6 / ratio, kernel_size))
def forward(self, x: torch.Tensor) -> torch.Tensor:
channels = x.size(1)
x = F.pad(x, (self.pad, self.pad), mode="replicate")
x = self.ratio * F.conv_transpose1d(x, self.filter.expand(channels, -1, -1), stride=self.ratio, groups=channels)
return x[..., self.pad_left : -self.pad_right]
class Downsample(nn.Module):
"""Decimation by ``ratio`` behind a low-pass; ``lowpass`` holds the filter buffer."""
def __init__(self, ratio: int = 2, kernel_size: int = 12, causal: bool = False) -> None:
super().__init__()
self.lowpass = LowPass(
cutoff=0.5 / ratio, half_width=0.6 / ratio, stride=ratio, kernel_size=kernel_size, causal=causal
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.lowpass(x)
class AliasFreeActivation(nn.Module):
"""Oversample, apply the pointwise activation, decimate, so snake harmonics do not fold back."""
def __init__(
self,
activation: nn.Module,
up_ratio: int = 2,
down_ratio: int = 2,
up_kernel_size: int = 12,
down_kernel_size: int = 12,
causal: bool = False,
) -> None:
super().__init__()
self.act = activation
self.upsample = Upsample(up_ratio, up_kernel_size)
self.downsample = Downsample(down_ratio, down_kernel_size, causal=causal)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.downsample(self.act(self.upsample(x)))
class AmpBlock(nn.Module):
"""Anti-aliased multi-periodicity residual block: alternating alias-free snake and dilated convs."""
def __init__(
self,
channels: int,
kernel_size: int,
dilations: tuple[int, ...],
snake_logscale: bool = True,
causal: bool = True,
act_causal: bool = False,
) -> None:
super().__init__()
self.convs1 = nn.ModuleList(
[_weight_norm(Conv(channels, channels, kernel_size, 1, dilation=d, causal=causal)) for d in dilations]
)
self.convs2 = nn.ModuleList(
[_weight_norm(Conv(channels, channels, kernel_size, 1, dilation=1, causal=causal)) for _ in dilations]
)
self.activations = nn.ModuleList(
[
AliasFreeActivation(SnakeBeta(channels, alpha_logscale=snake_logscale), causal=act_causal)
for _ in range(len(self.convs1) + len(self.convs2))
]
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
acts1, acts2 = self.activations[::2], self.activations[1::2]
for conv1, conv2, act1, act2 in zip(self.convs1, self.convs2, acts1, acts2, strict=True):
x = conv2(act2(conv1(act1(x)))) + x
return x
class AuKVAE(nn.Module):
"""AuK's audio codec: :meth:`encode` waveform to normalized latents, :meth:`decode` back.
Build from the released ``model.vae.model_init_kwargs`` with :meth:`from_config`, then
:meth:`load_weights`. Latents are normalized by the checkpoint's global statistics, which is
the space the rectified-flow transformer works in.
"""
def __init__(
self,
*,
upsample_rates: tuple[int, ...] = (5, 4, 3, 2, 2, 2),
upsample_kernel_sizes: tuple[int, ...] = (10, 8, 6, 4, 4, 4),
upsample_initial_channel: int = 1536,
resblock_kernel_sizes: tuple[int, ...] = (3, 7, 11),
resblock_dilation_sizes: tuple[tuple[int, ...], ...] = ((1, 3, 5), (1, 3, 5), (1, 3, 5)),
downsample_rates: tuple[int, ...] = (2, 2, 2, 3, 4, 5),
downsample_channels: tuple[int, ...] = (12, 24, 48, 96, 192, 384, 768),
snake_logscale: bool = True,
latent_dim: int = 64,
use_vae: bool = True,
causal: bool = True,
act_causal: bool = True,
sample_rate: int = 24000,
) -> None:
super().__init__()
if not use_vae:
raise ValueError("AuKVAE requires use_vae=True: the encoder head emits mean/log-std pairs")
self.latent_dim = latent_dim
self.sample_rate = sample_rate
self.hop_size = math.prod(downsample_rates)
self.num_kernels = len(resblock_kernel_sizes)
self.num_upsamples = len(upsample_rates)
self._norm_folded = False
self.register_buffer("global_mean", torch.zeros(latent_dim, dtype=torch.float32))
self.register_buffer("global_log_std", torch.ones(latent_dim, dtype=torch.float32))
self.audio_encoder = Encoder(
latent_dim=latent_dim,
channels=tuple(downsample_channels),
down_sample_factors=tuple(downsample_rates),
)
self.conv_pre = _weight_norm(Conv(latent_dim, upsample_initial_channel, 7, 1, causal=False))
self.ups = nn.ModuleList()
for i, (rate, kernel) in enumerate(zip(upsample_rates, upsample_kernel_sizes, strict=True)):
# One-element inner list: the checkpoint keys are ``ups.<i>.0.*``.
self.ups.append(
nn.ModuleList(
[
_weight_norm(
ConvTranspose(
upsample_initial_channel // (2**i),
upsample_initial_channel // (2 ** (i + 1)),
kernel,
rate,
causal=causal,
)
)
]
)
)
self.resblocks = nn.ModuleList()
channels = upsample_initial_channel
for i in range(self.num_upsamples):
channels = upsample_initial_channel // (2 ** (i + 1))
for kernel, dilations in zip(resblock_kernel_sizes, resblock_dilation_sizes, strict=True):
self.resblocks.append(
AmpBlock(
channels,
kernel,
tuple(dilations),
snake_logscale=snake_logscale,
causal=causal,
act_causal=act_causal,
)
)
self.activation_post = AliasFreeActivation(
SnakeBeta(channels, alpha_logscale=snake_logscale), causal=act_causal
)
self.conv_post = _weight_norm(Conv(channels, 1, 7, 1, causal=causal, bias=False))
@classmethod
def from_config(cls, cfg: dict) -> AuKVAE:
"""Build from the released ``model_init_kwargs`` mapping, ignoring training-only entries."""
accepted = set(inspect.signature(cls.__init__).parameters) - {"self"}
return cls(**{key: value for key, value in cfg.items() if key in accepted})
def load_weights(
self, path: str | Path, *, device: str | torch.device | None = None, fold_weight_norm: bool = True
) -> tuple[list[str], list[str]]:
"""Load a released ``vae.safetensors``, then fold weight norm away. Returns (missing, unexpected).
``device`` defaults to where the module already lives, which is the placement that matters:
the fold reduces ``weight_v`` to a norm, and a CPU reduction lands up to one ULP away from the
accelerator's. The encoder amplifies its activations roughly fiftyfold, so that one ULP grows
into a ~4e-4 relative drift by the latent head. Move the module first, then load.
"""
target = self.global_mean.device if device is None else torch.device(device)
missing, unexpected = self.load_state_dict(load_file(str(path), device=str(target)), strict=False)
missing, unexpected = list(missing), list(unexpected)
stray = [key for key in missing + unexpected if not key.startswith(TRAINING_ONLY_PREFIX)]
if stray:
raise ValueError(f"AuK VAE weights at {path} do not match this module: {sorted(stray)[:8]}")
logger.info(
"Loaded AuK VAE from %s (skipped %d training-only %s* tensors)", path, len(unexpected), TRAINING_ONLY_PREFIX
)
if fold_weight_norm:
self.remove_weight_norm()
return missing, unexpected
def remove_weight_norm(self) -> None:
"""Fold ``weight_g``/``weight_v`` into plain weights, on whichever device the module is on.
Idempotent, and meant to run once the checkpoint is in. See :meth:`load_weights` for why the
device this runs on is a numeric decision rather than a convenience.
"""
if self._norm_folded:
return
folded = 0
for module in self.modules():
if hasattr(module, "weight_g"):
_fold_weight_norm(module)
folded += 1
self._norm_folded = True
logger.debug("Folded weight norm on %d AuK VAE convolutions", folded)
def encode(
self, wav: torch.Tensor, *, sample: bool = False, generator: torch.Generator | None = None
) -> torch.Tensor:
"""Encode a mono ``[1, T]`` waveform at :attr:`sample_rate` into ``[1, T / hop_size, latent_dim]``.
``sample=False`` takes the posterior mean, which is what a reproducible pipeline wants;
``sample=True`` draws ``mean + randn * exp(log_std)`` from ``generator``. Latents come back
normalized by the checkpoint's global statistics.
"""
if wav.dim() != 2 or wav.size(0) != 1:
raise ValueError(f"encode expects a mono [1, T] waveform, got {tuple(wav.shape)}")
# Statistics stay in fp32 even under an ambient autocast, as in the reference.
with torch.autocast(device_type=wav.device.type, enabled=False):
mean, log_std = self.audio_encoder(wav.unsqueeze(1)).chunk(2, dim=1)
if sample:
latents = mean + self._noise_like(mean, generator) * torch.exp(log_std)
else:
latents = mean
latents = latents.transpose(1, 2).float()
return (latents - self.global_mean.float()) / torch.sqrt(self.global_log_std.float())
def decode(self, latents: torch.Tensor) -> torch.Tensor:
"""Decode normalized ``[B, Np, latent_dim]`` latents into a ``[B, Np * hop_size]`` waveform in [-1, 1]."""
if latents.dim() != 3 or latents.size(-1) != self.latent_dim:
raise ValueError(f"decode expects [B, Np, {self.latent_dim}] latents, got {tuple(latents.shape)}")
x = latents.float() * torch.sqrt(self.global_log_std.float()) + self.global_mean.float()
x = self.conv_pre(x.permute(0, 2, 1))
for i in range(self.num_upsamples):
for up in self.ups[i]:
x = up(x)
first = i * self.num_kernels
residual = self.resblocks[first](x)
for j in range(1, self.num_kernels):
residual = residual + self.resblocks[first + j](x)
x = residual / self.num_kernels
x = self.conv_post(self.activation_post(x))
return torch.clamp(x, min=-1.0, max=1.0).squeeze(1)
@staticmethod
def _noise_like(reference: torch.Tensor, generator: torch.Generator | None) -> torch.Tensor:
"""Draw standard normal noise shaped like ``reference``; ``generator`` decides which RNG stream."""
device = reference.device if generator is None else generator.device
noise = torch.randn(reference.shape, generator=generator, dtype=reference.dtype, device=device)
return noise.to(reference.device)
@@ -0,0 +1,486 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""AuK audio-editing pipeline for vLLM-Omni.
Turns a layer-fused text condition (produced by the encoder stage) plus an
optional source clip into a 24 kHz waveform: the source clip is encoded to VAE
latents, a rectified-flow DiT integrates the target latents conditioned on
both, and the BigVGAN-flow decoder renders the waveform.
"""
from __future__ import annotations
import json
import os
from collections.abc import Iterable
from typing import Any, ClassVar
import numpy as np
import torch
import torchaudio
from safetensors import safe_open
from torch import nn
from vllm.logger import init_logger
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.models.auk.auk_transformer import AuKTransformer, dit_state_dict, sample_latents
from vllm_omni.diffusion.models.auk.auk_vae import AuKVAE
from vllm_omni.diffusion.models.interface import (
SupportAudioInput,
SupportAudioOutput,
SupportsComponentDiscovery,
)
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
from vllm_omni.model_extras.auk import resolve_gen_frames
logger = init_logger(__name__)
# Longest ref + target latent sequence the released checkpoints accept.
MAX_LATENT_FRAMES = 65536
# Weight-file layout: the DiT lives under this prefix; the layer-fusion
# parameters sit next to it but belong to the encoder stage.
_DIT_PREFIX = "transformer."
_FUSION_KEYS = frozenset({"layer_weights", "layer_scale"})
# The distilled variant only reproduces its training recipe at these settings.
_FLASH_NFE = 4
_FLASH_CFG = 0.0
# Decorrelates the VAE posterior draw from the initial latent for the same request seed.
_VAE_SEED_OFFSET = 0x5EED_0A0C
def get_auk_post_process_func(od_config: OmniDiffusionConfig):
"""Create the post-processing function for AuK audio output.
Tensor output types pass through; anything else becomes a numpy waveform.
The sample rate is not attached here: the output formatter reads
``AuKPipeline.audio_sample_rate`` for audio-output pipelines.
"""
del od_config # The conversion does not depend on the config.
def post_process_func(
audio: torch.Tensor,
output_type: str = "np",
):
if output_type in ("pt", "latent"):
return audio
return audio.cpu().float().numpy()
return post_process_func
def _prompt_mapping(prompt: Any) -> dict[str, Any]:
"""Return the prompt dict, or an empty mapping for a bare text prompt."""
if isinstance(prompt, dict):
return prompt
return {}
def _unwrap_single(value: Any) -> Any:
"""Unwrap the one-element lists the serving layer sometimes produces."""
if isinstance(value, list) and len(value) == 1:
return value[0]
return value
def _split_audio(audio: Any, default_sample_rate: int) -> tuple[Any, int]:
"""Split a multimodal audio item into raw samples and a sample rate."""
if isinstance(audio, (tuple, list)) and len(audio) == 2 and isinstance(audio[1], (int, float)):
return audio[0], int(audio[1])
return audio, default_sample_rate
class AuKPipeline(nn.Module, SupportAudioInput, SupportAudioOutput, SupportsComponentDiscovery):
"""Instruction-driven audio generation and editing with AuK.
One request per forward: the rectified-flow ODE runs over the whole target
span and the batch dimension carries the CFG branches, so there is nothing
to share between requests yet.
Args:
od_config: OmniDiffusion configuration. ``od_config.model`` must be an
assembled AuK directory (``config.json``, ``auk.safetensors``,
``vae.safetensors``), as produced by
``tools/prepare_auk_checkpoint.py``.
prefix: Unused; kept for the pipeline construction contract.
"""
supports_request_batch = False
# Picked up by ``supports_audio_output`` in the diffusion engine so the
# default stage metadata reports ``final_output_type="audio"`` and the
# ``multimodal_output`` payload includes the sample rate.
support_audio_output: ClassVar[bool] = True
support_audio_input: ClassVar[bool] = True
audio_sample_rate: ClassVar[int] = 24000
# The DiT cannot run without an encoder-stage text condition, which the
# engine's synthetic warmup request has no way to produce.
dummy_run_num_frames: ClassVar[int] = 0
_dit_modules: ClassVar[list[str]] = ["dit"]
_encoder_modules: ClassVar[list[str]] = []
_vae_modules: ClassVar[list[str]] = ["vae"]
def __init__(
self,
*,
od_config: OmniDiffusionConfig,
prefix: str = "",
) -> None:
super().__init__()
del prefix # Weights are not namespaced: one checkpoint, one pipeline.
self.od_config = od_config
self.device = get_local_device()
self.dtype = getattr(od_config, "dtype", None) or torch.bfloat16
model_dir = od_config.model
if not model_dir or not os.path.isdir(model_dir):
raise ValueError(
f"AuK needs an assembled local checkpoint directory, got {model_dir!r}. "
"Build one with tools/prepare_auk_checkpoint.py."
)
config = _read_config(model_dir)
vae_config = dict(config["vae"])
self.latent_dim = int(vae_config["latent_dim"])
self.hop_size = int(vae_config["downsample_rate"])
self.sample_rate = int(vae_config["target_sample_rate"])
self.variant = str(config.get("variant", "base"))
self.is_flash = self.variant == "flash"
self.flash_t_grid = [float(t) for t in config.get("flash_t_grid") or ()]
if self.is_flash and len(self.flash_t_grid) != _FLASH_NFE + 1:
raise ValueError(f"The flash variant needs a {_FLASH_NFE + 1}-point flash_t_grid, got {self.flash_t_grid}.")
defaults = dict(config.get("defaults") or {})
self.default_nfe = int(defaults.get("nfe", 32))
self.default_cfg = float(defaults.get("cfg", 2.0))
self.default_sway = defaults.get("sway", -1.0)
self._flash_lock_logged = False
# The codec is small and numerically sensitive: it stays in fp32. It
# must sit on the inference device BEFORE load_weights folds weight
# norm: a CPU fold lands one ULP off the accelerator's and the encoder
# amplifies that into a 1e-2 latent drift.
self.vae = AuKVAE.from_config(vae_config["model_init_kwargs"]).to(device=self.device, dtype=torch.float32)
self.vae.load_weights(os.path.join(model_dir, "vae.safetensors"))
self.vae = self.vae.eval()
self.vae.requires_grad_(False)
self._check_vae_geometry()
# The transformer owns every key the checkpoint tool writes into `dit`,
# `attn_mask_enabled` included, so the section passes straight through.
self.dit = AuKTransformer(latent_dim=self.latent_dim, **config["dit"])
self.dit = self.dit.to(dtype=self.dtype)
self.dit.load_state_dict(_read_dit_weights(model_dir, self.dtype), strict=True)
self.dit = self.dit.to(device=self.device).eval()
self.dit.requires_grad_(False)
logger.info(
"AuK pipeline ready: variant=%s dtype=%s latent_dim=%d hop=%d sample_rate=%d",
self.variant,
self.dtype,
self.latent_dim,
self.hop_size,
self.sample_rate,
)
# The assembled checkpoint is not a diffusers layout: __init__ reads
# auk.safetensors and vae.safetensors directly, so the loader has no
# component sources to stream and load_weights only reports what is loaded.
weights_sources: ClassVar[tuple] = ()
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
stray = [name for name, _ in weights]
if stray:
logger.warning("AuKPipeline ignores %d loader-provided weights (e.g. %s)", len(stray), stray[:3])
return {name for name, _ in self.named_parameters()}
def _check_vae_geometry(self) -> None:
"""Fail fast when config.json and the VAE disagree on latent geometry."""
declared = {
"latent_dim": (self.latent_dim, int(self.vae.latent_dim)),
"downsample_rate": (self.hop_size, int(self.vae.hop_size)),
"target_sample_rate": (self.sample_rate, int(self.vae.sample_rate)),
}
bad = {name: pair for name, pair in declared.items() if pair[0] != pair[1]}
if bad:
raise ValueError(f"config.json and the AuK VAE disagree (config, vae): {bad}")
if self.sample_rate != self.audio_sample_rate:
raise ValueError(
f"AuK advertises {self.audio_sample_rate} Hz output but the checkpoint is {self.sample_rate} Hz."
)
def _resolve_generator(self, sampling_params: Any) -> torch.Generator | None:
"""Per-request generator; the process-global RNG is never seeded."""
generator = sampling_params.generator
if isinstance(generator, list):
if len(generator) > 1:
logger.warning(
"AuKPipeline runs one request per forward; using the first of %d generators", len(generator)
)
generator = generator[0] if generator else None
if generator is None and sampling_params.seed is not None:
generator = torch.Generator(device=self.device).manual_seed(int(sampling_params.seed))
return generator
def _prepare_waveform(self, audio: Any) -> torch.Tensor:
"""Return mono float32 samples ``[1, T]`` at the VAE sample rate.
``T`` is truncated to a whole number of latent frames. The encoder is
causal, so dropping a trailing partial frame leaves every emitted frame
unchanged.
"""
data, sample_rate = _split_audio(audio, self.sample_rate)
if isinstance(data, np.ndarray):
wav = torch.from_numpy(np.ascontiguousarray(data))
else:
wav = torch.as_tensor(data)
wav = wav.detach().to(device="cpu", dtype=torch.float32)
if wav.ndim == 1:
wav = wav.unsqueeze(0)
elif wav.ndim == 2:
# Accept both [channels, samples] and soundfile's [samples, channels];
# the channel axis is the short one (at most 8 wide).
if wav.shape[0] > wav.shape[1] and wav.shape[1] <= 8:
wav = wav.transpose(0, 1)
if wav.shape[0] > 1:
wav = wav.mean(dim=0, keepdim=True)
else:
raise ValueError(f"AuK audio input must be [samples] or [channels, samples], got {tuple(wav.shape)}.")
if wav.shape[-1] == 0:
raise ValueError("AuK audio input is empty.")
if not torch.isfinite(wav).all():
raise ValueError("AuK audio input contains NaN or Inf.")
if sample_rate != self.sample_rate:
wav = torchaudio.functional.resample(wav, sample_rate, self.sample_rate)
frames = wav.shape[-1] // self.hop_size
if frames < 1:
raise ValueError(
f"AuK audio input is shorter than one latent frame ({self.hop_size} samples at {self.sample_rate} Hz)."
)
return wav[..., : frames * self.hop_size]
def _encode_source(
self,
audio: Any,
*,
sample: bool,
generator: torch.Generator | None,
) -> torch.Tensor:
"""Encode the source clip to normalized latents ``[1, np, latent_dim]``."""
if audio is None:
return torch.zeros(1, 0, self.latent_dim, device=self.device, dtype=torch.float32)
wav = self._prepare_waveform(_unwrap_single(audio)).to(self.device)
return self.vae.encode(wav, sample=sample, generator=generator)
def _target_frames(self, gen_seconds: Any, ref_frames: int) -> int:
"""Target latent length, capped by the remaining context."""
frames = resolve_gen_frames(
None if gen_seconds is None else float(gen_seconds),
ref_frames,
sample_rate=self.sample_rate,
hop=self.hop_size,
)
budget = MAX_LATENT_FRAMES - ref_frames
if budget < 1:
raise ValueError(
f"The source clip already fills the {MAX_LATENT_FRAMES}-frame context ({ref_frames} frames)."
)
if frames > budget:
logger.warning("AuK target of %d frames exceeds the remaining context; clamping to %d.", frames, budget)
frames = budget
return frames
def _resolve_schedule(
self,
sampling_params: Any,
knobs: dict[str, Any],
) -> tuple[int, float, float | None, list[float] | None]:
"""Resolve (nfe, cfg, sway, t_grid), locking the distilled recipe on Flash.
A knob present but ``None`` counts as unspecified: the stage input
processor fills every key it knows about, whether the caller set it or
not.
"""
steps = sampling_params.num_inference_steps
nfe = self.default_nfe if steps is None else int(steps)
if nfe < 1:
raise ValueError(f"num_inference_steps must be >= 1 for AuK; got {steps}")
cfg = float(sampling_params.guidance_scale) if sampling_params.guidance_scale_provided else self.default_cfg
sway = knobs.get("sway")
sway = self.default_sway if sway is None else float(sway)
raw_grid = knobs.get("t_grid")
t_grid = [float(t) for t in raw_grid] if raw_grid else None
if not self.is_flash:
return nfe, cfg, sway, t_grid
locked = (_FLASH_NFE, _FLASH_CFG, None, self.flash_t_grid)
if (nfe, cfg, sway, t_grid) != locked and not self._flash_lock_logged:
self._flash_lock_logged = True
logger.warning(
"AuK-Flash ignores per-request sampling knobs (asked nfe=%s cfg=%s sway=%s t_grid=%s); "
"using the distilled recipe nfe=%d cfg=%s with the checkpoint time grid.",
nfe,
cfg,
sway,
t_grid,
_FLASH_NFE,
_FLASH_CFG,
)
return locked
def _dit_autocast(self):
"""Match the reference, which runs the DiT under bf16 autocast."""
return torch.autocast(
device_type=self.device.type,
dtype=self.dtype,
enabled=self.dtype in (torch.bfloat16, torch.float16),
)
def forward(self, req: DiffusionRequestBatch) -> list[DiffusionOutput]:
"""Generate one waveform.
Args:
req: Request batch holding exactly one request. The prompt carries
``prompt_embeds`` (the fused text condition ``[nt, 2048]``), an
optional ``multi_modal_data["audio"]`` source clip, and
``additional_information["auk"]`` with ``gen_seconds``,
``sway``, ``t_grid`` and ``vae_sample``. ``num_inference_steps``,
``guidance_scale`` and ``seed``/``generator`` come from the
sampling params.
Returns:
One ``DiffusionOutput`` whose ``output`` is a float32 mono waveform
``[T]`` at 24 kHz, or the normalized target latents
``[1, gen_frames, latent_dim]`` when ``output_type`` is ``latent``.
"""
assert req.num_reqs == 1, f"AuKPipeline runs one request per forward, got {req.num_reqs}."
prompt = _prompt_mapping(req.prompts[0])
sampling_params = req.sampling_params
knobs = dict((prompt.get("additional_information") or {}).get("auk") or {})
text = _unwrap_single(prompt.get("prompt_embeds"))
if text is None:
raise ValueError("AuK stage 1 needs `prompt_embeds`, the fused text condition from the encoder stage.")
text = torch.as_tensor(text).to(device=self.device, dtype=self.dtype)
if text.ndim == 3 and text.shape[0] == 1:
text = text[0]
if text.ndim != 2:
raise ValueError(f"AuK `prompt_embeds` must be [nt, text_hidden_dim], got {tuple(text.shape)}.")
text = text.unsqueeze(0)
c_mask = torch.ones(text.shape[:2], dtype=torch.bool, device=self.device)
generator = self._resolve_generator(sampling_params)
audio = (prompt.get("multi_modal_data") or {}).get("audio")
output_type = sampling_params.output_type or "np"
with torch.inference_mode():
# The VAE posterior draw gets its own generator, seeded with a
# fixed offset from the request seed: the initial latent below then
# still equals the reference's fresh manual_seed draw, and the two
# noise streams are not copies of each other.
vae_generator = None
if knobs.get("vae_sample") and generator is not None:
vae_seed = (int(generator.initial_seed()) + _VAE_SEED_OFFSET) % (2**63)
vae_generator = torch.Generator(device=self.device).manual_seed(vae_seed)
ref = self._encode_source(audio, sample=bool(knobs.get("vae_sample")), generator=vae_generator)
ref_frames = ref.shape[1]
ref_mask = torch.ones(ref.shape[:2], dtype=torch.bool, device=self.device)
gen_frames = self._target_frames(knobs.get("gen_seconds"), ref_frames)
nfe, cfg, sway, t_grid = self._resolve_schedule(sampling_params, knobs)
with self._dit_autocast():
latents = sample_latents(
self.dit,
text=text,
c_mask=c_mask,
ref=ref,
ref_mask=ref_mask,
gen_frames=gen_frames,
nfe=nfe,
cfg_strength=cfg,
sway_sampling_coef=sway,
t_grid=t_grid,
seed=None,
latent_dim=self.latent_dim,
device=self.device,
dtype=torch.float32,
generator=generator,
)
latents = latents.float()
if not torch.isfinite(latents).all():
raise RuntimeError("AuK generated latents contain NaN or Inf.")
if output_type == "latent":
return [DiffusionOutput(output=latents.detach().cpu())]
wav = self.vae.decode(latents)
# One mono waveform per request; the formatter expects [T].
wav = wav.detach().to(device="cpu", dtype=torch.float32).reshape(-1)
if not torch.isfinite(wav).all():
raise RuntimeError("AuK generated audio contains NaN or Inf.")
return [DiffusionOutput(output=wav)]
def _read_config(model_dir: str) -> dict[str, Any]:
"""Read the assembled AuK ``config.json``."""
path = os.path.join(model_dir, "config.json")
try:
with open(path) as handle:
config = json.load(handle)
except FileNotFoundError as exc:
raise ValueError(f"AuK checkpoint is missing config.json: {path}") from exc
except json.JSONDecodeError as exc:
logger.error("AuK config.json is not valid JSON: %s", path)
raise ValueError(f"AuK config.json is not valid JSON: {path}") from exc
missing = [key for key in ("dit", "vae") if key not in config]
if missing:
raise ValueError(f"AuK config.json is missing required sections {missing}: {path}")
return config
def _read_dit_weights(model_dir: str, dtype: torch.dtype) -> dict[str, torch.Tensor]:
"""Read the DiT state dict from ``auk.safetensors``, cast to ``dtype``.
Tensors are cast one at a time so the fp32 checkpoint is never fully
resident alongside the model.
"""
path = os.path.join(model_dir, "auk.safetensors")
if not os.path.isfile(path):
raise ValueError(f"AuK checkpoint is missing auk.safetensors: {path}")
with safe_open(path, framework="pt", device="cpu") as checkpoint:
keys = list(checkpoint.keys())
state = dit_state_dict(((key, checkpoint.get_tensor(key).to(dtype)) for key in keys), _DIT_PREFIX)
if not state:
raise ValueError(f"AuK checkpoint has no '{_DIT_PREFIX}*' weights: {path}")
unexpected = sorted(key for key in keys if key not in _FUSION_KEYS and not key.startswith(_DIT_PREFIX))
if unexpected:
logger.warning("Ignoring %d unrecognized keys in %s, e.g. %s", len(unexpected), path, unexpected[:5])
return state
@@ -1,6 +1,7 @@
# Copyright 2025 Bytedance Ltd. and/or its affiliates.
# Copyright (c) 2024 The Qwen Team and The HuggingFace Inc. team.
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
#
# This file has been modified by ByteDance Ltd. and/or its affiliates.
#
@@ -48,10 +49,10 @@ from vllm_omni.diffusion.distributed.parallel_state import (
get_sp_group,
)
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
from vllm_omni.diffusion.layers.mot.mot_layernorm import MoTRMSNorm
from vllm_omni.diffusion.layers.mot.mot_qkv_parallel_linear import MoTQKVParallelLinear
from vllm_omni.diffusion.layers.mot.mot_row_parallel_linear import MoTRowParallelLinear
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
from vllm_omni.diffusion.models.bagel.mot.mot_layernorm import MoTRMSNorm
from vllm_omni.diffusion.models.bagel.mot.mot_qkv_parallel_linear import MoTQKVParallelLinear
from vllm_omni.diffusion.models.bagel.mot.mot_row_parallel_linear import MoTRowParallelLinear
from vllm_omni.diffusion.utils.kv_utils import left_pad_stack
from vllm_omni.model_executor.layers.timestep_embedding import timestep_embedding
Whitespace-only changes.
@@ -0,0 +1,110 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# ruff: noqa: N803, E741
"""Mixture-of-Tokens (MoT) RMS Normalization layer.
Holds two sets of weights (text / gen) and routes tokens to the
appropriate weight based on indices. When text_indices is None the
layer degrades to a standard RMSNorm using self.weight (und mode).
"""
import torch
import torch.nn as nn
from vllm import ir
from vllm_omni.diffusion.layers.custom_op import CustomOp
class MoTRMSNorm(CustomOp):
"""Mixture-of-Tokens RMS Normalization.
In *und* mode (``text_indices is None``), every token is normalised
with ``self.weight`` – exactly like a vanilla RMSNorm.
In *gen* mode, text tokens are normalised with ``self.weight`` and
gen tokens are normalised with ``self.gen_weight``, using a single
fused Triton kernel that avoids the gather / scatter overhead.
"""
def __init__(
self,
hidden_size: int,
head_norm: bool = False,
eps: float = 1e-6,
) -> None:
super().__init__()
self.hidden_size = hidden_size
self.variance_epsilon = eps
self.weight = nn.Parameter(torch.ones(hidden_size))
self.gen_weight = nn.Parameter(torch.ones(hidden_size))
self.head_norm = head_norm
# ------------------------------------------------------------------
# Native (pure-PyTorch) fallback
# ------------------------------------------------------------------
def forward_native(
self,
x: torch.Tensor,
text_indices: torch.Tensor | None = None,
vae_indices: torch.Tensor | None = None,
) -> torch.Tensor:
if text_indices is None:
return self._rms_norm_native(x, self.weight)
output = torch.empty_like(x)
output[text_indices] = self._rms_norm_native(x[text_indices], self.weight)
output[vae_indices] = self._rms_norm_native(x[vae_indices], self.gen_weight)
return output
# ------------------------------------------------------------------
# CUDA fast-path
# ------------------------------------------------------------------
def forward_cuda(
self,
x: torch.Tensor,
text_indices: torch.Tensor | None = None,
vae_indices: torch.Tensor | None = None,
) -> torch.Tensor:
if text_indices is None:
# und mode – delegate to vllm's highly-optimised CUDA kernel
return ir.ops.rms_norm(x, self.weight.data, self.variance_epsilon)
# gen mode – fused MoT Triton kernel
from vllm_omni.diffusion.models.bagel.mot.ops.mot_rms_norm import (
mot_rms_norm,
)
return mot_rms_norm(
x,
self.weight.data,
self.gen_weight.data,
text_indices,
vae_indices,
head_norm=self.head_norm,
eps=self.variance_epsilon,
)
# ------------------------------------------------------------------
# NPU fast-path (not implemented yet; reserved for future optimization)
# ------------------------------------------------------------------
def forward_npu(
self,
x: torch.Tensor,
text_indices: torch.Tensor | None = None,
vae_indices: torch.Tensor | None = None,
) -> torch.Tensor:
return self.forward_native(x, text_indices, vae_indices)
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
def _rms_norm_native(self, x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
orig_dtype = x.dtype
x = x.float()
variance = x.pow(2).mean(dim=-1, keepdim=True)
x = x * torch.rsqrt(variance + self.variance_epsilon)
return (x * weight.float()).to(orig_dtype)
def extra_repr(self) -> str:
return f"hidden_size={self.hidden_size}, eps={self.variance_epsilon}"
@@ -0,0 +1,367 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import torch
from torch.nn.parameter import Parameter
from vllm.distributed import (
tensor_model_parallel_all_gather,
)
from vllm.logger import init_logger
from vllm.model_executor.layers.linear import (
WEIGHT_LOADER_V2_SUPPORTED,
QKVParallelLinear,
)
from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
)
from vllm.model_executor.utils import set_weight_attrs
from vllm.platforms import current_platform
from vllm_omni.diffusion.models.bagel.mot.ops.mot_gemm import invoke_mot_gemm
logger = init_logger(__name__)
class MoTQKVParallelLinear(QKVParallelLinear):
"""QKVParallelLinear with Mixture-of-Tokens routing.
Text weights: stored directly on self (self.weight, self.weight_scale, ...),
created through the standard QKVParallelLinear.__init__ process.
VAE weights: stored in the permanent submodule self.gen_exp
(self.gen_exp.weight, ...),
created via quant_method.create_weights(self.gen_exp, ...).
gen_exp.quant_method points to the same quant_method, so that
the vLLM framework’s process_weights_after_loading
can automatically detect and process it.
Forward behavior:
- und mode (text_indices is None): fully reuse super().forward()
- gen mode: call the MoT fused GEMM kernel
"""
def __init__(
self,
hidden_size: int,
head_size: int,
total_num_heads: int,
total_num_kv_heads: int | None = None,
bias: bool = True,
vae_bias: bool = False,
skip_bias_add: bool = False,
params_dtype: torch.dtype | None = None,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
*,
return_bias: bool = True,
disable_tp: bool = False,
v_head_size: int | None = None,
):
# ---- 1) Parent class creates text weights ----
# super().__init__ will do the following:
# quant_method.create_weights(self, ...) → self.weight, self.weight_scale, ...
# QKVParallelLinear hardcodes gather_output=False
super().__init__(
hidden_size,
head_size,
total_num_heads,
total_num_kv_heads,
bias,
skip_bias_add,
params_dtype,
quant_config,
prefix,
return_bias=return_bias,
disable_tp=disable_tp,
v_head_size=v_head_size,
)
# ---- 2) Create vae weights (permanent submodule) ----
if self.quant_method is None:
raise ValueError(
f"quant_method must not be None for MoTQKVParallelLinear (prefix={prefix!r}). "
"Ensure a valid QuantizationConfig is provided or the default UnquantizedLinearMethod is set."
)
# NOTE: We instantiate a bare torch.nn.Module() here as a lightweight namespace
# container to hold the secondary VAE weights.
# This is a design choice for dynamically attaching `quant_method` to the bare module.
# This is slightly unconventional but necessary. It allows vLLM's framework
# (specifically `process_weights_after_loading`) to automatically discover
# and process these secondary weights without requiring a dedicated,
# boilerplate Module subclass just for the VAE pathway.
self.gen_exp = torch.nn.Module()
# ``gen_exp`` participates in the same tensor-parallel layout as this
# layer. vLLM's online quantizers inspect these attributes while
# processing weights (for example, FP8 uses them to share scales across
# TP ranks), so the lightweight container must expose the parallel
# linear metadata rather than only holding parameters.
for attr in (
"tp_rank",
"tp_size",
"input_size",
"input_size_per_partition",
"output_size",
"output_size_per_partition",
):
setattr(self.gen_exp, attr, getattr(self, attr))
# Use the same weight_loader as text
vae_weight_loader = (
self.weight_loader_v2
if self.quant_method.__class__.__name__ in WEIGHT_LOADER_V2_SUPPORTED
else self.weight_loader
)
self.quant_method.create_weights(
layer=self.gen_exp,
input_size_per_partition=self.input_size_per_partition,
output_partition_sizes=self.output_partition_sizes,
input_size=self.input_size,
output_size=self.output_size,
params_dtype=self.params_dtype,
weight_loader=vae_weight_loader,
)
# Make gen_exp discoverable by vLLM framework's process_weights_after_loading
self.gen_exp.quant_method = self.quant_method
# ---- 3) vae bias ----
if vae_bias:
self.gen_exp.bias = Parameter(torch.empty(self.output_size_per_partition, dtype=self.params_dtype))
set_weight_attrs(
self.gen_exp.bias,
{"output_dim": 0, "weight_loader": self.weight_loader},
)
else:
self.gen_exp.register_parameter("bias", None)
self.update_param_tp_status()
# ==================================================================
# Forward
# ==================================================================
def forward(
self,
input_: torch.Tensor,
text_indices: torch.Tensor | None = None,
vae_indices: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, Parameter | None]:
# ---- und mode: fully reuse parent class (only text path) ----
if text_indices is None:
return super().forward(input_)
# ---- gen mode: fuse MoT GEMM ----
output_parallel = self._mot_gemm_dispatch(input_, text_indices, vae_indices)
# QKVParallelLinear hardcodes gather_output=False, this branch never enters;
# retained for future subclass changes
if self.gather_output and self.tp_size > 1:
output = tensor_model_parallel_all_gather(output_parallel)
else:
output = output_parallel
if not self.return_bias:
return output
if self.skip_bias_add and text_indices is not None and (self.bias is not None or self.gen_exp.bias is not None):
merged_bias = torch.zeros(
output.size(0),
self.output_size_per_partition,
dtype=output.dtype,
device=output.device,
)
if self.bias is not None:
merged_bias[text_indices] = self.bias
if self.gen_exp.bias is not None:
merged_bias[vae_indices] = self.gen_exp.bias
return output, merged_bias
output_bias = self.bias if self.skip_bias_add else None
return output, output_bias
# ==================================================================
# MoT GEMM dispatcher
# ==================================================================
def _mot_gemm_dispatch(
self,
x: torch.Tensor,
text_indices: torch.Tensor,
vae_indices: torch.Tensor,
) -> torch.Tensor:
# Any other backend (ROCm, XPU, TPU, CPU) uses the safe vllm fallback.
if not current_platform.is_cuda():
return self._mot_fallback(x, text_indices, vae_indices)
"""Dispatch to different MoT kernel paths based on weight dtype / quant attributes."""
bias_text = self.bias if not self.skip_bias_add else None
bias_vae = self.gen_exp.bias if not self.skip_bias_add else None
w_text = self.weight
w_vae = self.gen_exp.weight
assert w_text.dtype.is_floating_point == w_vae.dtype.is_floating_point, (
"weight of text expert and image expert should be the same dtype."
)
# w_text.dtype.itemsize >= 2 means bytes_per_element >= 2 (16bits or 32bits)
if w_text.dtype.is_floating_point and w_text.dtype.itemsize >= 2:
return self._mot_gemm_unquantized(
x,
text_indices,
vae_indices,
bias_text,
bias_vae,
)
elif w_text.dtype == torch.float8_e4m3fn:
return self._mot_gemm_fp8_w8a8(
x,
text_indices,
vae_indices,
bias_text,
bias_vae,
)
elif w_text.dtype == torch.int8:
return self._mot_gemm_weight_only(
x,
text_indices,
vae_indices,
bias_text,
bias_vae,
)
else:
return self._mot_fallback(
x,
text_indices,
vae_indices,
)
# ==================================================================
# Implementation of each quantization path
# ==================================================================
def _mot_gemm_unquantized(self, x, text_idx, vae_idx, bias_t, bias_v):
"""BF16/FP16 path."""
N = self.output_size_per_partition
C = torch.zeros(x.size(0), N, dtype=x.dtype, device=x.device)
invoke_mot_gemm(
A=x,
B_text=self.weight.data.t(),
B_vae=self.gen_exp.weight.data.t(),
C=C,
bias_text=bias_t,
bias_vae=bias_v,
text_indices=text_idx,
vae_indices=vae_idx,
A_scale=None,
B_text_scale=None,
B_vae_scale=None,
use_fp8_w8a8=False,
use_int8_w8a8=False,
use_int8_w8a16=False,
use_int4_w4a16=False,
A_per_channel_quant=False,
B_per_channel_quant=False,
)
return C
def _mot_gemm_fp8_w8a8(self, x, text_idx, vae_idx, bias_t, bias_v):
"""FP8 W8A8 path.
1) Activation quantization: reuse vllm's ops.scaled_fp8_quant
2) MoT GEMM: text/vae use different fp8 weights and weight_scale
3) De-quantization: done by MoT kernel's epilogue
"""
from vllm import _custom_ops as ops
x_2d = x.view(-1, x.shape[-1])
input_scale = getattr(self, "input_scale", None)
x_fp8, x_scale = ops.scaled_fp8_quant(
x_2d,
input_scale,
use_per_token_if_dynamic=True,
)
N = self.output_size_per_partition
C = torch.zeros(x.size(0), N, dtype=x.dtype, device=x.device)
invoke_mot_gemm(
A=x_fp8,
B_text=self.weight.data,
B_vae=self.gen_exp.weight.data,
C=C,
bias_text=bias_t,
bias_vae=bias_v,
text_indices=text_idx,
vae_indices=vae_idx,
A_scale=x_scale,
B_text_scale=self.weight_scale.data,
B_vae_scale=self.gen_exp.weight_scale.data,
use_fp8_w8a8=True,
use_int8_w8a8=False,
use_int8_w8a16=False,
use_int4_w4a16=False,
A_per_channel_quant=True,
B_per_channel_quant=False,
)
return C
def _mot_gemm_weight_only(self, x, text_idx, vae_idx, bias_t, bias_v):
"""Weight-Only W8A16 path.
Activation values kept as bf16/fp16, weights are int8 + per-channel scale.
De-quantization done by MoT kernel's epilogue.
"""
N = self.output_size_per_partition
C = torch.zeros(x.size(0), N, dtype=x.dtype, device=x.device)
invoke_mot_gemm(
A=x,
B_text=self.weight.data.t(),
B_vae=self.gen_exp.weight.data.t(),
C=C,
bias_text=bias_t,
bias_vae=bias_v,
text_indices=text_idx,
vae_indices=vae_idx,
A_scale=None,
B_text_scale=self.weight_scale.data,
B_vae_scale=self.gen_exp.weight_scale.data,
use_fp8_w8a8=False,
use_int8_w8a8=False,
use_int8_w8a16=True,
use_int4_w4a16=False,
A_per_channel_quant=False,
B_per_channel_quant=True,
)
return C
def _mot_fallback(self, x, text_idx, vae_idx):
"""Fallback: fall back to gather/scatter + quant_method.apply.
For unsupported quantization types, call standard forward for text/vae tokens.
"""
if self.quant_method is None:
raise ValueError(
"quant_method must not be None in MoTQKVParallelLinear._mot_fallback. "
"This indicates an initialization error."
)
bias_text = self.bias if not self.skip_bias_add else None
bias_vae = self.gen_exp.bias if not self.skip_bias_add else None
output = torch.zeros(
x.size(0),
self.output_size_per_partition,
dtype=x.dtype,
device=x.device,
)
output_text = self.quant_method.apply(self, x[text_idx], bias_text)
output_vae = self.quant_method.apply(
self.gen_exp,
x[vae_idx],
bias_vae,
)
output[text_idx] = output_text
output[vae_idx] = output_vae
return output
@@ -0,0 +1,379 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import torch
from torch.nn.parameter import Parameter
from vllm.distributed import (
split_tensor_along_last_dim,
tensor_model_parallel_all_reduce,
)
from vllm.model_executor.layers.linear import (
WEIGHT_LOADER_V2_SUPPORTED,
RowParallelLinear,
)
from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
)
from vllm.model_executor.utils import set_weight_attrs
from vllm.platforms import current_platform
from vllm_omni.diffusion.models.bagel.mot.ops.mot_gemm import invoke_mot_gemm
class MoTRowParallelLinear(RowParallelLinear):
"""RowParallelLinear with Mixture-of-Tokens routing.
text weights: directly on self (self.weight, self.weight_scale, ...),
created by RowParallelLinear.__init__ standard process.
vae weights: on permanent submodule self.gen_exp (self.gen_exp.weight, ...),
created by quant_method.create_weights(self.gen_exp, ...).
gen_exp.quant_method points to the same quant_method, enabling
vLLM framework's process_weights_after_loading to automatically
discover and process it.
Forward behavior:
- und mode (text_indices is None): fully reuse super().forward()
- gen mode: call MoT fused GEMM kernel, then execute TP all-reduce
"""
def __init__(
self,
input_size: int,
output_size: int,
bias: bool = True,
vae_bias: bool = False,
input_is_parallel: bool = True,
skip_bias_add: bool = False,
params_dtype: torch.dtype | None = None,
reduce_results: bool = True,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
*,
return_bias: bool = True,
disable_tp: bool = False,
):
# ---- Step 1: Parent class creates text weights ----
# super().__init__ internally calls:
# quant_method.create_weights(self, ...) → self.weight, self.weight_scale, ...
super().__init__(
input_size,
output_size,
bias,
input_is_parallel,
skip_bias_add,
params_dtype,
reduce_results,
quant_config,
prefix,
return_bias=return_bias,
disable_tp=disable_tp,
)
# ---- Step 2: Create vae weights (permanent submodule) ----
if self.quant_method is None:
raise ValueError(
f"quant_method must not be None for MoTRowParallelLinear (prefix={prefix!r}). "
"Ensure a valid QuantizationConfig is provided or the default UnquantizedLinearMethod is set."
)
# NOTE: We instantiate a bare torch.nn.Module() here as a lightweight namespace
# container to hold the secondary VAE weights.
# This is a design choice for dynamically attaching `quant_method` to the bare module.
# This is slightly unconventional but necessary. It allows vLLM's framework
# (specifically `process_weights_after_loading`) to automatically discover
# and process these secondary weights without requiring a dedicated,
# boilerplate Module subclass just for the VAE pathway.
self.gen_exp = torch.nn.Module()
# ``gen_exp`` participates in the same tensor-parallel layout as this
# layer. vLLM's online quantizers inspect these attributes while
# processing weights (for example, FP8 uses them to share scales across
# TP ranks), so the lightweight container must expose the parallel
# linear metadata rather than only holding parameters.
for attr in (
"tp_rank",
"tp_size",
"input_size",
"input_size_per_partition",
"output_size",
"output_size_per_partition",
):
setattr(self.gen_exp, attr, getattr(self, attr))
# Select weight_loader consistent with text
vae_weight_loader = (
self.weight_loader_v2
if self.quant_method.__class__.__name__ in WEIGHT_LOADER_V2_SUPPORTED
else self.weight_loader
)
self.quant_method.create_weights(
layer=self.gen_exp,
input_size_per_partition=self.input_size_per_partition,
output_partition_sizes=self.output_partition_sizes,
input_size=self.input_size,
output_size=self.output_size,
params_dtype=self.params_dtype,
weight_loader=vae_weight_loader,
)
# Enable gen_exp to be automatically discovered by vLLM framework's process_weights_after_loading
self.gen_exp.quant_method = self.quant_method
# ---- Step 3: vae bias ----
# RowParallelLinear's bias is full output_size (not sharded)
if vae_bias:
self.gen_exp.bias = Parameter(torch.empty(self.output_size, dtype=self.params_dtype))
set_weight_attrs(
self.gen_exp.bias,
{"output_dim": 0, "weight_loader": self.weight_loader},
)
else:
self.gen_exp.register_parameter("bias", None)
self.update_param_tp_status()
# ==================================================================
# Forward
# ==================================================================
def forward(
self,
input_: torch.Tensor,
text_indices: torch.Tensor | None = None,
vae_indices: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, Parameter | None]:
# ---- und mode: fully reuse parent class (only text path) ----
if text_indices is None:
return super().forward(input_)
# ---- gen mode ----
# Handle input_is_parallel (consistent with parent class logic)
if self.input_is_parallel:
input_parallel = input_
else:
split_input = split_tensor_along_last_dim(input_, num_partitions=self.tp_size)
input_parallel = split_input[self.tp_rank].contiguous()
# Fused MoT GEMM
output_parallel = self._mot_gemm_dispatch(input_parallel, text_indices, vae_indices)
# ---- TP communication: all-reduce (consistent with parent class) ----
if self.reduce_results and self.tp_size > 1:
output = tensor_model_parallel_all_reduce(output_parallel)
else:
output = output_parallel
if not self.return_bias:
return output
if self.skip_bias_add and text_indices is not None and (self.bias is not None or self.gen_exp.bias is not None):
# Construct per-token mixed bias
merged_bias = torch.zeros(
output.size(0),
self.output_size_per_partition,
dtype=output.dtype,
device=output.device,
)
if self.bias is not None:
merged_bias[text_indices] = self.bias
if self.gen_exp.bias is not None:
merged_bias[vae_indices] = self.gen_exp.bias
return output, merged_bias
output_bias = self.bias if self.skip_bias_add else None
return output, output_bias
# ==================================================================
# MoT GEMM Dispatcher
# ==================================================================
def _mot_gemm_dispatch(
self,
x: torch.Tensor,
text_indices: torch.Tensor,
vae_indices: torch.Tensor,
) -> torch.Tensor:
"""Dispatch to different MoT kernel paths based on weight dtype / quant attributes."""
# Any other backend (ROCm, XPU, TPU, CPU) uses the safe vllm fallback.
if not current_platform.is_cuda():
return self._mot_fallback(x, text_indices, vae_indices)
# RowParallelLinear: bias only fused into GEMM at rank 0,
# other ranks pass None to avoid duplicate accumulation
bias_text = None if (self.tp_rank > 0 or self.skip_bias_add) else self.bias
bias_vae = None if (self.tp_rank > 0 or self.skip_bias_add) else self.gen_exp.bias
# Determine quantization type by weight dtype, avoid isinstance coupling to specific quant_method
# TODO: Currently does not support online quantization fp8, does not support quantization types involving int4
w_text = self.weight
w_vae = self.gen_exp.weight
assert w_text.dtype.is_floating_point == w_vae.dtype.is_floating_point, (
"weight of text expert and image expert should be the same dtype."
)
# w_text.dtype.itemsize >= 2 means bytes_per_element >= 2 (16bits or 32bits)
if w_text.dtype.is_floating_point and w_text.dtype.itemsize >= 2:
# ---- Path 0: BF16 / FP16 (unquantized) ----
return self._mot_gemm_unquantized(
x,
text_indices,
vae_indices,
bias_text,
bias_vae,
)
elif w_text.dtype == torch.float8_e4m3fn:
# ---- Path 1: FP8 W8A8 ----
return self._mot_gemm_fp8_w8a8(
x,
text_indices,
vae_indices,
bias_text,
bias_vae,
)
elif w_text.dtype == torch.int8:
# ---- Path 2: Weight-Only INT8 W8A16 ----
return self._mot_gemm_weight_only(
x,
text_indices,
vae_indices,
bias_text,
bias_vae,
)
else:
# ---- Fallback: gather/scatter + quant_method.apply ----
return self._mot_fallback(
x,
text_indices,
vae_indices,
)
# ==================================================================
# Specific implementations for each quantization path
# ==================================================================
def _mot_gemm_unquantized(self, x, text_idx, vae_idx, bias_t, bias_v):
"""BF16/FP16 path."""
N = self.output_size_per_partition
C = torch.empty(x.size(0), N, dtype=x.dtype, device=x.device)
invoke_mot_gemm(
A=x,
B_text=self.weight.data.t(),
B_vae=self.gen_exp.weight.data.t(),
C=C,
bias_text=bias_t,
bias_vae=bias_v,
text_indices=text_idx,
vae_indices=vae_idx,
A_scale=None,
B_text_scale=None,
B_vae_scale=None,
use_fp8_w8a8=False,
use_int8_w8a8=False,
use_int8_w8a16=False,
use_int4_w4a16=False,
A_per_channel_quant=False,
B_per_channel_quant=False,
)
return C
def _mot_gemm_fp8_w8a8(self, x, text_idx, vae_idx, bias_t, bias_v):
"""FP8 W8A8 path.
1) Activation quantization: reuse vllm's ops.scaled_fp8_quant
2) MoT GEMM: text/vae each use different fp8 weights and weight_scale
3) Dequantization: completed by MoT kernel internal epilogue
"""
from vllm import _custom_ops as ops
x_2d = x.view(-1, x.shape[-1])
input_scale = getattr(self, "input_scale", None)
x_fp8, x_scale = ops.scaled_fp8_quant(
x_2d,
input_scale,
use_per_token_if_dynamic=True,
)
N = self.output_size_per_partition
C = torch.empty(x.size(0), N, dtype=x.dtype, device=x.device)
# weight has been transposed to (K, N) in process_weights_after_loading
invoke_mot_gemm(
A=x_fp8,
B_text=self.weight.data,
B_vae=self.gen_exp.weight.data,
C=C,
bias_text=bias_t,
bias_vae=bias_v,
text_indices=text_idx,
vae_indices=vae_idx,
A_scale=x_scale,
B_text_scale=self.weight_scale.data,
B_vae_scale=self.gen_exp.weight_scale.data,
use_fp8_w8a8=True,
use_int8_w8a8=False,
use_int8_w8a16=False,
use_int4_w4a16=False,
A_per_channel_quant=True,
B_per_channel_quant=False,
)
return C
def _mot_gemm_weight_only(self, x, text_idx, vae_idx, bias_t, bias_v):
"""Weight-Only W8A16 path.
Activations remain bf16/fp16, weights are int8 + per-channel scale.
MoT kernel internally performs immediate dequantization.
"""
N = self.output_size_per_partition
C = torch.empty(x.size(0), N, dtype=x.dtype, device=x.device)
invoke_mot_gemm(
A=x,
B_text=self.weight.data.t(),
B_vae=self.gen_exp.weight.data.t(),
C=C,
bias_text=bias_t,
bias_vae=bias_v,
text_indices=text_idx,
vae_indices=vae_idx,
A_scale=None,
B_text_scale=self.weight_scale.data,
B_vae_scale=self.gen_exp.weight_scale.data,
use_fp8_w8a8=False,
use_int8_w8a8=False,
use_int8_w8a16=True,
use_int4_w4a16=False,
A_per_channel_quant=False,
B_per_channel_quant=True,
)
return C
def _mot_fallback(self, x, text_idx, vae_idx):
"""Fallback: degrade to gather/scatter + quant_method.apply.
For unsupported quantization types, call standard forward separately for text/vae tokens.
"""
if self.quant_method is None:
raise ValueError(
"quant_method must not be None in MoTRowParallelLinear._mot_fallback. "
"This indicates an initialization error."
)
# RowParallelLinear: bias only fused at rank 0
bias_text = None if (self.tp_rank > 0 or self.skip_bias_add) else self.bias
bias_vae = None if (self.tp_rank > 0 or self.skip_bias_add) else self.gen_exp.bias
output = torch.empty(
x.size(0),
self.output_size_per_partition,
dtype=x.dtype,
device=x.device,
)
# text tokens → standard quant_method (operate on weights on self)
output[text_idx] = self.quant_method.apply(self, x[text_idx], bias_text)
# vae tokens → same quant_method (operate on weights on gen_exp)
output[vae_idx] = self.quant_method.apply(
self.gen_exp,
x[vae_idx],
bias_vae,
)
return output
Whitespace-only changes.
@@ -0,0 +1,911 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# ruff: noqa: N803, E741
import functools
import json
import logging
import os
import pathlib
import re
from typing import Any
import torch
from vllm.triton_utils import tl, triton
logger = logging.getLogger(__name__)
# =====================================================================
# MoT GEMM Config Loading (3-tier: env → built-in → default)
#
# Usage pattern (mirrors vLLM fused_moe):
# 1. Layer invokes invoke_mot_gemm(...) without extra config context.
# 2. invoke_mot_gemm lazily calls
# get_mot_configs(K, N, dtype_str)
# which is @lru_cache'd and lazily loads the JSON on first hit.
# 3. If get_mot_configs returns None, fall back to
# get_mot_default_config(M, N, K, ...)
# =====================================================================
_CONFIGS_DIR = pathlib.Path(__file__).resolve().parent.parent / "configs"
_ENV_CONFIG_FOLDER = "VLLM_TUNED_CONFIG_FOLDER"
def get_device_name() -> str:
"""Sanitized GPU device name, matching mot_linear_benchmarks.py output."""
raw = torch.cuda.get_device_name(0)
name = re.sub(r"[^a-zA-Z0-9]", "", raw.replace(" ", ""))
for prefix in ("NVIDIA", "AMD"):
if name.startswith(prefix):
name = name[len(prefix) :]
# --- Device Aliasing Patch ---
alias_map = {
"A800": "A100",
"H800": "H100",
}
# map A800/H800 to A100/H100 for chinese market
for key, target in alias_map.items():
if key in name:
name = name.replace(key, target)
break
return name
def build_config_filename(device_name: str, dtype_str: str) -> str:
return f"device_name={device_name},dtype={dtype_str}.json"
def _try_load_json(filepath: str) -> dict | None:
if os.path.isfile(filepath):
with open(filepath) as f:
return json.load(f)
return None
@functools.lru_cache
def _load_mot_config_file(dtype_str: str) -> dict | None:
"""Load and cache the full MoT config JSON (one file per device/dtype).
Search order:
1. ``$VLLM_TUNED_CONFIG_FOLDER/device_name=...,dtype=....json``
2. ``vllm_omni/.../mot/configs/device_name=...,dtype=....json``
3. Return ``None`` (caller falls back to ``get_mot_default_config``).
"""
device_name = get_device_name()
filename = build_config_filename(device_name, dtype_str)
config_file_paths: list[str] = []
env_dir = os.environ.get(_ENV_CONFIG_FOLDER)
if env_dir:
config_file_paths.append(str(pathlib.Path(env_dir) / filename))
config_file_paths.append(str(_CONFIGS_DIR / filename))
for path in config_file_paths:
data = _try_load_json(path)
if data is not None:
logger.info("MoT config loaded from %s", path)
return data
logger.warning(
f"\n{'=' * 80}\n"
f" ⚠️ [WARNING] No tuned MoT config found.\n"
f" Searched paths: {', '.join(config_file_paths)}\n"
f" Using conservative default configs which are NOT optimal.\n"
f" Run `python benchmarks/kernels/mot_linear_benchmarks.py --tune` \n"
f" to generate hardware-specific optimal configs.\n"
f"{'=' * 80}\n"
)
return None
@functools.lru_cache
def get_mot_configs(
K: int,
N: int,
dtype_str: str | None = None,
) -> dict[int, dict[str, int]] | None:
"""Return ``{M: tile_config}`` for a given (K, N) shape, or ``None``.
The return value maps an irregular grid of batch sizes (M) to Triton
tile configurations. The caller should pick the entry whose M is
closest to the actual batch size.
Config file is selected by ``device_name + dtype``.
"""
file_data = _load_mot_config_file(dtype_str or "w16a16")
if file_data is None:
return None
shape_entry = file_data.get(f"{K}_{N}")
if shape_entry is None:
logger.warning(
f"\n{'=' * 80}\n"
f" ⚠️ [WARNING] MoT config file found, but NO tuned entry for shape K={K}, N={N}.\n"
f" Using conservative default configs which are NOT optimal for this specific shape.\n"
f" Run `python benchmarks/kernels/mot_linear_benchmarks.py --tune` \n"
f" to generate hardware-specific optimal configs.\n"
f"{'=' * 80}\n"
)
return None
return {int(k): dict(v) for k, v in shape_entry.items() if k != "_comment"}
def get_mot_default_config(
M: int,
N: int,
K: int,
dtype: str | None = None,
block_quant_shape: list[int] | None = None,
) -> dict[str, int]:
"""Conservative fallback config guaranteed to compile on all hardware.
Trades peak performance for universal compatibility (T4 / V100 / A100 /
H100, CUDA & ROCm).
"""
# FP8 block-wise quantization requires strict alignment
if dtype == "fp8_w8a8" and block_quant_shape is not None:
return {
"BLOCK_SIZE_M": 64,
"BLOCK_SIZE_N": block_quant_shape[0],
"BLOCK_SIZE_K": block_quant_shape[1],
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2,
}
# Very small M (tail batches, final feature concat, etc.)
# NOTE If M is not a multiple of the block size (e.g., M=3 with BLOCK_SIZE_M=16),
# the kernel will allocate a full tile. Correctness is guaranteed by boundary masks.
# We tolerate this minor compute/SRAM padding to avoid generating excessive
# Triton compiled variants for extremely small sequence lengths.
if M <= 64:
return {
"BLOCK_SIZE_M": 16 if M <= 16 else 32,
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 32,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2,
}
# Standard fallback for typical image-generation M (2048 / 4096 / …)
# SRAM usage: (64*32 + 64*32) * 2 * 2 = 16 KB — safe on decade-old GPUs
return {
"BLOCK_SIZE_M": 64,
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 32,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2,
}
def get_best_mot_config(M: int, N: int, K: int, dtype_str: str | None = None) -> tuple[int, dict[str, int]]:
configs = get_mot_configs(K, N, dtype_str)
if configs:
loaded_m_key = min(configs.keys(), key=lambda x: abs(x - M))
return loaded_m_key, configs[loaded_m_key]
else:
return -1, get_mot_default_config(M, N, K, dtype=dtype_str)
# =================================================================
# Part 1: The Router (Routing Component)
# Responsibilities: Handle PID mapping, Text/VAE distribution, indirect index loading, pointer calculation
# =================================================================
@triton.jit
def _get_mot_pointers(
# System Inputs
pid,
# Matrix Pointers
a_ptr,
b_text_ptr,
b_vae_ptr,
bias_text_ptr,
bias_vae_ptr,
scale_a_ptr,
scale_b_text_ptr,
scale_b_vae_ptr,
# Indices & Meta
text_indices_ptr,
vae_indices_ptr,
M_text,
M_vae,
N,
# Strides (need to select based on Text/VAE)
stride_bk_text,
stride_bn_text,
stride_bk_vae,
stride_bn_vae,
# Block Config
BLOCK_SIZE_M: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
GROUP_SIZE_M: tl.constexpr,
):
# 1. Calculate Text/VAE task boundaries
num_pid_m_text = tl.cdiv(M_text, BLOCK_SIZE_M)
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
# 2. MoT Routing
# Initialize VAE variables first and overwrite for Text
# VAE Path
cur_pid = pid - (num_pid_m_text * num_pid_n)
# Select VAE Pointers
cur_b_ptr = b_vae_ptr
cur_bias_ptr = bias_vae_ptr
cur_scale_b_ptr = scale_b_vae_ptr
cur_indices_ptr = vae_indices_ptr
# Select VAE Strides / Limits
cur_stride_bk = stride_bk_vae
cur_stride_bn = stride_bn_vae
M_limit = M_vae
# Text Path
if pid < num_pid_m_text * num_pid_n:
cur_pid = pid
# Select Text Pointers
cur_b_ptr = b_text_ptr
cur_bias_ptr = bias_text_ptr
cur_scale_b_ptr = scale_b_text_ptr
cur_indices_ptr = text_indices_ptr
# Select Text Strides / Limits
cur_stride_bk = stride_bk_text
cur_stride_bn = stride_bn_text
M_limit = M_text
# 3. Calculate Grid coordinates(grouping)
cur_num_pid_m = tl.cdiv(M_limit, BLOCK_SIZE_M)
num_pid_in_group = GROUP_SIZE_M * num_pid_n
group_id = cur_pid // num_pid_in_group
first_pid_m = group_id * GROUP_SIZE_M
group_size_m_adj = tl.minimum(cur_num_pid_m - first_pid_m, GROUP_SIZE_M)
pid_m = first_pid_m + (cur_pid % group_size_m_adj)
pid_n = (cur_pid % num_pid_in_group) // group_size_m_adj
# 4. Load indirect indices (Indirect Indexing for A)
# Calculate the M range covered by current Block [0, BLOCK_SIZE_M]
offs_m_idx = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to(tl.int64)
m_mask = offs_m_idx < M_limit
# Load real row indices from the index array
# for very big K (eg. ffn down proj*TP=1,K=16k), if M is also huge(M>130K)
# loading int32 indices may result in integer overflow when we compute offs_m
real_row_idxs = tl.load(cur_indices_ptr + offs_m_idx, mask=m_mask, other=0).to(tl.int64)
# 5. Calculate N-dimension Offsets
offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(tl.int64)
n_mask = offs_n < N
return (
pid_m,
pid_n, # Grid Coordinates
real_row_idxs,
m_mask, # M-dim info (Indirect)
offs_n,
n_mask, # N-dim info
M_limit, # Boundary
cur_b_ptr,
cur_bias_ptr, # Selected Pointers
cur_scale_b_ptr, # Selected Scale Pointer
cur_stride_bk,
cur_stride_bn, # Selected Strides
)
# =================================================================
# Part 2: Compute Cores
# Responsibilities: Execute specific Loop structures based on QUANT_TYPE
# =================================================================
# Core A: Standard GEMM (for BF16/FP16 and W8A8)
# Feature: No dequantization inside Loop, Scale is applied after Loop ends
@triton.jit
def _core_standard_gemm(
# Pointers
a_ptr,
b_ptr,
# Offsets & Masks
real_row_idxs,
m_mask,
offs_n,
n_mask,
offs_k,
# Strides
stride_am,
stride_ak,
stride_bk,
stride_bn,
# Quant-Related
scale_a_ptr,
scale_b_ptr,
stride_scale_a,
stride_scale_b,
# Loop Info
K,
BLOCK_SIZE_K: tl.constexpr,
# Configs
BLOCK_SIZE_M: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
ACCUMULATOR_DTYPE: tl.constexpr,
IS_W8A8: tl.constexpr,
# Accelerate Configs
EVEN_K: tl.constexpr,
EVEN_N: tl.constexpr,
STRIDE_AK_IS_1: tl.constexpr,
STRIDE_BK_IS_1: tl.constexpr,
STRIDE_BN_IS_1: tl.constexpr,
):
# 1. Stride optimizations (Bypassing compiler limitations for unit strides)
_stride_ak = 1 if STRIDE_AK_IS_1 else stride_ak
_stride_bk = 1 if STRIDE_BK_IS_1 else stride_bk
_stride_bn = 1 if STRIDE_BN_IS_1 else stride_bn
# Pointer initialization (A uses indirect indexing, B uses standard striding)
a_ptrs = a_ptr + (stride_am * real_row_idxs[:, None] + _stride_ak * offs_k[None, :])
b_ptrs = b_ptr + (_stride_bk * offs_k[:, None] + _stride_bn * offs_n[None, :])
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=ACCUMULATOR_DTYPE)
# 2. Unified Main Loop
# Triton evaluates `constexpr` conditions at compile time, ensuring zero runtime overhead
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
# Compute K-mask only if needed
if not EVEN_K:
mask_k = offs_k < K - k * BLOCK_SIZE_K
# Load A
if EVEN_K:
a = tl.load(a_ptrs, mask=m_mask[:, None], other=0.0)
else:
a = tl.load(a_ptrs, mask=m_mask[:, None] & mask_k[None, :], other=0.0)
# Load B
if EVEN_K and EVEN_N:
b = tl.load(b_ptrs)
elif not EVEN_K and EVEN_N:
b = tl.load(b_ptrs, mask=mask_k[:, None], other=0.0)
elif EVEN_K and not EVEN_N:
b = tl.load(b_ptrs, mask=n_mask[None, :], other=0.0)
else:
b = tl.load(b_ptrs, mask=mask_k[:, None] & n_mask[None, :], other=0.0)
# Compute & Advance
accumulator = tl.dot(a, b, accumulator, out_dtype=ACCUMULATOR_DTYPE)
a_ptrs += BLOCK_SIZE_K * _stride_ak
b_ptrs += BLOCK_SIZE_K * _stride_bk
# 3. Epilogue (only needed for W8A8)
if IS_W8A8:
accumulator = accumulator.to(tl.float32)
# Load Scale A
scale_a_ptrs = scale_a_ptr + real_row_idxs * stride_scale_a
sa = tl.load(scale_a_ptrs, mask=m_mask, other=1.0)
accumulator = accumulator * sa[:, None]
# Load Scale B
scale_b_ptrs = scale_b_ptr + offs_n * stride_scale_b
sb = tl.load(scale_b_ptrs, mask=n_mask, other=1.0)
accumulator = accumulator * sb[None, :]
return accumulator
# Core B: Weight Only GEMM (for W4A16 / W8A16)
# Feature: Dequantization inside Loop (Dequantize-on-the-fly)
# Currently only supports W8A16
@triton.jit
def _core_weight_only_gemm(
# Pointers
a_ptr,
b_ptr,
# Offsets & Masks
real_row_idxs,
m_mask,
offs_n,
n_mask,
offs_k,
# Strides
stride_am,
stride_ak,
stride_bk,
stride_bn,
# Quant-Related
scale_b_ptr,
stride_scale_b, # 1(per-channel) or 0(per-tensor)
# Loop Info
K,
BLOCK_SIZE_K: tl.constexpr,
# Configs
BLOCK_SIZE_M: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
ACCUMULATOR_DTYPE: tl.constexpr,
COMPUTE_DTYPE: tl.constexpr, # bf16 or fp16
WEIGHT_BITS: tl.constexpr, # 4 or 8
# Accelerate Configs
EVEN_K: tl.constexpr,
EVEN_N: tl.constexpr,
STRIDE_AK_IS_1: tl.constexpr,
STRIDE_BK_IS_1: tl.constexpr,
STRIDE_BN_IS_1: tl.constexpr,
):
# Compile-time Check
tl.static_assert(WEIGHT_BITS == 8, "For weight-only, we only support W8A16 at this point")
# 1. Stride optimizations
_stride_ak = 1 if STRIDE_AK_IS_1 else stride_ak
_stride_bk = 1 if STRIDE_BK_IS_1 else stride_bk
_stride_bn = 1 if STRIDE_BN_IS_1 else stride_bn
a_ptrs = a_ptr + (stride_am * real_row_idxs[:, None] + _stride_ak * offs_k[None, :])
b_ptrs = b_ptr + (_stride_bk * offs_k[:, None] + _stride_bn * offs_n[None, :])
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=ACCUMULATOR_DTYPE)
# 2. Unified Main Loop
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
if not EVEN_K:
mask_k = offs_k < K - k * BLOCK_SIZE_K
# Load A
if EVEN_K:
a = tl.load(a_ptrs, mask=m_mask[:, None], other=0.0)
else:
a = tl.load(a_ptrs, mask=m_mask[:, None] & mask_k[None, :], other=0.0)
# Load B (Int)
if EVEN_K and EVEN_N:
b_int = tl.load(b_ptrs)
elif not EVEN_K and EVEN_N:
b_int = tl.load(b_ptrs, mask=mask_k[:, None], other=0.0)
elif EVEN_K and not EVEN_N:
b_int = tl.load(b_ptrs, mask=n_mask[None, :], other=0.0)
else:
b_int = tl.load(b_ptrs, mask=mask_k[:, None] & n_mask[None, :], other=0.0)
# --- Dequantize Logic (Type Cast Only) ---
# No multiplication here, correct as long as per-tensor/per-channel scaling (scale_b.shape=(N,))
b_compute = b_int.to(COMPUTE_DTYPE)
# Compute & Advance
accumulator = tl.dot(a, b_compute, accumulator, out_dtype=ACCUMULATOR_DTYPE)
a_ptrs += BLOCK_SIZE_K * _stride_ak
b_ptrs += BLOCK_SIZE_K * _stride_bk
# 3. Epilogue: Apply Scale B safely outside the loop
# Load Scale B
scale_b_ptrs = scale_b_ptr + offs_n * stride_scale_b
sb = tl.load(scale_b_ptrs, mask=n_mask, other=1.0) # shape=(N,)
accumulator = accumulator * sb[None, :]
return accumulator
# =================================================================
# Part 3: Unified Entry Kernel
# Responsibilities: Call Router, statically dispatch Core, store results
# =================================================================
@triton.jit
def mot_unified_gemm_kernel(
# Inputs
a_ptr,
b_text_ptr,
b_vae_ptr,
c_ptr,
bias_text_ptr,
bias_vae_ptr,
text_indices_ptr,
vae_indices_ptr,
# Dimensions & Strides
M_text,
M_vae,
N,
K,
stride_am,
stride_ak,
stride_bk_text,
stride_bn_text,
stride_bk_vae,
stride_bn_vae,
stride_cm,
stride_cn,
# Scales (pass 0 if None)
scale_a_ptr,
scale_b_text_ptr,
scale_b_vae_ptr,
stride_scale_a,
stride_scale_b, # 1(per-channel) or 0(per-tensor)
# Metas
BLOCK_SIZE_M: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
BLOCK_SIZE_K: tl.constexpr,
GROUP_SIZE_M: tl.constexpr,
# accelerate config
EVEN_K: tl.constexpr,
EVEN_N: tl.constexpr,
STRIDE_AK_IS_1: tl.constexpr,
STRIDE_BK_IS_1: tl.constexpr,
STRIDE_BN_IS_1: tl.constexpr,
# Quant-related dtypes
ACCUMULATOR_DTYPE: tl.constexpr,
COMPUTE_DTYPE: tl.constexpr,
OUTPUT_DTYPE: tl.constexpr,
# Quant Control
# 0=None, 1=W8A8, 2=W8A16, 3=W4A16
QUANT_TYPE: tl.constexpr,
HAS_BIAS: tl.constexpr = False,
):
pid = tl.program_id(axis=0)
# -----------------------------------------------------------
# 1. Routing Phase (General)
# -----------------------------------------------------------
(
pid_m,
pid_n,
real_row_idxs,
m_mask,
offs_n,
n_mask,
M_limit,
cur_b_ptr,
cur_bias_ptr,
cur_scale_b_ptr,
cur_stride_bk,
cur_stride_bn,
) = _get_mot_pointers(
pid,
a_ptr,
b_text_ptr,
b_vae_ptr,
bias_text_ptr,
bias_vae_ptr,
scale_a_ptr,
scale_b_text_ptr,
scale_b_vae_ptr,
text_indices_ptr,
vae_indices_ptr,
M_text,
M_vae,
N,
stride_bk_text,
stride_bn_text,
stride_bk_vae,
stride_bn_vae,
BLOCK_SIZE_M,
BLOCK_SIZE_N,
GROUP_SIZE_M,
)
offs_k = tl.arange(0, BLOCK_SIZE_K)
# -----------------------------------------------------------
# 2. Compute Phase (Static Dispatch)
# -----------------------------------------------------------
if QUANT_TYPE == 0: # FP16 / BF16 Standard
c = _core_standard_gemm(
a_ptr,
cur_b_ptr,
real_row_idxs,
m_mask,
offs_n,
n_mask,
offs_k,
stride_am,
stride_ak,
cur_stride_bk,
cur_stride_bn,
0,
0,
0,
0,
K,
BLOCK_SIZE_K,
BLOCK_SIZE_M,
BLOCK_SIZE_N,
ACCUMULATOR_DTYPE,
IS_W8A8=False,
EVEN_K=EVEN_K,
EVEN_N=EVEN_N,
STRIDE_AK_IS_1=STRIDE_AK_IS_1,
STRIDE_BK_IS_1=STRIDE_BK_IS_1,
STRIDE_BN_IS_1=STRIDE_BN_IS_1,
)
elif QUANT_TYPE == 1: # W8A8
c = _core_standard_gemm(
a_ptr,
cur_b_ptr,
real_row_idxs,
m_mask,
offs_n,
n_mask,
offs_k,
stride_am,
stride_ak,
cur_stride_bk,
cur_stride_bn,
scale_a_ptr,
cur_scale_b_ptr,
stride_scale_a,
stride_scale_b,
K,
BLOCK_SIZE_K,
BLOCK_SIZE_M,
BLOCK_SIZE_N,
ACCUMULATOR_DTYPE,
IS_W8A8=True,
EVEN_K=EVEN_K,
EVEN_N=EVEN_N,
STRIDE_AK_IS_1=STRIDE_AK_IS_1,
STRIDE_BK_IS_1=STRIDE_BK_IS_1,
STRIDE_BN_IS_1=STRIDE_BN_IS_1,
)
elif QUANT_TYPE == 2 or QUANT_TYPE == 3: # Weight Only
bits = 8 if QUANT_TYPE == 2 else 4
c = _core_weight_only_gemm(
a_ptr,
cur_b_ptr,
real_row_idxs,
m_mask,
offs_n,
n_mask,
offs_k,
stride_am,
stride_ak,
cur_stride_bk,
cur_stride_bn,
cur_scale_b_ptr,
stride_scale_b,
K,
BLOCK_SIZE_K,
BLOCK_SIZE_M,
BLOCK_SIZE_N,
ACCUMULATOR_DTYPE,
COMPUTE_DTYPE,
WEIGHT_BITS=bits,
EVEN_K=EVEN_K,
EVEN_N=EVEN_N,
STRIDE_AK_IS_1=STRIDE_AK_IS_1,
STRIDE_BK_IS_1=STRIDE_BK_IS_1,
STRIDE_BN_IS_1=STRIDE_BN_IS_1,
)
# -----------------------------------------------------------
# 3. Store Phase (General)
# -----------------------------------------------------------
# Bias Add
if HAS_BIAS:
bias = tl.load(cur_bias_ptr + offs_n, mask=n_mask, other=0.0)
c = c + bias[None, :] # reshape to (1, BLOCK_SIZE_N)
# Cast C into the output dtype
c = c.to(OUTPUT_DTYPE)
# Store
offs_cm = real_row_idxs
c_ptrs = c_ptr + stride_cm * offs_cm[:, None] + stride_cn * offs_n[None, :]
# Need to be careful with the Mask here: real_row_idxs may contain 0
# (out-of-bounds padding), but c_mask needs the real boundary
store_mask = m_mask[:, None] & n_mask[None, :]
tl.store(c_ptrs, c, mask=store_mask)
# Define is_weak_contiguous
def is_weak_contiguous(x: torch.Tensor):
strides = x.stride()
sizes = x.shape
is_not_transpose = strides[0] == 1 and (strides[1] >= max(1, sizes[0]))
is_transpose = strides[1] == 1 and (strides[0] >= max(1, sizes[1]))
return is_transpose or is_not_transpose
def invoke_mot_gemm(
# Inputs
A: torch.Tensor,
B_text: torch.Tensor,
B_vae: torch.Tensor,
C: torch.Tensor,
bias_text: torch.Tensor | None,
bias_vae: torch.Tensor | None,
# Indices
text_indices: torch.Tensor,
vae_indices: torch.Tensor,
# Quant Scales (None if disabled)
A_scale: torch.Tensor | None,
B_text_scale: torch.Tensor | None,
B_vae_scale: torch.Tensor | None,
# Quant Flags
use_fp8_w8a8: bool,
use_int8_w8a8: bool,
use_int8_w8a16: bool,
use_int4_w4a16: bool,
# Quant Type
A_per_channel_quant: bool,
B_per_channel_quant: bool,
# Config
config: dict[str, Any] | None = None,
):
# ------ 1. Basic Assertions ------
M = A.size(0)
K = B_text.size(0)
N = B_text.size(1)
if config is None:
if use_fp8_w8a8:
_dtype_str: str | None = "fp8_w8a8"
elif use_int8_w8a16:
_dtype_str = "int8_w8a16"
else:
_dtype_str = None
loaded_m_key, config = get_best_mot_config(M, N, K, _dtype_str)
assert len(A.shape) == 2 and len(C.shape) == 2, (
"The input tensor and output tensor should be flattened to (batch_size*seq_len, hidden_dim)"
)
assert K == A.size(1), "the weights' first dimension should matchinputtensor's last dimension (hidden_dim)"
assert K == B_vae.size(0) and N == B_vae.size(1), (
"the weights dimension for text expert andimage expert should be the same"
)
assert C.size(0) == M and C.size(1) == N, "the output tensor shape is not correct"
M_text = text_indices.size(0)
M_vae = vae_indices.size(0)
assert M_text + M_vae == M, "the length sum of text and image indices should match input tensor's first dimension"
if bias_text is not None:
assert bias_text.dtype == C.dtype, "the bias tensor dtype should match the output tensor dtype"
if bias_vae is not None:
assert bias_vae.dtype == C.dtype, "the bias tensor dtype should match the output tensor dtype"
assert is_weak_contiguous(A)
assert is_weak_contiguous(B_text)
assert is_weak_contiguous(B_vae)
# --- 2. Quantization Logic Translation ---
def triton_dtype(torch_dtype):
if torch_dtype == torch.float8_e4m3fn:
return getattr(tl, "float8e4m3fn", tl.float8e4nv)
elif torch_dtype == torch.float8_e5m2:
return tl.float8e5
return {
torch.float16: tl.float16,
torch.bfloat16: tl.bfloat16,
torch.float32: tl.float32,
torch.int8: tl.int8,
torch.float8_e4m3fn: tl.float8e4nv,
torch.float8_e5m2: tl.float8e5,
}[torch_dtype]
# Determine QUANT_TYPE
# 0=None, 1=W8A8, 2=W8A16, 3=W4A16
quant_type = 0
ACCUMULATOR_DTYPE = tl.float32
COMPUTE_DTYPE = triton_dtype(A.dtype)
OUTPUT_DTYPE = triton_dtype(C.dtype)
if use_int8_w8a8 or use_fp8_w8a8:
quant_type = 1
assert A_scale is not None, "W8A8 requires A_scale"
assert B_text_scale is not None and B_vae_scale is not None, "W8A8 requires B_text_scale and B_vae_scale"
if use_int8_w8a8:
ACCUMULATOR_DTYPE = tl.int32
assert (
A.dtype == torch.int8
and B_text.dtype == torch.int8
and B_vae.dtype == torch.int8
and C.dtype in [torch.float16, torch.bfloat16]
), "if you want to use INT8_W8A8, A should be INT8, B should be INT8, C should be FP16/BF16"
else:
ACCUMULATOR_DTYPE = tl.float32
assert (
A.dtype in [torch.float8_e4m3fn, torch.float8_e5m2]
and B_text.dtype in [torch.float8_e4m3fn, torch.float8_e5m2]
and B_vae.dtype in [torch.float8_e4m3fn, torch.float8_e5m2]
and C.dtype in [torch.float16, torch.bfloat16]
), "if you want to use FP8_W8A8, A should be FP8, B should be FP8, C should be FP16/BF16"
elif use_int8_w8a16:
quant_type = 2
assert B_text_scale is not None and B_vae_scale is not None, "W8A16 requires B_text_scale and B_vae_scale"
ACCUMULATOR_DTYPE = tl.float32
assert (
A.dtype in [torch.float16, torch.bfloat16]
and B_text.dtype == torch.int8
and B_vae.dtype == torch.int8
and C.dtype in [torch.float16, torch.bfloat16]
), "if you want to use INT8_W8A16, A should be FP16/BF16, B should be INT8, C should be FP16/BF16"
elif use_int4_w4a16:
raise NotImplementedError("For weight-only, we only support W8A16 at this point")
# quant_type = 3
# ACCUMULATOR_DTYPE=tl.float32
# accelerate config
EVEN_K = K % config["BLOCK_SIZE_K"] == 0
EVEN_N = N % config["BLOCK_SIZE_N"] == 0
STRIDE_AK_IS_1 = A.stride(1) == 1
STRIDE_BK_IS_1 = (B_text.stride(0) == 1) and (B_vae.stride(0) == 1)
STRIDE_BN_IS_1 = (B_text.stride(1) == 1) and (B_vae.stride(1) == 1)
# bias check
assert (bias_text is None) == (bias_vae is None), (
"Bias must be provided for both Text and VAE simultaneously, or neither."
)
has_bias = bias_text is not None
# --- 3. Grid Calculation ---
def grid(META):
return (
(triton.cdiv(M_text, META["BLOCK_SIZE_M"]) + triton.cdiv(M_vae, META["BLOCK_SIZE_M"]))
* triton.cdiv(N, META["BLOCK_SIZE_N"]),
)
# --- 4. Launch ---
run_config = config.copy()
run_config.update(
{
"QUANT_TYPE": quant_type,
"ACCUMULATOR_DTYPE": ACCUMULATOR_DTYPE,
"COMPUTE_DTYPE": COMPUTE_DTYPE,
"OUTPUT_DTYPE": OUTPUT_DTYPE,
"HAS_BIAS": has_bias,
"EVEN_K": EVEN_K,
"EVEN_N": EVEN_N,
"STRIDE_AK_IS_1": STRIDE_AK_IS_1,
"STRIDE_BK_IS_1": STRIDE_BK_IS_1,
"STRIDE_BN_IS_1": STRIDE_BN_IS_1,
}
)
# Pointers (Handle None -> 0)
p_a_scale = A_scale if A_scale is not None else 0
p_b_text_scale = B_text_scale if B_text_scale is not None else 0
p_b_vae_scale = B_vae_scale if B_vae_scale is not None else 0
p_bias_text = bias_text if bias_text is not None else 0
p_bias_vae = bias_vae if bias_vae is not None else 0
# Quantization granularity
stride_scale_a = 1 if A_per_channel_quant else 0
stride_scale_b = 1 if B_per_channel_quant else 0
mot_unified_gemm_kernel[grid](
# Inputs
A,
B_text,
B_vae,
C,
p_bias_text,
p_bias_vae,
text_indices,
vae_indices,
# Dimensions
M_text,
M_vae,
N,
K,
# Strides
A.stride(0),
A.stride(1),
B_text.stride(0),
B_text.stride(1),
B_vae.stride(0),
B_vae.stride(1),
C.stride(0),
C.stride(1),
# Scales
p_a_scale,
p_b_text_scale,
p_b_vae_scale,
stride_scale_a,
stride_scale_b,
# Config
**run_config,
)
@@ -0,0 +1,286 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# ruff: noqa: N803, E741
import torch
from vllm.triton_utils import tl, triton
@triton.jit
def _mot_rms_norm_kernel(
input_ptr,
text_weight_ptr,
vae_weight_ptr,
text_indices_ptr, # MoT Routing Info
vae_indices_ptr, # MoT Routing Info
M_text, # MoT Routing Info
output_ptr,
input_row_stride,
output_row_stride,
n_cols,
eps,
BLOCK_SIZE: tl.constexpr,
):
"""
input shape: (batch_size*seq_len, hidden_size)
RMSNorm: y = x / sqrt(mean(x^2) + eps) * weight
"""
# Step 0: MoT Routing
pid = tl.program_id(0).to(tl.int64)
# dummy init (must be scalar int64[] to match tl.load return type)
row_idx = tl.cast(0, tl.int64)
weight_ptr = text_weight_ptr
if pid < M_text:
# --- Text Path ---
row_idx = tl.load(text_indices_ptr + pid)
weight_ptr = text_weight_ptr
else:
# --- VAE Path ---
vae_pid = pid - M_text
row_idx = tl.load(vae_indices_ptr + vae_pid)
weight_ptr = vae_weight_ptr
row_start_ptr = input_ptr + row_idx * input_row_stride
output_row_start_ptr = output_ptr + row_idx * output_row_stride
# Step 1: Compute sum of squares in float32 to avoid overflow
sum_sq = tl.zeros([1], dtype=tl.float32)
for col_offset in range(0, n_cols, BLOCK_SIZE):
col_idx = col_offset + tl.arange(0, BLOCK_SIZE)
mask = col_idx < n_cols
vals = tl.load(row_start_ptr + col_idx, mask=mask, other=0.0)
# Convert to float32 for accumulation to prevent overflow
vals_f32 = vals.to(tl.float32)
sq_vals = vals_f32 * vals_f32
sum_sq += tl.sum(tl.where(mask, sq_vals, 0.0))
# Step 2: Compute RMS (root mean square) in float32
mean_sq = sum_sq / n_cols
rms = tl.sqrt(mean_sq + eps)
inv_rms = 1.0 / rms
# Step 3: Normalize and apply weight
for col_offset in range(0, n_cols, BLOCK_SIZE):
col_idx = col_offset + tl.arange(0, BLOCK_SIZE)
mask = col_idx < n_cols
vals = tl.load(row_start_ptr + col_idx, mask=mask, other=0.0)
weight = tl.load(weight_ptr + col_idx, mask=mask, other=1.0)
# Compute in float32 then convert back to input dtype
vals_f32 = vals.to(tl.float32)
weight_f32 = weight.to(tl.float32)
output_f32 = vals_f32 * inv_rms * weight_f32
output = output_f32.to(vals.dtype)
tl.store(output_row_start_ptr + col_idx, output, mask=mask)
@triton.jit
def _mot_rms_norm_qk_kernel(
input_ptr,
text_weight_ptr,
vae_weight_ptr,
text_indices_ptr,
vae_indices_ptr,
M_text,
output_ptr,
stride_tok,
stride_head,
out_stride_tok,
out_stride_head,
num_heads,
head_dim,
eps,
BLOCK_DIM: tl.constexpr, # for head_dim=128,should be 128
SHARED_WEIGHT: tl.constexpr, # weights are shared across heads
):
pid_tok = tl.program_id(0).to(tl.int64)
# MoT Routing
if pid_tok < M_text:
row_idx = tl.load(text_indices_ptr + pid_tok)
weight_ptr = text_weight_ptr
else:
vae_pid = pid_tok - M_text
row_idx = tl.load(vae_indices_ptr + vae_pid)
weight_ptr = vae_weight_ptr
dim_offsets = tl.arange(0, BLOCK_DIM)
mask = dim_offsets < head_dim
# input.shape=(4098,28,128)=(seq_len,num_heads,head_dim)
# weight.shape=(28,128)=(num_heads,head_dim) or (128,)=(head_dim)
tok_in_ptr = input_ptr + row_idx * stride_tok
tok_out_ptr = output_ptr + row_idx * out_stride_tok
# if weight.shape=(128,)
if SHARED_WEIGHT:
weight = tl.load(weight_ptr + dim_offsets, mask=mask, other=1.0)
weight_f32 = weight.to(tl.float32)
# one program loop over all heads
for h in range(num_heads):
head_in_ptr = tok_in_ptr + h * stride_head
head_out_ptr = tok_out_ptr + h * out_stride_head
# if weight.shape=(28,128)
if not SHARED_WEIGHT:
weight_offset = h * head_dim + dim_offsets
weight = tl.load(weight_ptr + weight_offset, mask=mask, other=1.0)
weight_f32 = weight.to(tl.float32)
vals = tl.load(head_in_ptr + dim_offsets, mask=mask, other=0.0)
vals_f32 = vals.to(tl.float32)
sq_vals = vals_f32 * vals_f32
sum_sq = tl.sum(tl.where(mask, sq_vals, 0.0))
mean_sq = sum_sq / head_dim
rms = tl.sqrt(mean_sq + eps)
inv_rms = 1.0 / rms
output_f32 = vals_f32 * inv_rms * weight_f32
tl.store(head_out_ptr + dim_offsets, output_f32.to(vals.dtype), mask=mask)
def mot_rms_norm(
input: torch.Tensor,
text_weight: torch.Tensor,
vae_weight: torch.Tensor,
text_indices: torch.Tensor,
vae_indices: torch.Tensor,
head_norm: bool = False,
eps: float = 1e-6,
block_size: int | None = None,
) -> torch.Tensor:
"""
Compute RMS normalization using Triton kernel.
RMS Norm normalizes the input by the root mean square and scales by weight:
output = input / sqrt(mean(input^2) + eps) * weight
Args:
input: Input tensor of shape (batch_size*seq_len, hidden_size) or (batch_size,seq_len, hidden_size)
text_weight: Weight for text tokens tensor of shape (hidden_size,)
vae_weight: Weight for vae tokens tensor of shape (hidden_size,)
text_indices: indices of text tokens, (batch_size*2,)
vae_indices: indices of vae tokens, (batch_size*(seq_len-2),)
eps: Small constant for numerical stability
Returns:
Tensor with RMS normalization applied along the last dimension
"""
assert input.shape[-1] == text_weight.shape[-1], (
f"Input last dimension ({input.shape[-1]}) must match Text weight dimension ({text_weight.shape[-1]})"
)
assert input.shape[-1] == vae_weight.shape[-1], (
f"Input last dimension ({input.shape[-1]}) must match VAE weight dimension ({vae_weight.shape[-1]})"
)
original_shape = input.shape
text_indices = text_indices.reshape(-1)
vae_indices = vae_indices.reshape(-1)
M_text = text_indices.shape[0]
M_vae = vae_indices.shape[0]
num_tokens = M_text + M_vae
if not head_norm:
input_2d = input.reshape(-1, input.shape[-1])
assert input_2d.shape[0] == num_tokens, (
f"batch_size={input_2d.shape[0]}, len(text_indices)={M_text}, len(vae_indices)={M_vae}"
f"for layer norm, batched_token_length should match the sum of indices_length"
)
input_2d = input_2d.contiguous()
text_indices = text_indices.contiguous()
vae_indices = vae_indices.contiguous()
text_weight = text_weight.contiguous()
vae_weight = vae_weight.contiguous()
n_rows, n_cols = input_2d.shape
output = torch.empty_like(input_2d)
if block_size is None:
block_size = triton.next_power_of_2(n_cols)
block_size = min(block_size, 4096)
num_warps = 4
if block_size >= 2048:
num_warps = 8
elif block_size >= 1024:
num_warps = 4
else:
num_warps = 2
grid = (n_rows,)
_mot_rms_norm_kernel[grid](
input_2d,
text_weight,
vae_weight,
text_indices,
vae_indices,
M_text,
output,
input_2d.stride(0),
output.stride(0),
n_cols,
eps,
BLOCK_SIZE=block_size,
num_warps=num_warps,
)
return output.reshape(original_shape)
else:
# qk norm scenarios:
# input.shape=(batch_size, seq_len,head_num, head_dim) or
# input.shape=(batch_size*seq_len,head_num, head_dim)
assert len(original_shape) > 2, (
"If head_norm=True,input shape be 3D or 3D, last 2 dimensions should be head_num and head_dim"
)
num_heads = input.shape[-2]
head_dim = input.shape[-1]
is_shared_weight = text_weight.dim() == 1
if not is_shared_weight:
assert num_heads == text_weight.shape[0] and num_heads == vae_weight.shape[0], (
"when weights are not shared across heads, the first dimension of "
"weights should be num of heads and match input.shape[-2]"
)
# reshape to 3D
input_3d = input.view(-1, num_heads, head_dim)
input_3d = input_3d.contiguous()
text_indices = text_indices.contiguous()
vae_indices = vae_indices.contiguous()
text_weight = text_weight.contiguous()
vae_weight = vae_weight.contiguous()
output_3d = torch.empty_like(input_3d)
block_dim = triton.next_power_of_2(head_dim)
num_warps = 4 if block_dim > 128 else 2
num_stages = 3
_mot_rms_norm_qk_kernel[(num_tokens,)](
input_3d,
text_weight,
vae_weight,
text_indices,
vae_indices,
M_text,
output_3d,
input_3d.stride(0),
input_3d.stride(1),
output_3d.stride(0),
output_3d.stride(1),
num_heads,
head_dim,
eps,
BLOCK_DIM=block_dim,
SHARED_WEIGHT=is_shared_weight,
num_warps=num_warps,
num_stages=num_stages,
)
return output_3d.view(original_shape)
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""
BagelPipeline implementation for vLLM-Omni.
"""
@@ -316,6 +316,11 @@ class BagelPipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipelineProf
"bagel.connector",
"bagel.vit_pos_embed",
]
# LoRA scanning target. ``_dit_modules`` holds the dotted path
# "language_model.model", which DiffusionLoRAManager cannot resolve as a
# pipeline attribute, so the top-level ``bagel`` module (LLM plus ViT,
# connector, and VAE projections) is declared explicitly here.
_lora_components: ClassVar[list[str]] = ["bagel"]
supports_step_execution: ClassVar[bool] = True
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
@@ -15,6 +15,7 @@
# inference caches (TeaCache/TaylorSeer) are not ported.
import itertools
from collections import defaultdict
from collections.abc import Iterable
from typing import TYPE_CHECKING
@@ -24,17 +25,25 @@ import torch.nn.functional as F
from diffusers.models.embeddings import Timesteps, get_1d_rotary_pos_embed
from einops import rearrange, repeat
from vllm.logger import init_logger
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
MergedColumnParallelLinear,
QKVParallelLinear,
ReplicatedLinear,
RowParallelLinear,
)
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.platforms import current_platform
from vllm.triton_utils import HAS_TRITON
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.diffusion.layers.fused_qk_norm_rope import (
_fused_cuda_supported,
fused_qk_norm_rope,
fused_qk_norm_rope_min_tokens,
)
from vllm_omni.diffusion.layers.norm import RMSNorm
from vllm_omni.diffusion.models.utils import make_attention_mask
from vllm_omni.platforms import current_omni_platform
@@ -43,7 +52,10 @@ if TYPE_CHECKING:
logger = init_logger(__name__)
RotaryEmbedding = tuple[torch.Tensor, torch.Tensor]
# (cos, sin) — optionally (cos, sin, packed_table) where packed_table is the
# fp32 [tokens, head_dim] = [cos(theta) | sin(theta)] layout the fused
# qk-norm+RoPE op consumes; the eager path ignores the third element.
RotaryEmbedding = tuple[torch.Tensor, ...]
RotaryFrequencyTables = list[RotaryEmbedding]
@@ -56,9 +68,12 @@ def apply_rotary_emb(x: torch.Tensor, rotary_emb: RotaryEmbedding) -> torch.Tens
Args:
x: Query or key tensor of shape [B, S, H, D].
rotary_emb: Cosine and sine tensors, each shaped [B, S, D].
rotary_emb: Cosine and sine tensors, each shaped [B, S, D]. The tuple
may carry a third element (the packed table for the fused
qk-norm+RoPE path); it is ignored here, hence the indexed access
instead of tuple unpacking.
"""
freqs_cos, freqs_sin = rotary_emb
freqs_cos, freqs_sin = rotary_emb[0], rotary_emb[1]
freqs_cos = freqs_cos.unsqueeze(2)
freqs_sin = freqs_sin.unsqueeze(2)
@@ -73,6 +88,87 @@ def apply_rotary_emb(x: torch.Tensor, rotary_emb: RotaryEmbedding) -> torch.Tens
return x_out.type_as(x)
# The fused qk-norm+RoPE path is always on where the fast path exists; on
# other platforms the eager chain below is the behaviour-identical fallback.
_FUSED_QK_NORM_ROPE = HAS_TRITON and current_platform.is_cuda()
# Boogu's default for the fused-path token gate: fuse only when a rotary table
# spans at least this many positions (counted as B*S). Below the crossover a
# request is host-bound and the fused path's per-call Python launch (custom-op
# impl + Triton launcher) can cost more end-to-end than the kernel saves.
# Measured on one H200: on the pre-#6871 main, 512^2 (1.1k tokens) paid
# +191 ms/request and the crossover sat at ~2,350 tokens; on the current main
# the 512^2 family measures as noise (+/-25 ms, sign-inconsistent) while
# >=768^2 (2.3k tokens) gains. The crossover is host-dependent — re-benchmark
# on your hardware and override with VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS
# (0 = always fuse); see fused_qk_norm_rope_min_tokens().
_FUSED_MIN_TOKENS = 2048
def _with_packed_rope_table(rotary_emb: RotaryEmbedding) -> RotaryEmbedding:
"""Append the packed fp32 table the fused qk-norm+RoPE op consumes.
``freqs_cos``/``freqs_sin`` are theta-repeat-interleaved ``[B, S, D]``
(``cos[2i] == cos[2i+1] == cos(theta_i)``), so taking every even column
yields the theta-width halves and the packed table is
``[B*S, D] = [cos(theta) | sin(theta)]``. Tables spanning fewer positions
(counted as ``B*S``) than the token gate — Boogu's ``_FUSED_MIN_TOKENS``
default, overridable through ``VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS``
(``0`` = always fuse) — are returned unchanged: without the third element
every consumer stays on the eager chain (this also keeps short tables like
the context refiner's off the fused path).
"""
freqs_cos, freqs_sin = rotary_emb[0], rotary_emb[1]
if freqs_cos.shape[0] * freqs_cos.shape[1] < fused_qk_norm_rope_min_tokens(_FUSED_MIN_TOKENS):
return rotary_emb
packed = torch.cat((freqs_cos[..., ::2], freqs_sin[..., ::2]), dim=-1)
return freqs_cos, freqs_sin, packed.reshape(-1, freqs_cos.shape[-1]).float()
def _qk_norm_rope(
query: torch.Tensor,
key: torch.Tensor,
norm_q,
norm_k,
rotary_emb: RotaryEmbedding | None,
dtype: torch.dtype,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Per-head Q/K RMSNorm + RoPE + cast, fused into one kernel launch when
a packed rope table is present; otherwise the original eager chain."""
# Gate on the op's own fast-path predicate: when the fused CUDA kernel
# cannot run (dtype, device, or geometry outside even
# rotary_dim <= head_dim <= 256), the original chain below must be used
# bit-exactly rather than the op's internal eager fallback, whose rounding
# differs from vLLM's RMSNorm by one ulp on a fraction of elements.
if (
rotary_emb is not None
and len(rotary_emb) > 2
and rotary_emb[2] is not None
and _fused_cuda_supported(query, key, query.shape[-1], query.shape[-1], interleaved=True)
):
batch, seq_len, num_heads, head_dim = query.shape
num_kv_heads = key.shape[2]
fused_q, fused_k = fused_qk_norm_rope(
query.view(batch * seq_len, num_heads, head_dim),
key.view(batch * seq_len, num_kv_heads, head_dim),
norm_q.weight,
norm_k.weight,
rotary_emb[2],
norm_q.variance_epsilon,
interleaved=True,
)
return (
fused_q.view(batch, seq_len, num_heads, head_dim),
fused_k.view(batch, seq_len, num_kv_heads, head_dim),
)
query = norm_q(query)
key = norm_k(key)
if rotary_emb is not None:
query = apply_rotary_emb(query, rotary_emb)
key = apply_rotary_emb(key, rotary_emb)
return query.to(dtype), key.to(dtype)
def swiglu(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
return F.silu(x.float(), inplace=False).to(x.dtype) * y
@@ -166,7 +262,14 @@ class LuminaLayerNormContinuous(nn.Module):
class LuminaFeedForward(nn.Module):
"""SwiGLU feed-forward with tensor-parallel projections."""
"""SwiGLU feed-forward with tensor-parallel projections.
The ``gate`` and ``input`` projections are fused into a single
``MergedColumnParallelLinear`` (one GEMM instead of two), matching the
``gate_up_proj`` convention used by the Hunyuan Image 3 port. The SwiGLU
activation keeps its float32 computation for numerical parity with
upstream.
"""
def __init__(
self,
@@ -182,20 +285,13 @@ class LuminaFeedForward(nn.Module):
inner_dim = int(ffn_dim_multiplier * inner_dim)
inner_dim = multiple_of * ((inner_dim + multiple_of - 1) // multiple_of)
self.linear_1 = ColumnParallelLinear(
dim,
inner_dim,
self.gate_up_proj = MergedColumnParallelLinear(
input_size=dim,
output_sizes=[inner_dim, inner_dim],
bias=False,
quant_config=quant_config,
prefix=_join_prefix(prefix, "linear_1"),
) # gate
self.linear_3 = ColumnParallelLinear(
dim,
inner_dim,
bias=False,
quant_config=quant_config,
prefix=_join_prefix(prefix, "linear_3"),
) # input
prefix=_join_prefix(prefix, "gate_up_proj"),
)
self.linear_2 = RowParallelLinear(
inner_dim,
dim,
@@ -205,8 +301,8 @@ class LuminaFeedForward(nn.Module):
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
h1, _ = self.linear_1(x)
h2, _ = self.linear_3(x)
gate_up, _ = self.gate_up_proj(x)
h1, h2 = gate_up.chunk(2, dim=-1)
out, _ = self.linear_2(swiglu(h1, h2))
return out
@@ -499,28 +595,15 @@ class BooguImageSelfAttention(nn.Module):
) -> None:
super().__init__()
self.head_dim = dim // num_attention_heads
kv_dim = self.head_dim * num_kv_heads
self.to_q = ColumnParallelLinear(
dim,
dim,
self.to_qkv = QKVParallelLinear(
hidden_size=dim,
head_size=self.head_dim,
total_num_heads=num_attention_heads,
total_num_kv_heads=num_kv_heads,
bias=False,
quant_config=quant_config,
prefix=_join_prefix(prefix, "to_q"),
)
self.to_k = ColumnParallelLinear(
dim,
kv_dim,
bias=False,
quant_config=quant_config,
prefix=_join_prefix(prefix, "to_k"),
)
self.to_v = ColumnParallelLinear(
dim,
kv_dim,
bias=False,
quant_config=quant_config,
prefix=_join_prefix(prefix, "to_v"),
prefix=_join_prefix(prefix, "to_qkv"),
)
self.norm_q = RMSNorm(self.head_dim, eps=1e-5)
self.norm_k = RMSNorm(self.head_dim, eps=1e-5)
@@ -532,8 +615,10 @@ class BooguImageSelfAttention(nn.Module):
prefix=_join_prefix(prefix, "to_out"),
)
self.num_local_heads = self.to_q.output_size_per_partition // self.head_dim
self.num_local_kv_heads = self.to_k.output_size_per_partition // self.head_dim
self.num_local_heads = self.to_qkv.num_heads
self.num_local_kv_heads = self.to_qkv.num_kv_heads
self.q_size = self.num_local_heads * self.head_dim
self.kv_size = self.num_local_kv_heads * self.head_dim
self.attn = Attention(
num_heads=self.num_local_heads,
@@ -551,21 +636,14 @@ class BooguImageSelfAttention(nn.Module):
) -> torch.Tensor:
dtype = hidden_states.dtype
query, _ = self.to_q(hidden_states)
key, _ = self.to_k(hidden_states)
value, _ = self.to_v(hidden_states)
qkv, _ = self.to_qkv(hidden_states)
query, key, value = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
query = query.unflatten(-1, (self.num_local_heads, self.head_dim))
key = key.unflatten(-1, (self.num_local_kv_heads, self.head_dim))
value = value.unflatten(-1, (self.num_local_kv_heads, self.head_dim))
query = self.norm_q(query)
key = self.norm_k(key)
if rotary_emb is not None:
query = apply_rotary_emb(query, rotary_emb)
key = apply_rotary_emb(key, rotary_emb)
query, key = query.to(dtype), key.to(dtype)
query, key = _qk_norm_rope(query, key, self.norm_q, self.norm_k, rotary_emb, dtype)
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
attn_output = self.attn(query, key, value, attn_metadata)
@@ -595,50 +673,24 @@ class BooguImageJointAttention(nn.Module):
) -> None:
super().__init__()
self.head_dim = dim // num_attention_heads
kv_dim = self.head_dim * num_kv_heads
self.img_to_q = ColumnParallelLinear(
dim,
dim,
self.img_to_qkv = QKVParallelLinear(
hidden_size=dim,
head_size=self.head_dim,
total_num_heads=num_attention_heads,
total_num_kv_heads=num_kv_heads,
bias=False,
quant_config=quant_config,
prefix=_join_prefix(prefix, "img_to_q"),
prefix=_join_prefix(prefix, "img_to_qkv"),
)
self.img_to_k = ColumnParallelLinear(
dim,
kv_dim,
self.instruct_to_qkv = QKVParallelLinear(
hidden_size=dim,
head_size=self.head_dim,
total_num_heads=num_attention_heads,
total_num_kv_heads=num_kv_heads,
bias=False,
quant_config=quant_config,
prefix=_join_prefix(prefix, "img_to_k"),
)
self.img_to_v = ColumnParallelLinear(
dim,
kv_dim,
bias=False,
quant_config=quant_config,
prefix=_join_prefix(prefix, "img_to_v"),
)
self.instruct_to_q = ColumnParallelLinear(
dim,
dim,
bias=False,
quant_config=quant_config,
prefix=_join_prefix(prefix, "instruct_to_q"),
)
self.instruct_to_k = ColumnParallelLinear(
dim,
kv_dim,
bias=False,
quant_config=quant_config,
prefix=_join_prefix(prefix, "instruct_to_k"),
)
self.instruct_to_v = ColumnParallelLinear(
dim,
kv_dim,
bias=False,
quant_config=quant_config,
prefix=_join_prefix(prefix, "instruct_to_v"),
prefix=_join_prefix(prefix, "instruct_to_qkv"),
)
self.norm_q = RMSNorm(self.head_dim, eps=1e-5)
@@ -669,8 +721,10 @@ class BooguImageJointAttention(nn.Module):
prefix=_join_prefix(prefix, "to_out"),
)
self.num_local_heads = self.img_to_q.output_size_per_partition // self.head_dim
self.num_local_kv_heads = self.img_to_k.output_size_per_partition // self.head_dim
self.num_local_heads = self.img_to_qkv.num_heads
self.num_local_kv_heads = self.img_to_qkv.num_kv_heads
self.q_size = self.num_local_heads * self.head_dim
self.kv_size = self.num_local_kv_heads * self.head_dim
self.attn = Attention(
num_heads=self.num_local_heads,
@@ -692,13 +746,13 @@ class BooguImageJointAttention(nn.Module):
dtype = img_hidden_states.dtype
batch_size = img_hidden_states.shape[0]
img_query, _ = self.img_to_q(img_hidden_states)
img_key, _ = self.img_to_k(img_hidden_states)
img_value, _ = self.img_to_v(img_hidden_states)
img_qkv, _ = self.img_to_qkv(img_hidden_states)
img_query, img_key, img_value = img_qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
instruct_query, _ = self.instruct_to_q(instruct_hidden_states)
instruct_key, _ = self.instruct_to_k(instruct_hidden_states)
instruct_value, _ = self.instruct_to_v(instruct_hidden_states)
instruct_qkv, _ = self.instruct_to_qkv(instruct_hidden_states)
instruct_query, instruct_key, instruct_value = instruct_qkv.split(
[self.q_size, self.kv_size, self.kv_size], dim=-1
)
query, key, value = _concat_instruction_image_features(
[img_query, img_key, img_value],
@@ -711,13 +765,7 @@ class BooguImageJointAttention(nn.Module):
key = key.view(batch_size, -1, self.num_local_kv_heads, self.head_dim)
value = value.view(batch_size, -1, self.num_local_kv_heads, self.head_dim)
query = self.norm_q(query)
key = self.norm_k(key)
if rotary_emb is not None:
query = apply_rotary_emb(query, rotary_emb)
key = apply_rotary_emb(key, rotary_emb)
query, key = query.to(dtype), key.to(dtype)
query, key = _qk_norm_rope(query, key, self.norm_q, self.norm_k, rotary_emb, dtype)
attn_metadata = AttentionMetadata(attn_mask=joint_attention_mask) if joint_attention_mask is not None else None
attn_output = self.attn(query, key, value, attn_metadata)
@@ -1053,6 +1101,44 @@ def _cal_preprocessed_instruction_feat_dim(instruction_feature_configs: dict) ->
raise ValueError(f"Invalid reduce_type: {reduce_type}")
# Packed (fused) projections vs. the logical sub-projections the diffusers
# checkpoint stores, in the ``(param_name, shard_name, shard_id)`` form used
# across vllm-omni. ``load_weights`` consumes it directly, and loader consumers
# that discover it via ``stacked_params_mapping`` (LoRA, quantized loaders) get
# the packed -> sub-layer relationship for free.
#
# The QKV entries stay leaf-scoped: each fused source (``to_q`` on the
# self-attention module, ``img_to_q`` / ``instruct_to_q`` on the joint
# attention) has a distinct leaf, and ``.to_q.`` cannot collide with
# ``.img_to_q.`` because the preceding character is ``_`` rather than ``.``.
# The FFN entries are path-qualified instead: ``linear_1`` also names the
# timestep embedder and the ``norm_out`` projections, which must load 1:1 and
# are not fused.
_BOOGU_STACKED_PARAMS_MAPPING = (
# self-attention: noise / reference-image / context refiners, the
# single-stream blocks, and the double-stream image self-attention.
(".to_qkv.", ".to_q.", "q"),
(".to_qkv.", ".to_k.", "k"),
(".to_qkv.", ".to_v.", "v"),
# joint (instruction + image) attention of the double-stream blocks.
(".img_to_qkv.", ".img_to_q.", "q"),
(".img_to_qkv.", ".img_to_k.", "k"),
(".img_to_qkv.", ".img_to_v.", "v"),
(".instruct_to_qkv.", ".instruct_to_q.", "q"),
(".instruct_to_qkv.", ".instruct_to_k.", "k"),
(".instruct_to_qkv.", ".instruct_to_v.", "v"),
# feed-forward gate/up: ``linear_1`` is the gate (shard 0) and
# ``linear_3`` the input (shard 1), matching the packed order the SwiGLU
# activation consumes.
(".feed_forward.gate_up_proj.", ".feed_forward.linear_1.", 0),
(".feed_forward.gate_up_proj.", ".feed_forward.linear_3.", 1),
(".img_feed_forward.gate_up_proj.", ".img_feed_forward.linear_1.", 0),
(".img_feed_forward.gate_up_proj.", ".img_feed_forward.linear_3.", 1),
(".instruct_feed_forward.gate_up_proj.", ".instruct_feed_forward.linear_1.", 0),
(".instruct_feed_forward.gate_up_proj.", ".instruct_feed_forward.linear_3.", 1),
)
class BooguImageTransformer2DModel(nn.Module):
"""Boogu-Image transformer with mixed stream topology.
@@ -1078,6 +1164,10 @@ class BooguImageTransformer2DModel(nn.Module):
prefix: str = "",
) -> None:
super().__init__()
# Published here rather than in ``load_weights`` so loader consumers
# that only inspect the module tree (LoRA discovery, quantized weight
# loaders) always see the packed -> sub-layer relationship.
self.stacked_params_mapping = list(_BOOGU_STACKED_PARAMS_MAPPING)
self.od_config = od_config
cfg = od_config.tf_model_config
@@ -1449,6 +1539,11 @@ class BooguImageTransformer2DModel(nn.Module):
shift += ref_img_len
idx += 1
if _FUSED_QK_NORM_ROPE:
# The rebuilt per-reference-image tuple needs its own packed
# table; the forward-level tuples do not flow into this batch.
batch_ref_img_rotary_emb = _with_packed_rope_table(batch_ref_img_rotary_emb)
for layer in self.ref_image_refiner:
batch_ref_image_hidden_states = layer(
batch_ref_image_hidden_states, batch_ref_img_mask, batch_ref_img_rotary_emb, batch_temb
@@ -1534,6 +1629,17 @@ class BooguImageTransformer2DModel(nn.Module):
device,
)
if _FUSED_QK_NORM_ROPE:
# One packed [cos|sin] table per rotary embedding that reaches an
# attention, built once per forward; the tuples grow a third
# element that the fused path consumes and the eager path ignores.
# (ref_img_rotary_emb is packed inside img_patch_embed_and_refine,
# on the rebuilt per-reference-image batch tuple.)
context_rotary_emb = _with_packed_rope_table(context_rotary_emb)
noise_rotary_emb = _with_packed_rope_table(noise_rotary_emb)
rotary_emb = _with_packed_rope_table(rotary_emb)
combined_img_rotary_emb = _with_packed_rope_table(combined_img_rotary_emb)
# Context refinement.
for layer in self.context_refiner:
instruction_hidden_states = layer(instruction_hidden_states, instruction_attention_mask, context_rotary_emb)
@@ -1612,7 +1718,7 @@ class BooguImageTransformer2DModel(nn.Module):
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
"""Load diffusers-named checkpoint weights into the native module.
Two name promotions relative to upstream (see step 8/10 findings):
Name promotions relative to upstream (see step 8/10 findings):
- ``*.img_instruct_attn.processor.{img,instruct}_{to_q,to_k,to_v}`` /
``{instruct,img}_out`` -> drop ``.processor`` (upstream keeps the
@@ -1621,9 +1727,29 @@ class BooguImageTransformer2DModel(nn.Module):
- ``*.to_out.0.weight`` -> ``*.to_out.weight`` (diffusers wraps the
output projection in a ``ModuleList``; the native module uses a plain
linear).
Packed Q/K/V and FFN gate/input matrices are folded onto the fused
``QKVParallelLinear`` / ``MergedColumnParallelLinear`` parameters using
:attr:`stacked_params_mapping` — the same mapping loader consumers such
as LoRA discovery and quantized weight loaders read.
A fused parameter is only reported as loaded once *every* one of its
source matrices has arrived. The caller compares parameter names, so
reporting e.g. ``to_qkv`` complete after the first shard would let a
checkpoint carrying only ``to_q`` start up with the ``k``/``v`` slices
left uninitialized.
"""
stacked_params_mapping = self.stacked_params_mapping
# The shard ids each fused parameter is assembled from, keyed by the
# mapping entry that produces it.
expected_shards: dict[str, set[str | int]] = defaultdict(set)
for param_name, _weight_name, packed_shard_id in stacked_params_mapping:
expected_shards[param_name].add(packed_shard_id)
params_dict = dict(self.named_parameters())
loaded_params: set[str] = set()
# Fused parameter -> (mapping entry that produced it, shards received).
fused_params: dict[str, tuple[str, set[str | int]]] = {}
for name, loaded_weight in weights:
original_name = name
@@ -1632,15 +1758,36 @@ class BooguImageTransformer2DModel(nn.Module):
if ".to_out.0." in name:
name = name.replace(".to_out.0.", ".to_out.")
shard_id: str | int | None = None
matched_entry: str | None = None
for param_name, weight_name, packed_shard_id in stacked_params_mapping:
if weight_name in name:
name = name.replace(weight_name, param_name)
shard_id = packed_shard_id
matched_entry = param_name
break
if name not in params_dict:
logger.warning("Skipping unexpected checkpoint weight %s", original_name)
continue
param = params_dict[name]
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, loaded_weight)
if matched_entry is None:
weight_loader(param, loaded_weight)
else:
weight_loader(param, loaded_weight, shard_id)
_, received = fused_params.setdefault(name, (matched_entry, set()))
received.add(shard_id)
loaded_params.add(name)
# Withdraw any fused parameter that only received part of its source
# matrices, so the caller's "not initialized from checkpoint" check
# reports it as missing instead of accepting a half-filled parameter.
for name, (matched_entry, received) in fused_params.items():
if received != expected_shards[matched_entry]:
loaded_params.discard(name)
unloaded_params = sorted(params_dict.keys() - loaded_params)
if unloaded_params:
logger.warning("Model parameters not loaded from checkpoint: %s", unloaded_params)
@@ -34,9 +34,13 @@ from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from diffusers.utils.torch_utils import randn_tensor
from torch import nn
from torch.nn.attention import SDPBackend, sdpa_kernel
from transformers import Qwen3VLForConditionalGeneration, Qwen3VLProcessor
from transformers import AutoModel, Qwen3VLConfig, Qwen3VLForConditionalGeneration, Qwen3VLModel, Qwen3VLProcessor
from vllm.config.quantization import QuantizationConfigArgs
from vllm.logger import init_logger
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
from vllm.model_executor.layers.quantization.fp8 import Fp8Config
from vllm.model_executor.layers.quantization.online.base import OnlineQuantizationConfig
from vllm.model_executor.models.utils import AutoWeightsLoader, WeightsMapper
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
@@ -54,6 +58,7 @@ from vllm_omni.diffusion.models.boogu_image.scheduling_flow_match_euler_discrete
)
from vllm_omni.diffusion.models.interface import SupportImageInput, SupportsComponentDiscovery
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
from vllm_omni.diffusion.models.utils import create_transformers_model_with_vllm_linears
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch, split_diffusion_output_by_request
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
@@ -243,6 +248,7 @@ class BooguImagePipeline(CFGParallelMixin, nn.Module, ProgressBarMixin, Supports
self.od_config = od_config
self._raise_unsupported_features()
transformer_quant_config = resolve_component_quant_config(od_config.quantization_config, "transformer")
mllm_quant_config = resolve_component_quant_config(od_config.quantization_config, "mllm")
self.weights_sources = [
DiffusersPipelineLoader.ComponentSource(
model_or_path=od_config.model,
@@ -273,22 +279,7 @@ class BooguImagePipeline(CFGParallelMixin, nn.Module, ProgressBarMixin, Supports
local_files_only=local_files_only,
revision=od_config.revision,
)
mllm = from_pretrained_with_prefetch(
Qwen3VLForConditionalGeneration.from_pretrained,
model,
subfolder="mllm",
prefetch_list=boogu_subfolders,
local_files_only=local_files_only,
torch_dtype=od_config.dtype,
revision=od_config.revision,
)
# Upstream reuses the full VLM as an optional instruction rewriter and
# encodes with its inner model (no ``lm_head``); the rewriter is not
# ported, so keep only the inner ``Qwen3VLModel`` as the encoder.
if hasattr(mllm, "lm_head"):
mllm = mllm.model
self.mllm = mllm.to(self._execution_device)
self.mllm = self._load_mllm(model, local_files_only, mllm_quant_config, boogu_subfolders)
self.processor = Qwen3VLProcessor.from_pretrained(
model,
@@ -323,6 +314,68 @@ class BooguImagePipeline(CFGParallelMixin, nn.Module, ProgressBarMixin, Supports
self.SYSTEM_PROMPT_4_TI2I = SYSTEM_PROMPT_4_TI2I_UNIFIED
self.SYSTEM_PROMPT_4_I2I = SYSTEM_PROMPT_4_TI2I_UNIFIED
def _load_mllm(
self,
model_path: str,
local_files_only: bool,
quant_config: QuantizationConfig | None,
prefetch_list: list[str],
) -> Qwen3VLModel:
"""Load MLLM through HF, or prepare it for deferred online FP8 loading."""
config = None
if quant_config is not None:
if not isinstance(quant_config, Fp8Config):
raise ValueError(
"Boogu MLLM only supports FP8 quantization. Set mllm to null to disable online quantization."
)
config = Qwen3VLConfig.from_pretrained(
model_path, subfolder="mllm", local_files_only=local_files_only, revision=self.od_config.revision
)
# With no MLLM quantization override, or with checkpoint quantization
# metadata, preserve HF model initialization and weight loading.
if config is None or getattr(config, "quantization_config", None):
mllm = from_pretrained_with_prefetch(
Qwen3VLForConditionalGeneration.from_pretrained,
model_path,
subfolder="mllm",
prefetch_list=prefetch_list,
local_files_only=local_files_only,
torch_dtype=self.od_config.dtype,
revision=self.od_config.revision,
)
# Upstream reuses the full VLM as an optional instruction rewriter and
# encodes with its inner model (no ``lm_head``); the rewriter is not
# ported, so keep only the inner ``Qwen3VLModel`` as the encoder.
if hasattr(mllm, "lm_head"):
mllm = mllm.model
return mllm.to(self._execution_device)
online_quant_config = OnlineQuantizationConfig(
QuantizationConfigArgs(linear="fp8_per_block", ignore=quant_config.ignored_layers)
)
mllm = create_transformers_model_with_vllm_linears(
AutoModel,
config,
online_quant_config,
dtype=self.od_config.dtype,
device=self._execution_device,
prefix="mllm",
skip_modules=("mllm.visual",),
)
self.weights_sources.append(
DiffusersPipelineLoader.ComponentSource(
model_or_path=model_path,
subfolder="mllm",
revision=self.od_config.revision,
prefix="mllm.",
)
)
return mllm.requires_grad_(False).eval()
def _raise_unsupported_features(self) -> None:
"""Reject execution modes that do not have Boogu-specific support."""
parallel_config = self.od_config.parallel_config
@@ -339,7 +392,8 @@ class BooguImagePipeline(CFGParallelMixin, nn.Module, ProgressBarMixin, Supports
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
loader = AutoWeightsLoader(self)
return loader.load_weights(weights)
mapper = WeightsMapper(orig_to_new_prefix={"mllm.lm_head.": None, "mllm.model.": "mllm."})
return loader.load_weights(weights, mapper=mapper)
# ------------------------------------------------------------------
# Prompt encoding (upstream ``encode_instruction``, t2i path)
@@ -38,13 +38,24 @@ EMBODIMENT_TO_DOMAIN_ID: dict[str, int] = {
"bridge_orig_lerobot": 7,
"droid_lerobot": 8,
"robomind-franka": 8,
"embodiment_b": 9,
# Backward-compatible alias for the pre-generator Cosmos Framework name.
"galbot": 9,
"robomind-franka-dual": 12,
"robomind-ur": 13,
"agibotworld": 15,
"embodiment_c_gripper": 15,
"embodiment_c_gripper_ext": 15,
# Backward-compatible aliases for the pre-generator Cosmos Framework names.
"agibot_gear_gripper": 15,
"agibot_gear_gripper_ext": 15,
"xdof_yam": 16,
"molmoact2_yam": 16,
"abc_yam": 16,
"fractal": 20,
"drawanything": 21,
"behavior1k_lerobot": 22,
"maniparena": 23,
}
@@ -0,0 +1,14 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Scheduled A16 execution for quantized Cosmos3 checkpoints."""
from .checkpoint import resolve_mixed_precision_config
from .config import Cosmos3MixedPrecisionConfig
from .runtime import Cosmos3MixedPrecisionRuntime
__all__ = [
"Cosmos3MixedPrecisionConfig",
"Cosmos3MixedPrecisionRuntime",
"resolve_mixed_precision_config",
]
@@ -0,0 +1,176 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Checkpoint discovery for the Cosmos3 diffusion-step precision policy."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Literal, cast
from .config import Cosmos3MixedPrecisionConfig, ReasonerPolicy, _non_negative_int
PolicySource = Literal[
"none",
"checkpoint",
"additional_config",
"additional_config_disabled",
]
_COMPONENT = "transformer"
_POLICY_FIELDS = frozenset(
{
"schema_version",
"type",
"index_space",
"scope",
"default_mode",
"first_steps",
"last_steps",
"overlap",
"reasoner",
}
)
_STEP_RANGE_FIELDS = frozenset({"count", "mode"})
_SUPPORTED_MODEL_OPT_CONFIGS = frozenset(
{
"modelopt",
"modelopt_fp4",
}
)
def resolve_mixed_precision_config(
od_config: object,
) -> tuple[Cosmos3MixedPrecisionConfig | None, PolicySource]:
"""Resolve an explicit runtime override before the checkpoint default."""
override_present, override = Cosmos3MixedPrecisionConfig.resolve_additional_config(
getattr(od_config, "additional_config", None)
)
if override_present:
if override is not None:
_validate_checkpoint_quantization(od_config)
source: PolicySource = "additional_config" if override is not None else "additional_config_disabled"
return override, source
checkpoint = read_checkpoint_policy(od_config)
if checkpoint is not None:
return checkpoint, "checkpoint"
return None, "none"
def read_checkpoint_policy(od_config: object) -> Cosmos3MixedPrecisionConfig | None:
"""Read and validate a policy from ``transformer/config.json``.
Missing metadata preserves ordinary checkpoint behavior. Metadata that is
present but malformed or incompatible fails closed.
"""
tf_config = getattr(od_config, "tf_model_config", None)
params = getattr(tf_config, "params", None)
if not isinstance(params, Mapping):
return None
disk_quant_config = params.get("quantization_config")
if not isinstance(disk_quant_config, Mapping):
return None
if "runtime" not in disk_quant_config:
return None
runtime_config = disk_quant_config["runtime"]
if not isinstance(runtime_config, Mapping):
raise TypeError("quantization_config.runtime must be a mapping")
if "diffusion_step_policy" not in runtime_config:
return None
raw_policy = runtime_config["diffusion_step_policy"]
if not isinstance(raw_policy, Mapping):
raise TypeError("quantization_config.runtime.diffusion_step_policy must be a mapping")
policy = _parse_policy(raw_policy)
if policy is None:
return None
_validate_checkpoint_quantization(od_config)
return policy
def _parse_policy(policy: Mapping[str, object]) -> Cosmos3MixedPrecisionConfig | None:
fields = set(policy)
unknown = fields - _POLICY_FIELDS
if unknown:
raise ValueError(f"Unknown diffusion_step_policy fields: {sorted(unknown)}")
missing = _POLICY_FIELDS - fields
if missing:
raise ValueError(f"Missing diffusion_step_policy fields: {sorted(missing)}")
schema_version = policy["schema_version"]
if not isinstance(schema_version, int) or isinstance(schema_version, bool) or schema_version != 1:
raise ValueError("diffusion_step_policy.schema_version must be the integer 1")
if policy["type"] != "first_last_n":
raise ValueError("diffusion_step_policy.type must be 'first_last_n'")
if policy["index_space"] != "denoising_loop_iteration":
raise ValueError("diffusion_step_policy.index_space must be 'denoising_loop_iteration'")
if policy["default_mode"] != "native":
raise ValueError("diffusion_step_policy.default_mode must be 'native'")
if policy["overlap"] != "a16":
raise ValueError("diffusion_step_policy.overlap must be 'a16'")
scope = policy["scope"]
if not isinstance(scope, list) or not scope or not all(isinstance(item, str) for item in scope):
raise TypeError("diffusion_step_policy.scope must be a non-empty list of strings")
first_steps = _parse_step_range(policy["first_steps"], "first_steps")
last_steps = _parse_step_range(policy["last_steps"], "last_steps")
reasoner = policy["reasoner"]
if reasoner not in {"native", "a16"}:
raise ValueError("diffusion_step_policy.reasoner must be 'native' or 'a16'")
if _COMPONENT not in scope:
return None
return Cosmos3MixedPrecisionConfig(
first_steps=first_steps,
last_steps=last_steps,
reasoner=cast(ReasonerPolicy, reasoner),
)
def _parse_step_range(value: object, name: str) -> int:
if not isinstance(value, Mapping):
raise TypeError(f"diffusion_step_policy.{name} must be a mapping")
fields = set(value)
unknown = fields - _STEP_RANGE_FIELDS
if unknown:
raise ValueError(f"Unknown diffusion_step_policy.{name} fields: {sorted(unknown)}")
missing = _STEP_RANGE_FIELDS - fields
if missing:
raise ValueError(f"Missing diffusion_step_policy.{name} fields: {sorted(missing)}")
if value["mode"] != "a16":
raise ValueError(f"diffusion_step_policy.{name}.mode must be 'a16'")
return _non_negative_int(value["count"], f"diffusion_step_policy.{name}.count")
def _validate_checkpoint_quantization(od_config: object) -> None:
# Match the effective quantization used to construct the transformer linears.
quant_config = getattr(od_config, "quantization_config", None)
if quant_config is None:
tf_config = getattr(od_config, "tf_model_config", None)
quant_config = getattr(tf_config, "quant_config", None)
get_name = getattr(quant_config, "get_name", None)
name = get_name() if callable(get_name) else None
if name not in _SUPPORTED_MODEL_OPT_CONFIGS:
raise ValueError(f"diffusion_step_policy requires a serialized ModelOpt FP8 or NVFP4 checkpoint, got {name!r}")
if name == "modelopt":
_require_serialized(quant_config, "is_checkpoint_fp8_serialized", "FP8")
return
if name == "modelopt_fp4":
if getattr(quant_config, "quant_method", "NVFP4") != "NVFP4":
raise ValueError("diffusion_step_policy requires checkpoint-native NVFP4 W4A4 linears")
_require_serialized(quant_config, "is_checkpoint_nvfp4_serialized", "NVFP4")
return
def _require_serialized(quant_config: object | None, flag: str, format_name: str) -> None:
if not bool(getattr(quant_config, flag, False)):
raise ValueError(f"diffusion_step_policy requires serialized ModelOpt {format_name} weights")
@@ -0,0 +1,106 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Configuration parsing and denoising-step policy for mixed precision."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Literal, cast
ReasonerPolicy = Literal["native", "a16"]
_REASONER_POLICIES = frozenset({"native", "a16"})
_CONFIG_FIELDS = frozenset({"enabled", "first_steps", "last_steps", "reasoner"})
@dataclass(frozen=True)
class Cosmos3MixedPrecisionConfig:
"""Validated precision policy shared by every quantization strategy."""
first_steps: int = 3
last_steps: int = 3
reasoner: ReasonerPolicy = "a16"
@classmethod
def from_additional_config(
cls,
additional_config: Mapping[str, object] | None,
) -> Cosmos3MixedPrecisionConfig | None:
"""Parse Cosmos3 fields from vLLM-Omni's additional configuration."""
_, config = cls.resolve_additional_config(additional_config)
return config
@classmethod
def resolve_additional_config(
cls,
additional_config: Mapping[str, object] | None,
) -> tuple[bool, Cosmos3MixedPrecisionConfig | None]:
"""Return whether an override was supplied and its effective policy.
The separate presence bit distinguishes an absent runtime override from
an explicit disable. That distinction matters when a checkpoint owns a
default policy.
"""
if additional_config is not None and not isinstance(additional_config, Mapping):
raise TypeError("additional_config must be a mapping")
values = additional_config or {}
if "cosmos3_mixed_precision" not in values:
return False, None
raw_config = values["cosmos3_mixed_precision"]
if not isinstance(raw_config, Mapping):
raise TypeError("cosmos3_mixed_precision must be a mapping")
unknown = set(raw_config) - _CONFIG_FIELDS
if unknown:
raise ValueError(f"Unknown cosmos3_mixed_precision fields: {sorted(unknown)}")
enabled = raw_config.get("enabled", True)
if not isinstance(enabled, bool):
raise TypeError("cosmos3_mixed_precision.enabled must be a boolean")
if not enabled:
conflicting = set(raw_config) - {"enabled"}
if conflicting:
raise ValueError(
"cosmos3_mixed_precision.enabled=false cannot be combined with "
f"schedule fields: {sorted(conflicting)}"
)
return True, None
first_steps = _non_negative_int(
raw_config.get("first_steps", 3),
"cosmos3_mixed_precision.first_steps",
)
last_steps = _non_negative_int(
raw_config.get("last_steps", 3),
"cosmos3_mixed_precision.last_steps",
)
reasoner = str(raw_config.get("reasoner", "a16")).lower()
if reasoner not in _REASONER_POLICIES:
raise ValueError(
f"cosmos3_mixed_precision.reasoner must be one of {sorted(_REASONER_POLICIES)}, got {reasoner!r}"
)
config = cls(
first_steps=first_steps,
last_steps=last_steps,
reasoner=cast(ReasonerPolicy, reasoner),
)
if first_steps == 0 and last_steps == 0 and reasoner == "native":
return True, None
return True, config
def use_high_precision(self, step_index: int, num_steps: int) -> bool:
"""Select the high path for an actual scheduler-step index."""
if num_steps <= 0:
raise ValueError(f"num_steps must be positive, got {num_steps}")
if step_index < 0 or step_index >= num_steps:
raise IndexError(f"step_index must be in [0, {num_steps}), got {step_index}")
return step_index < self.first_steps or step_index >= num_steps - self.last_steps
def _non_negative_int(value: object, name: str) -> int:
"""Validate an integer configuration field without accepting booleans."""
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
raise TypeError(f"{name} must be a non-negative integer")
return value
@@ -0,0 +1,116 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Format-agnostic schedule state, linear discovery, and dispatch."""
from __future__ import annotations
from typing import Literal
import torch
from vllm.model_executor.layers.linear import LinearBase, LinearMethodBase
from .config import Cosmos3MixedPrecisionConfig
from .strategy import (
Cosmos3PrecisionStrategy,
Fp8W8A8W8A16Strategy,
Nvfp4W4A4W4A16Strategy,
)
PrecisionPath = Literal["reasoner", "generation"]
_STRATEGIES: tuple[Cosmos3PrecisionStrategy, ...] = (
Fp8W8A8W8A16Strategy(),
Nvfp4W4A4W4A16Strategy(),
)
def _strategy_for(method: object | None) -> Cosmos3PrecisionStrategy | None:
return next((strategy for strategy in _STRATEGIES if strategy.accepts(method)), None)
class Cosmos3MixedPrecisionLinearMethod(LinearMethodBase):
"""Dispatch between a checkpoint-native method and dense A16."""
def __init__(
self,
base_method: LinearMethodBase,
strategy: Cosmos3PrecisionStrategy,
runtime: Cosmos3MixedPrecisionRuntime,
module_name: str,
path: PrecisionPath,
) -> None:
self.base_method = base_method
self.strategy = strategy
self.runtime = runtime
self.module_name = module_name
self.path = path
def create_weights(self, *args, **kwargs) -> None:
self.base_method.create_weights(*args, **kwargs)
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
self.strategy.validate_before_processing(
self.base_method,
layer,
self.module_name,
)
self.base_method.process_weights_after_loading(layer)
self.strategy.validate_after_processing(layer, self.module_name)
def apply(
self,
layer: torch.nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None = None,
) -> torch.Tensor:
if not self.runtime.use_high_precision(self.path):
return self.base_method.apply(layer, x, bias)
return self.strategy.apply_high(layer, x, bias)
class Cosmos3MixedPrecisionRuntime:
"""Own one transformer's schedule state and wrapped linear inventory."""
def __init__(self, config: Cosmos3MixedPrecisionConfig) -> None:
self.config = config
# TODO: Make this request-local before Cosmos3 supports interleaved
# denoising requests on one transformer instance.
self._generation_high_precision = False
def install(self, transformer: torch.nn.Module) -> None:
components: dict[PrecisionPath, torch.nn.Module] = {
"generation": transformer.gen_layers,
}
if self.config.reasoner == "a16":
components["reasoner"] = transformer.language_model.layers
wrapped_count = 0
for path, component in components.items():
for local_name, layer in component.named_modules():
if not isinstance(layer, LinearBase):
continue
base_method = getattr(layer, "quant_method", None)
strategy = _strategy_for(base_method)
if strategy is None:
continue
module_name = getattr(layer, "prefix", None) or f"{path}.{local_name}"
layer.quant_method = Cosmos3MixedPrecisionLinearMethod(
base_method,
strategy,
self,
module_name,
path,
)
wrapped_count += 1
if not wrapped_count:
raise ValueError("Cosmos3 mixed precision found no compatible FP8 or NVFP4 ModelOpt linears")
def use_high_precision(self, path: PrecisionPath) -> bool:
return self.config.reasoner == "a16" if path == "reasoner" else self._generation_high_precision
def set_step(self, step_index: int, num_steps: int) -> None:
self._generation_high_precision = self.config.use_high_precision(step_index, num_steps)
def reset(self) -> None:
self._generation_high_precision = False
@@ -0,0 +1,218 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Format-specific live-weight validation and reference A16 materialization."""
from __future__ import annotations
import torch
import torch.nn.functional as F
from vllm.model_executor.layers.quantization.modelopt import (
ModelOptFp8LinearMethod,
ModelOptNvFp4LinearMethod,
)
from vllm.model_executor.layers.quantization.utils import nvfp4_emulation_utils
_NVFP4_BLOCK_SIZE = 16
class Cosmos3PrecisionStrategy:
"""Quantization-format boundary behind the shared precision schedule."""
def accepts(self, method: object | None) -> bool:
"""Return whether this strategy owns a native linear method."""
raise NotImplementedError
def validate_before_processing(
self,
method: object,
layer: torch.nn.Module,
module_name: str,
) -> None:
"""Reject native transforms that cannot support live dequantization."""
def validate_after_processing(
self,
layer: torch.nn.Module,
module_name: str,
) -> None:
"""Validate the live native weight representation."""
raise NotImplementedError
def materialize(self, layer: torch.nn.Module) -> torch.Tensor:
"""Materialize the live quantized weight as a dense BF16 matrix."""
raise NotImplementedError
def apply_high(
self,
layer: torch.nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None,
) -> torch.Tensor:
"""Apply the reference dense A16 path."""
input_size = int(layer.input_size_per_partition)
output_size = int(layer.output_size_per_partition)
weight = self.materialize(layer)
expected_shape = (output_size, input_size)
if tuple(weight.shape) != expected_shape:
raise RuntimeError(f"Dense weight shape {tuple(weight.shape)} does not match {expected_shape}")
x_2d = x.reshape(-1, x.shape[-1])
if x_2d.shape[1] != input_size:
raise ValueError(f"Expected activation width {input_size}, got {x_2d.shape[1]}")
weight = weight.to(dtype=x.dtype)
if bias is not None and bias.dtype != x.dtype:
bias = bias.to(dtype=x.dtype)
output = F.linear(x_2d, weight, bias)
return output.view(*x.shape[:-1], output_size)
class Fp8W8A8W8A16Strategy(Cosmos3PrecisionStrategy):
"""Use native ModelOpt W8A8 or reference dense W8A16."""
def accepts(self, method: object | None) -> bool:
return isinstance(method, ModelOptFp8LinearMethod)
def validate_before_processing(
self,
method: object,
layer: torch.nn.Module,
module_name: str,
) -> None:
if hasattr(layer, "pre_quant_scale"):
raise ValueError(f"{module_name} uses unsupported SmoothQuant pre_quant_scale")
weight_scale = getattr(layer, "weight_scale", None)
if not isinstance(weight_scale, torch.Tensor) or weight_scale.numel() != 1:
raise ValueError(f"{module_name} requires serialized tensorwise FP8 weights")
fp8_kernel = getattr(method, "fp8_linear", None)
from vllm.model_executor.kernels.linear.scaled_mm.marlin import (
MarlinFP8ScaledMMLinearKernel,
)
if isinstance(fp8_kernel, MarlinFP8ScaledMMLinearKernel):
raise ValueError(
f"{module_name} selected Marlin FP8, which repacks the only weight copy; "
"use a backend that retains canonical FP8 weights"
)
def validate_after_processing(
self,
layer: torch.nn.Module,
module_name: str,
) -> None:
weight = getattr(layer, "weight", None)
scale = getattr(layer, "weight_scale", None)
if not isinstance(weight, torch.Tensor) or weight.dtype != torch.float8_e4m3fn:
dtype = getattr(weight, "dtype", None)
raise TypeError(f"{module_name} requires a canonical FP8 weight, got {dtype}")
if weight.ndim != 2:
raise ValueError(f"{module_name} requires a rank-2 FP8 weight, got {tuple(weight.shape)}")
if not isinstance(scale, torch.Tensor):
raise ValueError(f"{module_name} has an FP8 weight but no weight_scale")
if scale.numel() != 1:
raise ValueError(f"{module_name} requires one live FP8 weight scale")
input_size = int(layer.input_size_per_partition)
output_size = int(layer.output_size_per_partition)
if weight.shape[0] < input_size or weight.shape[1] < output_size:
raise ValueError(
f"{module_name} live FP8 weight shape {tuple(weight.shape)} does not cover "
f"(K, N)=({input_size}, {output_size})"
)
_validate_positive_finite_scale(scale, module_name)
def materialize(self, layer: torch.nn.Module) -> torch.Tensor:
input_size = int(layer.input_size_per_partition)
output_size = int(layer.output_size_per_partition)
weight = layer.weight[:input_size, :output_size]
scale = layer.weight_scale.reshape(1).to(device=weight.device, dtype=torch.float32)
return (weight.to(torch.float32) * scale).t().to(torch.bfloat16)
class Nvfp4W4A4W4A16Strategy(Cosmos3PrecisionStrategy):
"""Use native ModelOpt W4A4 or reference dense W4A16."""
def accepts(self, method: object | None) -> bool:
return isinstance(method, ModelOptNvFp4LinearMethod)
def validate_before_processing(
self,
method: object,
layer: torch.nn.Module,
module_name: str,
) -> None:
kernel = getattr(method, "kernel", None)
from vllm.model_executor.kernels.linear.nvfp4.cutlass import (
CutlassNvFp4LinearKernel,
)
from vllm.model_executor.kernels.linear.nvfp4.flashinfer import (
FlashInferCuteDslNvFp4LinearKernel,
FlashInferCutlassNvFp4LinearKernel,
)
compatible_kernels = (
CutlassNvFp4LinearKernel,
FlashInferCuteDslNvFp4LinearKernel,
FlashInferCutlassNvFp4LinearKernel,
)
if not isinstance(kernel, compatible_kernels):
kernel_name = type(kernel).__name__ if kernel is not None else "none"
raise ValueError(
f"{module_name} selected unsupported NVFP4 backend {kernel_name}; "
"live W4A16 dequantization requires a CUTLASS-compatible layout"
)
global_scale = _nvfp4_global_scale(layer)
if global_scale is None or global_scale.numel() != 1:
raise ValueError(f"{module_name} is missing ModelOpt NVFP4 scales")
def validate_after_processing(
self,
layer: torch.nn.Module,
module_name: str,
) -> None:
packed = getattr(layer, "weight", None)
scale = getattr(layer, "weight_scale", None)
global_scale = getattr(layer, "weight_global_scale", None)
if not isinstance(packed, torch.Tensor) or packed.dtype != torch.uint8:
dtype = getattr(packed, "dtype", None)
raise TypeError(f"{module_name} requires a live packed NVFP4 weight, got {dtype}")
if not isinstance(scale, torch.Tensor) or not isinstance(global_scale, torch.Tensor):
raise ValueError(f"{module_name} is missing live NVFP4 scales")
output_size = int(layer.output_size_per_partition)
input_size = int(layer.input_size_per_partition)
if input_size % _NVFP4_BLOCK_SIZE != 0:
raise ValueError(f"{module_name} input size {input_size} is not divisible by {_NVFP4_BLOCK_SIZE}")
expected_weight = (output_size, input_size // 2)
if packed.shape[0] < expected_weight[0] or packed.shape[1] < expected_weight[1]:
raise ValueError(
f"{module_name} live NVFP4 weight shape {tuple(packed.shape)} does not cover {expected_weight}"
)
_validate_positive_finite_scale(global_scale, module_name)
lut_handle = nvfp4_emulation_utils.kE2M1ToFloat_handle
if lut_handle.val.device != packed.device:
lut_handle.val = lut_handle.val.to(packed.device)
def materialize(self, layer: torch.nn.Module) -> torch.Tensor:
output_size = int(layer.output_size_per_partition)
input_size = int(layer.input_size_per_partition)
packed = layer.weight[:output_size, : input_size // 2]
return nvfp4_emulation_utils.dequantize_to_dtype(
packed,
layer.weight_scale,
layer.weight_global_scale,
torch.bfloat16,
_NVFP4_BLOCK_SIZE,
True,
)
def _validate_positive_finite_scale(scale: torch.Tensor, module_name: str) -> None:
values = scale.detach().float()
if not torch.isfinite(values).all() or not (values > 0).all():
raise ValueError(f"{module_name} has a non-finite or non-positive weight scale")
def _nvfp4_global_scale(layer: torch.nn.Module) -> torch.Tensor | None:
for name in ("weight_scale_2", "weight_global_scale"):
value = getattr(layer, name, None)
if isinstance(value, torch.Tensor):
return value
return None
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Cosmos3 text/image/video/sound/action pipeline for vllm-omni.
One pipeline class serves the Cosmos3 family modes. Output modality is selected
@@ -34,6 +34,7 @@ import math
import os
import time
from collections.abc import Iterable, Mapping
from contextlib import nullcontext
from dataclasses import fields
from typing import Any, ClassVar
@@ -138,6 +139,7 @@ from .utils import (
ensure_gripper_array,
extract_robolab_image,
extract_robolab_prompt_image,
get_robolab_domain_id,
lazy_action_transform_pipeline,
make_robolab_action_postprocess_inputs,
next_robolab_seed,
@@ -947,6 +949,20 @@ class Cosmos3OmniDiffusersPipeline(
model_path = od_config.model
local_files_only = os.path.exists(model_path)
# Validate guidance parallelism from checkpoint metadata before loading
# components. Distilled checkpoints have only a conditional branch.
scheduler_config = FlowUniPCMultistepScheduler.load_config(
model_path,
subfolder="scheduler",
local_files_only=local_files_only,
)
self.is_distilled_model = scheduler_config.get("_class_name") == COSMOS3_DISTILLED_CHECKPOINT_SCHEDULER_CLASS
if self.is_distilled_model and od_config.parallel_config.cfg_parallel_size > 1:
raise ValueError(
"Distilled Cosmos3 checkpoints run without classifier-free guidance. "
"Set --cfg-parallel-size 1 and use --ulysses-degree for multi-GPU inference."
)
# --- Tokenizer ---
self.tokenizer = AutoTokenizer.from_pretrained(
model_path,
@@ -1009,20 +1025,7 @@ class Cosmos3OmniDiffusersPipeline(
logger.info("Cosmos3: session state manager enabled (max_sessions=%d)", mm_max_sessions)
# --- Scheduler ---
# Distilled model differs from regular one only by scheduler,
# distilled one uses FlowMatchEulerDiscreteScheduler, while
# regular should use FlowUniPCMultistepScheduler
scheduler_config = FlowUniPCMultistepScheduler.load_config(
model_path,
subfolder="scheduler",
local_files_only=local_files_only,
)
scheduler_class_name = scheduler_config.get("_class_name")
self.is_distilled_model = False
if scheduler_class_name == COSMOS3_DISTILLED_CHECKPOINT_SCHEDULER_CLASS:
if self.is_distilled_model:
fixed_step_config = scheduler_config.get("fixed_step_sampler_config")
if not isinstance(fixed_step_config, dict) or fixed_step_config.get("sample_type") != "sde":
raise ValueError("Cosmos3 distilled scheduler requires fixed_step_sampler_config.sample_type=sde.")
@@ -1034,7 +1037,6 @@ class Cosmos3OmniDiffusersPipeline(
stochastic_sampling=True,
)
self._scheduler_init_t_list = list(t_list)
self.is_distilled_model = True
else:
# Preserve compatible solver settings from the checkpoint, but keep
# the base shift neutral. The concrete request shift is applied when
@@ -1074,8 +1076,10 @@ class Cosmos3OmniDiffusersPipeline(
self._guidance_scale = None
self._num_timesteps = None
self._current_step_index = None
self._current_sigma = None
self._cosmos3_branch_caches: dict[str, tuple[Any, Any]] | None = None
self._robolab_transform = None
self._robolab_transforms: dict[bool, Any] = {}
# Set True by ``enable_cache_for_cosmos3`` when cache-dit is enabled on
# this pipeline. Tells the sequential-CFG loop to keep paired
@@ -1290,17 +1294,24 @@ class Cosmos3OmniDiffusersPipeline(
or a tuple in video, action, sound order for multimodal generation.
"""
cache_key = kwargs.pop("_cosmos3_cache_key", None)
if cache_key is None:
return self.transformer(**kwargs)
context_name = str(kwargs.pop("_cache_context", "cond"))
branch_caches = self._cosmos3_branch_caches
if branch_caches is None:
return self.transformer(**kwargs)
cache_key = str(cache_key)
self.transformer.cached_kv, self.transformer.cached_freqs_gen = branch_caches.get(cache_key, (None, None))
prediction = self.transformer(**kwargs)
branch_caches[cache_key] = (self.transformer.cached_kv, self.transformer.cached_freqs_gen)
context_factory = getattr(self, "_cache_context_factory", None)
context = context_factory(context_name) if callable(context_factory) else nullcontext()
with context:
if cache_key is None:
prediction = self.transformer(**kwargs)
else:
branch_caches = self._cosmos3_branch_caches
if branch_caches is None:
prediction = self.transformer(**kwargs)
else:
cache_key = str(cache_key)
self.transformer.cached_kv, self.transformer.cached_freqs_gen = branch_caches.get(
cache_key, (None, None)
)
prediction = self.transformer(**kwargs)
branch_caches[cache_key] = (self.transformer.cached_kv, self.transformer.cached_freqs_gen)
return prediction
def combine_multi_branch_cfg_noise(
@@ -1394,11 +1405,18 @@ class Cosmos3OmniDiffusersPipeline(
return val
return default
def _get_robolab_transform(self):
if self._robolab_transform is None:
def _get_robolab_transform(self, *, format_prompt_as_json: bool = False):
transforms = getattr(self, "_robolab_transforms", None)
if transforms is None:
transforms = {}
self._robolab_transforms = transforms
if format_prompt_as_json not in transforms:
action_dim = int(getattr(self.transformer, "action_dim", 64))
self._robolab_transform = lazy_action_transform_pipeline(action_dim)
return self._robolab_transform
transforms[format_prompt_as_json] = lazy_action_transform_pipeline(
action_dim,
format_prompt_as_json=format_prompt_as_json,
)
return transforms[format_prompt_as_json]
def _build_robolab_policy_inputs(
self,
@@ -1443,7 +1461,8 @@ class Cosmos3OmniDiffusersPipeline(
resolution = str(extra_param("resolution", ROBOLAB_DEFAULT_RESOLUTION))
fps = float(extra_param("conditioning_fps", ROBOLAB_DEFAULT_CONDITIONING_FPS))
domain_name = str(extra_param("domain_name", ROBOLAB_DEFAULT_DOMAIN_NAME))
domain_id = resolve_domain_id(domain_name=domain_name, require_explicit=True)
domain_id = get_robolab_domain_id(domain_name)
format_prompt_as_json = self._truthy(extra_param("format_prompt_as_json", False))
if use_state and history_length < 1:
raise ValueError("RoboLab history_length must be >= 1 when use_state is true.")
@@ -1506,7 +1525,9 @@ class Cosmos3OmniDiffusersPipeline(
"action": action,
# Cosmos Framework consumes this as an integer conditioning bucket.
"conditioning_fps": torch.tensor(fps, dtype=torch.long),
"mode": ACTION_MODE_POLICY,
# Cosmos Framework 1.2 renamed the internal policy transform mode to
# ``wam``. The public vLLM action_mode remains ``policy``.
"mode": "wam",
"domain_id": torch.tensor(domain_id, dtype=torch.long),
"viewpoint": "concat_view",
"additional_view_description": ROBOLAB_CONCAT_VIEW_DESCRIPTION,
@@ -1514,7 +1535,9 @@ class Cosmos3OmniDiffusersPipeline(
if history_action is not None:
sample["history_action"] = history_action
sample = self._get_robolab_transform()(sample, resolution)
sample = self._get_robolab_transform(format_prompt_as_json=format_prompt_as_json)(sample, resolution)
if isinstance(sample.get("ai_caption"), dict):
sample["ai_caption"] = json.dumps(sample["ai_caption"])
sequence_plan = sample["sequence_plan"]
video_tensor = sample["video"].float() / 127.5 - 1.0
raw_action_dim_tensor = sample.get("raw_action_dim")
@@ -1798,6 +1821,11 @@ class Cosmos3OmniDiffusersPipeline(
def _resolve_guidance_scale(self, sp: OmniDiffusionSamplingParams, default: float) -> float:
if self.is_distilled_model:
if sp.guidance_scale_provided and float(sp.guidance_scale) != 1.0:
logger.warning_once(
"Distilled Cosmos3 checkpoints run without classifier-free guidance. "
"The requested guidance_scale is overridden to 1.0; negative_prompt does not affect generation."
)
return 1.0
if sp.guidance_scale_provided:
return float(sp.guidance_scale)
@@ -1822,6 +1850,39 @@ class Cosmos3OmniDiffusersPipeline(
def num_timesteps(self):
return self._num_timesteps
@property
def current_step_index(self):
return self._current_step_index
@property
def current_sigma(self):
return self._current_sigma
def _set_denoise_step_metadata(
self,
step_index: int,
timesteps: torch.Tensor,
scheduler: Any,
) -> None:
self._current_step_index = step_index
self._num_timesteps = len(timesteps)
sigmas = getattr(scheduler, "sigmas", None)
self._current_sigma = sigmas[step_index] if sigmas is not None and step_index < len(sigmas) else None
def _clear_denoise_step_metadata(self) -> None:
self._current_step_index = None
self._current_sigma = None
def _set_mixed_precision_step(self, step_index: int, num_steps: int) -> None:
setter = getattr(self.transformer, "set_mixed_precision_step", None)
if setter is not None:
setter(step_index, num_steps)
def _reset_mixed_precision(self) -> None:
resetter = getattr(self.transformer, "reset_mixed_precision", None)
if resetter is not None:
resetter()
@staticmethod
def _distilled_unsupported_error(detail: str) -> ValueError:
return ValueError(
@@ -2819,7 +2880,9 @@ class Cosmos3OmniDiffusersPipeline(
# Each CFG-parallel rank runs exactly one branch (rank 0 -> cond,
# else uncond), so session keying loads/stores only this rank's branch.
cfg_rank_is_negative = get_classifier_free_guidance_rank() != 0
for t in self.progress_bar(timesteps):
for step_index, t in enumerate(self.progress_bar(timesteps)):
self._set_denoise_step_metadata(step_index, timesteps, step_scheduler)
self._set_mixed_precision_step(step_index, len(timesteps))
timestep = t.unsqueeze(0)
# Outside the interval, scale=1 makes the combined output equal
# the cond branch. Every rank remains on the same iteration and
@@ -2830,6 +2893,7 @@ class Cosmos3OmniDiffusersPipeline(
do_true_cfg=True,
true_cfg_scale=step_scale,
positive_kwargs=dict(
_cache_context="cond",
hidden_states=latents,
timestep=timestep,
text_ids=cond_ids,
@@ -2839,6 +2903,7 @@ class Cosmos3OmniDiffusersPipeline(
**shared_kwargs,
),
negative_kwargs=dict(
_cache_context="uncond",
hidden_states=latents,
timestep=timestep,
text_ids=uncond_ids,
@@ -2858,13 +2923,16 @@ class Cosmos3OmniDiffusersPipeline(
uncond_cache: tuple = (None, None)
keep_uncond_for_cache = self._cache_requires_paired_cfg()
for t in self.progress_bar(timesteps):
for step_index, t in enumerate(self.progress_bar(timesteps)):
self._set_denoise_step_metadata(step_index, timesteps, step_scheduler)
self._set_mixed_precision_step(step_index, len(timesteps))
timestep = t.unsqueeze(0)
cfg_active = _cfg_active_at(t)
if not self._kv_load_und(kv_state, is_negative=False):
self.transformer.cached_kv, self.transformer.cached_freqs_gen = cond_cache
noise_cond = self.transformer(
noise_cond = self.predict_noise(
_cache_context="cond",
hidden_states=latents,
timestep=timestep,
text_ids=cond_ids,
@@ -2881,7 +2949,8 @@ class Cosmos3OmniDiffusersPipeline(
if cfg_active or keep_uncond_for_cache:
if not self._kv_load_und(kv_state, is_negative=True):
self.transformer.cached_kv, self.transformer.cached_freqs_gen = uncond_cache
noise_uncond = self.transformer(
noise_uncond = self.predict_noise(
_cache_context="uncond",
hidden_states=latents,
timestep=timestep,
text_ids=uncond_ids,
@@ -2912,10 +2981,13 @@ class Cosmos3OmniDiffusersPipeline(
else:
# No CFG: a single cond branch per step. Bespoke (state None) keeps
# using the transformer-instance cache exactly as before.
for t in self.progress_bar(timesteps):
for step_index, t in enumerate(self.progress_bar(timesteps)):
self._set_denoise_step_metadata(step_index, timesteps, step_scheduler)
self._set_mixed_precision_step(step_index, len(timesteps))
timestep = t.unsqueeze(0)
self._kv_load_und(kv_state, is_negative=False)
noise_pred = self.transformer(
noise_pred = self.predict_noise(
_cache_context="cond",
hidden_states=latents,
timestep=timestep,
text_ids=cond_ids,
@@ -2928,6 +3000,8 @@ class Cosmos3OmniDiffusersPipeline(
self._kv_capture_und(kv_state, is_negative=False)
_assign_step_out(_step(noise_pred, t, latents, action_latents, sound_latents))
finally:
self._clear_denoise_step_metadata()
self._reset_mixed_precision()
# Cosmos3 currently receives a unique request_id rather than a
# reusable rollout session id. Retaining its state would only pin
# K/V buffers on device after this generation finishes.
@@ -3112,7 +3186,9 @@ class Cosmos3OmniDiffusersPipeline(
self.transformer.reset_cache()
self._cosmos3_branch_caches = {}
try:
for t in self.progress_bar(timesteps):
for step_index, t in enumerate(self.progress_bar(timesteps)):
self._set_denoise_step_metadata(step_index, timesteps, self.scheduler)
self._set_mixed_precision_step(step_index, len(timesteps))
timestep = t.unsqueeze(0)
step_guidance = guidance_scale if _active_at(t, guidance_interval) else 1.0
step_control = control_guidance if _active_at(t, control_guidance_interval) else 1.0
@@ -3120,6 +3196,7 @@ class Cosmos3OmniDiffusersPipeline(
needs_control_cfg = step_control != 1.0
cond_full_kwargs = dict(
_cache_context="cond",
hidden_states=latents,
timestep=timestep,
text_ids=cond_ids,
@@ -3133,6 +3210,7 @@ class Cosmos3OmniDiffusersPipeline(
branches_kwargs = [
cond_full_kwargs,
dict(
_cache_context="cond_no_control",
hidden_states=latents,
timestep=timestep,
text_ids=cond_ids,
@@ -3142,6 +3220,7 @@ class Cosmos3OmniDiffusersPipeline(
**shared_kwargs,
),
dict(
_cache_context="uncond",
hidden_states=latents,
timestep=timestep,
text_ids=uncond_ids,
@@ -3167,6 +3246,7 @@ class Cosmos3OmniDiffusersPipeline(
branches_kwargs = [
cond_full_kwargs,
dict(
_cache_context="cond_no_control",
hidden_states=latents,
timestep=timestep,
text_ids=cond_ids,
@@ -3190,6 +3270,7 @@ class Cosmos3OmniDiffusersPipeline(
branches_kwargs = [
cond_full_kwargs,
dict(
_cache_context="uncond",
hidden_states=latents,
timestep=timestep,
text_ids=uncond_ids,
@@ -3224,6 +3305,8 @@ class Cosmos3OmniDiffusersPipeline(
)[0]
latents = velocity_mask * latents + (1.0 - velocity_mask) * condition_latents
finally:
self._clear_denoise_step_metadata()
self._reset_mixed_precision()
self._cosmos3_branch_caches = None
self.transformer.reset_cache()
return latents
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Cosmos3 VFM Transformer for vllm-omni.
Implements the Mixture-of-Transformers architecture with two pathways:
@@ -14,7 +14,7 @@ from __future__ import annotations
import math
from collections.abc import Iterator
from contextlib import AbstractContextManager, contextmanager, nullcontext
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, NamedTuple
import torch
import torch.distributed as dist
@@ -40,6 +40,12 @@ from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_
from vllm_omni.diffusion.layers.norm import RMSNorm as _VllmRMSNorm
from vllm_omni.platforms import current_omni_platform
from .mixed_precision import (
Cosmos3MixedPrecisionConfig,
Cosmos3MixedPrecisionRuntime,
resolve_mixed_precision_config,
)
if TYPE_CHECKING:
from vllm_omni.diffusion.offloader.sequential_backend import SequentialOffloadHook
@@ -136,6 +142,26 @@ def _od_config_get(od_config: Any, key: str, default: Any = None) -> Any:
return default if value is None else value
def _validate_mixed_precision_runtime(
config: Cosmos3MixedPrecisionConfig | None,
od_config: OmniDiffusionConfig,
) -> None:
if config is None:
return
if get_tensor_model_parallel_world_size() != 1:
raise ValueError("Cosmos3 mixed precision currently supports tensor parallel size 1 only")
if int(getattr(od_config, "max_num_seqs", 1)) != 1:
raise ValueError("Cosmos3 mixed precision currently supports one active request per worker")
if bool(getattr(od_config, "enable_distributed_layerwise_offload", False)):
raise ValueError(
"Cosmos3 mixed precision does not support distributed layer-wise offload "
"because its direct loader bypasses ModelOpt post-load transformations"
)
parallel_config = getattr(od_config, "parallel_config", None)
if bool(getattr(parallel_config, "use_hsdp", False)):
raise ValueError("Cosmos3 mixed precision has not validated live backend weights under HSDP")
def _as_bool(value: Any) -> bool:
if isinstance(value, str):
return value.strip().lower() in {"1", "true", "yes", "on"}
@@ -401,7 +427,7 @@ class TimestepEmbedder(nn.Module):
max_period: int = 10000,
) -> None:
super().__init__()
# Following diffusers naming pattern here for checkpoint compatibility.
# Preserve checkpoint-compatible parameter names.
self.linear_1 = nn.Linear(frequency_embedding_size, hidden_size, bias=True)
self.act = nn.SiLU()
self.linear_2 = nn.Linear(hidden_size, hidden_size, bias=True)
@@ -1079,6 +1105,28 @@ class Cosmos3GenSPPrepare(nn.Module):
return hidden_gen, freqs_cos, freqs_sin
class _GenPrepared(NamedTuple):
"""GEN-pathway state shared by normal and cached execution."""
hidden_gen: torch.Tensor
time_embed: torch.Tensor
t: int
h: int
w: int
s_video: int
s_control: int
s_action: int
s_sound: int
has_control: bool
has_action: bool
has_sound: bool
action_domain_ids: torch.Tensor | None
ulysses_size: int
use_multi_control_attention: bool
multi_control_token_sizes: tuple[int, ...] | None
multi_control_weights: tuple[float, ...] | None
class Cosmos3VFMTransformer(nn.Module):
"""Cosmos3 VFM Transformer: UND language model + GEN denoising layers.
@@ -1241,6 +1289,19 @@ class Cosmos3VFMTransformer(nn.Module):
dtype = od_config.dtype
quant_config = getattr(od_config, "quantization_config", None) if od_config else None
mixed_precision_config, mixed_precision_source = resolve_mixed_precision_config(od_config)
if mixed_precision_config is None:
if mixed_precision_source == "additional_config_disabled":
logger.info("Cosmos3 checkpoint mixed-precision policy disabled by additional_config")
else:
logger.info(
"Cosmos3 mixed precision active (source=%s): first_steps=%d last_steps=%d reasoner=%s",
mixed_precision_source,
mixed_precision_config.first_steps,
mixed_precision_config.last_steps,
mixed_precision_config.reasoner,
)
_validate_mixed_precision_runtime(mixed_precision_config, od_config)
self.language_model = self._language_model_cls(
hidden_size=self.hidden_size,
@@ -1300,6 +1361,11 @@ class Cosmos3VFMTransformer(nn.Module):
]
)
self.mixed_precision_runtime: Cosmos3MixedPrecisionRuntime | None = None
if mixed_precision_config is not None:
self.mixed_precision_runtime = Cosmos3MixedPrecisionRuntime(mixed_precision_config)
self.mixed_precision_runtime.install(self)
self.norm_moe_gen = RMSNorm(self.hidden_size, eps=self.rms_norm_eps)
self.gen_sp_prepare = Cosmos3GenSPPrepare()
self.gen_sp_gather = nn.Identity()
@@ -1631,6 +1697,61 @@ class Cosmos3VFMTransformer(nn.Module):
pad = (-(base + sound_frames)) % ulysses_size
return sound_frames + pad
def _run_gen_layers(
self,
hidden_gen: torch.Tensor,
*,
s_video: int,
s_control: int,
s_action: int,
s_sound: int,
has_action: bool,
has_sound: bool,
has_control: bool,
ulysses_size: int,
use_multi_control_attention: bool,
multi_control_token_sizes: tuple[int, ...] | None,
multi_control_weights: tuple[float, ...] | None,
) -> torch.Tensor:
"""Run the complete GEN decoder between full-layout boundaries."""
if self.cached_kv is None or self.cached_freqs_gen is None:
raise RuntimeError("Cosmos3 GEN cache was not initialized before running GEN layers.")
freqs_cos, freqs_sin = self.cached_freqs_gen
if not use_multi_control_attention:
hidden_gen, freqs_cos, freqs_sin = self.gen_sp_prepare(hidden_gen, freqs_cos, freqs_sin)
freqs_gen = (freqs_cos, freqs_sin)
if len(self.gen_layers) == len(self.cached_kv):
for layer, (k_und, v_und) in zip(self.gen_layers, self.cached_kv, strict=True):
hidden_gen = layer(
hidden_gen,
k_und=k_und,
v_und=v_und,
freqs_cos=freqs_cos,
freqs_sin=freqs_sin,
control_token_sizes=multi_control_token_sizes,
control_weights=multi_control_weights,
)
# Cache-dit's block wrapper may return a tuple; unwrap it.
if isinstance(hidden_gen, tuple):
hidden_gen = hidden_gen[0]
else:
# Cache-dit patches gen_layers to a grouped wrapper.
for layer in self.gen_layers:
hidden_gen = layer(
hidden_gen,
cached_kv=self.cached_kv,
freqs_gen=freqs_gen,
control_token_sizes=multi_control_token_sizes,
control_weights=multi_control_weights,
)
if isinstance(hidden_gen, tuple):
hidden_gen = hidden_gen[0]
if not use_multi_control_attention:
hidden_gen = self.gen_sp_gather(hidden_gen)
return hidden_gen
# -- Forward -------------------------------------------------------------
def forward(
@@ -1653,7 +1774,51 @@ class Cosmos3VFMTransformer(nn.Module):
transfer_share_vision_temporal_positions: bool = True,
**kwargs,
) -> torch.Tensor | tuple[torch.Tensor, ...]:
"""Run the shared Cosmos3 GEN preprocess, stack, and postprocess path."""
if kwargs:
raise TypeError(f"Unexpected Cosmos3 transformer kwargs: {sorted(kwargs)}")
prep = self._gen_preprocess(
hidden_states,
timestep,
text_ids,
text_mask,
video_shape,
fps=fps,
action_latents=action_latents,
action_domain_ids=action_domain_ids,
action_noisy_mask=action_noisy_mask,
action_start_frame_offset=action_start_frame_offset,
action_fps=action_fps,
sound_latents=sound_latents,
noisy_frame_mask=noisy_frame_mask,
control_latents=control_latents,
control_weights=control_weights,
transfer_share_vision_temporal_positions=transfer_share_vision_temporal_positions,
)
return self._gen_postprocess(self._run_gen_stack(prep), prep)
def _gen_preprocess(
self,
hidden_states: torch.Tensor,
timestep: torch.Tensor,
text_ids: torch.Tensor,
text_mask: torch.Tensor,
video_shape: tuple[int, int, int],
fps: float | None = None,
action_latents: torch.Tensor | None = None,
action_domain_ids: torch.Tensor | None = None,
action_noisy_mask: torch.Tensor | None = None,
action_start_frame_offset: int = 1,
action_fps: float | None = None,
sound_latents: torch.Tensor | None = None,
noisy_frame_mask: torch.Tensor | None = None,
control_latents: list[torch.Tensor] | tuple[torch.Tensor, ...] | torch.Tensor | None = None,
control_weights: list[float] | tuple[float, ...] | torch.Tensor | None = None,
transfer_share_vision_temporal_positions: bool = True,
) -> _GenPrepared:
"""
Prepare the packed GEN sequence before its cacheable execution region.
Args:
hidden_states: [B, C, t, h, w] noisy latents
timestep: [B] diffusion timestep
@@ -1676,13 +1841,9 @@ class Cosmos3VFMTransformer(nn.Module):
transfer controls. Values are normalized to sum to one.
Returns:
[B, C, t, h, w] velocity prediction, or
tuple outputs in video, action, sound order when action/sound streams
are provided. Transfer-control streams condition the video prediction
and are not returned.
Packed GEN inputs and metadata consumed by the shared execution and
postprocessing helpers.
"""
if kwargs:
raise TypeError(f"Unexpected Cosmos3 transformer kwargs: {sorted(kwargs)}")
t, h, w = video_shape
hp, wp, _, _ = self._pad_to_patch_size(h, w)
text_lengths = text_mask.sum(dim=1)
@@ -1882,79 +2043,90 @@ class Cosmos3VFMTransformer(nn.Module):
hidden_parts.append(hidden_sound)
hidden_gen = torch.cat(hidden_parts, dim=1)
# Run GEN layers. UND K/V (replicated) is passed to each layer;
# the Cosmos3CrossAttention forwards them as joint_key/value so the
# framework Attention handles the Ulysses head-slicing internally.
if self.cached_kv is None or self.cached_freqs_gen is None:
raise RuntimeError("Cosmos3 GEN cache was not initialized before running GEN layers.")
freqs_cos, freqs_sin = self.cached_freqs_gen
if not use_multi_control_attention:
hidden_gen, freqs_cos, freqs_sin = self.gen_sp_prepare(hidden_gen, freqs_cos, freqs_sin)
freqs_gen = (freqs_cos, freqs_sin)
return _GenPrepared(
hidden_gen=hidden_gen,
time_embed=time_embed,
t=t,
h=h,
w=w,
s_video=s_video,
s_control=s_control,
s_action=s_action,
s_sound=s_sound,
has_control=has_control,
has_action=has_action,
has_sound=has_sound,
action_domain_ids=action_domain_ids,
ulysses_size=ulysses_size,
use_multi_control_attention=use_multi_control_attention,
multi_control_token_sizes=multi_control_token_sizes,
multi_control_weights=multi_control_weights,
)
if len(self.gen_layers) == len(self.cached_kv):
for layer, (k_und, v_und) in zip(self.gen_layers, self.cached_kv, strict=True):
hidden_gen = layer(
hidden_gen,
k_und=k_und,
v_und=v_und,
freqs_cos=freqs_cos,
freqs_sin=freqs_sin,
control_token_sizes=multi_control_token_sizes,
control_weights=multi_control_weights,
)
# Cache-dit's block wrapper may return a tuple; unwrap it.
if isinstance(hidden_gen, tuple):
hidden_gen = hidden_gen[0]
else:
# Cache-dit patches gen_layers to a grouped wrapper.
for layer in self.gen_layers:
hidden_gen = layer(
hidden_gen,
cached_kv=self.cached_kv,
freqs_gen=freqs_gen,
control_token_sizes=multi_control_token_sizes,
control_weights=multi_control_weights,
)
if isinstance(hidden_gen, tuple):
hidden_gen = hidden_gen[0]
def _run_gen_stack(self, prep: _GenPrepared) -> torch.Tensor:
"""Execute the cacheable full-layout GEN stack, including final norm."""
hidden_gen = self._run_gen_layers(
prep.hidden_gen,
s_video=prep.s_video,
s_control=prep.s_control,
s_action=prep.s_action,
s_sound=prep.s_sound,
has_action=prep.has_action,
has_sound=prep.has_sound,
has_control=prep.has_control,
ulysses_size=prep.ulysses_size,
use_multi_control_attention=prep.use_multi_control_attention,
multi_control_token_sizes=prep.multi_control_token_sizes,
multi_control_weights=prep.multi_control_weights,
)
return self.norm_moe_gen(hidden_gen)
if not use_multi_control_attention:
hidden_gen = self.gen_sp_gather(hidden_gen)
def _gen_postprocess(
self,
hidden_gen: torch.Tensor,
prep: _GenPrepared,
) -> torch.Tensor | tuple[torch.Tensor, ...]:
"""Project an already-normalized packed GEN state to model outputs."""
if not prep.has_action and not prep.has_sound and not prep.has_control:
return self.unpatchify(self.proj_out(hidden_gen), prep.t, prep.h, prep.w)
# Final norm and project back to latent space
hidden_gen = self.norm_moe_gen(hidden_gen)
if not has_action and not has_sound and not has_control:
return self.unpatchify(self.proj_out(hidden_gen), t, h, w)
split_sizes = []
if has_control:
split_sizes.append(s_control)
split_sizes.append(s_video)
if has_action:
split_sizes.append(s_action)
if has_sound:
split_sizes.append(s_sound)
split_hidden = hidden_gen.split(split_sizes, dim=1)
split_idx = 0
if has_control:
split_idx += 1
hidden_video = split_hidden[split_idx]
split_sizes = []
if prep.has_control:
split_sizes.append(prep.s_control)
split_sizes.append(prep.s_video)
if prep.has_action:
split_sizes.append(prep.s_action)
if prep.has_sound:
split_sizes.append(prep.s_sound)
split_hidden = hidden_gen.split(split_sizes, dim=1)
split_idx = 0
if prep.has_control:
split_idx += 1
video_pred = self.unpatchify(self.proj_out(hidden_video), t, h, w)
if has_control:
return video_pred
outputs: list[torch.Tensor] = [video_pred]
if has_action:
hidden_action = split_hidden[split_idx]
split_idx += 1
assert action_domain_ids is not None
outputs.append(self.unpack_action(self.action_proj_out(hidden_action, action_domain_ids)))
if has_sound:
hidden_sound = split_hidden[split_idx]
outputs.append(self.unpack_sound(self.audio_proj_out(hidden_sound)))
return tuple(outputs)
hidden_video = split_hidden[split_idx]
split_idx += 1
video_pred = self.unpatchify(self.proj_out(hidden_video), prep.t, prep.h, prep.w)
if prep.has_control:
return video_pred
outputs: list[torch.Tensor] = [video_pred]
if prep.has_action:
hidden_action = split_hidden[split_idx]
split_idx += 1
assert prep.action_domain_ids is not None
outputs.append(self.unpack_action(self.action_proj_out(hidden_action, prep.action_domain_ids)))
if prep.has_sound:
hidden_sound = split_hidden[split_idx]
outputs.append(self.unpack_sound(self.audio_proj_out(hidden_sound)))
return tuple(outputs)
def post_load_weights(self) -> None:
"""Post-load processing: ensure correct dtypes."""
self.time_embedder.to(torch.float32)
def set_mixed_precision_step(self, step_index: int, num_steps: int) -> None:
if self.mixed_precision_runtime is not None:
self.mixed_precision_runtime.set_step(step_index, num_steps)
def reset_mixed_precision(self) -> None:
if self.mixed_precision_runtime is not None:
self.mixed_precision_runtime.reset()
+78 -38
View File
@@ -78,6 +78,12 @@ ROBOLAB_CONCAT_VIEW_DESCRIPTION = (
"sides, with the robot visible."
)
_LEGACY_EMBODIMENT_ALIASES = {
"galbot": "embodiment_b",
"agibot_gear_gripper": "embodiment_c_gripper",
"agibot_gear_gripper_ext": "embodiment_c_gripper_ext",
}
@dataclass(frozen=True)
class RoboLabPolicyInputs:
@@ -252,33 +258,83 @@ def extract_robolab_prompt_image(prompt_data: Any | None) -> np.ndarray | None:
return ensure_rgb_uint8_image(image, "multi_modal_data.image")
_ROBOLAB_FRAMEWORK_IMPORT_ERROR = (
"Cosmos3 RoboLab policy serving requires a compatible cosmos_framework source on PYTHONPATH."
)
_ROBOLAB_FRAMEWORK_IMPORTS: dict[str, tuple[str, str]] = {
"ActionTransformPipeline": (
"cosmos_framework.data.generator.action.utils.transforms",
"ActionTransformPipeline",
),
"convert_rotation": (
"cosmos_framework.data.generator.action.utils.pose_utils",
"convert_rotation",
),
"pose_abs_to_rel": (
"cosmos_framework.data.generator.action.utils.pose_utils",
"pose_abs_to_rel",
),
"pose_rel_to_abs": (
"cosmos_framework.data.generator.action.utils.pose_utils",
"pose_rel_to_abs",
),
"build_abs_pose_from_components": (
"cosmos_framework.data.generator.action.utils.pose_utils",
"build_abs_pose_from_components",
),
"FlowUniPCMultistepScheduler": (
"cosmos_framework.model.generator.diffusion.samplers.fm_solvers_unipc",
"FlowUniPCMultistepScheduler",
),
"get_domain_id": (
"cosmos_framework.data.generator.action.utils.domain_utils",
"get_domain_id",
),
}
def lazy_import(module_name: str, symbol_name: str, error_message: str):
try:
module = import_module(module_name)
except ModuleNotFoundError as exc:
raise ModuleNotFoundError(error_message) from exc
return getattr(module, symbol_name)
return getattr(module, symbol_name)
except (ImportError, AttributeError) as exc:
raise ImportError(
f"{error_message} Could not import required symbol {symbol_name!r} from {module_name!r}."
) from exc
def lazy_action_transform_pipeline(max_action_dim: int):
ActionTransformPipeline = lazy_import(
"cosmos_framework.data.vfm.action.transforms",
"ActionTransformPipeline",
"Cosmos3 RoboLab policy serving requires cosmos_framework on PYTHONPATH so the "
"golden ActionTransformPipeline can be reused.",
def _load_robolab_framework_symbol(symbol_name: str):
module_name, exported_name = _ROBOLAB_FRAMEWORK_IMPORTS[symbol_name]
return lazy_import(
module_name,
exported_name,
_ROBOLAB_FRAMEWORK_IMPORT_ERROR,
)
return ActionTransformPipeline(max_action_dim=max_action_dim, cfg_dropout_rate=0.0)
def preflight_cosmos3_action_framework_imports() -> None:
"""Validate every Cosmos Framework symbol used by action policy serving."""
for symbol_name in _ROBOLAB_FRAMEWORK_IMPORTS:
_load_robolab_framework_symbol(symbol_name)
def lazy_action_transform_pipeline(max_action_dim: int, *, format_prompt_as_json: bool = False):
ActionTransformPipeline = _load_robolab_framework_symbol("ActionTransformPipeline")
return ActionTransformPipeline(
max_action_dim=max_action_dim,
cfg_dropout_rate=0.0,
format_prompt_as_json=format_prompt_as_json,
)
def get_robolab_domain_id(domain_name: str) -> int:
get_domain_id = _load_robolab_framework_symbol("get_domain_id")
canonical_name = _LEGACY_EMBODIMENT_ALIASES.get(domain_name.lower().strip(), domain_name)
return int(get_domain_id(canonical_name))
def build_robolab_unipc_scheduler(num_steps: int, shift: float, device: torch.device):
FlowUniPCMultistepScheduler = lazy_import(
"cosmos_framework.model.vfm.diffusion.samplers.fm_solvers_unipc",
"FlowUniPCMultistepScheduler",
(
"Cosmos3 RoboLab policy serving requires cosmos_framework on PYTHONPATH so the "
"golden FlowUniPCMultistepScheduler can be reused."
),
)
FlowUniPCMultistepScheduler = _load_robolab_framework_symbol("FlowUniPCMultistepScheduler")
scheduler = FlowUniPCMultistepScheduler(
num_train_timesteps=1000,
@@ -290,38 +346,22 @@ def build_robolab_unipc_scheduler(num_steps: int, shift: float, device: torch.de
def convert_midtrain_rotation(value: Any, src: str, dst: str) -> np.ndarray:
convert_rotation = lazy_import(
"cosmos_framework.data.vfm.action.pose_utils",
"convert_rotation",
"Cosmos3 RoboLab midtrain action serving requires cosmos_framework pose_utils on PYTHONPATH.",
)
convert_rotation = _load_robolab_framework_symbol("convert_rotation")
return convert_rotation(value, src, dst)
def pose_abs_to_rel(*args, **kwargs) -> np.ndarray:
pose_abs_to_rel_func = lazy_import(
"cosmos_framework.data.vfm.action.pose_utils",
"pose_abs_to_rel",
"Cosmos3 RoboLab midtrain action serving requires cosmos_framework pose_utils on PYTHONPATH.",
)
pose_abs_to_rel_func = _load_robolab_framework_symbol("pose_abs_to_rel")
return pose_abs_to_rel_func(*args, **kwargs)
def pose_rel_to_abs(*args, **kwargs) -> np.ndarray:
pose_rel_to_abs_func = lazy_import(
"cosmos_framework.data.vfm.action.pose_utils",
"pose_rel_to_abs",
"Cosmos3 RoboLab midtrain action serving requires cosmos_framework pose_utils on PYTHONPATH.",
)
pose_rel_to_abs_func = _load_robolab_framework_symbol("pose_rel_to_abs")
return pose_rel_to_abs_func(*args, **kwargs)
def build_abs_pose_from_components(*args, **kwargs) -> np.ndarray:
build_abs_pose_from_components_func = lazy_import(
"cosmos_framework.data.vfm.action.pose_utils",
"build_abs_pose_from_components",
"Cosmos3 RoboLab midtrain action serving requires cosmos_framework pose_utils on PYTHONPATH.",
)
build_abs_pose_from_components_func = _load_robolab_framework_symbol("build_abs_pose_from_components")
return build_abs_pose_from_components_func(*args, **kwargs)
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Adapted from https://github.com/FunAudioLLM/CosyVoice/tree/main/cosyvoice/flow/DiT
# Refactored to use vllm_omni diffusion infrastructure for optimized attention backends
@@ -15,8 +15,10 @@ from torch import nn
from vllm.logger import init_logger
from x_transformers.x_transformers import RotaryEmbedding, apply_rotary_pos_emb
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.layer import Attention as DiffusionAttention
from vllm_omni.model_executor.layers.timestep_embedding import DiTTimestepEmbedding
from vllm_omni.model_executor.models.cosyvoice3.runtime import cosyvoice3_batch_flow_profile
logger = init_logger(__name__)
@@ -52,6 +54,22 @@ def get_pos_embed_indices(start, length, max_pos, scale=1.0):
return pos
def _normalize_attention_mask(mask: torch.Tensor | None, batch_size: int, seq_len: int) -> torch.Tensor | None:
if mask is None:
return None
if mask.dim() == 2:
attn_mask = mask
elif mask.dim() == 3 and mask.shape[1] == 1:
attn_mask = mask[:, 0]
elif mask.dim() == 4:
attn_mask = mask[:, 0, -1]
else:
return None
if attn_mask.shape != (batch_size, seq_len):
return None
return attn_mask.bool()
class FeedForward(nn.Module):
"""Feed-forward network with GELU activation."""
@@ -114,42 +132,39 @@ class DiTAttention(nn.Module):
) -> torch.Tensor:
batch_size, seq_len = x.shape[0], x.shape[1]
# Project to Q, K, V
query = self.to_q(x)
key = self.to_k(x)
value = self.to_v(x)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention_qkv_projection"):
query = self.to_q(x)
key = self.to_k(x)
value = self.to_v(x)
# Apply rotary position embedding
if rope is not None:
freqs, xpos_scale = rope
q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention_rope"):
if rope is not None:
freqs, xpos_scale = rope
q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
# Reshape for attention: (batch, seq, heads, head_dim)
query = query.view(batch_size, seq_len, self.heads, self.dim_head)
key = key.view(batch_size, seq_len, self.heads, self.dim_head)
value = value.view(batch_size, seq_len, self.heads, self.dim_head)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention_backend"):
# Reshape for attention: (batch, seq, heads, head_dim)
query = query.view(batch_size, seq_len, self.heads, self.dim_head)
key = key.view(batch_size, seq_len, self.heads, self.dim_head)
value = value.view(batch_size, seq_len, self.heads, self.dim_head)
# Use diffusion attention backend
# The diffusion Attention layer expects (batch, seq, heads, head_dim)
out = self.attn(query, key, value, attn_metadata=None)
# The diffusion Attention layer expects (batch, seq, heads, head_dim)
attn_mask = _normalize_attention_mask(mask, batch_size, seq_len)
attn_metadata = AttentionMetadata(attn_mask=attn_mask) if attn_mask is not None else None
out = self.attn(query, key, value, attn_metadata=attn_metadata)
# Some attention backends return a non-contiguous layout.
out = out.reshape(batch_size, seq_len, self.inner_dim)
out = out.to(query.dtype)
# Output projection
out = self.to_out(out)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention_output_projection"):
# Some attention backends return a non-contiguous layout.
out = out.reshape(batch_size, seq_len, self.inner_dim)
out = out.to(x.dtype)
out = self.to_out(out)
# Apply mask if provided
if mask is not None:
if mask.dim() == 2:
mask = mask.unsqueeze(-1)
elif mask.dim() == 4:
# (batch, heads, seq, seq) -> use last dim
mask = mask[:, 0, -1].unsqueeze(-1)
out = out.masked_fill(~mask.bool(), 0.0)
attn_mask = _normalize_attention_mask(mask, batch_size, seq_len)
if attn_mask is not None:
out = out.masked_fill(~attn_mask.unsqueeze(-1), 0.0)
return out
@@ -172,18 +187,19 @@ class DiTBlock(nn.Module):
self.ff = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh")
def forward(self, x, t, mask=None, rope=None):
# pre-norm & modulation for attention input
norm, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.attn_norm(x, emb=t)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_adalayernorm_attention"):
norm, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.attn_norm(x, emb=t)
# attention
attn_output = self.attn(x=norm, mask=mask, rope=rope)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention"):
attn_output = self.attn(x=norm, mask=mask, rope=rope)
# process attention output for input x
x = x + gate_msa.unsqueeze(1) * attn_output
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention_residual"):
x = x + gate_msa.unsqueeze(1) * attn_output
ff_norm = self.ff_norm(x) * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
ff_output = self.ff(ff_norm)
x = x + gate_mlp.unsqueeze(1) * ff_output
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_layernorm_ffn"):
ff_norm = self.ff_norm(x) * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
ff_output = self.ff(ff_norm)
x = x + gate_mlp.unsqueeze(1) * ff_output
return x
@@ -205,19 +221,20 @@ class CausalConvPositionEmbedding(nn.Module):
)
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None):
if mask is not None:
mask = mask[..., None]
x = x.masked_fill(~mask, 0.0)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_causal_conv_position_embedding"):
if mask is not None:
mask = mask[..., None]
x = x.masked_fill(~mask, 0.0)
x = x.permute(0, 2, 1)
x = F.pad(x, (self.kernel_size - 1, 0, 0, 0))
x = self.conv1(x)
x = F.pad(x, (self.kernel_size - 1, 0, 0, 0))
x = self.conv2(x)
out = x.permute(0, 2, 1)
x = x.permute(0, 2, 1)
x = F.pad(x, (self.kernel_size - 1, 0, 0, 0))
x = self.conv1(x)
x = F.pad(x, (self.kernel_size - 1, 0, 0, 0))
x = self.conv2(x)
out = x.permute(0, 2, 1)
if mask is not None:
out = out.masked_fill(~mask, 0.0)
if mask is not None:
out = out.masked_fill(~mask, 0.0)
return out
@@ -327,13 +344,15 @@ class InputEmbedding(nn.Module):
self.conv_pos_embed = CausalConvPositionEmbedding(dim=out_dim)
def forward(self, x, cond, text_embed, spks):
to_cat = [x, cond, text_embed]
if self.spk_dim > 0:
spks = repeat(spks, "b c -> b t c", t=x.shape[1])
to_cat.append(spks)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_input_projection"):
to_cat = [x, cond, text_embed]
if self.spk_dim > 0:
spks = repeat(spks, "b c -> b t c", t=x.shape[1])
to_cat.append(spks)
x = self.proj(torch.cat(to_cat, dim=-1))
x = self.conv_pos_embed(x) + x
x = self.proj(torch.cat(to_cat, dim=-1))
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_input_causal_conv"):
x = self.conv_pos_embed(x) + x
return x
@@ -385,31 +404,37 @@ class DiT(nn.Module):
self.num_decoding_left_chunks = num_decoding_left_chunks
def forward(self, x, mask, mu, t, spks=None, cond=None):
x = x.transpose(1, 2)
mu = mu.transpose(1, 2)
cond = cond.transpose(1, 2)
spks = spks.unsqueeze(dim=1)
batch, seq_len = x.shape[0], x.shape[1]
if t.ndim == 0:
t = t.repeat(batch)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_prepare_inputs"):
x = x.transpose(1, 2)
mu = mu.transpose(1, 2)
cond = cond.transpose(1, 2)
spks = spks.unsqueeze(dim=1)
batch, seq_len = x.shape[0], x.shape[1]
if t.ndim == 0:
t = t.repeat(batch)
# t: conditioning time, c: context (text + masked cond audio), x: noised input audio
t = self.time_embed(t)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_time_embedding"):
t = self.time_embed(t)
x = self.input_embed(x, cond, mu, spks.squeeze(1))
rope = self.rotary_embed.forward_from_seq_len(seq_len)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_rope_and_mask"):
rope = self.rotary_embed.forward_from_seq_len(seq_len)
attn_mask = mask[:, 0].bool() if mask.dim() == 3 and mask.shape[1] == 1 else mask.bool()
if self.long_skip_connection is not None:
residual = x
attn_mask = mask.bool().repeat(1, x.size(1), 1).unsqueeze(dim=1)
for block in self.transformer_blocks:
x = block(x, t, mask=attn_mask.bool(), rope=rope)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_transformer_blocks"):
for block_index, block in enumerate(self.transformer_blocks):
with cosyvoice3_batch_flow_profile(f"cosyvoice3_dit_transformer_block_{block_index}"):
x = block(x, t, mask=attn_mask.bool(), rope=rope)
if self.long_skip_connection is not None:
x = self.long_skip_connection(torch.cat((x, residual), dim=-1))
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_long_skip_projection"):
x = self.long_skip_connection(torch.cat((x, residual), dim=-1))
x = self.norm_out(x, t)
output = self.proj_out(x).transpose(1, 2)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_final_adalayernorm"):
x = self.norm_out(x, t)
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_final_projection"):
output = self.proj_out(x).transpose(1, 2)
return output
@@ -17,6 +17,7 @@ import re as re_module
from collections import OrderedDict
from collections.abc import Iterable
from contextlib import contextmanager
from typing import ClassVar
import numpy as np
import torch
@@ -121,6 +122,10 @@ class DreamZeroPipeline(nn.Module, CFGParallelMixin):
methods below. The runner binds one session state only for ``forward()``.
"""
# Generic warmup cannot synthesize robot observations. AR-Diffusion uses
# ar_diffusion_warmup_requests() for model-specific warmup instead.
dummy_run_num_frames: ClassVar[int] = 0
_POSITIVE_BRANCH = "positive"
_NEGATIVE_BRANCH = "negative"
_ar_diffusion_kv_state = None
@@ -715,7 +720,7 @@ class DreamZeroPipeline(nn.Module, CFGParallelMixin):
def warmup_compile(self) -> None:
"""Warm up compiled text/image/VAE paths before timed inference."""
if not torch.cuda.is_available():
if not torch.accelerator.is_available():
return
state = self.state
@@ -796,12 +801,12 @@ class DreamZeroPipeline(nn.Module, CFGParallelMixin):
latents: tuple[torch.Tensor, torch.Tensor],
do_true_cfg: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Post-step sync: .contiguous() + cuda.synchronize()"""
"""Post-step sync: .contiguous() + accelerator stream synchronize"""
latents = tuple(t.contiguous() for t in latents)
if do_true_cfg and get_classifier_free_guidance_world_size() > 1:
device = next((t.device for t in latents if t.is_cuda), None)
device = next((t.device for t in latents if t.device.type != "cpu"), None)
if device is not None:
torch.cuda.current_stream(device).synchronize()
torch.accelerator.current_stream(device).synchronize()
return latents
# -----------------------------------------------------------------------
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Adapted from: https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_ernie_image.py
from collections.abc import Iterable
@@ -28,6 +28,9 @@ from vllm_omni.diffusion.distributed.sp_plan import (
SequenceParallelInput,
SequenceParallelOutput,
)
from vllm_omni.diffusion.models.ernie_image.fused_rope import (
try_fused_qk_rotary_emb,
)
logger = init_logger(__name__)
@@ -101,6 +104,26 @@ def _apply_rotary_emb(
return torch.cat((x_rot * cos_ + x_rotated * sin_, x[..., rot_dim:]), dim=-1)
def _apply_qk_rotary_emb(
query: torch.Tensor,
key: torch.Tensor,
freqs_cos: torch.Tensor,
freqs_sin: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
fused = try_fused_qk_rotary_emb(
query,
key,
freqs_cos,
freqs_sin,
)
if fused is not None:
return fused
return (
_apply_rotary_emb(query, freqs_cos, freqs_sin),
_apply_rotary_emb(key, freqs_cos, freqs_sin),
)
class ErnieImageEmbedND3(nn.Module):
def __init__(self, dim: int, theta: int, axes_dim: tuple[int, int, int]):
super().__init__()
@@ -340,8 +363,7 @@ class ErnieImageAttention(nn.Module):
if image_rotary_emb is not None:
freqs_cos, freqs_sin = image_rotary_emb
query = _apply_rotary_emb(query, freqs_cos, freqs_sin)
key = _apply_rotary_emb(key, freqs_cos, freqs_sin)
query, key = _apply_qk_rotary_emb(query, key, freqs_cos, freqs_sin)
attn_metadata = None
if attention_mask is not None:
@@ -599,17 +621,12 @@ class ErnieImageTransformer2DModel(nn.Module):
hidden_states, freqs_cos, freqs_sin, attention_mask = self.unified_prepare(hidden_states, text_bth, text_lens)
attention_mask = self._slice_attention_mask_for_ring(attention_mask)
rotary_pos_emb = (freqs_cos, freqs_sin)
S = hidden_states.shape[0]
sample = self.time_proj(timestep)
sample = sample.to(dtype=dtype)
c = self.time_embedding(sample)
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = [
t.unsqueeze(0).expand(S, -1, -1).contiguous() for t in self.adaLN_modulation(c).chunk(6, dim=-1)
]
temb = self.adaLN_modulation(c).chunk(6, dim=-1)
for layer in self.layers:
temb = [shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp]
if torch.is_grad_enabled() and self.gradient_checkpointing:
hidden_states = self._gradient_checkpointing_func(
layer,
@@ -0,0 +1,211 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Lossless eager Q/K RoPE fusion for ERNIE-Image."""
from __future__ import annotations
import logging
from collections import OrderedDict
import torch
from vllm.triton_utils import HAS_TRITON, tl, triton
from vllm_omni.platforms import current_omni_platform
logger = logging.getLogger(__name__)
_FAILED_KEYS_MAX_SIZE = 128
_FAILED_KEYS: OrderedDict[tuple[object, ...], None] = OrderedDict()
if HAS_TRITON:
@triton.jit
def _round_bf16_to_fp32(value):
"""RNE-round FP32 to BF16 precision in an FP32 register."""
bits = value.to(tl.int32, bitcast=True)
rounding_bias = 0x7FFF + ((bits >> 16) & 1)
rounded_bits = (bits + rounding_bias) & -65536
return rounded_bits.to(tl.float32, bitcast=True)
@triton.jit
def _qk_rope_kernel(
out_q_ptr,
out_k_ptr,
q_ptr,
k_ptr,
cos_ptr,
sin_ptr,
heads,
head_dim: tl.constexpr,
rotary_dim: tl.constexpr,
rotary_half: tl.constexpr,
heads_block: tl.constexpr,
half_block: tl.constexpr,
tail_block: tl.constexpr,
):
row = tl.program_id(0).to(tl.int64)
is_key = tl.program_id(1)
base = row * heads * head_dim
head_offsets = tl.arange(0, heads_block)[:, None]
head_mask = head_offsets < heads
columns = tl.arange(0, half_block)[None, :]
column_mask = columns < rotary_half
mask = head_mask & column_mask
if is_key == 0:
input_ptr = q_ptr
output_ptr = out_q_ptr
else:
input_ptr = k_ptr
output_ptr = out_k_ptr
first_offsets = base + head_offsets * head_dim + columns
second_offsets = first_offsets + rotary_half
first = tl.load(input_ptr + first_offsets, mask=mask, other=0.0).to(tl.float32)
second = tl.load(input_ptr + second_offsets, mask=mask, other=0.0).to(tl.float32)
# The eager path casts FP32 frequencies to BF16, duplicates adjacent
# values, rounds both BF16 multiplies, and finally rounds the add.
first_freq = columns // 2
second_freq = (rotary_half + columns) // 2
cos_first = _round_bf16_to_fp32(tl.load(cos_ptr + row * rotary_half + first_freq, mask=column_mask))
cos_second = _round_bf16_to_fp32(tl.load(cos_ptr + row * rotary_half + second_freq, mask=column_mask))
sin_first = _round_bf16_to_fp32(tl.load(sin_ptr + row * rotary_half + first_freq, mask=column_mask))
sin_second = _round_bf16_to_fp32(tl.load(sin_ptr + row * rotary_half + second_freq, mask=column_mask))
out_first = _round_bf16_to_fp32(first * cos_first) + _round_bf16_to_fp32(-second * sin_first)
out_second = _round_bf16_to_fp32(second * cos_second) + _round_bf16_to_fp32(first * sin_second)
tl.store(output_ptr + first_offsets, out_first, mask=mask)
tl.store(output_ptr + second_offsets, out_second, mask=mask)
if head_dim > rotary_dim:
tail_columns = rotary_dim + tl.arange(0, tail_block)[None, :]
tail_mask = head_mask & (tail_columns < head_dim)
tail_offsets = base + head_offsets * head_dim + tail_columns
tail = tl.load(input_ptr + tail_offsets, mask=tail_mask, other=0.0)
tl.store(output_ptr + tail_offsets, tail, mask=tail_mask)
def _runtime_key(
query: torch.Tensor,
key: torch.Tensor,
freqs_cos: torch.Tensor,
) -> tuple[object, ...]:
return (
query.device.index,
tuple(query.shape),
tuple(key.shape),
tuple(freqs_cos.shape),
query.dtype,
freqs_cos.dtype,
)
def _is_failed_runtime_key(runtime_key: tuple[object, ...]) -> bool:
if runtime_key not in _FAILED_KEYS:
return False
_FAILED_KEYS.move_to_end(runtime_key)
return True
def _record_failed_runtime_key(runtime_key: tuple[object, ...]) -> None:
_FAILED_KEYS[runtime_key] = None
_FAILED_KEYS.move_to_end(runtime_key)
while len(_FAILED_KEYS) > _FAILED_KEYS_MAX_SIZE:
_FAILED_KEYS.popitem(last=False)
def _supported_inputs(
query: torch.Tensor,
key: torch.Tensor,
freqs_cos: torch.Tensor,
freqs_sin: torch.Tensor,
) -> bool:
if torch.compiler.is_compiling():
return False
if any(tensor.requires_grad for tensor in (query, key, freqs_cos, freqs_sin)):
return False
if not HAS_TRITON or not current_omni_platform.is_cuda():
return False
if query.dtype is not torch.bfloat16 or not query.is_cuda:
return False
if query.ndim != 4 or key.shape != query.shape or key.dtype is not query.dtype or key.device != query.device:
return False
if not query.is_contiguous() or not key.is_contiguous():
return False
if freqs_cos.dtype is not torch.float32 or freqs_sin.dtype is not torch.float32:
return False
if not freqs_cos.is_cuda or freqs_cos.device != query.device:
return False
if freqs_sin.device != query.device or freqs_sin.shape != freqs_cos.shape:
return False
if not freqs_cos.is_contiguous() or not freqs_sin.is_contiguous():
return False
batch, sequence, _, head_dim = query.shape
rotary_half = freqs_cos.shape[-1] if freqs_cos.ndim == 3 else 0
return (
query.numel() > 0
and freqs_cos.shape == (batch, sequence, rotary_half)
and rotary_half > 0
and rotary_half * 2 <= head_dim
)
def _launch_fused_qk_rotary_emb(
query: torch.Tensor,
key: torch.Tensor,
freqs_cos: torch.Tensor,
freqs_sin: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
batch, sequence, heads, head_dim = query.shape
rotary_half = freqs_cos.shape[-1]
rotary_dim = rotary_half * 2
tail = head_dim - rotary_dim
output_query = torch.empty_like(query)
output_key = torch.empty_like(key)
with torch.accelerator.device_index(query.device.index):
_qk_rope_kernel[(batch * sequence, 2)](
output_query,
output_key,
query,
key,
freqs_cos,
freqs_sin,
heads,
head_dim=head_dim,
rotary_dim=rotary_dim,
rotary_half=rotary_half,
heads_block=triton.next_power_of_2(heads),
half_block=triton.next_power_of_2(rotary_half),
tail_block=triton.next_power_of_2(max(tail, 1)),
)
return output_query, output_key
def try_fused_qk_rotary_emb(
query: torch.Tensor,
key: torch.Tensor,
freqs_cos: torch.Tensor,
freqs_sin: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor] | None:
"""Return fused Q/K outputs, or ``None`` to request the eager fallback."""
if not _supported_inputs(query, key, freqs_cos, freqs_sin):
return None
runtime_key = _runtime_key(query, key, freqs_cos)
if _is_failed_runtime_key(runtime_key):
return None
try:
return _launch_fused_qk_rotary_emb(query, key, freqs_cos, freqs_sin)
except Exception:
_record_failed_runtime_key(runtime_key)
logger.exception("ERNIE-Image fused Q/K RoPE failed; using the eager fallback")
return None
__all__ = ["try_fused_qk_rotary_emb"]
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import math
from collections.abc import Iterable
@@ -124,8 +124,8 @@ class GlmImageImageProjector(nn.Module):
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
batch_size, channel, height, width = hidden_states.shape
post_patch_height = torch.tensor(height // self.patch_size, device=hidden_states.device, dtype=torch.int64)
post_patch_width = torch.tensor(width // self.patch_size, device=hidden_states.device, dtype=torch.int64)
post_patch_height = height // self.patch_size
post_patch_width = width // self.patch_size
# Reshape: [B, C, H, W] -> [B, H', W', C*p*p] -> [B, H'*W', C*p*p]
hidden_states = hidden_states.reshape(
@@ -189,18 +189,16 @@ class GlmImagePrepare(nn.Module):
self,
image_projector: nn.Module,
rope: GlmImageRotaryPosEmbed,
patch_size: int,
):
super().__init__()
self.image_projector = image_projector
self.rope = rope
self.patch_size = patch_size
def forward(
self,
hidden_states: torch.Tensor,
prior_hidden_states: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Process hidden_states and compute RoPE embeddings.
Args:
@@ -211,14 +209,7 @@ class GlmImagePrepare(nn.Module):
hidden_states: Patched hidden states [B, seq_len, D]
rope_cos: RoPE cos embeddings [seq_len, dim]
rope_sin: RoPE sin embeddings [seq_len, dim]
post_patch_height: Scalar tensor for height after patching
post_patch_width: Scalar tensor for width after patching
"""
batch_size, num_channels, height, width = hidden_states.shape
post_patch_height = torch.tensor(height // self.patch_size, device=hidden_states.device, dtype=torch.int64)
post_patch_width = torch.tensor(width // self.patch_size, device=hidden_states.device, dtype=torch.int64)
# Compute RoPE (uses original 4D hidden_states shape)
image_rotary_emb = self.rope(hidden_states)
rope_cos = image_rotary_emb[0].to(hidden_states.device)
@@ -231,7 +222,7 @@ class GlmImagePrepare(nn.Module):
if prior_hidden_states is not None:
hidden_states = hidden_states + prior_hidden_states
return hidden_states, rope_cos, rope_sin, post_patch_height, post_patch_width
return hidden_states, rope_cos, rope_sin
class GlmImageAdaLayerNormZero(nn.Module):
@@ -961,7 +952,6 @@ class GlmImageTransformer2DModel(CachedTransformer):
1: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True, auto_pad=True),
# RoPE sin: [seq_len, dim] - shard along sequence dimension
2: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True, auto_pad=True),
# post_patch_height and post_patch_width are scalars, not sharded
},
# Gather output at proj_out
"proj_out": SequenceParallelOutput(gather_dim=1, expected_dims=3),
@@ -1044,7 +1034,7 @@ class GlmImageTransformer2DModel(CachedTransformer):
)
# Prepare module for SP (encapsulates patch embedding and RoPE for _sp_plan)
self.prepare = GlmImagePrepare(self.image_projector, self.rope, patch_size)
self.prepare = GlmImagePrepare(self.image_projector, self.rope)
self.time_condition_embed = GlmImageCombinedTimestepSizeEmbeddings(
embedding_dim=time_embed_dim,
@@ -1137,12 +1127,10 @@ class GlmImageTransformer2DModel(CachedTransformer):
# 1. Prepare hidden_states and RoPE via GlmImagePrepare module
# _sp_plan will shard hidden_states and RoPE together via split_output=True
hidden_states, rope_cos, rope_sin, post_patch_height_t, post_patch_width_t = self.prepare(
hidden_states, prior_hidden_states
)
hidden_states, rope_cos, rope_sin = self.prepare(hidden_states, prior_hidden_states)
image_rotary_emb = (rope_cos, rope_sin)
post_patch_height = int(post_patch_height_t.item())
post_patch_width = int(post_patch_width_t.item())
post_patch_height = height // self.patch_size
post_patch_width = width // self.patch_size
# Timestep conditioning
temb = self.time_condition_embed(timestep, target_size, crop_coords, hidden_states.dtype)
@@ -1163,8 +1151,6 @@ class GlmImageTransformer2DModel(CachedTransformer):
device=hidden_states.device,
)
hidden_states_mask[:, ctx.sp_original_seq_len :] = False
if hidden_states_mask.all():
hidden_states_mask = None
# 2. Transformer blocks
for layer_idx, block in enumerate(self.transformer_blocks):
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Adapted from Helios (https://github.com/BestWishYsh/Helios)
import math
@@ -27,10 +27,7 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.cache.cachedit import CacheDiTAdapterConfig
from vllm_omni.diffusion.distributed.sp_plan import (
SequenceParallelInput,
SequenceParallelOutput,
)
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelOutput
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.base_config import (
@@ -448,6 +445,12 @@ class HeliosCrossAttention(nn.Module):
num_kv_heads=self.num_heads,
softmax_scale=1.0 / (head_dim**0.5),
causal=False,
# Text K/V is replicated on every SP rank, so Ulysses must not be
# used here: its all-to-all would treat the per-rank replicas as
# sequence shards and ws-fold duplicate the keys. Sharded Q over
# full replicated K/V is correct locally and needs no
# communication (same as Wan2.2 cross-attn).
skip_sequence_parallel=True,
)
def project_kv(self, encoder_hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
@@ -624,16 +627,50 @@ class HeliosTransformer3DModel(nn.Module):
_hsdp_shard_conditions = [_is_transformer_block]
_sp_plan = {
"rope": {
0: SequenceParallelInput(split_dim=1, expected_dims=4, split_output=True, auto_pad=True),
1: SequenceParallelInput(split_dim=1, expected_dims=4, split_output=True, auto_pad=True),
},
"blocks.0": {
"hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, auto_pad=True),
},
# "rope" and "blocks.0" are intentionally omitted.
# The rope hook splits along dim=1 of the 5D output [B, D, T, H, W],
# which is the frequency dimension, NOT the sequence dimension.
# The blocks.0 hook splits the concatenated hidden_states as a whole,
# which can put all history tokens in one rank (original_context_length=0).
# Instead, hidden_states and rotary_emb are split per-component in
# forward() after flatten+transpose, ensuring each rank gets half
# of each component (history and current).
"proj_out": SequenceParallelOutput(gather_dim=1, expected_dims=3),
}
def _sp_split_seq(self, x: torch.Tensor) -> torch.Tensor:
"""Split tensor along sequence dim (dim=1) for Ulysses SP.
If seq_len is not divisible by world_size, replicate the last
token(s) to pad to a divisible length. This avoids crashing
on non-divisible history components (which use different patch
sizes and thus produce different token counts).
Residual caveat: the replicated padding tokens attend unmasked
in attn1 on the last rank (at most ws-1 replicas per component).
The impact is bounded, but this is the first place to look if
odd resolutions ever show quality drift.
"""
from vllm_omni.diffusion.distributed.parallel_state import (
get_sequence_parallel_rank,
get_sequence_parallel_world_size,
)
ws = get_sequence_parallel_world_size()
if ws > 1 and x.dim() >= 2 and x.shape[1] > 0:
seq_len = x.shape[1]
remainder = seq_len % ws
if remainder != 0:
pad = ws - remainder
# Replicate the last token to fill the padding
last = x[:, -1:, ...].expand(-1, pad, *([-1] * (x.dim() - 2)))
x = torch.cat([x, last], dim=1)
seq_len = x.shape[1]
r = get_sequence_parallel_rank()
n = seq_len // ws
x = x[:, r * n : (r + 1) * n, ...].contiguous()
return x
def __init__(
self,
patch_size: tuple[int, ...] = (1, 2, 2),
@@ -860,6 +897,9 @@ class HeliosTransformer3DModel(nn.Module):
device=hidden_states.device,
)
rotary_emb = rotary_emb.flatten(2).transpose(1, 2)
# USP: per-component split (each rank gets half of current frames)
hidden_states = self._sp_split_seq(hidden_states)
rotary_emb = self._sp_split_seq(rotary_emb)
original_context_length = hidden_states.shape[1]
# 2. Process short history latents
@@ -876,6 +916,9 @@ class HeliosTransformer3DModel(nn.Module):
device=latents_history_short.device,
)
rotary_emb_history_short = rotary_emb_history_short.flatten(2).transpose(1, 2)
# USP: per-component split
latents_history_short = self._sp_split_seq(latents_history_short)
rotary_emb_history_short = self._sp_split_seq(rotary_emb_history_short)
hidden_states = torch.cat([latents_history_short, hidden_states], dim=1)
rotary_emb = torch.cat([rotary_emb_history_short, rotary_emb], dim=1)
@@ -896,6 +939,9 @@ class HeliosTransformer3DModel(nn.Module):
rotary_emb_history_mid = pad_for_3d_conv(rotary_emb_history_mid, (2, 2, 2))
rotary_emb_history_mid = center_down_sample_3d(rotary_emb_history_mid, (2, 2, 2))
rotary_emb_history_mid = rotary_emb_history_mid.flatten(2).transpose(1, 2)
# USP: per-component split
latents_history_mid = self._sp_split_seq(latents_history_mid)
rotary_emb_history_mid = self._sp_split_seq(rotary_emb_history_mid)
hidden_states = torch.cat([latents_history_mid, hidden_states], dim=1)
rotary_emb = torch.cat([rotary_emb_history_mid, rotary_emb], dim=1)
@@ -916,6 +962,9 @@ class HeliosTransformer3DModel(nn.Module):
rotary_emb_history_long = pad_for_3d_conv(rotary_emb_history_long, (4, 4, 4))
rotary_emb_history_long = center_down_sample_3d(rotary_emb_history_long, (4, 4, 4))
rotary_emb_history_long = rotary_emb_history_long.flatten(2).transpose(1, 2)
# USP: per-component split
latents_history_long = self._sp_split_seq(latents_history_long)
rotary_emb_history_long = self._sp_split_seq(rotary_emb_history_long)
hidden_states = torch.cat([latents_history_long, hidden_states], dim=1)
rotary_emb = torch.cat([rotary_emb_history_long, rotary_emb], dim=1)
@@ -958,6 +1007,18 @@ class HeliosTransformer3DModel(nn.Module):
timestep_proj = timestep_proj.permute(0, 2, 1, 3)
# 6. Transformer blocks
# Manually increment _sp_shard_depth so that attention layers
# know SP is active and perform Ulysses All-to-All communication.
# Normally this is done by split_output=True hooks (e.g. rope),
# but those are removed because they split the wrong dimension.
from vllm_omni.diffusion.forward_context import (
get_forward_context,
is_forward_context_available,
)
if is_forward_context_available():
get_forward_context()._sp_shard_depth += 1
hidden_states = hidden_states.contiguous()
encoder_hidden_states = encoder_hidden_states.contiguous()
rotary_emb = rotary_emb.contiguous()
@@ -979,6 +1040,11 @@ class HeliosTransformer3DModel(nn.Module):
hidden_states = self.proj_out(hidden_states)
# 8. Unpatchify
# proj_out gather may include padded tokens from non-divisible
# sequences. Slice to the expected size before reshape.
expected_seq = post_patch_num_frames * post_patch_height * post_patch_width
if hidden_states.shape[1] > expected_seq:
hidden_states = hidden_states[:, :expected_seq, :]
hidden_states = hidden_states.reshape(
batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
)
@@ -535,19 +535,23 @@ class HeliosPipeline(
"zero_steps": int(extra.get("zero_steps", 1)),
}
)
self.prepare_next_chunk(state)
return state
def peek_chunk_media(self, state: StepRequestState) -> ChunkMediaSpec:
"""Expose this chunk's decoded media extent for interaction timelines."""
num_frames = int(state.extra["window_num_frames"])
num_media_frames = int(state.extra["window_num_frames"])
num_latent_frames = int(state.extra["num_latent_frames_per_chunk"])
fps = state.sampling.fps
if fps is None or float(fps) <= 0:
raise ValueError(
"sampling.fps is required and must be > 0 for interaction modalities that use the "
f"chunk media timeline, got {fps!r} (request_id={state.request_id!r})"
)
return ChunkMediaSpec(num_frames=num_frames, fps=float(fps))
return ChunkMediaSpec(
num_media_frames=num_media_frames,
fps=float(fps),
num_latent_frames=num_latent_frames,
)
@override
def prepare_next_chunk(self, state: StepRequestState) -> None:
@@ -75,7 +75,11 @@ from vllm_omni.diffusion.distributed.sp_plan import (
SequenceParallelOutput,
)
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
from vllm_omni.diffusion.forward_context import (
get_paged_kv_computed_tokens,
paged_kv_prefill,
set_forward_context_denoise_step_idx,
)
from vllm_omni.diffusion.layers.fused_moe import FusedMoE
from vllm_omni.diffusion.layers.norm import RMSNorm
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
@@ -1097,8 +1101,6 @@ class ImageKVCacheManager(nn.Module):
layer resolves the actual CUDA or Ascend paged kernel.
"""
if uncond_cfg_prefill:
raise RuntimeError("Hunyuan negative-CFG prefill must run before paged row activation")
if self._injected_ar_kv is not None:
raise NotImplementedError("Hunyuan Scheduler-paged KV does not support imported AR KV")
if not query_lens or len(seq_lens) != len(query_lens):
@@ -1109,7 +1111,6 @@ class ImageKVCacheManager(nn.Module):
self.clear_legacy_prompt_kv_cache()
bs = len(query_lens)
q_len = query_lens[0]
seq_len = seq_lens[0]
assert query.shape[0] == bs * q_len, f"{query.shape[0]} != {bs * q_len}"
head_num_per_rank = query.shape[1]
@@ -1121,22 +1122,19 @@ class ImageKVCacheManager(nn.Module):
value = value.reshape(bs, q_len, kv_head_num_per_rank, head_dim)
joint_text_query = joint_text_key = joint_text_value = None
if self.sp_size > 1 and first_step:
if self.sp_size > 1 and uncond_cfg_prefill:
joint_text_query, joint_text_key, joint_text_value = query, key, value
query, key, value = query[:, :0], key[:, :0], value[:, :0]
elif self.sp_size > 1 and first_step:
if shard_image_size is None or shard_image_size <= 0:
raise ValueError("Hunyuan paged Ulysses requires a positive local image shard size")
local_prompt_len = seq_len - shard_image_size
joint_query_len = query.shape[1] - shard_image_size
if local_prompt_len != joint_query_len:
raise ValueError(
"Hunyuan paged Ulysses prompt layout mismatch: "
f"key_prompt={local_prompt_len}, query_prompt={joint_query_len}"
)
joint_text_query = query[:, :joint_query_len]
joint_text_key = key[:, :local_prompt_len]
joint_text_value = value[:, :local_prompt_len]
joint_text_key = key[:, :joint_query_len]
joint_text_value = value[:, :joint_query_len]
query = query[:, joint_query_len:]
key = key[:, local_prompt_len:]
value = value[:, local_prompt_len:]
key = key[:, joint_query_len:]
value = value[:, joint_query_len:]
if joint_text_query is None:
attn_metadata = AttentionMetadata(full_attn_spans=full_attn_spans)
@@ -1254,6 +1252,8 @@ class ImageKVCacheManager(nn.Module):
) -> torch.Tensor:
self.image_token_len = kwargs.get("num_image_tokens")
if self.attn.is_paged_kv_active():
# A native connector fills the same Scheduler-owned pages as
# local prefill. Imported prefixes need no dense reconstruction.
full_attn_spans = kwargs.get("full_attn_spans")
if full_attn_spans is None:
raise ValueError("Hunyuan Scheduler-paged KV requires full_attn_spans metadata")
@@ -1837,7 +1837,9 @@ class HunYuanAttention(nn.Module):
num_kv_heads=self.num_kv_heads,
scaling=self.scaling,
image_token_len=4097,
prefix=f"{prefix}.image_attn",
# Native Mooncake pairs this canonical KV layer name with the AR
# HunYuanAttention: model.layers.N.self_attn.attn. Keep both in sync.
prefix=f"model.{prefix}",
)
self.image_rope2d_emb = HunYuanRotary2DEmbedder(
num_heads=self.num_heads,
@@ -2964,7 +2966,10 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
seq_lens=[prefill_seq_len],
num_image_tokens=0,
ar_kv_reuse_len=negative_reuse_len,
full_attn_spans=model_kwargs["full_attn_spans"][batch_slice]
full_attn_spans=[
[(start, min(end, prefill_seq_len)) for start, end in spans if start < prefill_seq_len]
for spans in model_kwargs["full_attn_spans"][batch_slice]
]
if model_kwargs.get("full_attn_spans")
else None,
)
@@ -3019,6 +3024,28 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
device,
):
ar_kv_data = model_kwargs.pop("ar_kv_data", None)
computed_tokens = get_paged_kv_computed_tokens()
if computed_tokens and computed_tokens[0] > 0:
positive_reuse_len = computed_tokens[0]
if (
len(computed_tokens) > 1
and computed_tokens[1] < positive_reuse_len
and (not cfg_parallel_ready or cfg_rank == 1)
):
prefill_inputs = self._build_negative_cfg_prefill_inputs(
input_ids,
model_kwargs,
batch_size,
computed_tokens[1],
positive_reuse_len,
cfg_parallel_ready,
)
with (
paged_kv_prefill(1, positive_reuse_len),
torch.autocast(device_type=device.type, dtype=torch.bfloat16),
):
self.model.forward_call(**prefill_inputs)
return self._truncate_reused_prefix(input_ids, model_kwargs, positive_reuse_len), positive_reuse_len
if ar_kv_data is None:
logger.debug(
"[AR KV Reuse] cfg_rank=%s: no AR KV received, fallback to full recompute (reuse_len=0)",
@@ -3040,7 +3067,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
# 3. negative cfg prefill
# For CFG distilled models, skip negative CFG prefill (cfg_factor=1, no negative prompt)
if self.do_classifier_free_guidance and not self.model.config.cfg_distilled:
if self.do_classifier_free_guidance and not getattr(self.model.config, "cfg_distilled", False):
self._maybe_run_negative_cfg_prefill(
input_ids=input_ids,
model_kwargs=model_kwargs,
@@ -3151,7 +3178,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
# For CFG distilled models, skip CFG parallel (cfg_factor=1, no negative branch)
cfg_parallel_ready = (
self.do_classifier_free_guidance
and not self.model.config.cfg_distilled
and not getattr(self.model.config, "cfg_distilled", False)
and get_classifier_free_guidance_world_size() == 2
)
@@ -3207,7 +3234,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
self._split_model_kwargs_for_cfg_parallel(model_kwargs, batch_size, cfg_rank)
else:
# For CFG distilled models, cfg_factor is always 1 (CFG embedded in model)
if self.model.config.cfg_distilled:
if getattr(self.model.config, "cfg_distilled", False):
cfg_factor = 1
else:
cfg_factor = 1 + self.do_classifier_free_guidance
@@ -3252,7 +3279,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
# Sequential CFG: double the batch
latent_model_input = torch.cat([latents] * cfg_factor)
if self.model.config.use_meanflow:
if getattr(self.model.config, "use_meanflow", False):
r = self.scheduler.get_timestep_r(t)
r_expand = r.repeat(latent_model_input.shape[0])
else:
@@ -3281,7 +3308,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
if should_compute:
# Handle guidance for CFG distilled models
if self.model.config.cfg_distilled:
if getattr(self.model.config, "cfg_distilled", False):
model_kwargs["guidance"] = torch.tensor(
[1000.0 * self._guidance_scale],
device=self.device,
@@ -3308,7 +3335,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
# Perform guidance
# For CFG distilled models, guidance is already embedded in the model,
# so we skip the explicit CFG computation
if self.model.config.cfg_distilled:
if getattr(self.model.config, "cfg_distilled", False):
# CFG distilled: guidance is handled internally via guidance_emb
pass
elif cfg_parallel_ready:
@@ -338,6 +338,9 @@ class HunyuanImage3Pipeline(
supports_step_execution: ClassVar[bool] = True
supports_request_batch = False
support_image_input = True
# The warmup request's blank image routes this AR+diffusion model down its
# image-edit path, where the token block cannot match the latent patch grid.
dummy_run_num_frames: ClassVar[int] = 0
_dit_modules: ClassVar[list[str]] = ["model"]
_encoder_modules: ClassVar[list[str]] = ["vision_model"]
_vae_modules: ClassVar[list[str]] = ["vae"]
@@ -364,6 +367,8 @@ class HunyuanImage3Pipeline(
def __init__(self, od_config: OmniDiffusionConfig) -> None:
self.hf_config = get_config(od_config.model, trust_remote_code=True)
self.hf_config.cfg_distilled = _config_flag(self.hf_config, "cfg_distilled")
self.hf_config.use_meanflow = _config_flag(self.hf_config, "use_meanflow")
super().__init__(self.hf_config)
# update diffusion config
self.generation_config = GenerationConfig.from_pretrained(od_config.model)
@@ -1279,7 +1284,9 @@ class HunyuanImage3Pipeline(
# 4. Encode conditional images
# Skip encoding if AR KV reuse is enabled
has_ar_kv = kwargs.get("ar_kv_data")
has_ar_kv = kwargs.get("ar_kv_data") or request_layout_utils.native_kv_covers_cond_images(
output, kwargs.get("kv_computed_tokens", ())
)
if batch_cond_image_info is not None and len(batch_cond_image_info[0]) > 0 and not has_ar_kv:
cond_vae_images, cond_timestep, cond_vit_images = self._encode_cond_image(
batch_cond_image_info, cfg_factor[mode], generator=generator
@@ -1891,6 +1898,7 @@ class HunyuanImage3Pipeline(
pipe._guidance_scale = guidance_scale
pipe._guidance_rescale = getattr(sampling, "guidance_rescale", 0.0)
ar_kv_kwargs = self._extract_ar_kv_from_sampling(sampling)
model_kwargs = self.prepare_model_inputs(
prompt=prompt,
cot_text=cot_text,
@@ -1903,8 +1911,10 @@ class HunyuanImage3Pipeline(
batch_cond_image_info=batch_cond_image_info,
bot_task=tokenizer_bot_task,
prepared_layout=request_layout_utils.get_hunyuan_prepared_layout(state),
kv_computed_tokens=state.extra.get("kv_computed_tokens", ()),
**ar_kv_kwargs,
)
model_kwargs.update(self._extract_ar_kv_from_sampling(sampling))
model_kwargs.update(ar_kv_kwargs)
model_kwargs["use_cache"] = False
input_ids = model_kwargs.pop("input_ids")
@@ -2334,6 +2344,7 @@ class HunyuanImage3Pipeline(
batch_cond_image_info=batch_cond_image_info,
bot_task=tokenizer_bot_task,
prepared_layout=request_layout_utils.get_hunyuan_prepared_layout(req.requests[0]),
kv_computed_tokens=getattr(req.requests[0], "kv_computed_tokens", ()),
**ar_kv_kwargs,
)
@@ -60,6 +60,48 @@ HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS: dict[str, int] = {
"<img_ratio_36>": 130106,
}
def validate_special_token_ids(tokenizer: Any) -> None:
"""Fail fast if a real tokenizer's ids drift from the hardcoded table.
``HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS`` exists so stop-token / trigger-tag
resolution doesn't need a tokenizer round-trip, but that only holds as
long as the ids match ``tokenizer.json`` for whatever model repo/revision
is actually loaded. Call this once a real tokenizer is available (the
example scripts do, right after loading it) to catch drift immediately
instead of silently producing a request that runs to completion with the
wrong stop tokens. Not wired into ``build_prompt_tokens`` itself: callers
that intentionally pass a stand-in tokenizer with different ids (e.g.
this module's own unit tests) must not be forced through this check.
Both ``tencent/HunyuanImage-3.0`` (base) and ``-Instruct`` report the
same ``model_class_name`` (``HunyuanImage3ForCausalMM``), so this hook
fires for either checkpoint -- but the base tokenizer's vocab doesn't
include the Instruct-only ``<img_ratio_33>``-``<img_ratio_36>`` tokens
(added for it2i's second aspect-ratio range). A token the tokenizer
doesn't recognize at all (``convert_tokens_to_ids`` returning
``unk_token_id``, or ``None`` for tokenizers without an unk concept) is
"not part of this checkpoint's vocab," not "drifted"; only an id that
resolves to something *else* indicates the hardcoded table is stale.
"""
unk_id = getattr(tokenizer, "unk_token_id", None)
mismatches: dict[str, tuple[int, int]] = {}
for tok, expected_id in HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS.items():
actual_id = tokenizer.convert_tokens_to_ids(tok)
if actual_id is None or (unk_id is not None and actual_id == unk_id):
continue # not in this checkpoint's vocab -- nothing to compare
if actual_id != expected_id:
mismatches[tok] = (expected_id, actual_id)
if mismatches:
details = ", ".join(f"{tok!r}: expected {exp}, got {act}" for tok, (exp, act) in mismatches.items())
raise ValueError(
"HunyuanImage-3.0 tokenizer special-token ids no longer match "
f"HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS ({details}). The loaded "
"tokenizer/model revision has likely changed; update the hardcoded "
"table in prompt_utils.py to match."
)
# bot_task -> (sys_type, trigger_tag).
# ``vanilla`` is special-cased downstream: it bypasses the chat template
# (no ``User:`` / ``Assistant:`` framing) and is only valid with
@@ -317,12 +359,106 @@ def build_prompt_tokens(
)
@dataclass
class ARPromptInputs:
"""Fully-resolved AR-stage inputs for one HunyuanImage3 request.
Consolidates the three things every caller (offline example, OpenAI
server) must compute before submitting an AR request: the AR prefill
(as segment-tokenized ``prompt_token_ids`` when a tokenizer is
available, else a formatted ``prompt`` string), the resolved DiT
system-prompt type, and the AR ``stop_token_ids``.
"""
prompt: str | None
prompt_token_ids: list[int] | None
system_prompt_type: str
stop_token_ids: list[int]
def build_ar_prompt_inputs(
user_prompt: str,
task: str = "t2i",
bot_task: str | None | _DefaultBotTask = _DEFAULT_BOT_TASK,
sys_type: str | None = None,
custom_system_prompt: str | None = None,
num_images: int = 1,
tokenizer: Any | None = None,
image_size: str | None = None,
) -> ARPromptInputs:
"""Build the complete AR-stage inputs for a HunyuanImage3 request.
Wraps :func:`build_prompt_tokens` (byte-for-byte HF parity when
``tokenizer`` is given), the :func:`build_prompt` string fallback (when
no tokenizer is available), and :func:`resolve_stop_token_ids` behind
one call, so a caller doesn't have to re-derive the AR prefill/stop-token
logic -- and, critically, doesn't have to independently resolve
``bot_task`` for the prompt-building call vs. the stop-token call, which
can silently diverge if a caller passes the same nominal ``bot_task``
value to both but resolves "omitted" vs. "explicit None" differently for
each (this seam always forwards the identical resolved value to both).
Used by all four offline shared task examples: ``text_to_image.py`` /
``image_edit.py`` (via ``model_extras.hunyuan_image3.build_ar_stage_inputs``)
and ``x_to_text.py`` (via ``build_x_to_text_prompt``, which also calls
``build_ar_stage_inputs``). The OpenAI server's ``serving_chat.py`` does
not currently call this seam -- it still independently calls
``build_prompt``/``build_prompt_tokens``/``resolve_stop_token_ids``, and
can hit exactly the divergence described above when ``bot_task`` is
omitted from ``extra_body`` (pre-existing, unrelated to this module).
``image_size`` follows the same convention as :func:`resolve_stop_token_ids`
(``None``/``"auto"`` lets the AR predict the aspect ratio; an explicit
``"{w}x{h}"`` makes it stop at the terminator).
"""
if tokenizer is not None:
result = build_prompt_tokens(
user_prompt,
tokenizer,
task=task,
bot_task=bot_task,
sys_type=sys_type,
custom_system_prompt=custom_system_prompt,
num_images=num_images,
)
prompt_str: str | None = None
prompt_token_ids: list[int] | None = result.token_ids
system_prompt_type = result.system_prompt_type
else:
prompt_str = build_prompt(
user_prompt,
task=task,
bot_task=bot_task,
sys_type=sys_type,
custom_system_prompt=custom_system_prompt,
num_images=num_images,
)
prompt_token_ids = None
_, resolved_bot_task = _normalize_task_and_bot_task(task, bot_task)
system_prompt_type = sys_type or resolve_sys_type(resolved_bot_task)
stop_token_ids = resolve_stop_token_ids(
task=task,
bot_task=bot_task,
tokenizer=tokenizer,
image_size=image_size,
)
return ARPromptInputs(
prompt=prompt_str,
prompt_token_ids=prompt_token_ids,
system_prompt_type=system_prompt_type,
stop_token_ids=stop_token_ids,
)
__all__ = [
"HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS",
"validate_special_token_ids",
"MAX_IMAGES_PER_REQUEST",
"_TASK_PRESETS",
"ARPromptInputs",
"available_bot_tasks",
"available_tasks",
"build_ar_prompt_inputs",
"build_prompt",
"build_prompt_tokens",
"resolve_stop_token_ids",
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
@@ -373,7 +373,32 @@ def build_hunyuan_diffusion_kv_requests(
real_pos = tokenizer_output.real_pos
assert prefix_positions is not None and real_pos is not None
def boundary_rows(field_name: str) -> list[int | None]:
positions = getattr(tokenizer_output, field_name)
if positions is None:
return [None] * cfg_factor
if not isinstance(positions, list) or not positions:
raise ValueError(f"Hunyuan {field_name} must be a non-empty boundary list")
# Batched tokenizer output contains a separate boundary for each CFG
# row. Never broadcast a conditional boundary into a negative row.
if cfg_factor == 1 and len(positions) == 1 and (positions[0] is None or type(positions[0]) is int):
return positions
if len(positions) == cfg_factor and all(
isinstance(row, list) and len(row) == 1 and (row[0] is None or type(row[0]) is int) for row in positions
):
return [row[0] for row in positions]
raise ValueError(f"Hunyuan {field_name} must contain one boundary per CFG row")
think_boundaries = boundary_rows("think_recaption_end_pos")
uncond_boundaries = boundary_rows("uncond_cfg_start_pos")
target_len = hunyuan_num_image_tokens(prepared_layout.generated_image_info)
reusable_lens = [0] * cfg_factor
if think_boundaries[0] is not None:
reusable_lens[0] = think_boundaries[0] or 0
if any(boundary is not None for boundary in uncond_boundaries):
for sequence_id in range(1, cfg_factor):
reusable_lens[sequence_id] = min(reusable_lens[0], uncond_boundaries[sequence_id] or 0)
return tuple(
DiffusionKVRequest(
f"{request.request_id}/diffusion-kv/{sequence_id}",
@@ -383,6 +408,7 @@ def build_hunyuan_diffusion_kv_requests(
prefix_len=int(prefix_row[-1].item()),
target_len=target_len,
seq_len=int(valid_row[-1].item()),
prompt_token_ids=tokenizer_output.tokens[sequence_id, : reusable_lens[sequence_id]].tolist(),
# Prompt and reference-image tokens are already embedded in this
# row's primary self-attention sequence. Hunyuan therefore has no
# independently projected cross/joint-attention KV context.
@@ -401,3 +427,14 @@ def get_hunyuan_prepared_layout(source: Any) -> HunyuanPreparedLayout | None:
f"HunyuanImage3 expected prepared_layout to be HunyuanPreparedLayout, got {type(prepared_layout).__name__}"
)
return prepared_layout
def native_kv_covers_cond_images(output: TokenizerEncodeOutput, computed_tokens: tuple[int, ...]) -> bool:
"""Skip image encoding only when every CFG row already contains its image KV."""
image_slices = output.joint_image_slices
if not image_slices or len(image_slices) != len(computed_tokens):
return False
return all(
slices and all(image_slice.stop <= computed for image_slice in slices)
for slices, computed in zip(image_slices, computed_tokens, strict=True)
)
+9 -2
View File
@@ -92,6 +92,13 @@ class SupportsStepExecution(Protocol):
``prepare_encode()`` (one-time request setup), ``denoise_step()``
(one denoise forward), ``step_scheduler()`` (one scheduler update),
and ``post_decode()`` (final decode).
A pipeline may additionally set the optional class attribute
``supports_chunk_step_grouping = True`` to declare that its request state
may advance through every denoise step of its current chunk without a
serving-scheduler cycle in between (a capability, not a policy: the runner
that owns the scheduling decision chooses whether to group steps). It is
optional so it does not become part of the runtime protocol check.
"""
supports_step_execution: ClassVar[bool] = True
@@ -151,10 +158,10 @@ class SupportsInteractionApply(Protocol):
"""Optional protocol for pipelines with unified mid-generation, chunk-boundary hooks."""
def peek_chunk_media(self, state: StepRequestState) -> ChunkMediaSpec:
"""Return the media timeline represented by the upcoming/current chunk.
"""Return the media timeline and latent frame count for the upcoming/current chunk.
Useful when interaction handler needs interpolation/integration on a frame-by-frame basis,
or for backpressure/pacing.
and/or for backpressure/pacing.
"""
...
@@ -62,6 +62,7 @@ from vllm_omni.diffusion.models.bagel.pipeline_bagel import (
from vllm_omni.model_executor.model_loader.weight_utils import (
download_weights_from_hf_specific,
)
from vllm_omni.model_executor.models.utils import normalize_decoded_video_frames
from .lance_transformer import (
LanceBagel,
@@ -1454,6 +1455,8 @@ class LancePipeline(BagelPipeline):
frames_bgr.append(_cv2.cvtColor(f, _cv2.COLOR_BGR2RGB))
cap.release()
video_raw = _np.stack(frames_bgr, axis=0)
elif isinstance(video_input, (list, tuple)):
video_raw, origin_fps = normalize_decoded_video_frames(video_input, default_fps=origin_fps_default)
elif isinstance(video_input, _np.ndarray):
video_raw = video_input
origin_fps = origin_fps_default
@@ -25,6 +25,7 @@ from vllm_omni.experimental.ar_diffusion.tick_protocol import (
LINGBOT_CAMERA_ACTION_SCHEMA = "lingbot.camera_actions.v1"
LINGBOT_CAMERA_TRAJECTORY_SCHEMA = "lingbot.camera_trajectory.v1"
LINGBOT_CONTROLLER_TRANSLATION_UNIT = 0.05
_ACTION_ORDER = ("w", "a", "s", "d", "i", "j", "k", "l")
_VALID_ACTIONS = frozenset(_ACTION_ORDER)
_REFERENCE_HEIGHT = 480
@@ -282,7 +283,7 @@ def integrate_lingbot_camera_actions(
"""Convert latent-frame WASD/IJKL controls to cumulative C2W poses.
Calibration and motion constants intentionally match SGLang's LingBot
adapter: movement 0.05, pitch 4 degrees, yaw 6 degrees, pitch clamp 85
adapter: movement 0.05 (LINGBOT_CONTROLLER_TRANSLATION_UNIT), pitch 4 degrees, yaw 6 degrees, pitch clamp 85
degrees, and target-resolution focal lengths of 500 pixels.
"""
@@ -325,13 +326,31 @@ def integrate_lingbot_camera_actions(
right /= right_norm + 1e-6
movement = np.zeros(3, dtype=np.float64)
movement += forward * 0.05 * (("w" in actions) - ("s" in actions))
movement += right * 0.05 * (("d" in actions) - ("a" in actions))
movement += forward * LINGBOT_CONTROLLER_TRANSLATION_UNIT * (("w" in actions) - ("s" in actions))
movement += right * LINGBOT_CONTROLLER_TRANSLATION_UNIT * (("d" in actions) - ("a" in actions))
# Keep the cumulative controller pose in FP64 between chunks, matching
# SGLang's NumPy integration and avoiding long-session drift.
current_pose = np.eye(4, dtype=np.float64)
current_pose[:3, :3] = new_rotation
current_pose[:3, 3] = translation + movement
poses.append(current_pose)
trajectory = camera_trajectory_from_absolute_pose(torch.from_numpy(np.stack(poses)), width=width, height=height)
return trajectory, current_pitch
def camera_trajectory_from_absolute_pose(
poses: torch.Tensor,
*,
width: int,
height: int,
) -> CameraTrajectory:
if width <= 0 or height <= 0:
raise ValueError("camera action resolution must be positive.")
if poses.ndim != 3 or poses.shape[-2:] != (4, 4):
raise ValueError(f"absolute camera poses must have shape [frames, 4, 4], got {tuple(poses.shape)}.")
if poses.shape[0] == 0:
raise ValueError("absolute camera poses must not be empty.")
# build_plucker_embedding expects intrinsics in the 832x480 reference
# coordinate system. These values become SGLang's [500, 500, W/2, H/2]
# after that function scales them to the requested resolution.
@@ -342,9 +361,7 @@ def integrate_lingbot_camera_actions(
_REFERENCE_HEIGHT / 2,
)
trajectory = CameraTrajectory(
# Keep the cumulative controller pose in FP64 between chunks, matching
# SGLang's NumPy integration and avoiding long-session drift.
poses=torch.from_numpy(np.stack(poses)),
poses=poses,
intrinsics=torch.tensor(reference_intrinsics, dtype=torch.float32).repeat(len(poses), 1),
)
return trajectory, current_pitch
return trajectory
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Camera trajectory loading and geometry for LingBot World v2 conditioning."""
from __future__ import annotations
@@ -19,7 +19,6 @@ import torch
_REFERENCE_HEIGHT = 480
_REFERENCE_WIDTH = 832
_MAX_ACTION_FRAMES = 117
_MAX_SOURCE_ACTION_FRAMES = 4096
_MAX_NPY_HEADER_BYTES = 10_000
_DIRECTORY_OPEN_FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
@@ -207,9 +206,7 @@ def _load_bounded_npy(
array = np.load(snapshot_file, allow_pickle=False)
except (EOFError, TypeError, ValueError):
raise ValueError(f"{filename} does not contain a valid numeric NPY array.") from None
# Official LingBot trajectories may be longer than one request. Only
# materialize the bounded prefix that any supported request can consume.
result: np.ndarray = np.asarray(array[:_MAX_ACTION_FRAMES], dtype=np.float32)
result: np.ndarray = np.asarray(array, dtype=np.float32)
return result
@@ -392,7 +389,11 @@ def _invert_camera_poses(poses: torch.Tensor) -> torch.Tensor:
return inverse
def _prepare_framewise_poses(raw_poses: torch.Tensor) -> torch.Tensor:
def _prepare_framewise_poses(
raw_poses: torch.Tensor,
*,
translation_scale: float | None = None,
) -> torch.Tensor:
"""Convert raw C2W poses to normalized first-relative framewise deltas."""
# Remove global placement, then convert the sequence to framewise deltas.
@@ -405,12 +406,19 @@ def _prepare_framewise_poses(raw_poses: torch.Tensor) -> torch.Tensor:
relative_poses[1:],
)
# Only relative direction/magnitude matters to the checkpoint; normalizing
# by the largest step removes the trajectory's arbitrary translation scale.
# Normalizing the control's scale. Different between scripted and realtime input.
translations = relative_poses[:, :3, 3]
max_translation_norm = torch.linalg.vector_norm(translations, dim=-1).max()
if max_translation_norm > 0:
relative_poses[:, :3, 3] = translations / max_translation_norm
if translation_scale is None:
# Scripted action_path input: divide by the largest step so an arbitrary recording scale becomes 1.
scale = torch.linalg.vector_norm(translations, dim=-1).max()
else:
# Realtime interaction input: use the controller translation unit (one WASD step = full speed).
# It cannot see future motion or normalize globally.
if translation_scale <= 0:
raise ValueError(f"translation_scale must be > 0, got {translation_scale}")
scale = translation_scale
if float(scale) > 0:
relative_poses[:, :3, 3] = translations / scale
return relative_poses
@@ -423,6 +431,7 @@ def build_plucker_embedding(
target_width: int,
device: torch.device,
dtype: torch.dtype,
translation_scale: float | None = None,
) -> torch.Tensor:
"""Build checkpoint-ordered ``(ray origin, ray direction)`` channels."""
@@ -441,7 +450,10 @@ def build_plucker_embedding(
# Compute geometry in at least FP32, then cast at the model boundary.
compute_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
poses = _prepare_framewise_poses(trajectory.poses.to(device=device, dtype=compute_dtype))
poses = _prepare_framewise_poses(
trajectory.poses.to(device=device, dtype=compute_dtype),
translation_scale=translation_scale,
)
intrinsics = trajectory.intrinsics.to(device=device, dtype=compute_dtype).clone()
intrinsics[:, (0, 2)] *= width / _REFERENCE_WIDTH
intrinsics[:, (1, 3)] *= height / _REFERENCE_HEIGHT
@@ -22,6 +22,7 @@ from diffusers.utils.torch_utils import randn_tensor
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
from vllm_omni.diffusion.models.lingbot_world.transformer import (
CameraModulationCache,
LingBotAttentionCache,
LingBotTransformerCache,
)
@@ -109,11 +110,16 @@ class LingBotDMDBlockRunner:
start_frame: int,
timestep_value: float,
step_index: int,
camera_cache: CameraModulationCache | None = None,
) -> torch.Tensor:
"""Predict flow for one denoise step.
A probe never writes KV: only the clean x0 of a finished block may
enter the cache, which is ``commit_block_kv``'s job.
``camera_cache`` is the block's camera-modulation cache when the caller
holds it across separate calls (the stepwise path); ``generate_block``
opens the window itself instead.
"""
if not self.enforce_eager:
torch.compiler.cudagraph_mark_step_begin()
@@ -130,6 +136,7 @@ class LingBotDMDBlockRunner:
cache=self._block_cache(condition=condition, cache=cache, ar=ar, commit_current=False),
start_frame=start_frame,
update_cache=False,
camera_modulation_cache=camera_cache,
)
if flow_prediction.shape != current_latents.shape:
raise RuntimeError(
@@ -172,11 +179,13 @@ class LingBotDMDBlockRunner:
cache: LingBotTransformerCache | None,
ar: ARBlockContext | None,
start_frame: int,
camera_cache: CameraModulationCache | None = None,
) -> None:
"""Write the finished block's clean x0 into KV and commit its pages.
The fifth transformer call of a block, deliberately not a denoise step:
on the stepwise path it belongs to ``post_decode()``.
on the stepwise path it belongs to ``post_decode()``. ``camera_cache``
is as in ``probe_step``.
"""
# Commit K/V only for the final clean block, never for noisy probes.
cache_input = torch.cat((latents.to(dtype=condition.dtype), condition), dim=1)
@@ -190,6 +199,7 @@ class LingBotDMDBlockRunner:
cache=self._block_cache(condition=condition, cache=cache, ar=ar, commit_current=True),
start_frame=start_frame,
update_cache=True,
camera_modulation_cache=camera_cache,
)
if ar is not None:
ar.state.commit_paged_context(ar.branch)
@@ -210,6 +220,10 @@ class LingBotDMDBlockRunner:
"""Request mode: all probes of one block, then its commit."""
block_shape = (1, self.transformer.config.out_channels, *condition.shape[2:5])
current_latents = randn_tensor(block_shape, generator=generator, device=self.device, dtype=torch.float32)
# Every forward below -- each probe and the commit -- reads the same camera trajectory, so the camera
# injector is built once per block: one cache for the whole loop, exactly as the stepwise path holds
# one per block across its separate calls.
camera_cache = CameraModulationCache()
for step_index, (timestep_value, sigma) in enumerate(schedule):
flow_prediction = self.probe_step(
current_latents=current_latents,
@@ -221,6 +235,7 @@ class LingBotDMDBlockRunner:
start_frame=start_frame,
timestep_value=timestep_value,
step_index=step_index,
camera_cache=camera_cache,
)
next_sigma = schedule[step_index + 1][1] if step_index + 1 < len(schedule) else None
current_latents = self.apply_transition(
@@ -235,5 +250,6 @@ class LingBotDMDBlockRunner:
cache=cache,
ar=ar,
start_frame=start_frame,
camera_cache=camera_cache,
)
return current_latents
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Checkpoint-compatible causal DiT for the LingBot World v2 model package."""
from __future__ import annotations
@@ -24,6 +24,9 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.utils import set_weight_attrs
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.distributed.comm import SeqAllToAll4D, all_to_all_5D
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelInput, SequenceParallelOutput
from vllm_omni.diffusion.layers.norm import LayerNorm
from vllm_omni.diffusion.layers.rope import RotaryEmbeddingWan
from vllm_omni.experimental.ar_diffusion.kv_cache.paged_attention import (
@@ -127,6 +130,37 @@ def _projection_prefix(prefix: str, name: str) -> str:
return f"{prefix}.{name}" if prefix else name
def _ulysses_state() -> tuple[int, int, torch.distributed.ProcessGroup | None]:
coordinator = get_sp_group()
return (
int(coordinator.ulysses_world_size),
int(coordinator.ulysses_rank),
coordinator.ulysses_group,
)
class _LingBotSPPrepare(nn.Module):
"""Expand frame conditioning only when Ulysses shards the token sequence."""
def forward(
self,
hidden_states: torch.Tensor,
camera_hidden_states: torch.Tensor,
timestep_projection: torch.Tensor,
rotary_emb: tuple[torch.Tensor, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
num_frames = timestep_projection.shape[1]
if hidden_states.shape[1] % num_frames:
raise ValueError("LingBot token count must be divisible by the latent frame count.")
tokens_per_frame = hidden_states.shape[1] // num_frames
if get_sp_group().ulysses_world_size > 1:
timestep_projection = (
timestep_projection.unsqueeze(2).expand(-1, -1, tokens_per_frame, -1, -1).flatten(1, 2)
)
cosine, sine = rotary_emb
return hidden_states, camera_hidden_states, timestep_projection, cosine, sine
class LingBotSelfAttention(nn.Module):
"""Block-causal self-attention over retained history and one full chunk."""
@@ -157,6 +191,13 @@ class LingBotSelfAttention(nn.Module):
prefix=_projection_prefix(prefix, "qkv"),
)
self.num_local_heads = self.qkv.num_heads
self.ulysses_world_size, self.ulysses_rank, self.ulysses_group = _ulysses_state()
if self.num_local_heads % self.ulysses_world_size:
raise ValueError(
"LingBot local attention heads must be divisible by the Ulysses degree: "
f"heads={self.num_local_heads}, ulysses={self.ulysses_world_size}."
)
self.num_sp_heads = self.num_local_heads // self.ulysses_world_size
self.tp_inner_dim = self.num_local_heads * self.head_dim
self.o = RowParallelLinear(
dim,
@@ -170,9 +211,9 @@ class LingBotSelfAttention(nn.Module):
self.norm_k = _LingBotRMSNorm(self.tp_inner_dim, eps)
self.rotary_embedding = RotaryEmbeddingWan(is_neox_style=False, half_head_dim=True)
self.attn = Attention(
num_heads=self.num_local_heads,
num_heads=self.num_sp_heads,
head_size=self.head_dim,
num_kv_heads=self.num_local_heads,
num_kv_heads=self.num_sp_heads,
softmax_scale=self.head_dim**-0.5,
causal=False,
role="self",
@@ -287,6 +328,20 @@ class LingBotSelfAttention(nn.Module):
query = self.rotary_embedding(query, cos, sin)
key = self.rotary_embedding(key, cos, sin)
if self.ulysses_world_size > 1:
# One fused sequence->head all-to-all for q/k/v instead of three:
# (B, S/N, 3, H, D) -> (B, S, 3, H/N, D). Same head-group assignment
# as the per-tensor 4D exchange (rank r receives head group r), so
# the result is a pure permutation of the three-call version, with a
# 3x larger message and one third of the latency-bound collectives.
qkv = all_to_all_5D(
torch.stack((query, key, value), dim=2),
scatter_idx=3,
gather_idx=1,
group=self.ulysses_group,
)
query, key, value = qkv.unbind(2)
if isinstance(cache, ARDiffusionPagedLayerInputs):
if query.shape[0] != 1:
raise RuntimeError("LingBot AR-Diffusion paged attention requires batch_size=1.")
@@ -347,6 +402,8 @@ class LingBotSelfAttention(nn.Module):
)
else:
output = self.attn(query, visible_key, visible_value)
if self.ulysses_world_size > 1:
output = SeqAllToAll4D.apply(self.ulysses_group, output, 1, 2, False)
return self.o(output.flatten(2, 3))
@@ -373,6 +430,11 @@ class LingBotCrossAttention(nn.Module):
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.num_local_heads = num_heads // tp_size
# Cross-attention keeps every local head on every Ulysses rank and attends the rank's own sequence
# shard. Each query token attends the whole text sequence independently of the others, so there is
# nothing to exchange: the sequence split Ulysses already gives us is the only split needed, and both
# all-to-all collectives -- one for the query, one for the output -- disappear. The cost is that the text K/V is
# replicated per rank instead of head-sharded; ar_diffusion_kv_cache_spec sizes the pool for it.
self.tp_inner_dim = self.num_local_heads * self.head_dim
self.q = ColumnParallelLinear(
@@ -525,6 +587,16 @@ class LingBotAttentionBlock(nn.Module):
self.cam_scale_layer = nn.Linear(dim, dim)
self.cam_shift_layer = nn.Linear(dim, dim)
def camera_modulation(self, camera_hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""Build this block's camera scale and shift from the patchified camera tokens.
Depends only on ``camera_hidden_states``, so a caller holding the camera trajectory fixed -- every
denoise forward of one AR chunk does -- can build this once and pass it back through ``forward``.
"""
camera_features = self.cam_injector_layer2(F.silu(self.cam_injector_layer1(camera_hidden_states)))
camera_features = camera_features + camera_hidden_states
return self.cam_scale_layer(camera_features), self.cam_shift_layer(camera_features)
def forward(
self,
hidden_states: torch.Tensor,
@@ -538,9 +610,21 @@ class LingBotAttentionBlock(nn.Module):
sink_tokens: int,
update_cache: bool,
rotary_emb: tuple[torch.Tensor, torch.Tensor],
camera_modulation: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> tuple[torch.Tensor, LingBotAttentionCache]:
batch_size, token_count, dim = hidden_states.shape
if (
timestep_projection.ndim != 4
or timestep_projection.shape[0] != batch_size
or timestep_projection.shape[2:] != (6, dim)
):
raise ValueError("LingBot timestep projection must have shape (batch, frames or tokens, 6, dim).")
num_frames = timestep_projection.shape[1]
if num_frames == 0 or token_count % num_frames:
raise ValueError("LingBot timestep projection must align with hidden tokens.")
if self.self_attn.ulysses_world_size > 1 and num_frames != token_count:
raise ValueError("LingBot Ulysses requires one timestep projection per local token.")
# Without SP, broadcast per frame. With SP, each entry represents one token.
tokens_per_frame = token_count // num_frames
# Timestep, camera, and text remain separate conditioning paths.
modulation = self.modulation.unsqueeze(1) + timestep_projection.float()
@@ -560,10 +644,9 @@ class LingBotAttentionBlock(nn.Module):
hidden_grid = hidden_grid + attention_output.unflatten(1, (num_frames, tokens_per_frame)) * gate_msa
hidden_states = hidden_grid.flatten(1, 2).to(hidden_states.dtype)
camera_features = self.cam_injector_layer2(F.silu(self.cam_injector_layer1(camera_hidden_states)))
camera_features = camera_features + camera_hidden_states
camera_scale = self.cam_scale_layer(camera_features)
camera_shift = self.cam_shift_layer(camera_features)
camera_scale, camera_shift = (
self.camera_modulation(camera_hidden_states) if camera_modulation is None else camera_modulation
)
hidden_states = ((1 + camera_scale) * hidden_states + camera_shift).to(hidden_states.dtype)
attention_output, cross_cache = self.cross_attn(
@@ -635,13 +718,26 @@ class _LingBotHead(nn.Module):
self,
hidden_states: torch.Tensor,
timestep_embedding: torch.Tensor,
*,
tokens_per_frame: int | None = None,
token_offset: int = 0,
) -> torch.Tensor:
num_frames = timestep_embedding.shape[1]
tokens_per_frame = hidden_states.shape[1] // num_frames
modulation = self.modulation.unsqueeze(1) + timestep_embedding.unsqueeze(2).float()
shift, scale = modulation.chunk(2, dim=2)
normalized = self.norm(hidden_states.float()).unflatten(1, (num_frames, tokens_per_frame))
normalized = (normalized * (1 + scale) + shift).flatten(1, 2).to(hidden_states.dtype)
normalized = self.norm(hidden_states.float())
if tokens_per_frame is None:
normalized = normalized.unflatten(1, (num_frames, -1))
normalized = (normalized * (1 + scale) + shift).flatten(1, 2)
else:
# A sequence shard can begin/end inside a frame.
frames = (
torch.arange(hidden_states.shape[1], device=hidden_states.device) + token_offset
) // tokens_per_frame
scale = scale.squeeze(2).index_select(1, frames)
shift = shift.squeeze(2).index_select(1, frames)
normalized = normalized * (1 + scale) + shift
normalized = normalized.to(hidden_states.dtype)
return self.head(normalized)
@@ -658,7 +754,7 @@ def _sinusoidal_embedding(dim: int, timestep: torch.Tensor) -> torch.Tensor:
return torch.cat((phase.cos(), phase.sin()), dim=1)
def _rope_axis(max_seq_len: int, dim: int) -> tuple[torch.Tensor, torch.Tensor]:
def _rope_axis(max_seq_len: int, dim: int, *, start: int = 0) -> tuple[torch.Tensor, torch.Tensor]:
if dim == 0:
empty = torch.empty(max_seq_len, 0, dtype=torch.float32)
return empty, empty.clone()
@@ -668,16 +764,42 @@ def _rope_axis(max_seq_len: int, dim: int) -> tuple[torch.Tensor, torch.Tensor]:
10000,
torch.arange(0, dim, 2, dtype=torch.float64) / dim,
)
phase = torch.outer(torch.arange(max_seq_len, dtype=torch.float64), frequencies)
phase = torch.outer(torch.arange(start, start + max_seq_len, dtype=torch.float64), frequencies)
return phase.cos().float(), phase.sin().float()
class CameraModulationCache:
"""Per-block camera scale and shift, held by the caller across the forwards of one AR block.
The camera injector is four projections and a SiLU per block and reads only the camera tokens, which do
not change between the denoise steps and the clean commit of one block. The caller that owns that
invariant creates one of these per block and passes it to every forward of the block; ``forward`` fills a
block's entry on first use and reads it after. Its lifetime is the caller's: the AR runner keeps one per
block, ``generate_block`` one per loop, and nothing here checks the camera tensor for change.
"""
__slots__ = ("entries",)
def __init__(self) -> None:
self.entries: dict[int, tuple[torch.Tensor, torch.Tensor]] = {}
class CausalLingBotWorldTransformer3DModel(nn.Module):
"""Checkpoint-compatible causal LingBot World video transformer."""
_repeated_blocks = ["LingBotAttentionBlock"]
packed_modules_mapping = {"qkv": ["q", "k", "v"]}
_layerwise_offload_blocks_attrs = ["blocks"]
_sp_plan = {
"sp_prepare": {
0: SequenceParallelInput(split_dim=1, expected_dims=3, split_output=True),
1: SequenceParallelInput(split_dim=1, expected_dims=3, split_output=True),
2: SequenceParallelInput(split_dim=1, expected_dims=4, split_output=True),
3: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True),
4: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True),
},
"sp_output_gather": SequenceParallelOutput(gather_dim=1, expected_dims=3),
}
def __init__(
self,
@@ -768,6 +890,8 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
stride=patch_size,
)
self.patch_embedding_wancamctrl = _LingBotCameraPatchEmbedding(6 * 8 * 8, dim, patch_size)
self.sp_prepare = _LingBotSPPrepare()
self.sp_output_gather = nn.Identity()
self.c2ws_hidden_states_layer1 = ColumnParallelLinear(
dim,
dim,
@@ -819,6 +943,27 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
cosine, sine = _rope_axis(rope_max_seq_len, axis_dim)
self.register_buffer(f"_rope_{axis}_cosine", cosine, persistent=False)
self.register_buffer(f"_rope_{axis}_sine", sine, persistent=False)
# One static-address buffer per shape for the per-token timestep
# projection; see _stage_timestep_projection.
self._timestep_projection_buffers: dict[tuple[tuple[int, ...], torch.dtype, torch.device], torch.Tensor] = {}
def _stage_timestep_projection(self, projection: torch.Tensor) -> torch.Tensor:
"""Hand the blocks the timestep projection from a buffer whose address never changes.
Every regional block graph takes the projection as an input. Under CUDA-graph replay an input that
arrives in a fresh tensor each forward is copied into the graph's placeholder on every replay: at
480x832 with four Ulysses ranks that is a 72 MB copy per block, forty times per forward, two hundred
times per AR chunk. Copying the projection once per forward into a buffer marked static lets every
replay read it in place. The values the blocks see are the same; only where they live changes.
"""
key = (tuple(projection.shape), projection.dtype, projection.device)
buffer = self._timestep_projection_buffers.get(key)
if buffer is None:
buffer = torch.empty(projection.shape, dtype=projection.dtype, device=projection.device)
torch._dynamo.mark_static_address(buffer)
self._timestep_projection_buffers[key] = buffer
buffer.copy_(projection)
return buffer
@property
def dtype(self) -> torch.dtype:
@@ -904,8 +1049,7 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
self.config.local_attn_size if self.config.local_attn_size != -1 else self.config.sliding_window_num_frames
)
max_tokens = int(window_frames * post_patch_height * post_patch_width)
tp_size = get_tensor_model_parallel_world_size()
num_local_heads = self.config.num_attention_heads // tp_size
num_local_heads = self.blocks[0].self_attn.num_sp_heads
return allocate_lingbot_cache(
batch_size=batch_size,
num_layers=self.config.num_layers,
@@ -926,23 +1070,29 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
dtype: torch.dtype,
device: torch.device,
) -> tuple[torch.Tensor, torch.Tensor]:
if start_frame + frames > self.config.rope_max_seq_len:
raise ValueError("Temporal RoPE positions exceed rope_max_seq_len.")
if height > self.config.rope_max_seq_len or width > self.config.rope_max_seq_len:
raise ValueError("Spatial RoPE positions exceed rope_max_seq_len.")
if start_frame + frames <= self._rope_temporal_cosine.shape[0]:
temporal_cosine = self._rope_temporal_cosine[start_frame : start_frame + frames]
temporal_sine = self._rope_temporal_sine[start_frame : start_frame + frames]
else:
# Keep absolute positions and checkpoint frequencies, computing only
# this block instead of growing a table for the whole session.
temporal_dim = self._rope_temporal_cosine.shape[1] * 2
temporal_cosine, temporal_sine = _rope_axis(frames, temporal_dim, start=start_frame)
temporal_cosine = temporal_cosine.to(self._rope_temporal_cosine)
temporal_sine = temporal_sine.to(self._rope_temporal_sine)
def expand_axis(table: torch.Tensor, axis: str) -> torch.Tensor:
if axis == "temporal":
return (
table[start_frame : start_frame + frames].view(frames, 1, 1, -1).expand(frames, height, width, -1)
)
return table.view(frames, 1, 1, -1).expand(frames, height, width, -1)
if axis == "height":
return table[:height].view(1, height, 1, -1).expand(frames, height, width, -1)
return table[:width].view(1, 1, width, -1).expand(frames, height, width, -1)
cosine = torch.cat(
(
expand_axis(self._rope_temporal_cosine, "temporal"),
expand_axis(temporal_cosine, "temporal"),
expand_axis(self._rope_height_cosine, "height"),
expand_axis(self._rope_width_cosine, "width"),
),
@@ -950,7 +1100,7 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
)
sine = torch.cat(
(
expand_axis(self._rope_temporal_sine, "temporal"),
expand_axis(temporal_sine, "temporal"),
expand_axis(self._rope_height_sine, "height"),
expand_axis(self._rope_width_sine, "width"),
),
@@ -1070,6 +1220,7 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
cache: LingBotTransformerCache,
start_frame: int,
update_cache: bool,
camera_modulation_cache: CameraModulationCache | None = None,
) -> torch.Tensor:
if not isinstance(update_cache, bool):
raise ValueError("update_cache must be a boolean.")
@@ -1138,15 +1289,51 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
query_len=hidden_states.shape[1],
)
cache.self_attention = [layer_context.to_layer_inputs() for layer_context in cache.self_attention]
sp_size = self.blocks[0].self_attn.ulysses_world_size
global_tokens = patched_frames * tokens_per_frame
hidden_dim = hidden_states.shape[-1]
rope_dim = rotary_emb[0].shape[-1]
if global_tokens % sp_size:
raise ValueError("LingBot Ulysses requires the token count to be divisible by its degree.")
hidden_states, camera_hidden_states, timestep_projection, cosine, sine = self.sp_prepare(
hidden_states,
camera_hidden_states,
timestep_projection,
rotary_emb,
)
if sp_size > 1:
local_tokens = global_tokens // sp_size
expected_hidden = (batch_size, local_tokens, hidden_dim)
if (
hidden_states.shape != expected_hidden
or camera_hidden_states.shape != expected_hidden
or timestep_projection.shape != (batch_size, local_tokens, 6, hidden_dim)
or cosine.shape != (local_tokens, rope_dim)
or sine.shape != (local_tokens, rope_dim)
):
raise RuntimeError(
"LingBot SP input hooks did not shard all conditioning tensors consistently; "
f"expected {local_tokens} tokens per rank. Check SP hook registration and input dimensions."
)
timestep_projection = self._stage_timestep_projection(timestep_projection)
rotary_emb = (cosine, sine)
# Phase 3: each layer receives its own cache entry. Text K/V is passed
# only when absent; the returned cache is stored for subsequent DMD
# steps and causal blocks in this request.
# steps and causal blocks in this request. A caller-held camera cache
# gives every block its modulation once per AR block.
for index, block in enumerate(self.blocks):
camera_modulation = None
if camera_modulation_cache is not None:
camera_modulation = camera_modulation_cache.entries.get(index)
if camera_modulation is None:
camera_modulation = block.camera_modulation(camera_hidden_states)
camera_modulation_cache.entries[index] = camera_modulation
hidden_states, cross_cache = block(
hidden_states,
projected_text if cache.cross_attention[index] is None else None,
timestep_projection,
camera_hidden_states,
camera_modulation=camera_modulation,
self_cache=cache.self_attention[index],
cross_cache=cache.cross_attention[index],
current_start=current_start,
@@ -1156,9 +1343,17 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
)
cache.cross_attention[index] = cross_cache
# Phase 4: map tokens to per-patch 16-channel flow values and restore
# [B, C, F, H, W] for the Pipeline's sampler update.
hidden_states = self.head(hidden_states, timestep_embedding)
# Phase 4: project local tokens before gathering the much narrower flow values.
hidden_states = self.head(
hidden_states,
timestep_embedding,
tokens_per_frame=tokens_per_frame if sp_size > 1 else None,
token_offset=get_sp_group().ulysses_rank * (global_tokens // sp_size) if sp_size > 1 else 0,
)
hidden_states = self.sp_output_gather(hidden_states)
projected_dim = self.config.out_channels * math.prod(self.config.patch_size)
if sp_size > 1 and hidden_states.shape != (batch_size, global_tokens, projected_dim):
raise RuntimeError("LingBot SP output hook did not gather the full projected token sequence.")
return self._unpatchify(
hidden_states,
batch_size=batch_size,
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from collections import OrderedDict
from collections.abc import Iterable
from typing import Any
@@ -16,6 +17,8 @@ from vllm.model_executor.layers.activation import get_act_fn
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import ColumnParallelLinear, QKVParallelLinear, RowParallelLinear
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.platforms import current_platform
from vllm.triton_utils import HAS_TRITON
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.layer import Attention
@@ -26,10 +29,150 @@ from vllm_omni.diffusion.distributed.sp_plan import (
SequenceParallelOutput,
)
from vllm_omni.diffusion.forward_context import get_forward_context
from vllm_omni.diffusion.layers.fused_qk_norm_rope import fused_qk_norm_rope_min_tokens
from vllm_omni.diffusion.layers.fused_qk_rope import fused_qk_rope, fused_qk_rope_supported
from vllm_omni.platforms import current_omni_platform
logger = init_logger(__name__)
RotaryEmbedding = tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, int]
# All LongCat production attention spans contain at least 512 tokens. Reuse
# the shared Q/K fusion threshold override so deployments can retain a
# hardware-specific crossover without adding another environment variable.
_FUSED_MIN_TOKENS = 512
_FUSED_QK_ROPE = HAS_TRITON and current_platform.is_cuda()
_FAILED_QK_ROPE_SIGNATURES_MAX_SIZE = 128
_FAILED_QK_ROPE_SIGNATURES: OrderedDict[tuple[object, ...], None] = OrderedDict()
def _fusion_enabled(sequence_parallel_size: int | None, *, enforce_eager: bool) -> bool:
return (
_FUSED_QK_ROPE
and enforce_eager
and not torch.compiler.is_compiling()
and not torch.is_grad_enabled()
and not (sequence_parallel_size is not None and sequence_parallel_size > 1)
)
def _prepare_rotary_emb(
txt_cos: torch.Tensor,
txt_sin: torch.Tensor,
img_cos: torch.Tensor,
img_sin: torch.Tensor,
*,
enable_fusion: bool,
) -> RotaryEmbedding:
"""Join text/image tables and resolve the shared token gate once."""
joint = torch.cat((txt_cos, img_cos), dim=0), torch.cat((txt_sin, img_sin), dim=0)
if not enable_fusion:
return joint
return joint[0], joint[1], fused_qk_norm_rope_min_tokens(_FUSED_MIN_TOKENS)
def _apply_qk_rope_reference(
query: torch.Tensor,
key: torch.Tensor,
rotary_emb: tuple[torch.Tensor, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor]:
return (
apply_rotary_emb(query, rotary_emb, sequence_dim=1),
apply_rotary_emb(key, rotary_emb, sequence_dim=1),
)
def _qk_rope_signature(
query: torch.Tensor,
key: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
) -> tuple[object, ...]:
"""Identify a runtime layout for failure-cache fallback."""
return (
query.device.type,
query.device.index,
query.dtype,
tuple(query.shape),
tuple(query.stride()),
tuple(key.shape),
tuple(key.stride()),
cos.dtype,
tuple(cos.shape),
tuple(cos.stride()),
tuple(sin.stride()),
)
def _is_failed_qk_rope_signature(signature: tuple[object, ...]) -> bool:
if signature not in _FAILED_QK_ROPE_SIGNATURES:
return False
_FAILED_QK_ROPE_SIGNATURES.move_to_end(signature)
return True
def _record_failed_qk_rope_signature(signature: tuple[object, ...]) -> None:
_FAILED_QK_ROPE_SIGNATURES[signature] = None
_FAILED_QK_ROPE_SIGNATURES.move_to_end(signature)
while len(_FAILED_QK_ROPE_SIGNATURES) > _FAILED_QK_ROPE_SIGNATURES_MAX_SIZE:
_FAILED_QK_ROPE_SIGNATURES.popitem(last=False)
def _can_use_fused_qk_rope(
query: torch.Tensor,
key: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
sequence_parallel_size: int | None,
min_tokens: int | None,
) -> bool:
"""Keep compile, autograd, capture, SP, and unsupported inputs native."""
if (
torch.compiler.is_compiling()
or torch.is_grad_enabled()
or (sequence_parallel_size is not None and sequence_parallel_size > 1)
or min_tokens is None
or not fused_qk_rope_supported(query, key, cos, sin)
or torch.cuda.is_current_stream_capturing()
):
return False
return query.shape[0] * query.shape[1] >= min_tokens
def _apply_qk_rope(
query: torch.Tensor,
key: torch.Tensor,
rotary_emb: RotaryEmbedding | None,
sequence_parallel_size: int | None,
min_tokens: int | None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Apply one paired RoPE launch, falling back after launch failures."""
if rotary_emb is None:
return query, key
rotary_pair = rotary_emb[:2]
cos, sin = rotary_pair
if not _can_use_fused_qk_rope(query, key, cos, sin, sequence_parallel_size, min_tokens):
return _apply_qk_rope_reference(query, key, rotary_pair)
signature = _qk_rope_signature(query, key, cos, sin)
if _is_failed_qk_rope_signature(signature):
return _apply_qk_rope_reference(query, key, rotary_pair)
try:
return fused_qk_rope(query, key, cos, sin)
except Exception as exc: # noqa: BLE001 - optimized-path failures must fall back
_record_failed_qk_rope_signature(signature)
logger.warning(
"Disabling LongCat paired Q/K RoPE fusion for signature %s after failure: %s",
signature,
exc,
)
return _apply_qk_rope_reference(query, key, rotary_pair)
class FeedForward(nn.Module):
def __init__(self, dim: int, dim_out: int | None = None, mult: int = 4, bias: bool = True):
@@ -121,7 +264,7 @@ class LongCatImageAttention(nn.Module):
text_key: torch.Tensor,
text_value: torch.Tensor,
text_seq_len: int,
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None,
image_rotary_emb: RotaryEmbedding | None,
) -> torch.Tensor:
"""
Apply RoPE separately to text and image Q/K, then run SP attention with joint tensors.
@@ -139,7 +282,7 @@ class LongCatImageAttention(nn.Module):
Attention output with shape (B, txt_len + img_len/SP, H, D)
"""
if image_rotary_emb is not None:
freqs_cos, freqs_sin = image_rotary_emb
freqs_cos, freqs_sin = image_rotary_emb[:2]
txt_rotary_emb = (freqs_cos[:text_seq_len], freqs_sin[:text_seq_len])
img_rotary_emb_split = (freqs_cos[text_seq_len:], freqs_sin[text_seq_len:])
# Apply RoPE to image Q/K
@@ -165,7 +308,7 @@ class LongCatImageAttention(nn.Module):
self,
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor | None = None,
image_rotary_emb: torch.Tensor | None = None,
image_rotary_emb: RotaryEmbedding | None = None,
**kwargs,
) -> torch.Tensor:
"""
@@ -196,6 +339,8 @@ class LongCatImageAttention(nn.Module):
query = self.norm_q(query)
key = self.norm_k(key)
rotary_pair = image_rotary_emb[:2] if image_rotary_emb is not None else None
min_tokens = image_rotary_emb[2] if image_rotary_emb is not None and len(image_rotary_emb) > 2 else None
if self.added_kv_proj_dim is not None:
encoder_qkv, _ = self.add_kv_proj(encoder_hidden_states)
@@ -222,7 +367,7 @@ class LongCatImageAttention(nn.Module):
text_key=encoder_key,
text_value=encoder_value,
text_seq_len=encoder_query.shape[1],
image_rotary_emb=image_rotary_emb,
image_rotary_emb=rotary_pair,
)
else:
# Non-SP Mode: Concat first, then apply RoPE to full sequence
@@ -230,10 +375,15 @@ class LongCatImageAttention(nn.Module):
joint_key = torch.cat([encoder_key, key], dim=1)
joint_value = torch.cat([encoder_value, value], dim=1)
if image_rotary_emb is not None:
# Apply RoPE to full (text + image) sequence
joint_query = apply_rotary_emb(joint_query, image_rotary_emb, sequence_dim=1)
joint_key = apply_rotary_emb(joint_key, image_rotary_emb, sequence_dim=1)
# Keep the native RMSNorm and text-then-image concatenation
# order, then combine only the two independent RoPE calls.
joint_query, joint_key = _apply_qk_rope(
joint_query,
joint_key,
rotary_pair,
sp_size,
min_tokens,
)
hidden_states = self.attn(
joint_query,
@@ -272,13 +422,17 @@ class LongCatImageAttention(nn.Module):
text_key=key[:, :text_seq_len],
text_value=value[:, :text_seq_len],
text_seq_len=text_seq_len,
image_rotary_emb=image_rotary_emb,
image_rotary_emb=rotary_pair,
)
else:
# Non-SP Mode: standard path
if image_rotary_emb is not None:
query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1)
key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1)
query, key = _apply_qk_rope(
query,
key,
rotary_pair,
sp_size,
min_tokens,
)
hidden_states = self.attn(
query,
@@ -345,7 +499,7 @@ class LongCatImageTransformerBlock(nn.Module):
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor,
temb: torch.Tensor,
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
image_rotary_emb: RotaryEmbedding | None = None,
joint_attention_kwargs: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
@@ -536,7 +690,7 @@ class LongCatImageSingleTransformerBlock(nn.Module):
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor,
temb: torch.Tensor,
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
image_rotary_emb: RotaryEmbedding | None = None,
joint_attention_kwargs: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
@@ -632,6 +786,7 @@ class LongCatImageTransformer2DModel(nn.Module):
# Store parallel config for SP support
self.parallel_config = od_config.parallel_config
self.enforce_eager = bool(getattr(od_config, "enforce_eager", False))
self.pos_embed = LongCatImagePosEmbed(theta=10000, axes_dim=axes_dims_rope)
self.rope_preparer = RoPEPreparer(self.pos_embed)
@@ -701,11 +856,15 @@ class LongCatImageTransformer2DModel(nn.Module):
# txt_cos/txt_sin (outputs 0, 1) remain replicated for dual-stream attention
txt_cos, txt_sin, img_cos, img_sin = self.rope_preparer(txt_ids, img_ids)
# Reconstruct image_rotary_emb with chunked values
# Final shape: (txt_seq_len + img_seq_len // SP, head_dim)
image_rotary_emb = (
torch.cat([txt_cos, img_cos], dim=0),
torch.cat([txt_sin, img_sin], dim=0),
# Preserve the ordinary full-width tables. A third scalar only marks
# the eligible eager SP=1 route and resolves the shared threshold once
# for all attention blocks in this transformer call.
image_rotary_emb = _prepare_rotary_emb(
txt_cos,
txt_sin,
img_cos,
img_sin,
enable_fusion=_fusion_enabled(sp_size, enforce_eager=self.enforce_eager),
)
for block in self.transformer_blocks:
@@ -16,6 +16,7 @@ import os
from collections.abc import Iterable
from enum import IntEnum
from functools import partial
from typing import Any
import torch
import torch.nn as nn
@@ -28,6 +29,7 @@ from .configuration_magi2 import Magi2PreviewConfig
from .layers import (
ElementWiseFourierEmbed,
MHCHandler,
MHCTensorTuple,
ModalityDispatcher,
MultiModalityRMSNorm,
make_grouped_linear,
@@ -130,14 +132,12 @@ class Magi2Attention(nn.Module):
start = self.tp_group.rank * self.num_heads_q
return checkpoint_tensor[:, start : start + self.num_heads_q]
def forward(
def project(
self,
hidden_states: torch.Tensor,
rope: torch.Tensor,
varlen_handler: VarlenHandler,
modality_dispatcher: ModalityDispatcher,
cp_split_sizes: list[int] | torch.Tensor,
) -> torch.Tensor:
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
normalized = self.pre_norm(hidden_states, modality_dispatcher)
gates = self.linear_g(normalized, modality_dispatcher)
qkv = self.linear_qkv(normalized, modality_dispatcher)
@@ -159,8 +159,17 @@ class Magi2Attention(nn.Module):
q = apply_rotary_emb(q, cos, sin).squeeze(0).to(self.config.params_dtype)
k = apply_rotary_emb(k, cos, sin).squeeze(0).to(self.config.params_dtype)
v = v.squeeze(0).to(self.config.params_dtype)
return q, k, v, gates
output = self.packed_attention(
def attend(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
varlen_handler: VarlenHandler,
cp_split_sizes: list[int] | torch.Tensor,
) -> torch.Tensor:
return self.packed_attention(
q,
k,
v,
@@ -172,7 +181,14 @@ class Magi2Attention(nn.Module):
}
),
)
output = modality_dispatcher.permute(output)
def output(
self,
attention: torch.Tensor,
gates: torch.Tensor,
modality_dispatcher: ModalityDispatcher,
) -> torch.Tensor:
output = modality_dispatcher.permute(attention)
output = output * torch.sigmoid(gates)
output = output.reshape(-1, self.q_size).to(self.config.params_dtype)
return self.linear_proj(output, modality_dispatcher)
@@ -303,12 +319,21 @@ class Magi2MultiHeadMoELayer(nn.Module):
modality.contiguous(), dispatcher
)
def forward(self, hidden_states: torch.Tensor, dispatcher: ModalityDispatcher) -> torch.Tensor:
def route_input(
self,
hidden_states: torch.Tensor,
dispatcher: ModalityDispatcher,
) -> tuple[torch.Tensor, torch.Tensor]:
normalized = self.pre_norm(hidden_states, dispatcher)
routed = self.split_linear(normalized)
routed = self.moe_mlp(routed)
routed = self.merge_linear(routed)
return routed + self._shared_experts(normalized, dispatcher)
return normalized, self.split_linear(normalized)
def combine(
self,
normalized: torch.Tensor,
routed: torch.Tensor,
dispatcher: ModalityDispatcher,
) -> torch.Tensor:
return self.merge_linear(routed) + self._shared_experts(normalized, dispatcher)
class Magi2PreAdapter(nn.Module):
@@ -339,37 +364,28 @@ class Magi2PreAdapter(nn.Module):
def forward(
self,
packed: torch.Tensor,
coords_mapping: torch.Tensor,
video_indices: torch.Tensor,
audio_indices: torch.Tensor,
text_indices: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
rope = self.rope(coords_mapping)
output = torch.zeros(
) -> torch.Tensor:
# Every token belongs to exactly one modality, so the three copies
# below cover the whole buffer. Embedding in fp32 and rounding each
# modality once matches the released cast at the block boundary.
output = torch.empty(
packed.shape[0],
self.adapter_dim,
dtype=torch.float32,
dtype=self.config.params_dtype,
device=packed.device,
)
if text_indices.numel():
output.index_copy_(
0,
text_indices,
self.text_embedder(packed.index_select(0, text_indices)[:, : self.config.text_in_channels].float()),
)
if audio_indices.numel():
output.index_copy_(
0,
audio_indices,
self.audio_embedder(packed.index_select(0, audio_indices)[:, : self.config.audio_in_channels].float()),
)
if video_indices.numel():
output.index_copy_(
0,
video_indices,
self.video_embedder(packed.index_select(0, video_indices)[:, : self.config.video_in_channels].float()),
)
return output, rope
for indices, embedder, in_channels in (
(text_indices, self.text_embedder, self.config.text_in_channels),
(audio_indices, self.audio_embedder, self.config.audio_in_channels),
(video_indices, self.video_embedder, self.config.video_in_channels),
):
if indices.numel():
tokens = packed[:, :in_channels].index_select(0, indices).float()
output.index_copy_(0, indices, embedder(tokens).to(output.dtype))
return output
class Magi2PostAdapter(nn.Module):
@@ -425,8 +441,10 @@ class Magi2TransformerLayer(nn.Module):
self.mlp: nn.Module
if layer_index in config.moe.layers:
self.mlp = Magi2MultiHeadMoELayer(config)
self.region_methods = ("_attention_input", "_moe_input", "_moe_output")
else:
self.mlp = Magi2MLP(config, num_modality=num_modality)
self.region_methods = ("_attention_input", "_dense_output")
self._init_mhc(num_modality)
def _init_mhc(self, num_modality: int) -> None:
@@ -525,6 +543,74 @@ class Magi2TransformerLayer(nn.Module):
)
return self.mhc_handler.hyper_connect(streams, output, post, residual)
# The layer forward is split into compile regions around the two eager
# kernels: packed attention and the multi-head MoE.
def _attention_input(
self,
hidden_states: torch.Tensor,
rope: torch.Tensor,
modality_dispatcher: ModalityDispatcher,
) -> tuple[torch.Tensor, MHCTensorTuple, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
streams = hidden_states.reshape(hidden_states.shape[0], self.config.mhc.num_streams, self.config.hidden_size)
attention_logits = self._branch_logits(streams, "attn", modality_dispatcher)
attention_input = self._branch_input(streams, "attn", attention_logits)
q, k, v, gates = self.attention.project(attention_input, rope, modality_dispatcher)
return streams, attention_logits, q, k, v, gates
def _mlp_input(
self,
streams: torch.Tensor,
attention: torch.Tensor,
gates: torch.Tensor,
attention_logits: MHCTensorTuple,
modality_dispatcher: ModalityDispatcher,
) -> tuple[torch.Tensor, MHCTensorTuple, torch.Tensor]:
attention_output = self.attention.output(attention, gates, modality_dispatcher)
streams = self._connect(streams, attention_output, "attn", attention_logits)
mlp_logits = self._branch_logits(streams, "mlp", modality_dispatcher)
return streams, mlp_logits, self._branch_input(streams, "mlp", mlp_logits)
def _dense_output(
self,
streams: torch.Tensor,
attention: torch.Tensor,
gates: torch.Tensor,
attention_logits: MHCTensorTuple,
modality_dispatcher: ModalityDispatcher,
) -> torch.Tensor:
streams, mlp_logits, mlp_input = self._mlp_input(
streams, attention, gates, attention_logits, modality_dispatcher
)
streams = self._connect(streams, self.mlp(mlp_input, modality_dispatcher), "mlp", mlp_logits)
return streams.reshape(streams.shape[0], -1)
def _moe_input(
self,
streams: torch.Tensor,
attention: torch.Tensor,
gates: torch.Tensor,
attention_logits: MHCTensorTuple,
modality_dispatcher: ModalityDispatcher,
) -> tuple[torch.Tensor, MHCTensorTuple, torch.Tensor, torch.Tensor]:
streams, mlp_logits, mlp_input = self._mlp_input(
streams, attention, gates, attention_logits, modality_dispatcher
)
normalized, routed = self.mlp.route_input(mlp_input, modality_dispatcher)
return streams, mlp_logits, normalized, routed
def _moe_output(
self,
streams: torch.Tensor,
mlp_logits: MHCTensorTuple,
normalized: torch.Tensor,
routed: torch.Tensor,
modality_dispatcher: ModalityDispatcher,
) -> torch.Tensor:
mlp_output = self.mlp.combine(normalized, routed, modality_dispatcher)
streams = self._connect(streams, mlp_output, "mlp", mlp_logits)
return streams.reshape(streams.shape[0], -1)
def forward(
self,
hidden_states: torch.Tensor,
@@ -533,22 +619,15 @@ class Magi2TransformerLayer(nn.Module):
modality_dispatcher: ModalityDispatcher,
cp_split_sizes: list[int] | torch.Tensor,
) -> torch.Tensor:
streams = hidden_states.reshape(hidden_states.shape[0], self.config.mhc.num_streams, self.config.hidden_size)
attention_logits = self._branch_logits(streams, "attn", modality_dispatcher)
attention_input = self._branch_input(streams, "attn", attention_logits)
attention_output = self.attention(
attention_input,
rope,
varlen_handler,
modality_dispatcher,
cp_split_sizes,
streams, attention_logits, q, k, v, gates = self._attention_input(hidden_states, rope, modality_dispatcher)
attention = self.attention.attend(q, k, v, varlen_handler, cp_split_sizes)
if not isinstance(self.mlp, Magi2MultiHeadMoELayer):
return self._dense_output(streams, attention, gates, attention_logits, modality_dispatcher)
streams, mlp_logits, normalized, routed = self._moe_input(
streams, attention, gates, attention_logits, modality_dispatcher
)
streams = self._connect(streams, attention_output, "attn", attention_logits)
mlp_logits = self._branch_logits(streams, "mlp", modality_dispatcher)
mlp_input = self._branch_input(streams, "mlp", mlp_logits)
mlp_output = self.mlp(mlp_input, modality_dispatcher)
streams = self._connect(streams, mlp_output, "mlp", mlp_logits)
return streams.reshape(streams.shape[0], -1)
routed = self.mlp.moe_mlp(routed)
return self._moe_output(streams, mlp_logits, normalized, routed, modality_dispatcher)
class Magi2TransformerBlock(nn.Module):
@@ -570,7 +649,6 @@ class Magi2TransformerBlock(nn.Module):
modality_dispatcher: ModalityDispatcher,
cp_split_sizes: list[int] | torch.Tensor,
) -> torch.Tensor:
hidden_states = hidden_states.to(self.config.params_dtype)
hidden_states = modality_dispatcher.permute(hidden_states)
for layer in self.layers:
hidden_states = layer(
@@ -592,11 +670,9 @@ def _is_magi2_transformer_layer(_name: str, module: nn.Module) -> bool:
class Magi2PreviewTransformer(nn.Module):
"""Native preview DiT with the released checkpoint hierarchy."""
# ``block`` must remain the registered child name because it is part of the
# released checkpoint hierarchy. The ``layers`` property below exposes its
# ModuleList through the standard layerwise-offload contract without
# changing the registered module names.
_layerwise_offload_blocks_attrs = ["layers"]
# ``block`` is the registered child module containing the repeated
# layers, exposed as the streamable blocks container for layerwise offload.
_layerwise_offload_blocks_attrs = ["block"]
_hsdp_shard_conditions = [_is_magi2_transformer_layer]
_hsdp_preserve_parameter_dtypes = True
_EP_SHARDED_SUFFIXES = (
@@ -626,10 +702,19 @@ class Magi2PreviewTransformer(nn.Module):
@property
def layers(self) -> nn.ModuleList:
"""Expose Preview layers to the shared offload block discovery API."""
"""Expose Preview layers for direct access and compatibility."""
return self.block.layers
def compile_regions(self, **compile_kwargs: Any) -> None:
"""Compile the dense compute between the eager attention and MoE kernels."""
self.pre_adapter.forward = torch.compile(self.pre_adapter.forward, **compile_kwargs)
self.post_adapter.forward = torch.compile(self.post_adapter.forward, **compile_kwargs)
for layer in self.block.layers:
for name in layer.region_methods:
setattr(layer, name, torch.compile(getattr(layer, name), **compile_kwargs))
def forward(
self,
x: torch.Tensor,
@@ -647,6 +732,7 @@ class Magi2PreviewTransformer(nn.Module):
assert dispatcher.split_sizes is not None
cp_split_sizes = dispatcher.split_sizes
rope = self.pre_adapter.rope(coords_mapping)
time_mask = modality_mapping == int(Modality.TIME)
modality_mapping = torch.where(time_mask, int(Modality.TEXT), modality_mapping)
modality_dispatcher = ModalityDispatcher(modality_mapping, 3)
@@ -654,13 +740,7 @@ class Magi2PreviewTransformer(nn.Module):
audio_indices = torch.nonzero(modality_mapping == int(Modality.AUDIO)).flatten()
text_indices = torch.nonzero(modality_mapping == int(Modality.TEXT)).flatten()
hidden_states, rope = self.pre_adapter(
x,
coords_mapping,
video_indices,
audio_indices,
text_indices,
)
hidden_states = self.pre_adapter(x, video_indices, audio_indices, text_indices)
if time_token_sequence is not None and time_token_sequence.shape[-1] > 0:
hidden_states[:, : time_token_sequence.shape[-1]] = time_token_sequence.to(hidden_states.dtype)
hidden_states = self.block(
@@ -695,6 +695,24 @@ class Magi2Pipeline(
return self.video_decoder.module
def setup_compile(self) -> None:
"""Compile the transformer regions; the attention and MoE kernels stay eager."""
granularity = self.od_config.diffusion_compile_granularity
if granularity != "regional":
logger.warning(
"MAGI-2 compiles the transformer regions itself; diffusion_compile_granularity=%r is ignored.",
granularity,
)
# The mHC connections chain bf16 ops that eager rounds after every op.
# Emulating those casts keeps the compiled rounding boundaries equal.
self.transformer.compile_regions(
fullgraph=True,
dynamic=self.od_config.diffusion_compile_dynamic,
options={"emulate_precision_casts": True},
)
def load_weights(
self,
weights: Iterable[tuple[str, torch.Tensor]],
@@ -308,29 +308,11 @@ class Magi2PreviewSampler(CFGParallelMixin):
per_token_video_t = t_batch.view(-1, 1, 1, 1, 1).expand(cfg_batch, 1, video_t, video_h, video_w)
per_token_audio_t = t_batch.view(-1, 1, 1).expand(cfg_batch, audio_t, 1)
audio_lengths = torch.full(
(cfg_batch,),
audio_latent_len,
device=latent.device,
dtype=torch.long,
)
text_lengths = torch.tensor(
[txt_feat_len] * batch_size + [null_txt_feat_len] * batch_size,
device=latent.device,
dtype=torch.long,
)
ref_audio_lengths = torch.full(
(cfg_batch,),
ref_audio_feat_len,
device=latent.device,
dtype=torch.long,
)
ref_video_lengths = torch.full(
(cfg_batch,),
ref_video_feat_len,
device=latent.device,
dtype=torch.long,
)
# Lengths stay host integers; the data proxy reads them as Python ints.
audio_lengths = [audio_latent_len] * cfg_batch
text_lengths = [txt_feat_len] * batch_size + [null_txt_feat_len] * batch_size
ref_audio_lengths = [ref_audio_feat_len] * cfg_batch
ref_video_lengths = [ref_video_feat_len] * cfg_batch
return ModelInput(
x_t=torch.cat((latent, latent), dim=0),
@@ -1,4 +1,5 @@
import math
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import torch
import torch.nn.functional as F
@@ -6,27 +7,14 @@ from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.models.attention_processor import Attention
from diffusers.models.embeddings import TimestepEmbedding, Timesteps
from diffusers.models.modeling_utils import ModelMixin
from einops import rearrange, repeat
from einops import rearrange
from torch import nn
from transformers.models.qwen2.modeling_qwen2 import Qwen2RMSNorm
from .rope_real import RotaryPosEmbedReal
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.layer import Attention as OmniAttention
try:
from transformers.modeling_flash_attention_utils import ( # type: ignore
flash_attn_varlen_func, # pyright: ignore[reportAttributeAccessIssue]
is_flash_attn_available,
)
except Exception: # pragma: no cover - best-effort compatibility
flash_attn_varlen_func = None # type: ignore[assignment]
def is_flash_attn_available() -> bool: # type: ignore[override]
return False
from .rope_real import apply_real_rotary_emb
_HAS_FLASH_ATTN_VARLEN = bool(is_flash_attn_available()) and flash_attn_varlen_func is not None
from .rope_real import RotaryPosEmbedReal, apply_real_rotary_emb
class LuminaRMSNormZero(nn.Module):
@@ -278,9 +266,14 @@ class SimpleQFormerImageRefiner(nn.Module):
class AttnProcessor:
def __init__(self) -> None:
if not hasattr(F, "scaled_dot_product_attention"):
raise ImportError("AttnProcessor requires PyTorch 2.0+ (F.scaled_dot_product_attention).")
"""Self-attention for the MammothModa2 DiT through the shared Omni attention layer.
The model-specific parts stay here: the projections, the per-head QK RMSNorm
and the interleaved real RoPE. The kernel, the padding mask and the
grouped-query heads are the shared backend's job, so K/V are handed over
with their native head count instead of being replicated to the query
head count first.
"""
def __call__(
self,
@@ -289,118 +282,55 @@ class AttnProcessor:
encoder_hidden_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
image_rotary_emb: torch.Tensor | None = None,
base_sequence_length: int | None = None,
) -> torch.Tensor:
batch_size, sequence_length, _ = hidden_states.shape
# Get Query-Key-Value Pair
query = attn.to_q(hidden_states)
key = attn.to_k(encoder_hidden_states)
value = attn.to_v(encoder_hidden_states)
query_dim = query.shape[-1]
inner_dim = key.shape[-1]
head_dim = query_dim // attn.heads
head_dim = query.shape[-1] // attn.heads
kv_heads = key.shape[-1] // head_dim
dtype = query.dtype
# Get key-value heads
kv_heads = inner_dim // head_dim
if sequence_length == 0 or key.shape[1] == 0:
# The pipeline's default unconditional branch is a text stream with
# zero tokens (negative_prompt_embeds has no rows), so under CFG the
# context refiner attends over an empty sequence. SDPA returns an
# empty tensor for that; the flash-attention varlen fallback builds
# cu_seqlens with arange(step=seq_len) and rejects step 0. Nothing
# to attend to either way, so hand the projection an empty input.
empty = query.new_zeros(batch_size, sequence_length, attn.heads * head_dim)
return attn.to_out[1](attn.to_out[0](empty))
# Reshape tensors for attention computation
query = query.view(batch_size, -1, attn.heads, head_dim)
key = key.view(batch_size, -1, kv_heads, head_dim)
value = value.view(batch_size, -1, kv_heads, head_dim)
# Apply Query-Key normalization
if attn.norm_q is not None:
query = attn.norm_q(query)
if attn.norm_k is not None:
key = attn.norm_k(key)
# Apply Rotary Position Embeddings
if image_rotary_emb is not None:
query = apply_real_rotary_emb(query, image_rotary_emb[0], image_rotary_emb[1])
key = apply_real_rotary_emb(key, image_rotary_emb[0], image_rotary_emb[1])
query, key = query.to(dtype), key.to(dtype)
# Calculate attention scale
if base_sequence_length is not None:
softmax_scale = math.sqrt(math.log(sequence_length, base_sequence_length)) * attn.scale
else:
softmax_scale = attn.scale
if _HAS_FLASH_ATTN_VARLEN and attention_mask is not None and hidden_states.is_cuda:
# Flash-Attn varlen expects packed tokens + cu_seqlens. Here we only need
# the self-attention case (q/k/v share the same padding mask).
if attention_mask is not None:
attention_mask = attention_mask.to(torch.bool)
seqlens = attention_mask.sum(dim=-1, dtype=torch.int32)
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
max_seqlen = int(seqlens.max().item())
cu_seqlens = F.pad(torch.cumsum(seqlens, dim=0, dtype=torch.int32), (1, 0))
query_states = query.reshape(batch_size * sequence_length, attn.heads, head_dim)[indices]
key_states = key.reshape(batch_size * sequence_length, kv_heads, head_dim)[indices]
value_states = value.reshape(batch_size * sequence_length, kv_heads, head_dim)[indices]
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
hidden_states = attn.omni_attn(query, key, value, attn_metadata)
if kv_heads < attn.heads:
key_states = repeat(key_states, "l h c -> l (h k) c", k=attn.heads // kv_heads)
value_states = repeat(value_states, "l h c -> l (h k) c", k=attn.heads // kv_heads)
if attention_mask is not None:
# Padded rows carry nothing downstream; keep them at zero as the
# previous varlen path did, since neither backend does it for us.
hidden_states = hidden_states * attention_mask[:, :, None, None]
attn_output_unpad = flash_attn_varlen_func(
query_states,
key_states,
value_states,
cu_seqlens_q=cu_seqlens,
cu_seqlens_k=cu_seqlens,
max_seqlen_q=max_seqlen,
max_seqlen_k=max_seqlen,
dropout_p=0.0,
causal=False,
softmax_scale=softmax_scale,
)
hidden_states = hidden_states.reshape(batch_size, sequence_length, attn.heads * head_dim).type_as(query)
out = torch.zeros(
(batch_size * sequence_length, attn.heads, head_dim),
device=attn_output_unpad.device,
dtype=attn_output_unpad.dtype,
)
out[indices] = attn_output_unpad
hidden_states = out.view(batch_size, sequence_length, attn.heads, head_dim).flatten(-2)
hidden_states = hidden_states.type_as(query)
else:
# PyTorch SDPA path.
attn_mask = None
if attention_mask is not None:
attention_mask = attention_mask.to(torch.bool)
attn_mask = attention_mask.view(batch_size, 1, 1, -1)
query = query.transpose(1, 2) # [B, H, S, D]
key = key.transpose(1, 2) # [B, H_kv, S, D]
value = value.transpose(1, 2)
if kv_heads < attn.heads:
key = key.repeat_interleave(attn.heads // kv_heads, dim=1)
value = value.repeat_interleave(attn.heads // kv_heads, dim=1)
hidden_states = F.scaled_dot_product_attention(
query,
key,
value,
attn_mask=attn_mask,
dropout_p=0.0,
is_causal=False,
scale=softmax_scale,
)
if attention_mask is not None:
# Keep padding tokens consistent with the flash-varlen path (zero output).
hidden_states = hidden_states * attention_mask[:, None, :, None]
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
hidden_states = hidden_states.type_as(query)
# Apply output projection
hidden_states = attn.to_out[0](hidden_states)
hidden_states = attn.to_out[1](hidden_states)
@@ -441,6 +371,18 @@ class TransformerBlock(nn.Module):
# 显式使用 transformers 的 Qwen2RMSNorm,避免依赖 diffusers 内部创建的 `RMSNorm` 再做递归替换。
self.attn.norm_q = Qwen2RMSNorm(self.head_dim, eps=1e-5)
self.attn.norm_k = Qwen2RMSNorm(self.head_dim, eps=1e-5)
# The kernel itself runs through the shared Omni attention layer: backend
# selection, padding-mask handling and native grouped-query heads live
# there. It owns no parameters, so checkpoint keys are unchanged. The
# diffusers Attention above is kept for its projections and QK norms.
self.attn.omni_attn = OmniAttention(
num_heads=num_attention_heads,
head_size=self.head_dim,
causal=False,
softmax_scale=self.attn.scale,
num_kv_heads=num_kv_heads,
allow_fp32_fallback=True,
)
# Initialize feed-forward network
self.feed_forward = LuminaFeedForward(
@@ -1,19 +1,25 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from collections.abc import Iterable
from typing import Any, ClassVar
from dataclasses import dataclass
from typing import ClassVar
import torch
from diffusers.image_processor import VaeImageProcessor
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from diffusers.utils.torch_utils import randn_tensor
from torch import nn
from transformers.models.qwen2.modeling_qwen2 import Qwen2RMSNorm
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.models.utils import AutoWeightsLoader, WeightsMapper
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
from vllm_omni.diffusion.models.interface import SupportsComponentDiscovery
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
from vllm_omni.transformers_utils.configs.mammoth_moda2 import Mammothmoda2Config
from .mammothmoda2_dit_model import SimpleQFormerImageRefiner, Transformer2DModel
@@ -23,6 +29,59 @@ from .schedulers import FlowMatchEulerDiscreteScheduler
logger = init_logger(__name__)
def _first_request_value(value: object) -> object:
if isinstance(value, (list, tuple)):
return value[0] if value else None
return value
def get_mammoth_moda2_post_process_func(
_od_config: OmniDiffusionConfig,
):
image_processor = VaeImageProcessor()
def post_process_func(images: torch.Tensor):
return image_processor.postprocess(images)
return post_process_func
def _build_mammoth_config(od_config: OmniDiffusionConfig) -> Mammothmoda2Config:
raw_config = od_config.tf_model_config.to_dict()
if not raw_config:
raise ValueError("MammothModa2 diffusion stage requires the root checkpoint config")
return Mammothmoda2Config(**raw_config)
def _root_weight_source(
od_config: OmniDiffusionConfig,
) -> DiffusersPipelineLoader.ComponentSource:
if not od_config.model:
raise ValueError("MammothModa2 diffusion stage requires a model path")
return DiffusersPipelineLoader.ComponentSource(
model_or_path=od_config.model,
subfolder=None,
revision=od_config.revision,
prefix="",
fall_back_to_pt=True,
)
@dataclass(frozen=True)
class _MammothRequest:
request_id: str
full_hidden_states: torch.Tensor
full_token_ids: list[int]
answer_start_index: int
height: int
width: int
text_guidance_scale: float
cfg_range: tuple[float, float]
num_inference_steps: int
seed: int | None
generator: torch.Generator | list[torch.Generator] | None
class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
"""
MammothModa2 DiT + VAE generation stage (non-autoregressive).
@@ -36,7 +95,8 @@ class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
_encoder_modules: ClassVar[list[str]] = ["gen_image_condition_refiner"]
_vae_modules: ClassVar[list[str]] = ["gen_vae"]
have_multimodal_outputs = True
supports_request_batch = False
supports_step_execution = False
# Load only gen_* weights; ignore llm_model.* to prevent loading the entire LLM backbone in the DiT stage.
hf_to_vllm_mapper = WeightsMapper(
@@ -46,15 +106,13 @@ class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
}
)
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
super().__init__()
del prefix
hf_config = vllm_config.model_config.hf_config
if not isinstance(hf_config, Mammothmoda2Config):
raise TypeError(f"Expected Mammothmoda2Config, got {type(hf_config)}")
self.config = hf_config
self.od_config = od_config
self.device = get_local_device()
self.config = _build_mammoth_config(od_config)
self.weights_sources = [_root_weight_source(od_config)]
# --- Build DiT / VAE modules (names must match checkpoint keys) ---
if self.config.gen_vae_config is None or self.config.gen_dit_config is None:
@@ -109,9 +167,6 @@ class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
theta=10000,
)
# vLLM PP interface compatibility
self.make_empty_intermediate_tensors = lambda: None
self._llm_hidden_size = llm_hidden_size
def _reinit_caption_embedder(self, in_features: int) -> None:
@@ -123,39 +178,118 @@ class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
nn.Linear(in_features, out_features, bias=True),
)
def get_dummy_runtime_additional_information(self, num_reqs: int) -> list[dict[str, object]]:
if num_reqs <= 0:
raise ValueError(f"num_reqs must be positive, got {num_reqs}")
if num_reqs > 1:
raise NotImplementedError(
f"get_dummy_runtime_additional_information does not support num_reqs > 1, got {num_reqs}"
)
text_prompt_embeds = torch.zeros((1, self._llm_hidden_size), dtype=torch.float32)
image_prompt_embeds = torch.zeros((1, self._llm_hidden_size), dtype=torch.float32)
negative_prompt_embeds = torch.zeros((0, self._llm_hidden_size), dtype=torch.float32)
info = {
"text_prompt_embeds": text_prompt_embeds,
"image_prompt_embeds": image_prompt_embeds,
"negative_prompt_embeds": negative_prompt_embeds,
"negative_prompt_attention_mask": [],
"image_height": [512],
"image_width": [512],
"text_guidance_scale": [1.0],
"cfg_range": [0.0, 1.0],
"num_inference_steps": [1],
}
return [info for _ in range(num_reqs)]
def _parse_request(self, req: DiffusionRequestBatch) -> _MammothRequest:
if req.num_reqs != 1:
raise ValueError("MammothModa2 diffusion requires exactly one request")
request_id = req.request_id
sampling = req.sampling_params
if sampling.num_outputs_per_prompt != 1:
raise ValueError(f"MammothModa2 requires num_outputs_per_prompt=1 for request {request_id}")
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
# DiT stage does not consume token embeddings; return a dummy tensor.
prompt = req.prompts[0]
prompt = prompt if isinstance(prompt, dict) else {}
info = prompt.get("additional_information")
if req.is_dummy_run():
full_hidden_states = torch.zeros((2, self._llm_hidden_size), dtype=torch.float32, device="cpu")
full_token_ids = [0, int(self.config.llm_config.gen_vocab_start_index)]
answer_start_index = 1
else:
if not isinstance(info, dict):
raise ValueError(f"Missing additional_information AR conditions for request {request_id}")
full_hidden_states = info.get("full_hidden_states")
full_token_ids = info.get("full_token_ids")
if not isinstance(full_hidden_states, torch.Tensor) or not isinstance(full_token_ids, list):
raise ValueError(f"Expected full_hidden_states tensor and full_token_ids list for request {request_id}")
try:
answer_start_index = int(info.get("answer_start_index"))
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError(f"Invalid answer_start_index for request {request_id}") from exc
if full_hidden_states.ndim != 2:
raise ValueError(f"Expected 2D full_hidden_states for request {request_id}")
if full_hidden_states.shape[0] != len(full_token_ids):
raise ValueError(f"AR hidden-state/token-count mismatch for request {request_id}")
if not 0 <= answer_start_index <= len(full_token_ids):
raise ValueError(f"answer_start_index outside token range for request {request_id}")
try:
full_token_ids = [int(token_id) for token_id in full_token_ids]
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError(f"Invalid full_token_ids for request {request_id}") from exc
dimensions = []
for name in ("height", "width"):
value = DiffusionRequestBatch.get_prompt_field(prompt, name)
if value is None:
value = getattr(sampling, name)
if value is None:
value = 1024
try:
dimensions.append(int(value))
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError(f"Invalid image size {name}={value!r} for request {request_id}") from exc
height, width = dimensions
if height <= 0 or width <= 0:
raise ValueError(f"Invalid image size: {height}x{width} for request {request_id}")
if height % 16 != 0 or width % 16 != 0:
raise ValueError(f"Image size must be multiples of 16, got {height}x{width} for request {request_id}")
request_info = info if isinstance(info, dict) else {}
extra_args = sampling.extra_args or {}
guidance = extra_args.get("text_guidance_scale")
if guidance is None:
guidance = sampling.guidance_scale if sampling.guidance_scale_provided else None
if guidance is None:
guidance = _first_request_value(request_info.get("text_guidance_scale"))
if guidance is None:
guidance = 9.0
try:
dtype = next(self.parameters()).dtype
except StopIteration:
dtype = torch.float32
return torch.zeros(
(input_ids.numel(), self._llm_hidden_size),
device=input_ids.device,
dtype=dtype,
text_guidance_scale = float(guidance)
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError(f"Invalid text_guidance_scale for request {request_id}") from exc
raw_num_inference_steps = extra_args.get("num_inference_steps")
if raw_num_inference_steps is None:
raw_num_inference_steps = sampling.num_inference_steps
if raw_num_inference_steps is None:
raw_num_inference_steps = _first_request_value(request_info.get("num_inference_steps"))
if raw_num_inference_steps is None:
raw_num_inference_steps = 50
try:
num_inference_steps = int(raw_num_inference_steps)
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError(f"Invalid num_inference_steps for request {request_id}") from exc
if num_inference_steps <= 0:
raise ValueError(f"num_inference_steps must be positive for request {request_id}")
cfg_range = extra_args.get("cfg_range")
if cfg_range is None:
cfg_range = request_info.get("cfg_range")
if cfg_range is None:
cfg_range = [0.0, 1.0]
if not isinstance(cfg_range, (list, tuple)) or len(cfg_range) != 2:
raise ValueError(f"cfg_range requires two values for request {request_id}")
try:
cfg_start, cfg_end = float(cfg_range[0]), float(cfg_range[1])
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError(f"cfg_range requires two values convertible to floats for request {request_id}") from exc
if not 0 <= cfg_start <= cfg_end <= 1:
raise ValueError(f"cfg_range must satisfy 0 <= start <= end <= 1 for request {request_id}")
generator = sampling.generator
if isinstance(generator, list) and len(generator) != 1:
raise ValueError(
f"MammothModa2 single-output request mode requires exactly one generator for request {request_id}"
)
return _MammothRequest(
request_id=request_id,
full_hidden_states=full_hidden_states,
full_token_ids=full_token_ids,
answer_start_index=answer_start_index,
height=height,
width=width,
text_guidance_scale=text_guidance_scale,
cfg_range=(cfg_start, cfg_end),
num_inference_steps=num_inference_steps,
seed=sampling.seed,
generator=generator,
)
def _split_ar_conditions(
@@ -191,47 +325,28 @@ class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
text_mask = questions_mask & ~(visual_token_mask | gen_token_mask)
image_mask = answers_mask & gen_token_mask
text_cond = full_hidden_states[text_mask].to(dtype=torch.float32).contiguous()
image_cond = full_hidden_states[image_mask].to(dtype=torch.float32).contiguous()
# Keep the transferred representation compact until the final device/dtype
# conversion in ``forward``. The masks are dtype-independent, and an
# unconditional host-side float32 expansion here would otherwise double both
# the selected-condition staging footprint and BF16 H2D traffic.
text_cond = full_hidden_states[text_mask].contiguous()
image_cond = full_hidden_states[image_mask].contiguous()
return text_cond, image_cond
@torch.inference_mode()
def forward(
self,
*,
inputs_embeds: torch.Tensor | None = None,
**kwargs: Any, # noqa: ARG002
) -> OmniOutput:
runtime_addi = kwargs.get("runtime_additional_information", None)
info = runtime_addi[0]
# Sampling knobs are declared in vllm_omni/model_extras/mammothmodal2_preview.py
# and routed via extra_body -> sampling_params.extra_args (surfaced here as
# ``sampling_extra_args``). Fall back to runtime_additional_information for the
# legacy bespoke-example path during the transition.
extra_args_list = kwargs.get("sampling_extra_args") or []
extra_args = extra_args_list[0] if extra_args_list else {}
text_guidance_scale = float(extra_args.get("text_guidance_scale", info["text_guidance_scale"][0]))
cfg_range_val = extra_args.get("cfg_range", info["cfg_range"])
cfg_range = float(cfg_range_val[0]), float(cfg_range_val[1])
num_inference_steps = int(extra_args.get("num_inference_steps", info["num_inference_steps"][0]))
negative_cond = info.get("negative_prompt_embeds")
negative_attention_mask = info.get("negative_prompt_attention_mask")
image_hw = info["image_height"][0], info["image_width"][0]
# Split the AR hidden states into text / image conditions. The token ids that
# drive the split are sourced from the model config (see _split_ar_conditions),
# formerly supplied by the bespoke example via additional_information. Legacy
# fallback: ar2dit may have already produced the split conditions.
if "text_prompt_embeds" in info:
text_cond = info["text_prompt_embeds"]
image_cond = info["image_prompt_embeds"]
else:
text_cond, image_cond = self._split_ar_conditions(
full_hidden_states=info["full_hidden_states"],
full_token_ids=info["full_token_ids"],
answer_start_index=int(info["answer_start_index"][0]),
def forward(self, req: DiffusionRequestBatch) -> DiffusionOutput:
request = self._parse_request(req)
text_cond, image_cond = self._split_ar_conditions(
full_hidden_states=request.full_hidden_states,
full_token_ids=request.full_token_ids,
answer_start_index=request.answer_start_index,
)
if image_cond.shape[0] == 0:
answer_token_ids = request.full_token_ids[request.answer_start_index :]
raise ValueError(
"MammothModa2 AR stage produced no visual-token hidden states for "
f"request {request.request_id}; the DiT stage requires at least one generated visual token. "
f"Generated token ids: {answer_token_ids[:32]}"
)
# Move to model device/dtype.
@@ -241,22 +356,6 @@ class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
else:
target_dtype = next(self.gen_transformer.parameters()).dtype
def _ensure_2d(x: torch.Tensor, name: str) -> torch.Tensor:
if x.ndim == 3 and x.shape[0] == 1:
x = x[0]
if x.ndim != 2:
raise ValueError(f"Expected {name} to be 2D [T,H], got shape={tuple(x.shape)}")
return x
text_cond = _ensure_2d(text_cond, "text_prompt_embeds")
image_cond = _ensure_2d(image_cond, "image_prompt_embeds")
if image_cond.shape[0] == 0:
answer_token_ids = info.get("full_token_ids", [])[int(info.get("answer_start_index", [0])[0]) :]
raise ValueError(
"MammothModa2 AR stage produced no visual-token hidden states; "
"the DiT stage requires at least one generated visual token. "
f"Generated token ids: {answer_token_ids[:32]}"
)
text_cond = text_cond.to(device=model_device, dtype=target_dtype, non_blocking=True).contiguous()
image_cond = image_cond.to(device=model_device, dtype=target_dtype, non_blocking=True).contiguous()
@@ -295,63 +394,38 @@ class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
ar_image_embeds = image_embeds
ar_image_attention_mask = image_attention_mask
# Prepare negative prompt (for CFG). If none provided, fall back to unconditional.
# Empty unconditional prompt for classifier-free guidance.
negative_prompt_embeds = None
negative_prompt_attention_mask = None
if text_guidance_scale > 1.0:
if negative_cond is not None:
negative_cond = _ensure_2d(negative_cond, "negative_prompt_embeds")
negative_prompt_embeds = (
negative_cond.to(device=model_device, dtype=target_dtype, non_blocking=True)
.contiguous()
.unsqueeze(0)
)
if isinstance(negative_attention_mask, torch.Tensor):
neg_mask = negative_attention_mask
elif isinstance(negative_attention_mask, list):
neg_mask = torch.tensor(negative_attention_mask, dtype=torch.bool)
else:
neg_mask = None
if neg_mask is None:
negative_prompt_attention_mask = torch.ones(
(1, negative_prompt_embeds.shape[1]),
dtype=torch.bool,
device=negative_prompt_embeds.device,
)
else:
neg_mask = neg_mask.to(device=negative_prompt_embeds.device, dtype=torch.bool)
if neg_mask.ndim == 1:
neg_mask = neg_mask.unsqueeze(0)
negative_prompt_attention_mask = neg_mask
else:
hidden_size = int(prompt_embeds.shape[-1])
negative_prompt_embeds = torch.zeros(
(1, 0, hidden_size),
dtype=target_dtype,
device=prompt_embeds.device,
)
negative_prompt_attention_mask = torch.zeros(
(1, 0),
dtype=torch.bool,
device=prompt_embeds.device,
)
if request.text_guidance_scale > 1.0:
hidden_size = int(prompt_embeds.shape[-1])
negative_prompt_embeds = torch.zeros(
(1, 0, hidden_size),
dtype=target_dtype,
device=prompt_embeds.device,
)
negative_prompt_attention_mask = torch.zeros(
(1, 0),
dtype=torch.bool,
device=prompt_embeds.device,
)
generator = request.generator
if generator is None and request.seed is not None:
generator = torch.Generator(device=model_device).manual_seed(request.seed)
# Output image size (px), passed from stage input processor.
height, width = image_hw
if height <= 0 or width <= 0:
raise ValueError(f"Invalid image size: {height}x{width}")
if height % 16 != 0 or width % 16 != 0:
raise ValueError(f"Image size must be multiples of 16, got {height}x{width}")
height, width = request.height, request.width
vae_scale_factor = 16
latent_channels = int(self.gen_transformer.config.in_channels)
shape = (1, latent_channels, 2 * height // vae_scale_factor, 2 * width // vae_scale_factor)
latents = randn_tensor(shape, device=prompt_embeds.device, dtype=prompt_embeds.dtype)
latents = randn_tensor(shape, generator=generator, device=prompt_embeds.device, dtype=prompt_embeds.dtype)
scheduler = FlowMatchEulerDiscreteScheduler()
scheduler.set_timesteps(
num_inference_steps=num_inference_steps,
num_inference_steps=request.num_inference_steps,
device=prompt_embeds.device,
num_tokens=latents.shape[-2] * latents.shape[-1],
)
@@ -370,7 +444,9 @@ class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
ar_image_attention_mask=ar_image_attention_mask,
freqs_cis=self.gen_freqs_cis,
)
guidance_scale = text_guidance_scale if cfg_range[0] <= i / total_steps <= cfg_range[1] else 1.0
guidance_scale = (
request.text_guidance_scale if request.cfg_range[0] <= i / total_steps <= request.cfg_range[1] else 1.0
)
if guidance_scale > 1.0 and negative_prompt_embeds is not None:
model_pred_uncond = self.gen_transformer(
hidden_states=latents,
@@ -391,14 +467,7 @@ class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
latents = latents + self.gen_vae.config.shift_factor
image = self.gen_vae.decode(latents, return_dict=False)[0]
return OmniOutput(
text_hidden_states=inputs_embeds, # placeholder, not used by runner
multimodal_outputs=image,
intermediate_tensors=None,
)
def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None: # noqa: ARG002
return None
return DiffusionOutput(output=image)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
loader = AutoWeightsLoader(self)
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
@@ -0,0 +1,209 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""MiniMax-H3 VSA prefix routing, tile layout, and learned compression gate."""
from __future__ import annotations
import functools
import math
import torch
from vllm.logger import init_logger
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.backends.fastvideo_vsa import (
FastVideoVSAImpl,
_construct_variable_block_sizes,
_get_gate_compress,
_get_non_pad_index,
_get_tile_partition_indices,
)
from vllm_omni.diffusion.attention.ops.block_sparse import (
build_prefix_dense_block_map,
fastvideo_block_sparse_attn_bshd,
mean_pool_tiles,
)
logger = init_logger(__name__)
@functools.lru_cache(maxsize=32)
def _get_h3_tile_metadata(
prefix_segments: tuple[int, ...],
video_shape: tuple[int, int, int],
device: torch.device,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, int, int]:
"""Official FastVideo H3 geometry: pure prefix chunks + 3-D video tiles."""
block_size = (4, 4, 4)
block_elements = 64
prefix_len = sum(prefix_segments)
prefix_sizes: list[int] = []
for segment in prefix_segments:
full, remainder = divmod(segment, block_elements)
prefix_sizes.extend([block_elements] * full)
if remainder:
prefix_sizes.append(remainder)
video_indices = _get_tile_partition_indices(video_shape, block_size, device) + prefix_len
video_sizes = _construct_variable_block_sizes(video_shape, block_size, device)
partition = torch.cat([torch.arange(prefix_len, device=device, dtype=torch.long), video_indices])
sizes = torch.cat([torch.tensor(prefix_sizes, device=device, dtype=torch.int32), video_sizes.to(torch.int32)])
non_pad = _get_non_pad_index(sizes, block_elements)
untile = non_pad[torch.argsort(partition)]
total = prefix_len + math.prod(video_shape)
if int(sizes.sum()) != total or untile.numel() != total:
raise ValueError(
f"invalid H3 VSA geometry: prefix={prefix_segments}, video={video_shape}, "
f"sizes_sum={int(sizes.sum())}, total={total}"
)
return partition, sizes, non_pad, untile, len(prefix_sizes), int(video_sizes.numel())
def _get_h3_layout(
attn_metadata: AttentionMetadata | None,
) -> tuple[tuple[int, ...], tuple[int, int, int], int] | None:
if attn_metadata is None or attn_metadata.video_layout is None:
return None
prefix = attn_metadata.extra.get("vsa_h3_prefix_segments")
if not isinstance(prefix, (tuple, list)):
return None
target = next(
(span for span in reversed(attn_metadata.video_layout.video_spans) if span.role == "target"),
None,
)
if target is None:
return None
return tuple(int(x) for x in prefix if int(x) > 0), target.latent_grid, target.start
class MiniMaxH3VSAImpl(FastVideoVSAImpl):
"""Apply H3 tile64 routing after shared parallel attention dispatch."""
def _forward_h3(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_metadata: AttentionMetadata,
) -> torch.Tensor:
layout = _get_h3_layout(attn_metadata)
if layout is None:
raise ValueError("incomplete VSA-H3 layout metadata")
prefix_segments, video_shape, target_start = layout
if sum(prefix_segments) != target_start:
raise ValueError(f"VSA-H3 prefix segments sum to {sum(prefix_segments)}, target starts at {target_start}")
expected = target_start + math.prod(video_shape)
if query.shape[1] != expected:
raise ValueError(f"VSA-H3 layout has {expected} rows but attention received {query.shape[1]}")
if query.dtype not in (torch.float16, torch.bfloat16):
raise ValueError(f"VSA-H3 requires fp16/bf16 tensors, got {query.dtype}")
gate = _get_gate_compress(attn_metadata)
if gate is not None:
# H3 pads the packed document to 64 rows, while VSA operates on
# the valid prefix. Validate/slice before launching attention so a
# metadata error can never trigger an unsafe dense fallback after
# an asynchronous custom kernel.
if gate.shape[0] != query.shape[0] or gate.shape[2:] != query.shape[2:] or gate.shape[1] < query.shape[1]:
raise ValueError(f"gate_compress shape {gate.shape} cannot cover query shape {query.shape}")
gate = gate[:, : query.shape[1]]
partition, sizes, non_pad, untile, prefix_blocks, video_blocks = _get_h3_tile_metadata(
prefix_segments, video_shape, query.device
)
logical_blocks = int(sizes.numel())
# The native sm100a kernel assigns pairs of query blocks to CTAs. Its
# contract requires an even block count; the synthetic partner is
# transport-only and is removed before returning.
pair_pad = logical_blocks % 2
kernel_blocks = logical_blocks + pair_pad
target_shape = (query.shape[0], kernel_blocks * 64, query.shape[2], query.shape[3])
q_tiled = torch.zeros(target_shape, device=query.device, dtype=query.dtype)
k_tiled = torch.zeros_like(q_tiled)
v_tiled = torch.zeros_like(q_tiled)
q_tiled[:, non_pad] = query[:, partition]
k_tiled[:, non_pad] = key[:, partition]
v_tiled[:, non_pad] = value[:, partition]
q_pool = mean_pool_tiles(q_tiled[:, : logical_blocks * 64], sizes, block_size=64)
k_pool = mean_pool_tiles(k_tiled[:, : logical_blocks * 64], sizes, block_size=64)
scores = torch.matmul(q_pool, k_pool.transpose(-2, -1)) * self.softmax_scale
block_map = build_prefix_dense_block_map(scores, prefix_blocks, video_blocks, self.topk)
kernel_sizes = sizes
if pair_pad:
block_map = torch.nn.functional.pad(block_map, (0, 1, 0, 1), value=False)
kernel_sizes = torch.nn.functional.pad(sizes, (0, 1), value=0)
logger.info_once(
"FASTVIDEO_VSA H3 routing: seq_len=%d, prefix_segments=%s, video_shape=%s, "
"prefix_blocks=%d, video_blocks=%d, topk=%d, kernel_blocks=%d",
query.shape[1],
prefix_segments,
video_shape,
prefix_blocks,
video_blocks,
min(self.topk, video_blocks),
kernel_blocks,
)
output = fastvideo_block_sparse_attn_bshd(
q_tiled.contiguous(),
k_tiled.contiguous(),
v_tiled.contiguous(),
block_map.contiguous(),
kernel_sizes.contiguous(),
logical_blocks,
)[:, : logical_blocks * 64]
if gate is not None:
gate_tiled = torch.zeros_like(q_tiled[:, : logical_blocks * 64])
gate_tiled[:, non_pad] = gate[:, partition]
v_pool = mean_pool_tiles(v_tiled[:, : logical_blocks * 64], sizes, block_size=64)
compressed = torch.matmul(torch.softmax(scores, dim=-1), v_pool)
compressed = compressed.permute(0, 2, 1, 3).to(output.dtype)
output = (
output.view(output.shape[0], logical_blocks, 64, output.shape[2], output.shape[3])
+ compressed.unsqueeze(2)
* gate_tiled.view(gate_tiled.shape[0], logical_blocks, 64, gate_tiled.shape[2], gate_tiled.shape[3])
).view_as(output)
return output[:, untile].contiguous()
def forward_cuda(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_metadata: AttentionMetadata | None = None,
) -> torch.Tensor:
if _get_h3_layout(attn_metadata) is None:
return super().forward_cuda(query, key, value, attn_metadata)
original_query, original_key, original_value = query, key, value
original_seq_len = query.shape[1]
valid_seq_len = original_seq_len
if attn_metadata is not None and attn_metadata.packed_padding is not None:
valid_seq_len = attn_metadata.packed_padding.q_length
if attn_metadata.packed_padding.kv_length != valid_seq_len:
return self._fallback(
original_query, original_key, original_value, attn_metadata, "packed Q/KV lengths must match"
)
query = query[:, :valid_seq_len]
key = key[:, :valid_seq_len]
value = value[:, :valid_seq_len]
try:
output = self._forward_h3(query, key, value, attn_metadata)
if valid_seq_len == original_seq_len:
return output
restored = torch.zeros_like(original_query)
restored[:, :valid_seq_len] = output
return restored
except Exception as exc:
# A CUDA fault poisons the process context; attempting SDPA
# afterwards obscures the original kernel failure and cannot
# recover the request.
if isinstance(exc, torch.AcceleratorError):
raise
if not self.fallback_on_error:
raise
return self._fallback(
original_query, original_key, original_value, attn_metadata, f"VSA-H3 kernel failed: {exc}"
)
@@ -38,6 +38,8 @@ def minimax_h3_batched_forward_kwargs(
t_audio: Sequence[float],
imgvid_cond_timesteps: Sequence[float],
audio_ref_cond_timesteps: Sequence[float],
video_target_timesteps: Sequence[torch.Tensor | None] | None = None,
audio_target_timesteps: Sequence[torch.Tensor | None] | None = None,
) -> dict[str, Any]:
"""Build one DiT forward kwargs dict covering every request in the batch.
@@ -46,6 +48,16 @@ def minimax_h3_batched_forward_kwargs(
happen to agree -- which also keeps ``video_token_layout`` (the sparse-
attention hint) on the single-request step path.
"""
request_count = len(branches)
if video_target_timesteps is None:
video_target_timesteps = [None] * request_count
elif len(video_target_timesteps) != request_count:
raise ValueError(f"video_target_timesteps has {len(video_target_timesteps)} requests, expected {request_count}")
if audio_target_timesteps is None:
audio_target_timesteps = [None] * request_count
elif len(audio_target_timesteps) != request_count:
raise ValueError(f"audio_target_timesteps has {len(audio_target_timesteps)} requests, expected {request_count}")
if len(branches) == 1:
return branches[0].forward_kwargs(
video_rows=video_rows[0],
@@ -54,6 +66,8 @@ def minimax_h3_batched_forward_kwargs(
t_audio=t_audio[0],
imgvid_cond_timestep=imgvid_cond_timesteps[0],
audio_ref_cond_timestep=audio_ref_cond_timesteps[0],
video_target_timesteps=video_target_timesteps[0],
audio_target_timesteps=audio_target_timesteps[0],
)
device = branches[0].device
@@ -88,11 +102,15 @@ def minimax_h3_batched_forward_kwargs(
position_id_parts.append(branch.img_position_ids_dev)
text_embed_parts.append(branch.text_embeddings_dev)
timesteps[seq_offset : seq_offset + branch.seq_len] = float(t_video[index])
timesteps[img_pos[branch.update_mask_dev]] = float(t_video[index])
timesteps[img_pos[~branch.update_mask_dev]] = float(imgvid_cond_timesteps[index])
timesteps[audio_pos[branch.audio_update_mask_dev]] = float(t_audio[index])
timesteps[audio_pos[~branch.audio_update_mask_dev]] = float(audio_ref_cond_timesteps[index])
branch.fill_timesteps(
timesteps[seq_offset : seq_offset + branch.seq_len],
t_video=t_video[index],
t_audio=t_audio[index],
imgvid_cond_timestep=imgvid_cond_timesteps[index],
audio_ref_cond_timestep=audio_ref_cond_timesteps[index],
video_target_timesteps=video_target_timesteps[index],
audio_target_timesteps=audio_target_timesteps[index],
)
# Empty documents are omitted because not every varlen kernel accepts
# repeated interior boundaries.
@@ -0,0 +1,162 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Bounded H3 windows with synchronized latent-tail guides and global AV RoPE positions.
The guide/discard/append algorithm follows ComfyUI-Minimax-H3-Continuation:
https://github.com/ttulttul/ComfyUI-Minimax-H3-Continuation
"""
from __future__ import annotations
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any
import torch
from vllm.logger import init_logger
from vllm_omni.errors import OmniClientError
from vllm_omni.model_executor.models.minimax_h3.long_video import resolve_long_video_mode
from .packed_tokens import minimax_h3_pack_audio_latent, minimax_h3_patchify_video_latent
logger = init_logger(__name__)
def _video_t(frames: int) -> int:
return (frames - 5) // 17 * 5 + 2
def _audio_t(frame_boundary: int) -> int:
return round(frame_boundary * 5 / 3)
@dataclass(frozen=True)
class ContinuationWindow:
start: int
end: int
overlap: int
@property
def audio_start(self) -> int:
return _audio_t(self.start)
@property
def audio_end(self) -> int:
return _audio_t(self.end)
@property
def overlap_audio_t(self) -> int:
return _audio_t(self.start + self.overlap) - self.audio_start
def resolve_continuation(extra: Mapping[str, Any], *, task: str, step_execution: bool) -> tuple[int, int] | None:
mode = resolve_long_video_mode(extra, task)
if mode == "full":
return None
if task != "ref2va" or step_execution:
raise OmniClientError("MiniMax H3 continuation requires Ref2VA request execution (not step execution)")
window = extra.get("continuation_window_frames", 277)
overlap = extra.get("continuation_overlap_frames", 22)
for name, value in (("window", window), ("overlap", overlap)):
if isinstance(value, bool) or not isinstance(value, int) or value < 5 or value % 17 != 5:
raise OmniClientError(f"MiniMax H3 continuation {name} must be an integer on the 17n+5 frame grid")
if not 107 <= window <= 345 or overlap >= window:
raise OmniClientError("MiniMax H3 continuation window must be 107..345 frames and exceed its overlap")
return window, overlap
def plan_continuation_windows(total_frames: int, window_frames: int, overlap_frames: int) -> list[ContinuationWindow]:
if total_frames < 5 or total_frames % 17 != 5:
raise ValueError("total_frames must satisfy 17n+5")
if not 5 <= overlap_frames < window_frames or window_frames % 17 != 5 or overlap_frames % 17 != 5:
raise ValueError("window and overlap must satisfy 17n+5, with 5 <= overlap < window")
end = min(total_frames, window_frames)
windows = [ContinuationWindow(0, end, 0)]
while end < total_frames:
start = end - overlap_frames
end = min(total_frames, start + window_frames)
windows.append(ContinuationWindow(start, end, overlap_frames))
return windows
def diffuse_continuation(
diffuse: Callable[..., tuple[torch.Tensor, torch.Tensor]],
kwargs: dict[str, Any],
*,
window_frames: int,
overlap_frames: int,
text_conditioning: Sequence[tuple[torch.Tensor, torch.Tensor]] | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Denoise fresh windows; retain old latents and append only new suffixes.
Guides are extra condition rows sharing the new target's temporal origin,
not a masked target prefix. Audio boundaries refer to the cumulative frame
timeline, preventing per-window rounding from accumulating A/V drift.
Each window shifts temporal media positions onto that same global timeline
before RoPE is evaluated; text and static image references remain fixed.
"""
windows = plan_continuation_windows(kwargs["num_frames"], window_frames, overlap_frames)
if text_conditioning is not None and len(text_conditioning) != len(windows):
raise OmniClientError("MiniMax H3 requires one text conditioning per continuation window")
# Different prompts have different prefix lengths. Keep the media clock
# anchored after the longest prefix so text length cannot shift AV time.
media_time_origin = max(item[0].shape[0] for item in text_conditioning) if text_conditioning else None
source_rows = kwargs.get("locked_audio_rows")
source = None if source_rows is None else source_rows.reshape(2, kwargs["audio_t"], 32)
video = audio = None
for index, window in enumerate(windows):
frames = window.end - window.start
args = {
**kwargs,
"num_frames": frames,
"latent_t": _video_t(frames),
"audio_t": window.audio_end - window.audio_start,
# Keep fractional RoPE units; audio slice indices alone are rounded.
"temporal_offset": window.start * (40.0 / 24.0),
}
if text_conditioning is not None:
args["text_embeddings"], args["text_tags"] = text_conditioning[index]
args["media_time_origin"] = media_time_origin
if source is not None:
args["locked_audio_rows"] = source[:, window.audio_start : window.audio_end].reshape(-1, 32)
overlap_v = _video_t(window.overlap) if window.overlap else 0
if video is not None and audio is not None:
guide_video = minimax_h3_patchify_video_latent(video[:, :, -overlap_v:], patch_size=(1, 2, 2))
guide_audio = minimax_h3_pack_audio_latent(audio[..., -window.overlap_audio_t :])
for name, guide in (("visual_condition", guide_video), ("audio_condition", guide_audio)):
existing = kwargs.get(name)
args[name] = guide if existing is None else torch.cat((existing, guide), dim=0)
args["visual_condition_shapes"] = [
*(kwargs.get("visual_condition_shapes") or []),
(overlap_v, kwargs["latent_h"], kwargs["latent_w"]),
]
args["audio_condition_lengths"] = [*(kwargs.get("audio_condition_lengths") or []), window.overlap_audio_t]
args["ref_blocks"] = [
*(kwargs.get("ref_blocks") or []),
{
"kind": "latent_guide",
"latent_t": overlap_v,
"latent_h": kwargs["latent_h"],
"latent_w": kwargs["latent_w"],
"ref_audio_t": window.overlap_audio_t,
},
]
logger.info(
"MiniMax H3 continuation window %d/%d: frames [%d, %d), hidden overlap %d, temporal offset %.6f",
index + 1,
len(windows),
window.start,
window.end,
window.overlap,
args["temporal_offset"],
)
sampled_video, sampled_audio = diffuse(**args)
video = sampled_video if video is None else torch.cat((video, sampled_video[:, :, overlap_v:]), dim=2)
audio = (
sampled_audio if audio is None else torch.cat((audio, sampled_audio[..., window.overlap_audio_t :]), dim=-1)
)
assert video is not None and audio is not None
if video.shape[2] != kwargs["latent_t"] or audio.shape[-1] != kwargs["audio_t"]:
raise RuntimeError("MiniMax H3 continuation produced inconsistent cumulative AV lengths")
return video, audio
@@ -23,6 +23,7 @@ from vllm_omni.diffusion.forward_context import (
)
from vllm_omni.platforms import current_omni_platform
from .latent_mask import MiniMaxH3LatentEdit, minimax_h3_prepare_edit_rows
from .scheduling_minimax_h3_euler_ancestral import (
minimax_h3_euler_eta0_step,
minimax_h3_rf_v_to_x0,
@@ -86,6 +87,7 @@ class MiniMaxH3DenoiseBranch:
raise ValueError(f"token_tags length {int(token_tags.view(-1).shape[0])} != seq_len {seq_len}")
cu = packed["cu_seqlens"].to(torch.int32)
self.device = device
self.locked_audio_rows: torch.Tensor | None = None
# ``used_len`` is the real (non-padding) document length; step-mode
# batching concatenates layouts and needs both bounds as Python ints so
# it can rebuild ``cu_seqlens`` without a device sync per step.
@@ -185,25 +187,23 @@ class MiniMaxH3DenoiseBranch:
t_audio: float,
imgvid_cond_timestep: float,
audio_ref_cond_timestep: float,
video_target_timesteps: torch.Tensor | None = None,
audio_target_timesteps: torch.Tensor | None = None,
) -> dict[str, Any]:
x = self.x_base.clone()
x[0].index_copy_(0, self.img_pos_dev, video_rows)
audio_x = self.audio_x_base.clone()
audio_x[0].index_copy_(0, self.audio_pos_dev, audio_rows)
# Packed-sequence timestep semantics: non-media rows (text and
# padding) inherit the current video timestep. Later steps must reuse
# the previous step's updated rows; re-initializing from zeros is only
# valid at step 0.
timesteps = torch.full(
(self.seq_len,),
float(t_video),
dtype=torch.float32,
device=x.device,
timesteps = torch.empty(self.seq_len, dtype=torch.float32, device=self.device)
self.fill_timesteps(
timesteps,
t_video=t_video,
t_audio=t_audio,
imgvid_cond_timestep=imgvid_cond_timestep,
audio_ref_cond_timestep=audio_ref_cond_timestep,
video_target_timesteps=video_target_timesteps,
audio_target_timesteps=audio_target_timesteps,
)
timesteps[self.img_pos_dev[self.update_mask_dev]] = t_video
timesteps[self.img_pos_dev[~self.update_mask_dev]] = imgvid_cond_timestep
timesteps[self.audio_pos_dev[self.audio_update_mask_dev]] = t_audio
timesteps[self.audio_pos_dev[~self.audio_update_mask_dev]] = audio_ref_cond_timestep
unique_timesteps, inverse_indices = torch.unique(timesteps, sorted=True, return_inverse=True)
return {
**self.static_kwargs,
@@ -213,6 +213,56 @@ class MiniMaxH3DenoiseBranch:
"inverse_indices": inverse_indices,
}
def fill_timesteps(
self,
timesteps: torch.Tensor,
*,
t_video: float,
t_audio: float,
imgvid_cond_timestep: float,
audio_ref_cond_timestep: float,
video_target_timesteps: torch.Tensor | None = None,
audio_target_timesteps: torch.Tensor | None = None,
) -> None:
"""Fill one request's packed row timesteps in an existing tensor."""
if timesteps.shape != (self.seq_len,):
raise ValueError(f"timesteps must have shape ({self.seq_len},)")
# Packed-sequence timestep semantics: non-media rows (text and
# padding) inherit the current video timestep. Later steps must reuse
# the previous step's updated rows; re-initializing from zeros is only
# valid at step 0.
timesteps.fill_(float(t_video))
timestep_groups = (
(
"video_target_timesteps",
self.img_pos_dev,
self.update_mask_dev,
video_target_timesteps,
t_video,
imgvid_cond_timestep,
),
(
"audio_target_timesteps",
self.audio_pos_dev,
self.audio_update_mask_dev,
audio_target_timesteps,
t_audio if self.locked_audio_rows is None else 1.0,
audio_ref_cond_timestep,
),
)
for name, positions, update_mask, target_timesteps, current_timestep, condition_timestep in timestep_groups:
target_positions = positions[update_mask]
if target_timesteps is None:
timesteps[target_positions] = current_timestep
else:
target_timesteps = target_timesteps.to(device=self.device, dtype=torch.float32).reshape(-1)
if target_timesteps.shape[0] != target_positions.shape[0]:
raise ValueError(
f"{name} rows {target_timesteps.shape[0]} != target rows {target_positions.shape[0]}"
)
timesteps[target_positions] = target_timesteps
timesteps[positions[~update_mask]] = condition_timestep
def minimax_h3_prepare_denoise_rows(
*,
@@ -273,6 +323,8 @@ def minimax_h3_denoise_loop(
initial_audio_rows: torch.Tensor,
keyframe_cond_rows: torch.Tensor | None,
audio_ref_rows: torch.Tensor | None = None,
video_edit: MiniMaxH3LatentEdit | None = None,
audio_edit: MiniMaxH3LatentEdit | None = None,
sigmas_video: list[float],
sigmas_audio: list[float],
device: torch.device,
@@ -307,6 +359,10 @@ def minimax_h3_denoise_loop(
)
update = positive.update_mask_dev
audio_update = positive.audio_update_mask_dev
if video_edit is not None:
video_edit = video_edit.to(device=device, dtype=torch.float32)
if audio_edit is not None:
audio_edit = audio_edit.to(device=device, dtype=torch.float32)
num_steps = len(sigmas_video) - 1
for step in range(num_steps):
@@ -323,40 +379,73 @@ def minimax_h3_denoise_loop(
imgvid_cond_t = max(t_v, float(imgvid_cond_noise_aug_for_inference))
audio_ref_cond_t = max(t_a, float(audio_cond_noise_aug_for_inference))
model_video_rows, video_target_timesteps = minimax_h3_prepare_edit_rows(
video_rows,
update,
video_edit,
t_v,
imgvid_cond_t,
sigma=s_v,
)
model_audio_rows, audio_target_timesteps = minimax_h3_prepare_edit_rows(
audio_rows,
audio_update,
audio_edit,
t_a,
audio_ref_cond_t,
sigma=s_a,
)
fk = positive.forward_kwargs(
video_rows=video_rows,
audio_rows=audio_rows,
video_rows=model_video_rows,
audio_rows=model_audio_rows,
t_video=t_v,
t_audio=t_a,
imgvid_cond_timestep=imgvid_cond_t,
audio_ref_cond_timestep=audio_ref_cond_t,
video_target_timesteps=video_target_timesteps,
audio_target_timesteps=audio_target_timesteps,
)
with torch.inference_mode():
v_video, v_audio = model(**fk)
mv_video_t = v_video.float()[update]
mv_audio_t = v_audio.float()[audio_update]
x0_video = minimax_h3_rf_v_to_x0(
video_rows[update],
mv_video_t,
torch.tensor(t_v, dtype=torch.float32, device=device),
)
if video_edit is None:
x0_video = minimax_h3_rf_v_to_x0(
video_rows[update],
mv_video_t,
torch.tensor(t_v, dtype=torch.float32, device=device),
)
else:
x0_video = video_edit.x0(
model_video_rows[update],
mv_video_t,
t_v,
)
new_target = minimax_h3_euler_eta0_step(video_rows[update], x0_video, sigma_curr=s_v, sigma_next=s_v_next)
video_rows = video_rows.clone()
video_rows[update] = new_target
if cond_anchor is not None:
video_rows[~update] = cond_anchor # per-step imgvid cond reset
x0_audio = minimax_h3_rf_v_to_x0(
audio_rows[audio_update],
mv_audio_t,
torch.tensor(t_a, dtype=torch.float32, device=device),
)
if audio_edit is None:
x0_audio = minimax_h3_rf_v_to_x0(
audio_rows[audio_update],
mv_audio_t,
torch.tensor(t_a, dtype=torch.float32, device=device),
)
else:
x0_audio = audio_edit.x0(
model_audio_rows[audio_update],
mv_audio_t,
t_a,
)
new_audio = minimax_h3_euler_eta0_step(
audio_rows[audio_update], x0_audio, sigma_curr=s_a, sigma_next=s_a_next
)
audio_rows = audio_rows.clone()
audio_rows[audio_update] = new_audio
audio_rows[audio_update] = new_audio if positive.locked_audio_rows is None else positive.locked_audio_rows
if audio_anchor is not None:
audio_rows[~audio_update] = audio_anchor # per-step audio ref reset
if on_step is not None:
@@ -102,6 +102,7 @@ _MODEL_LEVEL_TARGETS = {
"time_embedder.linear_2": "time_embedder.proj_out",
"norm_out.linear": "final_layer.adaln_proj.linear",
"norm_out.norm": "final_layer.norm",
"token_refiner.final_norm": "token_refiner.final_norm",
}
# Per-block adapter suffix -> (native suffix, how a delta enters the native
@@ -115,6 +116,8 @@ _BLOCK_TARGETS = {
"attn.to_v": ("attn.qkv_proj", _QKV_V),
"attn.to_out.0": ("attn.out_proj", _PLAIN),
"attn.to_gate_compress": ("attn.to_gate_compress", _PLAIN),
"attn.norm_q": ("attn.q_norm", _PLAIN),
"attn.norm_k": ("attn.k_norm", _PLAIN),
"ff.net.0.proj": ("mlp.fc1", _SWAP_HALVES),
"ff.net.2": ("mlp.fc2", _PLAIN),
"adaln_proj.linear": ("adaln_proj.linear", _PLAIN),
@@ -0,0 +1,131 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Sampling contract for FastVideo FastH3 full checkpoints."""
from __future__ import annotations
import json
import math
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any
from vllm_omni.diffusion.sched.sigma_schedule import DMD2SigmaSchedule
from vllm_omni.errors import OmniClientError
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
from .fasth3 import FASTH3_BASE_MODEL, _resolve_dit_attention_backend
if TYPE_CHECKING:
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
FASTH3_V2_MODEL_ID = "FastVideo/FastVideo-FastH3-8-Step-V2"
FASTH3_V2_BASE_SCHEDULE = DMD2SigmaSchedule.from_positions((0.999, 0.874, 0.749, 0.624, 0.5, 0.375, 0.25, 0.125, 0.0))
@dataclass(frozen=True)
class FastH3CheckpointSpec:
"""The full V2 release has its own schedule and trained attention policy.
This is independent of ``FastH3WeightFusion``: the released weights already
contain the entire student, including its learned compression gates.
"""
vsa_sparsity: float = 0.8
@classmethod
def from_metadata(cls, metadata: Mapping[str, object]) -> FastH3CheckpointSpec:
"""Validate the release's own fastvideo_inference.json."""
required = {
"model_id": FASTH3_V2_MODEL_ID,
"schema_version": "fasth3-inference-contract-v1",
"dmd_denoising_steps": [999, 874, 749, 624, 500, 375, 250, 125],
"transformer_forwards": 8,
"video_scheduler_shift": 10.0,
"audio_scheduler_shift": 3.0,
"guidance_scale": 1.0,
"attention_backend": "VIDEO_SPARSE_ATTN_H3",
"vsa_sparsity": 0.8,
"vsa_tile_size": 64,
"task": "t2av",
}
for key, expected in required.items():
if metadata.get(key) != expected:
raise ValueError(f"unsupported FastH3 contract: {key}={metadata.get(key)!r}, expected {expected!r}")
return cls()
def release_metadata(self) -> dict[str, Any]:
"""Express the sampling policy in the existing H3 pipeline schema."""
return {
"partition": "fl2va",
"tasks": ["t2va"],
"sigma_shift_scales": {"video": 10.0, "audio": 3.0},
"base_schedule": list(FASTH3_V2_BASE_SCHEDULE.base_schedule),
}
def resolve_native_vaes(self, model_root: Path) -> Path:
"""Reuse the frozen base VAEs with Omni's native tiled/parallel runtime.
Only VAE components are fetched; the student and text encoder come
directly from the FastVideo release. The release pins the base revision.
"""
provenance = json.loads((model_root / "provenance.json").read_text(encoding="utf-8"))
base = provenance.get("base_model", "")
prefix = f"hf://{FASTH3_BASE_MODEL}@"
if not isinstance(base, str) or not base.startswith(prefix) or not base[len(prefix) :]:
raise ValueError("FastH3 V2 provenance must pin a MiniMaxAI/MiniMax-H3 base revision")
return (
Path(
download_weights_from_hf_specific(
model_name_or_path=FASTH3_BASE_MODEL,
cache_dir=None,
allow_patterns=["FL2VA/video_vae/**", "FL2VA/audio_vae/**"],
revision=base[len(prefix) :],
require_all=True,
)
)
/ "FL2VA"
)
def check_serving_contract(self, *, partition: str, od_config: OmniDiffusionConfig) -> None:
if partition != "fl2va":
raise ValueError("FastH3 V2 requires --task-type fl2va (T2VA requests only)")
if getattr(od_config, "lora_path", None):
raise ValueError("FastH3 V2 is a full checkpoint; additional LoRA adapters are unsupported")
if _resolve_dit_attention_backend(od_config) != "FASTVIDEO_VSA":
raise ValueError("FastH3 V2 requires --diffusion-attention-backend FASTVIDEO_VSA")
attention_config = getattr(od_config, "diffusion_attention_config", None)
per_role = getattr(attention_config, "per_role", None) or {}
spec = per_role.get("self") or getattr(attention_config, "default", None)
if getattr(spec, "fastvideo_vsa_topk", None) is not None:
raise ValueError("FastH3 V2 pins VSA sparsity=0.8; remove the fixed fastvideo_vsa_topk override")
parallel = getattr(od_config, "parallel_config", None)
if any(int(getattr(parallel, key, 1) or 1) != 1 for key in ("ring_degree", "allgather_degree")):
raise ValueError("FastH3 V2 supports local attention or pure Ulysses sequence parallelism")
def check_request(self, sampling: OmniDiffusionSamplingParams, *, step_execution: bool = False) -> None:
if step_execution:
# StepScheduler admits requests before the pipeline hook runs and
# derives its lifetime from these fields. The pinned schedule must
# therefore be explicit and cannot be overridden by custom arrays.
if sampling.num_inference_steps != FASTH3_V2_BASE_SCHEDULE.num_inference_steps:
raise OmniClientError("FastH3 V2 step execution requires num_inference_steps=8")
if sampling.timesteps is not None or sampling.sigmas is not None:
raise OmniClientError("FastH3 V2 step execution does not support custom timesteps or sigmas")
if sampling.lora_request is not None:
raise OmniClientError("FastH3 V2 does not support per-request LoRA adapters")
steps = sampling.num_inference_steps
if steps is not None and steps != FASTH3_V2_BASE_SCHEDULE.num_inference_steps:
raise OmniClientError("FastH3 V2 requires num_inference_steps=8 (nine sigma points), or omitted")
extra = sampling.extra_args or {}
for key, expected in (("flow_shift", 10.0), ("audio_flow_shift", 3.0)):
try:
value = float(extra.get(key, expected))
except (TypeError, ValueError) as exc:
raise OmniClientError(f"FastH3 V2 requires {key}={expected:g}") from exc
if not math.isclose(value, expected):
raise OmniClientError(f"FastH3 V2 requires {key}={expected:g}, got {value:g}")
if sampling.guidance_scale is not None and sampling.guidance_scale != 1.0:
raise OmniClientError("FastH3 V2 requires guidance_scale=1")
@@ -0,0 +1,183 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""MiniMax H3 latent-edit mask parsing and sampler math."""
from __future__ import annotations
import math
from dataclasses import dataclass
import torch
from .scheduling_minimax_h3_euler_ancestral import minimax_h3_rf_v_to_x0
_MASK_LEVELS = 256.0
def _quantize(mask: torch.Tensor) -> torch.Tensor:
"""Match ComfyUI's token-grid mask used by H3's timestep embedding."""
return (torch.ceil(mask * _MASK_LEVELS) / _MASK_LEVELS).clamp_(0, 1)
@dataclass(frozen=True)
class MiniMaxH3ParsedMask:
"""Token mask for the model and raw mask for the final x0 restore."""
model_mask_rows: torch.Tensor
restore_mask_rows: torch.Tensor
def minimax_h3_video_edit_masks(
mask: torch.Tensor,
*,
latent_t: int,
latent_h: int,
latent_w: int,
) -> MiniMaxH3ParsedMask:
"""Map the canonical full-grid video mask to model and restore rows.
Full-grid masks are max-pooled over each 2x2 DiT token. Their raw four
cells are repeated in the packed 24-channel feature order for restoration.
"""
latent_t, latent_h, latent_w = int(latent_t), int(latent_h), int(latent_w)
if latent_t <= 0 or latent_h <= 0 or latent_w <= 0 or latent_h % 2 or latent_w % 2:
raise ValueError("video latent dimensions must be positive and spatially even")
token_shape = (latent_t, latent_h // 2, latent_w // 2)
full_shape = (latent_t, latent_h, latent_w)
row_count = math.prod(token_shape)
if mask.dtype != torch.float32 or tuple(mask.shape) != full_shape or not mask.is_contiguous():
raise ValueError(f"canonical video mask must be contiguous FP32 with shape {full_shape}")
cells = mask.reshape(latent_t, latent_h // 2, 2, latent_w // 2, 2).permute(0, 1, 3, 2, 4).contiguous()
model = _quantize(cells.amax(dim=(3, 4)).reshape(-1))
restore = cells.unsqueeze(3).expand(*cells.shape[:3], 24, 2, 2).reshape(row_count, 96).clone()
return MiniMaxH3ParsedMask(model, restore)
def minimax_h3_audio_edit_masks(mask: torch.Tensor, *, audio_t: int) -> MiniMaxH3ParsedMask:
"""Flatten the canonical channel-major audio mask to H3 row order."""
audio_t = int(audio_t)
if audio_t <= 0:
raise ValueError("audio_t must be positive")
expected_shape = (2, audio_t)
if mask.dtype != torch.float32 or tuple(mask.shape) != expected_shape or not mask.is_contiguous():
raise ValueError(f"canonical audio mask must be contiguous FP32 with shape {expected_shape}")
rows = mask.reshape(-1).clone()
return MiniMaxH3ParsedMask(_quantize(rows), rows)
@dataclass(frozen=True)
class MiniMaxH3LatentEdit:
"""Clean source, model anchor, and masks for one packed latent stream."""
clean_rows: torch.Tensor
anchor_rows: torch.Tensor
mask_rows: torch.Tensor
restore_mask_rows: torch.Tensor
@classmethod
def from_rows(
cls,
clean_rows: torch.Tensor,
anchor_rows: torch.Tensor,
mask_rows: torch.Tensor,
restore_mask_rows: torch.Tensor,
) -> MiniMaxH3LatentEdit:
"""Create an edit from already-validated encoder outputs.
Value validation and all-generate elision belong at the encoder input
boundary. This constructor only normalizes devices/dtypes and checks
the cheap row-shape invariants needed by the sampler math.
"""
if clean_rows.ndim != 2 or anchor_rows.shape != clean_rows.shape:
raise ValueError("clean_rows and anchor_rows must have matching [rows, width] shape")
raw_mask = torch.as_tensor(mask_rows, dtype=torch.float32, device=clean_rows.device)
if raw_mask.ndim != 1 or raw_mask.numel() != clean_rows.shape[0]:
raise ValueError(f"mask_rows must have shape ({clean_rows.shape[0]},)")
restore = torch.as_tensor(restore_mask_rows, dtype=torch.float32, device=clean_rows.device)
valid_restore = restore.ndim == 1 and restore.shape == raw_mask.shape
valid_restore |= restore.ndim == 2 and tuple(restore.shape) in {
(clean_rows.shape[0], 1),
tuple(clean_rows.shape),
}
if not valid_restore:
raise ValueError("restore_mask_rows must have one scalar or one feature row per clean row")
return cls(clean_rows, anchor_rows, raw_mask, restore)
def to(self, *, device: torch.device, dtype: torch.dtype = torch.float32) -> MiniMaxH3LatentEdit:
return MiniMaxH3LatentEdit(
self.clean_rows.to(device=device, dtype=dtype),
self.anchor_rows.to(device=device, dtype=dtype),
self.mask_rows.to(device=device),
self.restore_mask_rows.to(device=device),
)
def model_rows(self, state_rows: torch.Tensor) -> torch.Tensor:
return torch.lerp(self.anchor_rows, state_rows, self.mask_rows.to(state_rows.dtype).unsqueeze(-1))
def target_timesteps(
self,
timestep: float,
condition_timestep: float,
*,
sigma: float | None = None,
) -> torch.Tensor:
sigma = 1.0 - timestep if sigma is None else float(sigma)
return torch.clamp(1.0 - self.mask_rows * sigma, max=condition_timestep)
def prepare(
self,
state_rows: torch.Tensor,
timestep: float,
condition_timestep: float,
*,
sigma: float,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Prepare the model rows and per-row timesteps for one denoise step."""
return (
self.model_rows(state_rows),
self.target_timesteps(timestep, condition_timestep, sigma=sigma),
)
def x0(self, model_rows: torch.Tensor, velocity: torch.Tensor, timestep: float) -> torch.Tensor:
weight = self.mask_rows.to(model_rows.dtype).unsqueeze(-1)
predicted = minimax_h3_rf_v_to_x0(
model_rows,
velocity.to(model_rows.dtype) * weight,
torch.tensor(float(timestep), dtype=model_rows.dtype, device=model_rows.device),
)
restore = self.restore_mask_rows.to(model_rows.dtype)
if restore.ndim == 1:
restore = restore.unsqueeze(-1)
return torch.lerp(self.clean_rows, predicted, restore)
def minimax_h3_prepare_edit_rows(
rows: torch.Tensor,
update_mask: torch.Tensor,
edit: MiniMaxH3LatentEdit | None,
timestep: float,
condition_timestep: float,
*,
sigma: float,
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""Build one model input view without mutating the persistent sampler rows."""
if edit is None:
return rows, None
model_rows = rows.clone()
model_rows[update_mask], target_timesteps = edit.prepare(
rows[update_mask],
timestep,
condition_timestep,
sigma=sigma,
)
return model_rows, target_timesteps
__all__ = [
"MiniMaxH3LatentEdit",
"MiniMaxH3ParsedMask",
"minimax_h3_audio_edit_masks",
"minimax_h3_prepare_edit_rows",
"minimax_h3_video_edit_masks",
]
@@ -33,24 +33,30 @@ from vllm_omni.diffusion.attention.backends.abstract import (
VideoTokenLayout,
)
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.attention.ops.minimax_h3_modulation import (
indexed_gate,
indexed_gate_rms_norm_scale_shift,
indexed_scale_shift_,
rms_norm_indexed_scale_shift,
)
from vllm_omni.diffusion.cache.cachedit import CacheDiTAdapterConfig
from vllm_omni.diffusion.distributed.sp_plan import (
SequenceParallelInput,
SequenceParallelOutput,
)
from vllm_omni.diffusion.forward_context import (
get_forward_context,
is_forward_context_available,
)
from vllm_omni.diffusion.layers.activation import SiluAndMul
from vllm_omni.diffusion.layers.fused_qk_norm_rope import fused_qk_norm_rope
from vllm_omni.diffusion.layers.indexed_modulation import (
indexed_gate,
indexed_gate_rms_norm_scale_shift,
indexed_scale_shift_,
rms_norm_indexed_scale_shift,
)
from vllm_omni.diffusion.layers.norm import RMSNorm
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
from vllm_omni.diffusion.models.host_weight_contract import FinalLayoutModelContract
from vllm_omni.platforms import current_omni_platform
from .fasth3 import _resolve_native_target
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
@@ -67,6 +73,15 @@ logger = init_logger(__name__)
# packing, and ``_run_packed_attention`` re-checks it per forward; a name-only
# gate would let FLASH_ATTN's NPU/XPU code paths through even though those
# variants would silently attend across request boundaries.
def _ring_sequence_parallel_is_active(attention_layer: Attention) -> bool:
"""Match :meth:`Attention._get_active_parallel_strategy` for Ring."""
if not getattr(attention_layer, "use_ring", False) or getattr(attention_layer, "skip_sequence_parallel", False):
return False
if is_forward_context_available() and not get_forward_context().sp_active:
return False
return True
def _attention_isolates_packed_requests(attention_layer: Any) -> bool:
"""True if this attention layer keeps N-document packed boundaries.
@@ -78,7 +93,7 @@ def _attention_isolates_packed_requests(attention_layer: Any) -> bool:
backend = getattr(attention_layer, "attn_backend", None)
if backend is None or not backend.supports_multi_doc_packed_varlen():
return False
return not getattr(attention_layer, "use_ring", False)
return not _ring_sequence_parallel_is_active(attention_layer)
@dataclass
@@ -105,6 +120,18 @@ class MiniMaxH3DiTArchConfig:
@classmethod
def from_mapping(cls, config: Mapping[str, Any]) -> MiniMaxH3DiTArchConfig:
# The modular Diffusers checkpoint uses these spellings for the same
# architecture. Normalize before constructing the existing native DiT.
aliases = {
"num_refiner_layers": "token_refiner_num_layers",
"ffn_dim": "ffn_hidden_size",
"in_channels": "latents_dim",
"audio_in_channels": "audio_latents_dim",
"freq_dim": "timestep_input_dim",
"time_embed_hidden_dim": "time_embed_hidden_size",
"rope_freq_dim": "rope_inv_freq_len",
}
config = {aliases.get(name, name): value for name, value in config.items()}
fields = cls.__dataclass_fields__
values = {name: config[name] for name in fields if name in config}
if "patch_size" in values:
@@ -381,6 +408,9 @@ def _sdpa_varlen_attention(
class MiniMaxH3Attention(nn.Module):
# Full sparse checkpoints pin a ratio; legacy adapters use backend top-k.
vsa_sparsity: float | None = None
def __init__(
self,
arch: MiniMaxH3DiTArchConfig,
@@ -429,6 +459,8 @@ class MiniMaxH3Attention(nn.Module):
self._gate_hidden_size = arch.hidden_size
self._gate_quant_config = quant_config
self._gate_prefix = f"{prefix}.to_gate_compress"
from .attention.fastvideo_h3 import MiniMaxH3VSAImpl
self.attention = Attention(
num_heads=self.num_heads,
num_kv_heads=self.num_kv_heads,
@@ -441,6 +473,7 @@ class MiniMaxH3Attention(nn.Module):
role_category=role_category,
skip_sequence_parallel=skip_sequence_parallel,
prefix=prefix,
impl_overrides={"FASTVIDEO_VSA": MiniMaxH3VSAImpl},
)
def enable_vsa_gate(self) -> None:
@@ -508,6 +541,7 @@ class MiniMaxH3Attention(nn.Module):
)
attn_mask = None
mask_free_packed_padding = False
use_ring = _ring_sequence_parallel_is_active(self.attention)
if num_requests > 1:
# A step-mode batch packs one document per request, so its valid
# rows are block-diagonal rather than a prefix: neither a KV prefix
@@ -534,12 +568,15 @@ class MiniMaxH3Attention(nn.Module):
# supports_packed_mask_free: backend consumes the packed metadata
# without ever reading attn_mask (CUDA packed varlen, NPU
# npu_attn_varlen opt-in with its own fallback rebuild).
use_ring = getattr(self.attention, "use_ring", False)
mask_free_packed_padding = not use_ring and self.attention.attn_backend.supports_packed_mask_free()
no_mask = not use_ring and (
self.attention.attn_backend.supports_prefix_kv_slicing or mask_free_packed_padding
)
if used < packed_total and not no_mask:
# Hybrid Ulysses reshards Q to one ring partition before the ring
# kernel runs, so a global [packed_total] mask cannot pass its
# query-length check. Ring consumes valid_kv_length directly and
# trims the circulated K/V blocks instead.
if used < packed_total and not no_mask and not use_ring:
attn_mask = torch.arange(packed_total, device=q.device)[None] < used
metadata = AttentionMetadata(
attn_mask=attn_mask,
@@ -563,11 +600,12 @@ class MiniMaxH3Attention(nn.Module):
# quadratic full_qk mask is never materialized. Ring attention
# is excluded: it keeps the aligned padding rows for its
# fixed-size P2P buffers and still needs the mask.
"npu_attn_varlen": not getattr(self.attention, "use_ring", False),
"npu_attn_varlen": not use_ring,
# fp16-range protection for the ascend_laser_attention kernel
# (see MINIMAX_H3_LASER_INPUT_SCALE). Ignored by every other
# backend/path.
"laser_input_scale": MINIMAX_H3_LASER_INPUT_SCALE,
**({"vsa_h3_sparsity": self.vsa_sparsity} if self.vsa_sparsity is not None else {}),
# Present only for a VSA artifact; the VSA backend reads it as
# the learned compression gate and every other backend ignores it.
**({"gate_compress": gate_compress.unsqueeze(0)} if gate_compress is not None else {}),
@@ -1107,10 +1145,23 @@ class MiniMaxH3DiTModel(nn.Module):
self,
od_config: OmniDiffusionConfig,
quant_config: QuantizationConfig | None = None,
*,
diffusers_weights: bool | None = None,
) -> None:
super().__init__()
tf_config = od_config.tf_model_config
config_mapping = tf_config.to_dict() if hasattr(tf_config, "to_dict") else dict(tf_config)
# The native MiniMax-H3 Hub snapshot advertises the Diffusers
# transformer class in its root config, while its FL2VA/Ref2VA
# components still contain native weights. The pipeline has already
# resolved the actual source format, so let it override the
# class-name heuristic. Keep the heuristic for standalone callers.
self._diffusers_weights = (
config_mapping.get("_class_name") == "MiniMaxH3Transformer3DModel"
if diffusers_weights is None
else diffusers_weights
)
self._rope_theta = float(config_mapping.get("rope_theta", 10000.0))
arch = MiniMaxH3DiTArchConfig.from_mapping(config_mapping)
self.arch = arch
self.od_config = od_config
@@ -1191,7 +1242,7 @@ class MiniMaxH3DiTModel(nn.Module):
)
self._mark_missing_params_required()
def enable_vsa_gates(self) -> None:
def enable_vsa_gates(self, *, sparsity: float | None = None) -> None:
"""Give every DiT block's attention a VSA compression gate.
A FastH3 VSA artifact assigns these projections rather than adding to
@@ -1203,6 +1254,9 @@ class MiniMaxH3DiTModel(nn.Module):
return
for block in self.blocks:
block.attn.enable_vsa_gate()
block.attn.vsa_sparsity = sparsity
if sparsity is not None:
block.attn.to_gate_compress.weight.missing_param_init = "error"
self.vsa_gates_enabled = True
def _mark_missing_params_required(self) -> None:
@@ -1273,17 +1327,37 @@ class MiniMaxH3DiTModel(nn.Module):
self,
weights: Iterable[tuple[str, torch.Tensor]],
) -> set[str]:
"""Load exact H3 checkpoint names with logical TP-aware loaders."""
"""Load native or Diffusers H3 weights with the existing TP-aware loaders."""
params = dict(self.named_parameters())
params.update(dict(self.named_buffers()))
loaded: set[str] = set()
diffusers_weights = getattr(self, "_diffusers_weights", False)
qkv_parts: dict[str, set[str]] = {}
source_names: set[str] = set()
for name, loaded_weight in weights:
layout = "plain"
if diffusers_weights:
if name in source_names:
raise ValueError(f"duplicate Diffusers H3 weight: {name}")
source_names.add(name)
module, _, kind = name.rpartition(".")
target = _resolve_native_target(module)
if target is None or kind not in {"weight", "bias"}:
raise ValueError(f"unsupported Diffusers H3 weight: {name}")
name, layout = f"{target[0]}.{kind}", target[1]
param = params.get(name)
if param is None:
if diffusers_weights:
raise ValueError(f"Diffusers H3 weight has no model parameter: {name}")
logger.warning("Skipping MiniMax H3 weight not present in model: %s", name)
continue
weight_loader = getattr(param, "weight_loader", default_weight_loader)
if name.endswith(".attn.qkv_proj.weight"):
if layout in {"q", "k", "v"}:
# vLLM can load each projection directly into its packed QKV
# parameter, including TP slicing and online quantization.
weight_loader(param, loaded_weight, layout)
qkv_parts.setdefault(name, set()).add(layout)
elif name.endswith(".attn.qkv_proj.weight"):
# Transform checkpoint layout before entering vLLM's loader so
# online FP8 can keep ``online_process_loader`` outermost.
loaded_weight = _reorder_grouped_qkv_to_qkv(
@@ -1299,12 +1373,26 @@ class MiniMaxH3DiTModel(nn.Module):
"MiniMax H3 fc1 checkpoint rows must split evenly into "
f"gate/up matrices, got {tuple(loaded_weight.shape)}"
)
gate, up = loaded_weight.chunk(2, dim=0)
first, second = loaded_weight.chunk(2, dim=0)
gate, up = (second, first) if layout == "swap_halves" else (first, second)
weight_loader(param, gate, 0)
weight_loader(param, up, 1)
else:
weight_loader(param, loaded_weight)
loaded.add(name)
if diffusers_weights:
for name, parts in qkv_parts.items():
if parts != {"q", "k", "v"}:
raise ValueError(f"incomplete Diffusers H3 QKV group {name}: {sorted(parts)}")
# Diffusers reconstructs RoPE from config instead of storing this
# native checkpoint buffer. Compute on CPU for identical values.
freq_dim = self.arch.rope_inv_freq_len
rope = 1.0 / (
self._rope_theta
** (torch.arange(0, 2 * freq_dim, 2, dtype=torch.float32, device="cpu") / (2 * freq_dim))
)
default_weight_loader(params["rope.inv_freq"], rope)
loaded.add("rope.inv_freq")
return loaded
@staticmethod
@@ -11,18 +11,26 @@ if HAS_TRITON:
@triton.jit
def _qk_rms_norm_rope_exact_kernel(
x_ptr,
q_ptr,
k_ptr,
cos_ptr,
sin_ptr,
output_ptr,
x_stride_token,
x_stride_head,
x_stride_dim,
q_output_ptr,
k_output_ptr,
q_stride_token,
q_stride_head,
q_stride_dim,
k_stride_token,
k_stride_head,
k_stride_dim,
rope_stride_token,
rope_stride_dim,
output_stride_token,
output_stride_head,
output_stride_dim,
q_output_stride_token,
q_output_stride_head,
q_output_stride_dim,
k_output_stride_token,
k_output_stride_head,
k_output_stride_dim,
num_heads: tl.constexpr,
head_dim: tl.constexpr,
rotary_dim: tl.constexpr,
@@ -31,12 +39,15 @@ if HAS_TRITON:
):
token = tl.program_id(0)
head_group = tl.program_id(1)
qk_domain = tl.program_id(2)
heads = head_group * heads_per_program + tl.arange(0, heads_per_program)
dims = tl.arange(0, head_dim)
mask = heads[:, None] < num_heads
offsets = token * x_stride_token + heads[:, None] * x_stride_head + dims[None, :] * x_stride_dim
x = tl.load(x_ptr + offsets, mask=mask, other=0.0).to(tl.float32)
q_offsets = token * q_stride_token + heads[:, None] * q_stride_head + dims[None, :] * q_stride_dim
k_offsets = token * k_stride_token + heads[:, None] * k_stride_head + dims[None, :] * k_stride_dim
x_ptrs = tl.where(qk_domain == 0, q_ptr + q_offsets, k_ptr + k_offsets)
x = tl.load(x_ptrs, mask=mask, other=0.0).to(tl.float32)
inv_rms = tl.rsqrt(tl.sum(x * x, axis=1) / head_dim + eps)
normalized = (x * inv_rms[:, None]).to(tl.float16)
@@ -46,8 +57,10 @@ if HAS_TRITON:
dims + rotary_half,
tl.where(dims < rotary_dim, dims - rotary_half, dims),
)
pair_offsets = token * x_stride_token + heads[:, None] * x_stride_head + pair_dims[None, :] * x_stride_dim
pair_x = tl.load(x_ptr + pair_offsets, mask=mask, other=0.0).to(tl.float32)
q_pair_offsets = token * q_stride_token + heads[:, None] * q_stride_head + pair_dims[None, :] * q_stride_dim
k_pair_offsets = token * k_stride_token + heads[:, None] * k_stride_head + pair_dims[None, :] * k_stride_dim
pair_x_ptrs = tl.where(qk_domain == 0, q_ptr + q_pair_offsets, k_ptr + k_pair_offsets)
pair_x = tl.load(pair_x_ptrs, mask=mask, other=0.0).to(tl.float32)
pair_normalized = (pair_x * inv_rms[:, None]).to(tl.float16)
rope_mask = dims < rotary_dim
@@ -79,10 +92,18 @@ if HAS_TRITON:
)
output = tl.where(rope_mask[None, :], rotated, normalized)
output_offsets = (
token * output_stride_token + heads[:, None] * output_stride_head + dims[None, :] * output_stride_dim
q_output_offsets = (
token * q_output_stride_token + heads[:, None] * q_output_stride_head + dims[None, :] * q_output_stride_dim
)
tl.store(output_ptr + output_offsets, output, mask=mask)
k_output_offsets = (
token * k_output_stride_token + heads[:, None] * k_output_stride_head + dims[None, :] * k_output_stride_dim
)
output_ptrs = tl.where(
qk_domain == 0,
q_output_ptr + q_output_offsets,
k_output_ptr + k_output_offsets,
)
tl.store(output_ptrs, output, mask=mask)
def _supported_inputs(
@@ -143,11 +164,11 @@ def try_qk_norm_rope_exact(
sin = sin.reshape(tokens, sin.shape[-1])
q_output = torch.empty_like(q)
k_output = torch.empty_like(k)
# This launch layout is part of the exactness contract on the validated
# SM90 and SM103 targets: changing the warp-to-row mapping changes the
# FP32 RMS reduction order.
# The first two launch dimensions are part of the exactness contract on
# the validated SM90 and SM103 targets: changing the warp-to-row mapping
# changes the FP32 RMS reduction order.
heads_per_program = 8
grid = (tokens, triton.cdiv(heads, heads_per_program))
grid = (tokens, triton.cdiv(heads, heads_per_program), 2)
launch_args = {
"num_heads": heads,
"head_dim": head_dim,
@@ -158,29 +179,22 @@ def try_qk_norm_rope_exact(
}
_qk_rms_norm_rope_exact_kernel[grid](
q,
cos,
sin,
q_output,
q.stride(0),
q.stride(1),
q.stride(2),
cos.stride(0),
cos.stride(1),
q_output.stride(0),
q_output.stride(1),
q_output.stride(2),
**launch_args,
)
_qk_rms_norm_rope_exact_kernel[grid](
k,
cos,
sin,
q_output,
k_output,
q.stride(0),
q.stride(1),
q.stride(2),
k.stride(0),
k.stride(1),
k.stride(2),
cos.stride(0),
cos.stride(1),
q_output.stride(0),
q_output.stride(1),
q_output.stride(2),
k_output.stride(0),
k_output.stride(1),
k_output.stride(2),
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""MiniMax H3 packed-sequence materialization for FL2VA and Ref2VA tasks.
Layout: [text L | imgvid_cond C | audio A(=t*2ch) | video_target V | pad P].
@@ -13,11 +14,14 @@ Builder rules:
from __future__ import annotations
import math
from collections.abc import Mapping, Sequence
import numpy as np
import torch
from vllm_omni.errors import OmniClientError
MINIMAX_H3_FL2VA_KEYFRAME_SIGNATURES: tuple[tuple[int, ...], ...] = (
(0,),
(-1,),
@@ -38,13 +42,42 @@ _INTERP = 32
_T_GROUP = 5
_FRAME_PER_TOKEN = (1, 4, 4, 4, 4)
_FRAME_RESCALE = 5.0 / 3.0
_SEQ_ALIGN = 64
MINIMAX_H3_SEQ_ALIGN = 64
"""Row alignment of the packed sequence.
An explicit ``seq_len`` must be a multiple of this, so that pinning a length
lands on a bucket the default rounding could also produce.
"""
MINIMAX_H3_MAX_PAD_SEQ_LEN = 1 << 20
"""Ceiling for a request-pinned packed length.
Every packed row costs a fixed number of bytes across the structural tensors
built below, so an unbounded request value would size those allocations. The
largest shape this pipeline is documented against -- 672x384 at 209 frames --
packs about 16k rows, so this ceiling leaves roughly two orders of magnitude of
headroom while keeping the structural tensors in the tens of megabytes.
"""
# MiniMax H3 packs video latents with a fixed [1, 2, 2] (t, h, w) patch.
_PATCH_T = 1
_PATCH_H = 2
_PATCH_W = 2
def _resolve_padded_seq_len(used: int, seq_len: int | None) -> int:
"""Resolve the padded row count for a packed sequence.
Without an explicit ``seq_len`` the used rows are rounded up to the next
:data:`MINIMAX_H3_SEQ_ALIGN` boundary. An explicit value is honored as-is
and must cover the used rows.
"""
if seq_len is None:
return ((used + MINIMAX_H3_SEQ_ALIGN - 1) // MINIMAX_H3_SEQ_ALIGN) * MINIMAX_H3_SEQ_ALIGN
if seq_len < used:
raise OmniClientError(f"seq_len {seq_len} < used rows {used}")
return seq_len
def _keyframe_cond_frame_indices(
*,
include_keyframe_cond: bool,
@@ -124,10 +157,15 @@ def minimax_h3_packed_sequence(
include_keyframe_cond: bool,
keyframe_frame_indices: list[int] | tuple[int, ...] | None = None,
frame_count: int | None = None,
seq_len: int | None = None,
) -> dict[str, object]:
"""Build the packed-sequence structural fields for one CFG branch.
The used length is padded up to a multiple of 64.
The used length is padded up to a multiple of
:data:`MINIMAX_H3_SEQ_ALIGN`, or to an explicit ``seq_len`` that covers the
used rows -- the same contract
:func:`minimax_h3_packed_sequence_ref2va_blocks` already offers. Pinning
the length keeps requests of different prompt lengths on one packed shape.
"""
ph, pw = latent_h // _PATCH_H, latent_w // _PATCH_W
frame_rows = ph * pw
@@ -143,7 +181,7 @@ def minimax_h3_packed_sequence(
video_rows = latent_t * frame_rows
audio_rows = audio_t * audio_channel
used = text_len + cond_rows + audio_rows + video_rows
seq_len = ((used + _SEQ_ALIGN - 1) // _SEQ_ALIGN) * _SEQ_ALIGN
seq_len = _resolve_padded_seq_len(used, seq_len)
text_sl = slice(0, text_len)
cond_sl = slice(text_len, text_len + cond_rows)
@@ -308,6 +346,8 @@ def minimax_h3_packed_sequence_ref2va_blocks(
ref_blocks: Sequence[Mapping[str, object]],
audio_channel: int = 2,
seq_len: int | None = None,
temporal_offset: float = 0.0,
media_time_origin: int | None = None,
) -> dict[str, object]:
"""General ref2va-family packed layout.
@@ -316,12 +356,22 @@ def minimax_h3_packed_sequence_ref2va_blocks(
- ``{"kind": "audio", "ref_audio_t": T}``
- ``{"kind": "video"|"video_audio", "ref_audio_t": T,
"latent_t": RT, "latent_h": RH, "latent_w": RW}``
- Internal ``latent_guide``: a final AV condition block on the target's
spatial grid and temporal origin, without advancing the reference clock.
Video-bearing blocks pack their audio rows immediately before their video
rows; both share the same temporal origin and advance by the longer of the
audio and video spans. Standalone audio advances the target origin by its
own T, and image blocks advance it by one integer slot.
``temporal_offset`` is the window origin in 40-Hz RoPE units. It shifts
target AV, reference AV and latent guides together, leaving text, static
images, padding and all spatial coordinates unchanged.
"""
if not math.isfinite(temporal_offset) or temporal_offset < 0:
raise ValueError("temporal_offset must be finite and non-negative")
if media_time_origin is not None and media_time_origin < text_len:
raise ValueError("media_time_origin must follow the text prefix")
if not isinstance(ref_blocks, Sequence) or isinstance(ref_blocks, (str, bytes)):
raise ValueError("ref_blocks must be a sequence")
@@ -346,11 +396,15 @@ def minimax_h3_packed_sequence_ref2va_blocks(
rows = rt * audio_channel
item = {"kind": kind, "ref_audio_t": rt, "audio_rows": rows}
ref_audio_rows += rows
elif kind in ("video", "video_audio"):
elif kind in ("video", "video_audio", "latent_guide"):
rt = _positive_int(raw, "ref_audio_t", path, allow_zero=True)
vt = _positive_int(raw, "latent_t", path)
vh = _positive_int(raw, "latent_h", path)
vw = _positive_int(raw, "latent_w", path)
if kind == "latent_guide" and (
index != len(ref_blocks) - 1 or (vh, vw) != (latent_h, latent_w) or vt > latent_t or rt > audio_t
):
raise ValueError("latent_guide must be last, match the target canvas, and fit its AV lengths")
frame_rows = (vh // _PATCH_H) * (vw // _PATCH_W)
audio_rows = rt * audio_channel
video_rows = vt * frame_rows
@@ -376,10 +430,7 @@ def minimax_h3_packed_sequence_ref2va_blocks(
audio_rows = audio_t * audio_channel
ref_rows = ref_visual_rows + ref_audio_rows
used = text_len + ref_rows + audio_rows + video_rows
if seq_len is None:
seq_len = ((used + _SEQ_ALIGN - 1) // _SEQ_ALIGN) * _SEQ_ALIGN
if seq_len < used:
raise ValueError(f"seq_len {seq_len} < used rows {used}")
seq_len = _resolve_padded_seq_len(used, seq_len)
text_sl = slice(0, text_len)
cursor = text_len
@@ -413,7 +464,7 @@ def minimax_h3_packed_sequence_ref2va_blocks(
# device-to-host synchronization.
video_spans: list[dict[str, object]] = []
for item in block_slices:
if item["kind"] in ("video", "video_audio"):
if item["kind"] in ("video", "video_audio", "latent_guide"):
visual_sl = item["visual_sl"]
assert isinstance(visual_sl, slice)
video_spans.append(
@@ -451,7 +502,7 @@ def minimax_h3_packed_sequence_ref2va_blocks(
hh, ww = torch.meshgrid(h_grid, w_grid, indexing="ij")
target_frame = torch.stack([hh.reshape(-1), ww.reshape(-1)], dim=-1)
t_cursor = float(text_len)
t_cursor = float(text_len if media_time_origin is None else media_time_origin)
for item in block_slices:
kind = str(item["kind"])
if kind == "image":
@@ -533,7 +584,8 @@ def minimax_h3_packed_sequence_ref2va_blocks(
rv_g[:, :, 0] = _video_t_grid(vt, t_cursor)[:, None]
rv_g[:, :, 1:] = rv_frame[None]
g[visual_sl] = rv_g.reshape(-1, 3)
t_cursor += max(float(ref_t), _video_t_span(vt))
if kind != "latent_guide":
t_cursor += max(float(ref_t), _video_t_span(vt))
input_ids[audio_sl] = MINIMAX_H3_AUDIO_ID
input_ids[audio_sl.start] = MINIMAX_H3_AUDIO_FIRST_ID
@@ -557,6 +609,13 @@ def minimax_h3_packed_sequence_ref2va_blocks(
video_g[:, :, 1:] = target_frame[None]
g[video_sl] = video_g.reshape(-1, 3)
if temporal_offset:
g[audio_mask, 0] += temporal_offset
g[video_sl, 0] += temporal_offset
for item in block_slices:
if item["kind"] in ("video", "video_audio", "latent_guide"):
g[item["visual_sl"], 0] += temporal_offset
target_img_pos = _range_for_slice(video_sl)
target_audio_pos = _range_for_slice(audio_sl)
img_pos = _cat_ranges(ref_img_pos_parts + [target_img_pos])
File diff suppressed because it is too large. Load diff
+636 -37
View File
@@ -6,17 +6,21 @@ from __future__ import annotations
import importlib
import json
import os
from collections.abc import Iterator
from contextlib import AbstractContextManager, contextmanager, nullcontext
from pathlib import Path
from typing import Any, ClassVar
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
from PIL import Image
from safetensors import safe_open
from transformers.dynamic_module_utils import get_class_from_dynamic_module
from vllm.logger import init_logger
from vllm.utils.torch_utils import set_default_torch_dtype
from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor import (
DistributedVaeMixin,
@@ -31,11 +35,15 @@ from vllm_omni.diffusion.offloader.module_residency import (
from .chunked_decode import decode_h3_chunks
from .ops import install_h3_vae_optimizations
from .packed_tokens import minimax_h3_patchify_video_latent
from .vae_temporal import install_temporal_stream_patches
MINIMAX_H3_KEYFRAME_ENCODE_SEED = 42
MINIMAX_H3_AUDIO_SAMPLE_RATE = 32000
MINIMAX_H3_AUDIO_CHANNELS = 2
# Escape hatch back to the checkpoint's whole-video numpy preparation path.
_VAE_ENCODE_LEGACY_PREP_ENV = "VLLM_OMNI_VAE_ENCODE_LEGACY_PREP"
logger = init_logger(__name__)
@@ -61,6 +69,11 @@ def _minimax_h3_keyframe_encode_context(
yield
def _legacy_encode_prep_enabled() -> bool:
value = os.environ.get(_VAE_ENCODE_LEGACY_PREP_ENV, "0")
return value.strip().lower() not in ("", "0", "false", "off")
def _load_component_config(component_path: str) -> dict[str, Any]:
config_path = Path(component_path) / "config.json"
config = json.loads(config_path.read_text(encoding="utf-8"))
@@ -75,11 +88,23 @@ def _load_component_config(component_path: str) -> dict[str, Any]:
def _load_remote_component(
component_path: str,
config: dict[str, Any],
*,
trust_remote_code: bool,
) -> nn.Module:
auto_map = config.get("auto_map") or {}
class_reference = auto_map.get("AutoModel")
if not isinstance(class_reference, str):
raise ValueError(f"{component_path}/config.json must define auto_map.AutoModel")
if not trust_remote_code:
raise ValueError(
f"Loading {component_path} executes the modeling code shipped with "
f"the checkpoint (auto_map.AutoModel = {class_reference}). Pass "
"--trust-remote-code (or trust_remote_code=True) to allow it."
)
# ``trust_remote_code`` is checked here rather than forwarded to
# ``get_class_from_dynamic_module``: that helper takes no such argument and
# would silently absorb it into ``**kwargs``, so forwarding it would read
# like a gate while executing the remote code unconditionally.
component_cls = get_class_from_dynamic_module(
class_reference,
component_path,
@@ -94,6 +119,121 @@ def _load_remote_component(
return component_cls.from_pretrained(component_path)
def _check_trust_remote_code(
component_path: str,
config: dict[str, Any],
trust_remote_code: bool,
) -> None:
"""Apply the remote-code gate before either full or encoder-only loading."""
class_reference = (config.get("auto_map") or {}).get("AutoModel")
if isinstance(class_reference, str) and not trust_remote_code:
raise ValueError(
f"Loading {component_path} executes the modeling code shipped with "
f"the checkpoint (auto_map.AutoModel = {class_reference}). Pass "
"--trust-remote-code (or trust_remote_code=True) to allow it."
)
def _load_selected_state_dict(
model: nn.Module,
weights_path: Path,
prefixes: tuple[str, ...],
) -> None:
with safe_open(str(weights_path), framework="pt", device="cpu") as checkpoint:
selected = sorted(name for name in checkpoint.keys() if name.startswith(prefixes))
if not selected:
raise ValueError(f"{weights_path}: no VAE weights match prefixes {prefixes!r}")
state_dict = {name: checkpoint.get_tensor(name) for name in selected}
model.load_state_dict(state_dict, strict=True)
def _remove_modules(model: nn.Module, names: tuple[str, ...]) -> None:
for name in names:
if not isinstance(getattr(model, name, None), nn.Module):
raise ValueError(f"MiniMax H3 VAE model has no module {name!r}")
delattr(model, name)
def _load_video_vae_encoder(
component_path: str,
config: dict[str, Any],
) -> nn.Module:
class_reference = (config.get("auto_map") or {}).get("AutoModel")
if not isinstance(class_reference, str):
raise ValueError(f"{component_path}/config.json must define auto_map.AutoModel")
component_cls = get_class_from_dynamic_module(class_reference, component_path)
component_module = importlib.import_module(component_cls.__module__)
source_classes = getattr(component_module, "_SOURCE_CLASSES", None)
source_class_name = config.get("source_class_name")
if not isinstance(source_classes, dict) or source_class_name not in source_classes:
raise ValueError(f"unsupported MiniMax H3 video VAE source class {source_class_name!r}")
if bool(config["vae_parallel_tiling"]):
ensure_parallel_state = getattr(component_module, "_ensure_vae_parallel_state", None)
if not callable(ensure_parallel_state):
raise ValueError("MiniMax H3 video VAE remote module does not expose its parallel-state initializer")
ensure_parallel_state()
source_path = Path(component_path) / str(config["source_path"])
weights_path = source_path / str(config["source_safetensors_path"])
load_kwargs = {
"clip_length": int(config["vae_clip_length"]),
"token_drop": int(config["vae_token_drop"]),
"encoder_tiling": int(config["vae_encoder_tiling"]),
"decoder_tiling": int(config["vae_decoder_tiling"]),
"parallel_tiling": int(config["vae_parallel_tiling"]),
"tile_size": int(config["vae_tile_size"]),
"tile_overlap_min": int(config["vae_tile_overlap_min"]),
"encoder_parallel": int(config["vae_encoder_parallel"]),
"decoder_parallel": int(config["vae_decoder_parallel"]),
"chunk_dim": int(config["vae_chunk_dim"]),
}
source_cls = source_classes[source_class_name]
source_config = source_cls.load_config(str(source_path))
with set_default_torch_dtype(torch.float32), torch.device("cpu"):
model, _unused = source_cls.from_config(source_config, return_unused_kwargs=True, **load_kwargs)
_remove_modules(model, ("decoder", "post_quant_conv"))
_load_selected_state_dict(model, weights_path, ("encoder.", "quant_conv."))
model.eval()
return component_cls(model)
def _load_audio_vae_encoder(
component_path: str,
config: dict[str, Any],
) -> nn.Module:
class_reference = (config.get("auto_map") or {}).get("AutoModel")
if not isinstance(class_reference, str):
raise ValueError(f"{component_path}/config.json must define auto_map.AutoModel")
component_cls = get_class_from_dynamic_module(class_reference, component_path)
component_module = importlib.import_module(component_cls.__module__)
load_yaml = getattr(component_module, "_load_yaml", None)
model_cls = getattr(component_module, "DacAudioVAE", None)
if not callable(load_yaml) or not isinstance(model_cls, type):
raise ValueError("MiniMax H3 audio VAE remote module does not expose its source loader")
component_dir = Path(component_path)
audio_config = load_yaml(component_dir / str(config["source_config_path"]))
metadata_path = component_dir / str(config["source_metadata_path"])
metadata_doc = json.loads(metadata_path.read_text(encoding="utf-8"))
metadata = metadata_doc["metadata"]["kwargs"]
with set_default_torch_dtype(torch.float32), torch.device("cpu"):
model = model_cls(
encoder_rates=metadata["encoder_rates"],
decoder_rates=metadata["decoder_rates"],
attn_proj=metadata["attn_proj"],
decoder_type=metadata["decoder_type"],
decoder_dim=audio_config["model_config"]["decoder_dim"],
vae_latent_channels=audio_config["model_config"]["vae_latent_channels"],
sample_rate=metadata["sample_rate"],
)
_remove_modules(model, ("decoder", "dec_in_proj", "logs_proj"))
weights_path = component_dir / str(config["source_safetensors_path"])
_load_selected_state_dict(model, weights_path, ("encoder.", "pre_block.", "mean_proj."))
model.eval()
return component_cls(model)
class _AudioVAEDeterminismContext(AbstractContextManager):
def __enter__(self):
backends = torch.backends
@@ -135,6 +275,49 @@ class _AudioVAEDeterminismContext(AbstractContextManager):
return False
class _VideoVAEPartProxy(nn.Module):
"""Residency proxy for one half of the split video VAE.
The pipeline's ``_component_on_device`` drives whatever object it is
given through ``load_to_device``/``offload_to_cpu``. The checkpoint's
ViT decoder holds ~9GB of FP32 weights while the CNN encoder holds
~0.7GB, and each is used by exactly one direction, so routing those
calls per half keeps the decoder off the device while reference videos
encode and the encoder off while latents decode. ``object.__setattr__``
keeps the back-reference out of the module registry (registering the
adapter as a submodule would recurse through ``parameters()``).
"""
def __init__(self, vae: MiniMaxH3VideoVAE, part: str) -> None:
super().__init__()
object.__setattr__(self, "_vae", vae)
object.__setattr__(self, "_part", part)
def load_to_device(self) -> None:
self._vae._load_part_to_device(self._part)
def offload_to_cpu(self) -> None:
self._vae._offload_part_to_cpu(self._part)
def set_omni_component_cache(self, cache: BoundedAllocatorCache | None) -> None:
self._vae.set_omni_component_cache(cache)
@property
def sequential_offload_target(self) -> MiniMaxH3VideoVAE:
"""The module model-level CPU offload actually hooks.
``enable_omni_model_cpu_offload`` registers the sequential hook on the
real ``video_vae``, and the hook moves the whole module through
``parameters()`` — entering the sequential context through this proxy
would find no ``_hook_registry`` and raise, and whole-module movement
has no half-residency benefit anyway. ``_component_on_device`` unwraps
through this property before entering its sequential-offload branch;
the manual per-half staging above stays proxy-driven, where split
residency is the whole point.
"""
return self._vae
class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
"""Adapter around the checkpoint's native parallel-tiled video VAE."""
@@ -144,14 +327,24 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
*,
device: torch.device,
load_device: torch.device | None = None,
encode_only: bool = False,
decode_only: bool = False,
trust_remote_code: bool = False,
) -> None:
super().__init__()
self._device_target = device
self.encode_only = bool(encode_only)
self.decode_only = bool(decode_only)
if self.encode_only and self.decode_only:
raise ValueError("MiniMax H3 video VAE cannot be both encode-only and decode-only")
self.config_dict = _load_component_config(component_path)
self.remote = _load_remote_component(
component_path,
self.config_dict,
)
_check_trust_remote_code(component_path, self.config_dict, trust_remote_code)
if self.encode_only:
self.remote = _load_video_vae_encoder(component_path, self.config_dict)
else:
self.remote = _load_remote_component(component_path, self.config_dict, trust_remote_code=trust_remote_code)
if self.decode_only:
_remove_modules(self.remote.model, ("encoder", "quant_conv"))
# Match the reference loader contract before installing inference-only
# decoder fast paths. Keyframe encoding remains FP32; decoder Linear
# weights may be materialized in FP16 because reference decode casts
@@ -164,49 +357,126 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
decoder,
device=device,
)
self._stager = None
if initial_device.type == "cpu" and device.type not in ("cpu", "meta"):
self._stager = PinnedModuleStager(
self.remote,
device,
pin_memory=True,
)
install_temporal_stream_patches(self.remote.model)
self.model = self.remote.model
self._stager = None
self._encoder_stager = None
self._decoder_stager = None
if initial_device.type == "cpu" and device.type not in ("cpu", "meta"):
self._build_residency_stagers(device)
self.encoder_component = _VideoVAEPartProxy(self, "encoder")
self.decoder_component = _VideoVAEPartProxy(self, "decoder")
self.use_tiling = True
self.use_slicing = False
self.parallel_size = 1
self.device_module = torch.get_device_module()
self._tile_gather_workspace: torch.Tensor | None = None
self._tile_gather_stats = {"hits": 0, "allocs": 0, "workspace_bytes": 0}
self._checkpoint_tile_gather = None
if self._tile_gather_reuse_enabled():
self._install_persistent_tile_gather()
def _build_residency_stagers(self, device: torch.device) -> None:
"""Stage the encode and decode halves of the remote separately.
The encode path touches only ``encoder`` + ``quant_conv`` and the
decode path only ``post_quant_conv`` + ``decoder`` (verified against
the checkpoint's ``AutoencoderKLLegacy``: the one cross reference,
``tiled_decode``'s ``getattr(self.encoder, "mask_enabled")``, is
short-circuited by ``self.training`` at inference). No storage is
shared across the two groups, so independent staging is exact. When
the checkpoint's structure is not discoverable, fall back to
whole-module staging (the previous single-stager behavior).
"""
part_names = ("encoder", "quant_conv", "post_quant_conv", "decoder")
if all(isinstance(getattr(self.model, name, None), nn.Module) for name in part_names):
self._encoder_stager = PinnedModuleStager(
[self.model.encoder, self.model.quant_conv],
device,
pin_memory=True,
)
self._decoder_stager = PinnedModuleStager(
[self.model.post_quant_conv, self.model.decoder],
device,
pin_memory=True,
)
return
self._stager = PinnedModuleStager(
self.remote,
device,
pin_memory=True,
)
def _part_stager(self, part: str) -> PinnedModuleStager | None:
if part == "encoder":
return self._encoder_stager
if part == "decoder":
return self._decoder_stager
raise ValueError(f"unknown video VAE part {part!r}")
def _load_part_to_device(self, part: str) -> None:
stager = self._part_stager(part)
if stager is not None:
stager.load()
elif self._stager is not None:
self._stager.load()
else:
# No staged residency (the component lives on the device already
# or is fully CPU-resident): fall back to whole-module placement.
self.remote.to(self._device_target)
def _offload_part_to_cpu(self, part: str) -> None:
stager = self._part_stager(part)
if stager is not None:
stager.offload()
return
if self._stager is not None:
self._stager.offload()
return
self.remote.to("cpu")
self._release_component_cache()
def _release_component_cache(self) -> None:
cache = getattr(self, "_omni_component_cache", None)
if cache is None:
torch.accelerator.empty_cache()
else:
cache.release_if_needed()
def load_to_device(self) -> None:
if self._stager is not None:
if self._encoder_stager is not None:
self._encoder_stager.load()
self._decoder_stager.load()
elif self._stager is not None:
self._stager.load()
else:
self.remote.to(self._device_target)
def set_omni_component_cache(self, cache: BoundedAllocatorCache | None) -> None:
self._omni_component_cache = cache
if self._stager is not None:
self._stager.set_cache_retention(cache)
for stager in (self._encoder_stager, self._decoder_stager, self._stager):
if stager is not None:
stager.set_cache_retention(cache)
def offload_to_cpu(self) -> None:
if self._stager is not None:
if self._encoder_stager is not None:
self._encoder_stager.offload()
self._decoder_stager.offload()
elif self._stager is not None:
self._stager.offload()
else:
self.remote.to("cpu")
cache = getattr(self, "_omni_component_cache", None)
if cache is None:
torch.accelerator.empty_cache()
else:
cache.release_if_needed()
self._release_component_cache()
def set_parallel_size(
self,
parallel_size: int,
mode: str = "tile",
process_group: dist.ProcessGroup | None = None,
) -> None:
if mode != "tile":
raise ValueError(f"MiniMax H3 VAE supports its native tile parallel mode only, got {mode!r}")
group = get_world_group().device_group
group = process_group if process_group is not None else get_world_group().device_group
world_size = dist.get_world_size(group)
rank = dist.get_rank(group)
parallel_size = int(parallel_size)
@@ -241,6 +511,145 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
parallel_module = importlib.import_module(f"{package}.parallel")
return parallel_module.get_parallel_state()
def _tile_gather_reuse_enabled(self) -> bool:
"""Whether this device needs the tiled-VAE gather address kept stable.
XPU only. The accumulation this guards against is an XCCL-side
registration that is kept for every distinct receive-buffer address and
never reclaimed; no other backend in tree does that, so everywhere else
the checkpoint's own method is left in place and behaviour is unchanged.
The stable address comes from one grow-only byte workspace, so what the
adapter holds resident is one buffer for the largest geometry it has
seen rather than one per geometry.
"""
return self._device_target.type == "xpu"
def _install_persistent_tile_gather(self) -> None:
"""Route the checkpoint's tiled-VAE gather through a bounded workspace.
The checkpoint's ``_all_gather_tiled_results`` allocates its gather
output afresh on every call. Model-level offload calls ``empty_cache()``
once per request, so the next request's output lands on a new device
address; XCCL registers a non-reclaimable resource per new receive
address, and the registrations accumulate until the card is full. The
replacement below keeps a single byte workspace alive on this adapter
and carves every gather out of its front, so the address the collective
writes to is the same one every request.
The workspace only ever grows: a geometry that fits in the current
block reuses it as is, and a larger one replaces the block, which
drops the previous allocation before allocating its own. Resident
memory is therefore bounded by one buffer for the largest geometry the
adapter has seen, not by one buffer per distinct geometry.
The override is bound on the checkpoint *instance*, not its class: the
class is remote code shared by every component loaded from the same
checkpoint, and only this adapter knows the device it runs on.
"""
self._checkpoint_tile_gather = self.model._all_gather_tiled_results
self.model._all_gather_tiled_results = self._persistent_tile_gather
logger.info(
"[H3_VAE_GATHER] persistent tile gather installed device=%s",
self._device_target.type,
)
def _persistent_tile_gather(
self,
tasks: list[torch.Tensor],
num_tiles: int,
) -> list[torch.Tensor]:
"""Equal-shape replacement for the checkpoint's tiled-result gather.
Contract kept identical to the checkpoint's method: return a list of
``num_tiles`` tensors in global tile order, and raise on an empty local
share so a rank that owns no tile cannot silently skip the collective.
Tile ownership is round-robin (``range(sp_rank, num_tiles, sp_size)``),
so every rank can compute every other rank's task count from
``num_tiles`` and ``sp_size`` alone. That makes the per-rank payloads
equal once the leading task dimension is padded to ``max_tasks``, which
is what lets a single ``all_gather_into_tensor`` into a stable buffer
replace the variable-shape gather.
The landing buffer is a view onto the front of one byte workspace that
this adapter keeps alive and only ever grows, so its address stays
stable across requests while resident memory stays bounded by the
largest geometry seen rather than growing per geometry. A byte
workspace is dtype-agnostic, so mixed-precision requests share it too.
Returned tiles are cloned out of the buffer: the buffer is overwritten
by the next call and callers hold the tiles past that point.
"""
state = self._native_parallel_state()
group = state["sp_process_group"]
sp_size = int(state["sp_size"])
sp_rank = int(state["sp_rank"])
if not tasks:
raise ValueError(f"Found empty tasks on sp rank {sp_rank}")
max_tasks = -(-num_tiles // sp_size)
if len(tasks) > max_tasks:
raise ValueError(
f"sp rank {sp_rank} holds {len(tasks)} tiles but round-robin "
f"ownership of {num_tiles} tiles across {sp_size} ranks allows "
f"at most {max_tasks}"
)
if len(tasks) == max_tasks:
stacked = torch.stack(tasks, dim=0)
else:
# Pad the leading (task) dimension only. The padded slots belong to
# ranks whose share is short by construction, and the unpacking loop
# below never reads them back.
stacked = tasks[0].new_empty((max_tasks, *tasks[0].shape))
torch.stack(tasks, dim=0, out=stacked[: len(tasks)])
stacked[len(tasks) :].zero_()
need_bytes = sp_size * stacked.numel() * stacked.element_size()
workspace = self._tile_gather_workspace
if workspace is None or workspace.device != stacked.device or workspace.numel() < need_bytes:
# Drop the previous block before allocating its replacement so the
# two are never resident at once; only one workspace is ever held.
workspace = None
self._tile_gather_workspace = None
workspace = torch.empty(need_bytes, dtype=torch.uint8, device=stacked.device)
self._tile_gather_workspace = workspace
self._tile_gather_stats["allocs"] += 1
self._tile_gather_stats["workspace_bytes"] = need_bytes
reuse = "alloc"
else:
self._tile_gather_stats["hits"] += 1
reuse = "hit"
buffer = workspace[:need_bytes].view(stacked.dtype).view(sp_size, *stacked.shape)
# Quantities, not just presence: a line that only says "installed"
# cannot distinguish a buffer that is being reused from one that is
# reallocated every request, which is the whole failure being fixed.
# Debug level, because this fires once per decoder tile batch (12 times
# per request on the canonical 1344x768 geometry) and the one-shot
# "installed" line above is what an operator needs at info level.
logger.debug(
"[H3_VAE_GATHER] reuse=%s shape=%s/%s need_mib=%.2f workspace_mib=%.2f buf_ptr=0x%x hits=%d allocs=%d",
reuse,
tuple(stacked.shape),
stacked.dtype,
need_bytes / (1024.0 * 1024.0),
self._tile_gather_stats["workspace_bytes"] / (1024.0 * 1024.0),
workspace.data_ptr(),
self._tile_gather_stats["hits"],
self._tile_gather_stats["allocs"],
)
dist.all_gather_into_tensor(buffer, stacked, group=group)
results: list[torch.Tensor] = [None] * num_tiles # type: ignore[list-item]
for rank in range(sp_size):
num_rank_tasks = -(-(num_tiles - rank) // sp_size)
for k in range(num_rank_tasks):
results[k * sp_size + rank] = buffer[rank][k].clone()
return results
def _decoder_tile_count(self, latent: torch.Tensor) -> int:
"""Number of decoder tiles the checkpoint will split ``latent`` into.
@@ -254,15 +663,40 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
cols, _, _ = self.model.split_tiles(int(latent.shape[-1]) * ratio, True)
return len(rows) * len(cols)
def _encoder_tile_count(self, height: int, width: int) -> int:
processor = getattr(self.model, "processor", None)
align = getattr(processor, "_align_to_total_patch_size", None)
if callable(align):
height, width = align(int(height), int(width))
rows, _, _ = self.model.split_tiles(int(height), False)
cols, _, _ = self.model.split_tiles(int(width), False)
return len(rows) * len(cols)
def _encoder_tiling_context(
self,
height: int,
width: int,
) -> AbstractContextManager:
parallel_size = int(getattr(self, "parallel_size", 1))
if parallel_size <= 1:
return nullcontext()
num_tiles = self._encoder_tile_count(height, width)
if num_tiles >= parallel_size:
return nullcontext()
logger.warning_once(
"MiniMax-H3 VAE encode splits a %dx%d input into %d tile(s) but "
"the tile group has %d ranks; encoding rank-locally for this "
"shape instead, which avoids ranks without tiles hanging the "
"collective.",
width,
height,
num_tiles,
parallel_size,
)
return self._rank_local_tiling()
@contextmanager
def _rank_local_tiling(self) -> Iterator[None]:
"""Run one decode with tiling kept on this rank, then restore the group.
Used only when there are fewer tiles than ranks. Every rank then decodes
every tile, which is slower than sharing the work but is correct and
involves no collective.
"""
state = self._native_parallel_state()
saved_state = dict(state)
saved_tiling = self.model.parallel_tiling
@@ -290,15 +724,24 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
@torch.inference_mode()
def encode_image(self, image: Image.Image) -> torch.Tensor:
if getattr(self, "decode_only", False):
raise RuntimeError("MiniMax H3 decode-only video VAE cannot encode images")
previous_parallel = self.model.parallel_tiling
self.model.parallel_tiling = False
if int(getattr(self, "parallel_size", 1)) <= 1:
self.model.parallel_tiling = False
parameter = next(self.parameters())
previous_dtype = parameter.dtype
if previous_dtype != torch.float32:
self.to(torch.float32)
devices = [parameter.device] if parameter.device.type != "cpu" else []
try:
with torch.random.fork_rng(devices=devices, device_type=parameter.device.type):
with (
self._encoder_tiling_context(image.height, image.width),
torch.random.fork_rng(
devices=devices,
device_type=parameter.device.type,
),
):
torch.default_generator.manual_seed(MINIMAX_H3_KEYFRAME_ENCODE_SEED)
for device in devices:
with self.device_module.device(device):
@@ -332,22 +775,128 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
patch_size=(1, 2, 2),
).float()
def _stream_prepare_video_tensor(
self,
frames: np.ndarray,
device: torch.device,
) -> torch.Tensor | None:
"""Upload a uint8 ``(T, H, W, 3)`` video as one normalized FP32 tensor.
The checkpoint's numpy path uploads the whole video as FP32, then
``transform_tensor`` materializes a second normalized copy, then
``encode_temporal`` pads through a full-video ``torch.cat``: three
resident pixel-scale copies on the device. Here the padding is
replicated on the host, a single preallocated ``(3, T', H, W)`` tensor
receives clip-by-clip uploads, and the ``÷255 → (x-mean)/std`` chain
runs in place on each clip's staging buffer in the same op order as
``convert_numpy_to_tensor`` → ``transform_tensor``, so peak device
memory is the output tensor plus one clip instead of three copies.
Returns ``None`` whenever the checkpoint contract this mirrors (uint8
frames, ``clip_length`` alignment, processor ``transform`` constants)
is not discoverable; callers fall back to the legacy path.
"""
if frames.dtype != np.uint8 or frames.ndim != 4 or frames.shape[-1] != 3:
return None
if int(frames.shape[0]) == 0:
return None
model = self.model
clip_length = getattr(model, "clip_length", None)
transform = getattr(getattr(model, "processor", None), "transform", None)
mean = getattr(transform, "mean", None)
std = getattr(transform, "std", None)
if not isinstance(clip_length, int) or clip_length <= 0:
return None
if mean is None or std is None or len(mean) != 3 or len(std) != 3:
return None
# Mirror the checkpoint's temporal alignment so the device-side
# ``get_suitable_video_length`` trim is a no-op and the
# ``encode_temporal`` padding ``torch.cat`` never triggers. A
# trim-stable length is ``k * clip_length + tail`` (tail = frame
# overlap plus the isolated last frame); it also satisfies
# encode_temporal only when ``tail % clip_length == offset_frame``.
# With an asymmetric checkpoint (isolated last frame but no isolated
# first frame) no trim-stable length can satisfy encode_temporal, so
# the remote re-pads through a whole-video cat regardless and any
# host-side pad would be trimmed away before that -- keep the legacy
# frame count there instead of uploading dead frames.
isolated_first_frame = bool(getattr(model, "isolated_first_frame", False))
frame_pre_padding = int(getattr(model, "frame_pre_padding", 0) or 0)
offset = 1 if isolated_first_frame and frame_pre_padding == 0 else 0
processor = getattr(model, "processor", None)
tail = int(getattr(processor, "frame_overlap", 0) or 0)
if bool(getattr(processor, "isolated_last_frame", False)):
tail += 1
num_frames = int(frames.shape[0])
pad = 0
if tail % clip_length == offset:
align = getattr(processor, "align_video_length", None)
if callable(align):
pad = max(0, int(align(num_frames, mode="pad", granularity="chunk")))
else:
chunks = -(-(num_frames - tail) // clip_length)
pad = max(max(chunks, 1) * clip_length + tail - num_frames, 0)
if pad:
frames = np.concatenate([frames, np.repeat(frames[-1:], pad, axis=0)])
num_frames += pad
mean_t = torch.as_tensor(mean, dtype=torch.float32, device=device).view(3, 1, 1, 1)
std_t = torch.as_tensor(std, dtype=torch.float32, device=device).view(3, 1, 1, 1)
height, width = int(frames.shape[1]), int(frames.shape[2])
out = torch.empty(
(3, num_frames, height, width),
dtype=torch.float32,
device=device,
)
for start in range(0, num_frames, clip_length):
end = min(start + clip_length, num_frames)
# Frame slices of a C-contiguous (T, H, W, 3) array stay
# contiguous, so each clip uploads at uint8 width (4x less host
# traffic than the legacy FP32 upload) before the in-place
# normalization chain. permute lands on the checkpoint's
# (3, T, H, W) layout directly.
chunk = torch.from_numpy(frames[start:end]).to(device=device)
chunk = chunk.permute(3, 0, 1, 2).to(torch.float32).div_(255.0)
chunk = chunk.sub_(mean_t).div_(std_t)
out[:, start:end].copy_(chunk)
return out
@torch.inference_mode()
def encode_video(
self,
frames: Any,
) -> tuple[torch.Tensor, tuple[int, int, int]]:
if getattr(self, "decode_only", False):
raise RuntimeError("MiniMax H3 decode-only video VAE cannot encode videos")
parameter = next(self.parameters())
previous_dtype = parameter.dtype
if previous_dtype != torch.float32:
self.to(torch.float32)
devices = [parameter.device] if parameter.device.type != "cpu" else []
shape = getattr(frames, "shape", None)
if int(getattr(self, "parallel_size", 1)) > 1:
if shape is None or len(shape) != 4:
raise ValueError("parallel MiniMax H3 video encode requires a rank-4 frame array")
if int(shape[-1]) in {1, 3, 4}:
frame_height, frame_width = int(shape[-3]), int(shape[-2])
else:
frame_height, frame_width = int(shape[-2]), int(shape[-1])
tiling_context = self._encoder_tiling_context(frame_height, frame_width)
else:
tiling_context = nullcontext()
try:
with torch.random.fork_rng(devices=devices, device_type=parameter.device.type):
with tiling_context, torch.random.fork_rng(devices=devices, device_type=parameter.device.type):
torch.default_generator.manual_seed(MINIMAX_H3_KEYFRAME_ENCODE_SEED)
for device in devices:
with self.device_module.device(device):
self.device_module.manual_seed(MINIMAX_H3_KEYFRAME_ENCODE_SEED)
prepared = None
if isinstance(frames, np.ndarray) and not _legacy_encode_prep_enabled():
prepared = self._stream_prepare_video_tensor(frames, parameter.device)
if prepared is not None:
# Tensor inputs already carry the checkpoint's expected
# (3, T, H, W) normalized-FP32 contract, so encode_videos
# skips its own convert/transform/pad whole-video copies.
frames = [prepared]
latent = self.model.encode_videos(
frames,
use_fp16_latent=True,
@@ -403,9 +952,16 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
@torch.inference_mode()
def decode_latent(self, latent: torch.Tensor) -> torch.Tensor:
if getattr(self, "encode_only", False):
raise RuntimeError("MiniMax H3 encode-only video VAE cannot decode latents")
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))
if decoded.dtype == torch.uint8:
# The streaming uint8 write-back already ran the revert and the
# output quantizer inside write_part; nothing remains but the
# shape contract.
return self._normalize_decoded_frames(decoded)
return self._normalize_decoded_frames(self._revert_decoded_inplace(decoded))
def _denormalize_latent(self, latent: torch.Tensor) -> torch.Tensor:
channels = int(self.config_dict["latent_channels"])
@@ -422,7 +978,7 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
frames = frames.unsqueeze(0).transpose(1, 2)
if frames.ndim != 5:
raise ValueError(f"unexpected decoded video shape {tuple(frames.shape)}")
return frames.float()
return frames if frames.dtype == torch.uint8 else frames.float()
# Chunks are reverted through the checkpoint's processor, which
# denormalizes and clamps into the unit interval.
@@ -440,6 +996,8 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
the complete decode path. After a callback failure, the remaining
chunks are decoded and discarded before the exception is re-raised.
"""
if getattr(self, "encode_only", False):
raise RuntimeError("MiniMax H3 encode-only video VAE cannot decode latents")
if not callable(on_chunk):
raise TypeError("on_chunk must be callable")
if not callable(getattr(self.model, "_adaptive_decode", None)):
@@ -456,6 +1014,33 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
with self._decode_tiling_context(z):
decode_h3_chunks(self, z, on_chunk, group=group)
def _revert_decoded_inplace(self, decoded: torch.Tensor) -> torch.Tensor:
"""In-place counterpart of the processor's ``revert_tensor``.
The checkpoint version materializes a denormalized copy, a clamped
copy, and a contiguous copy of the whole decoded video -- three
pixel-scale tensors resident at the decode peak. Decoding owns the
tensor here, so the same op order (torchvision ``Normalize`` is
``(x - mean) / std``, then ``clamp(0, 1)``) runs in place on the
original ``(B, C, T, H, W)`` layout, which is bit-identical
elementwise to normalizing the ``(b t) c h w`` rearrangement and
returns with zero whole-video copies.
Falls back to ``processor.revert_tensor`` when the checkpoint's
denormalization constants are not discoverable.
"""
processor = getattr(self.model, "processor", None)
transform_rev = getattr(processor, "transform_rev", None)
mean = getattr(transform_rev, "mean", None)
std = getattr(transform_rev, "std", None)
if mean is None or std is None or len(mean) != 3 or len(std) != 3:
return processor.revert_tensor(decoded)
if bool(getattr(processor, "use_3d_conv", True)) and decoded.ndim == 4:
decoded = decoded.unsqueeze(2)
mean_t = torch.as_tensor(mean, dtype=decoded.dtype, device=decoded.device).view(1, 3, 1, 1, 1)
std_t = torch.as_tensor(std, dtype=decoded.dtype, device=decoded.device).view(1, 3, 1, 1, 1)
return decoded.sub_(mean_t).div_(std_t).clamp_(0.0, 1.0)
class MiniMaxH3AudioVAE(nn.Module):
def __init__(
@@ -464,14 +1049,24 @@ class MiniMaxH3AudioVAE(nn.Module):
*,
device: torch.device,
load_device: torch.device | None = None,
encode_only: bool = False,
decode_only: bool = False,
trust_remote_code: bool = False,
) -> None:
super().__init__()
self._device_target = device
self.encode_only = bool(encode_only)
self.decode_only = bool(decode_only)
if self.encode_only and self.decode_only:
raise ValueError("MiniMax H3 audio VAE cannot be both encode-only and decode-only")
self.config_dict = _load_component_config(component_path)
self.remote = _load_remote_component(
component_path,
self.config_dict,
)
_check_trust_remote_code(component_path, self.config_dict, trust_remote_code)
if self.encode_only:
self.remote = _load_audio_vae_encoder(component_path, self.config_dict)
else:
self.remote = _load_remote_component(component_path, self.config_dict, trust_remote_code=trust_remote_code)
if self.decode_only:
_remove_modules(self.remote.model, ("encoder", "pre_block", "mean_proj"))
# The checkpoint's audio VAE contract is FP32 for both reference
# encoding and waveform decoding.
initial_device = load_device or device
@@ -514,6 +1109,8 @@ class MiniMaxH3AudioVAE(nn.Module):
waveform: torch.Tensor,
sample_rate: int,
) -> tuple[torch.Tensor, int]:
if getattr(self, "decode_only", False):
raise RuntimeError("MiniMax H3 decode-only audio VAE cannot encode waveforms")
import torchaudio
waveform = waveform.float()
@@ -559,6 +1156,8 @@ class MiniMaxH3AudioVAE(nn.Module):
@torch.inference_mode()
def decode_latent(self, latent: torch.Tensor) -> torch.Tensor:
if getattr(self, "encode_only", False):
raise RuntimeError("MiniMax H3 encode-only audio VAE cannot decode latents")
channels = int(self.config_dict["latent_channels"])
mean = torch.tensor(
self.config_dict["latents_mean"],
@@ -0,0 +1,271 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Memory-optimized forks of the checkpoint's temporal VAE loops.
Two method replacements installed on the checkpoint's ``AutoencoderKLLegacy``
at adapter construction:
* ``encode_temporal`` pads misaligned frame counts by concatenating repeated
last frames onto the *whole* video before the chunk loop (~4GB copy for a
15s clip). The fork pads inside the tail chunk instead: the chunks see
bit-identical frames while the copy shrinks to a single clip.
* ``_decode_temporal_streaming`` accumulates the whole decoded video in a
floating-point buffer that is denormalized, clamped, and quantized to
uint8 only after the final chunk lands. The fork fuses the adapter's
in-place revert and the output quantizer into ``write_part`` and
accumulates directly into a uint8 buffer -- the same per-element op order
(``(x - mean) / std -> clamp(0, 1) -> *255 -> round -> uint8``), so the
delivered video is bit-identical while the resident decode buffer shrinks
4x.
Set ``VLLM_OMNI_VAE_LEGACY_TEMPORAL=1`` to keep the checkpoint's methods.
"""
from __future__ import annotations
import os
from types import MethodType
import torch
from vllm.logger import init_logger
logger = init_logger(__name__)
_LEGACY_TEMPORAL_ENV = "VLLM_OMNI_VAE_LEGACY_TEMPORAL"
def _legacy_temporal_enabled() -> bool:
value = os.environ.get(_LEGACY_TEMPORAL_ENV, "0")
return value.strip().lower() not in ("", "0", "false", "off")
def _encode_temporal_tail_pad(self, x):
"""Drop-in fork of the checkpoint's ``encode_temporal``.
Frame handling is identical to the original; only the padding site
moves from a whole-video ``torch.cat`` into the tail chunk.
"""
offset_frame = 1 if self.isolated_first_frame and self.frame_pre_padding == 0 else 0
orig_frames = int(x.shape[2])
pad_size = (offset_frame - orig_frames) % self.clip_length
padded_frames = orig_frames + pad_size
num_chunks = (padded_frames - offset_frame) // self.clip_length
z_list = []
for i in range(num_chunks):
start_idx = i * self.clip_length + offset_frame
end_idx = (i + 1) * self.clip_length + offset_frame
clip_x = x[:, :, start_idx : min(end_idx, orig_frames), :, :]
if end_idx > orig_frames:
# The original pads the whole video up front by repeating the
# last frame; repeating it inside the tail chunk feeds the
# identical frames to the identical encodes.
clip_x = torch.cat(
[clip_x, clip_x[:, :, -1:].repeat(1, 1, end_idx - orig_frames, 1, 1)],
dim=2,
)
if self.isolated_key_frame:
key_frame = clip_x[:, :, :1, :, :]
z_key = self._adaptive_encode(key_frame)
if clip_x.shape[2] > 1:
video_frames = clip_x[:, :, 1:, :, :]
z_video = self._adaptive_encode(video_frames)
z = torch.cat([z_key, z_video], dim=2)
else:
z = z_key
else:
z = self._adaptive_encode(clip_x)
z_list.append(z)
z = torch.cat(z_list, dim=2)
if self.token_drop > 0:
z = z[:, :, : -self.token_drop]
if self.isolated_first_frame:
input_first_frame = x[:, :, :1, :, :]
z_first_frame = self._adaptive_encode(input_first_frame)
if self.frame_pre_padding == 0:
z = torch.cat([z_first_frame, z], dim=2)
else:
z = torch.cat([z_first_frame, z[:, :, 1:, :, :]], dim=2)
if self.isolated_last_frame:
# The original indexes into the padded video: pad frames replicate
# the last real frame, out-of-range indexes produce an empty slice
# (a no-op), and negative indexes wrap. Reproduce that mapping
# against the unpadded tensor instead of materializing the pad.
last_frame_idx = padded_frames - self.frame_drop + offset_frame
if last_frame_idx < 0:
last_frame_idx += padded_frames
if 0 <= last_frame_idx < padded_frames:
src_idx = min(last_frame_idx, orig_frames - 1)
input_last_frame = x[:, :, src_idx : src_idx + 1, :, :]
z_last_frame = self._adaptive_encode(input_last_frame)
z = torch.cat([z, z_last_frame], dim=2)
return z
def _decode_temporal_streaming_uint8(self, z, z_head, z_tail, num_chunks, pad_tokens, temporal_cat_dtype):
"""Drop-in fork of the checkpoint's ``_decode_temporal_streaming``.
The chunk loop, overlap blending, frame plan, and assertions are
identical to the original. ``write_part`` additionally runs the
denormalize -> clamp -> quantize chain in place (the same op order the
pipeline applies after decode) and accumulates into a uint8 buffer.
"""
total_frames, pad_frames, output_frames = self._decode_temporal_output_frame_plan(
z, z_head, z_tail, num_chunks, pad_tokens
)
if output_frames <= 0:
raise ValueError(
f"decode_temporal streaming planned non-positive output_frames={output_frames} "
f"total_frames={total_frames} pad_frames={pad_frames}"
)
chunk_dec = self.tokens_chunk_size * self.vae_ratio_t
split_count = int(self.token_drop > 0) + 1
dec = None
dec_overlap = None
norm = None
write_pos = 0
logical_frames = 0
dropped_frames = 0
decoded_count = 0
def write_part(part):
nonlocal dec, dec_overlap, norm, write_pos, logical_frames, dropped_frames
part_frames = int(part.shape[2])
if part_frames <= 0:
return
logical_frames += part_frames
if dec is None:
out_shape = list(part.shape)
out_shape[2] = output_frames
dec = torch.empty(out_shape, dtype=torch.uint8, device=part.device)
transform_rev = self.processor.transform_rev
mean = torch.as_tensor(transform_rev.mean, dtype=part.dtype, device=part.device).view(1, 3, 1, 1, 1)
std = torch.as_tensor(transform_rev.std, dtype=part.dtype, device=part.device).view(1, 3, 1, 1, 1)
norm = (mean, std)
# revert_tensor ((x - mean) / std, clamp) followed by the output
# quantizer (*255, round, uint8), in place on the part: the blended
# raw values are consumed before this point, and every write into
# ``dec`` goes through here, so the final buffer matches the legacy
# post-decode chain element for element. Denormalization and clamping
# run in the decoded dtype exactly like the legacy adapter; the
# quantizer then runs in FP32 because the legacy adapter returned
# ``frames.float()`` before the pipeline multiplied and rounded —
# rounding fp16/bf16 directly flips borderline pixels by one.
mean_t, std_t = norm
part.sub_(mean_t).div_(std_t).clamp_(0.0, 1.0)
part = part.float()
part.mul_(255.0).round_()
remaining = int(dec.shape[2]) - write_pos
copy_frames = min(part_frames, max(0, remaining))
if copy_frames > 0:
dec[:, :, write_pos : write_pos + copy_frames, :, :].copy_(part[:, :, :copy_frames, :, :])
write_pos += copy_frames
dropped_frames += part_frames - copy_frames
for i in range(num_chunks):
t_start_idx = i * self.tokens_chunk_size
t_end_idx = t_start_idx + self.tokens_chunk_size + self.token_overlap
clip_z = z[:, :, t_start_idx:t_end_idx, :, :]
if i == 0 and z_head is not None:
clip_z = torch.cat([z_head, clip_z], dim=2)
if i == num_chunks - 1 and z_tail is not None:
clip_z = torch.cat([clip_z, z_tail], dim=2)
clip_dec = self._adaptive_decode(clip_z)
decoded_count += 1
if temporal_cat_dtype is not None and clip_dec.dtype != temporal_cat_dtype:
clip_dec = clip_dec.to(temporal_cat_dtype)
if clip_dec.device != z.device:
clip_dec = clip_dec.to(z.device)
dec_tail = None
if i == 0 and z_head is not None:
write_part(clip_dec[:, :, self.vae_ratio_t - 1 : self.vae_ratio_t, :, :])
clip_dec = clip_dec[:, :, self.vae_ratio_t :, :, :]
if i == num_chunks - 1 and z_tail is not None:
dec_tail = clip_dec[:, :, -1:, :, :]
clip_dec = clip_dec[:, :, : -self.vae_ratio_t, :, :]
for j in range(split_count):
f_start_idx = j * chunk_dec
f_end_idx = min(f_start_idx + chunk_dec, clip_dec.shape[2])
clip_dec_chunk = clip_dec[:, :, f_start_idx:f_end_idx, :, :]
clip_dec_chunk = clip_dec_chunk[:, :, self.frame_pre_padding :, :, :]
if j == 0:
if dec_overlap is not None:
clip_dec_chunk = self.blend(dec_overlap, clip_dec_chunk, self.frame_overlap, dim=-3)
dec_overlap = None
write_part(clip_dec_chunk)
else:
# Break the view's reference to the full decoded clip so earlier
# temporal chunks can be released before the final output exists.
dec_overlap = clip_dec_chunk.contiguous()
if i == num_chunks - 1:
if dec_overlap is not None:
write_part(dec_overlap)
dec_overlap = None
if dec_tail is not None:
write_part(dec_tail)
del clip_dec, clip_z
if dec is None:
raise RuntimeError("decode_temporal streaming produced no output tensor")
if logical_frames != total_frames or dropped_frames != pad_frames or write_pos != output_frames:
raise RuntimeError(
"decode_temporal streaming frame plan mismatch: "
f"logical_frames={logical_frames} total_frames={total_frames} "
f"dropped_frames={dropped_frames} pad_frames={pad_frames} "
f"write_pos={write_pos} output_frames={output_frames}"
)
return dec
def _processor_denorm_available(model) -> bool:
transform_rev = getattr(getattr(model, "processor", None), "transform_rev", None)
mean = getattr(transform_rev, "mean", None)
std = getattr(transform_rev, "std", None)
return mean is not None and std is not None and len(mean) == 3 and len(std) == 3
def install_temporal_stream_patches(model) -> None:
"""Install the memory-optimized temporal forks on the checkpoint model.
Each fork is installed only when the checkpoint contract it mirrors is
discoverable; otherwise the checkpoint's own method keeps running (the
adapter's post-decode revert already covers that path).
"""
if _legacy_temporal_enabled():
logger.info("MiniMax-H3 VAE temporal stream patches disabled by %s", _LEGACY_TEMPORAL_ENV)
return
if callable(getattr(model, "encode_temporal", None)) and hasattr(model, "clip_length"):
model.encode_temporal = MethodType(_encode_temporal_tail_pad, model)
logger.info("MiniMax-H3 VAE encode_temporal tail-padding patch installed")
else:
logger.warning("MiniMax-H3 VAE encode_temporal contract not found; keeping checkpoint method")
if callable(getattr(model, "_decode_temporal_streaming", None)) and _processor_denorm_available(model):
model._decode_temporal_streaming = MethodType(_decode_temporal_streaming_uint8, model)
logger.info("MiniMax-H3 VAE streaming uint8 decode patch installed")
else:
logger.warning("MiniMax-H3 VAE streaming decode contract not found; keeping checkpoint method")
__all__ = ["install_temporal_stream_patches"]
@@ -0,0 +1,71 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""π0.5 VLA model for vllm-omni.
PaliGemma (SigLIP vision + Gemma-2B LM) + Gemma-300M action expert with AdaRMS
timestep conditioning + a flow-matching action head. Outputs a continuous action
chunk ``[horizon, action_dim]`` rather than tokens.
Differs from π0 in five places: AdaRMS timestep conditioning (``time_mlp_*``
instead of ``action_time_mlp_*``), AdaRMS norms throughout the action expert, a
200-token tokenizer budget, a discretized state carried in the prompt (no
``state_proj``), and relative-action support.
"""
from vllm_omni.diffusion.models.pi05.config import (
Pi05Config,
UnsupportedCheckpointCapabilityError,
resolve_excluded_action_indices,
)
from vllm_omni.diffusion.models.pi05.modeling_pi05 import (
GemmaVariantConfig,
PaliGemmaWithActionExpertPi05,
Pi05AdaRMSNorm,
Pi05ForActionPrediction,
create_sinusoidal_pos_embedding,
get_gemma_config,
make_att_2d_masks,
prepare_attention_masks_4d,
)
from vllm_omni.diffusion.models.pi05.pipeline_pi05 import (
Pi05Pipeline,
get_pi05_post_process_func,
)
from vllm_omni.diffusion.models.pi05.processor_pi05 import (
Pi05ImageProcessor,
Pi05Processor,
Pi05RelativeActions,
apply_norm,
build_norm_stats,
build_pi05_prompt,
discretize_state,
pil_image_to_tensor,
resize_with_pad,
tokenize_prompt,
)
__all__ = [
"Pi05Config",
"UnsupportedCheckpointCapabilityError",
"resolve_excluded_action_indices",
"Pi05ForActionPrediction",
"PaliGemmaWithActionExpertPi05",
"Pi05AdaRMSNorm",
"GemmaVariantConfig",
"get_gemma_config",
"create_sinusoidal_pos_embedding",
"make_att_2d_masks",
"prepare_attention_masks_4d",
"Pi05ImageProcessor",
"Pi05Processor",
"Pi05RelativeActions",
"build_pi05_prompt",
"discretize_state",
"apply_norm",
"build_norm_stats",
"pil_image_to_tensor",
"resize_with_pad",
"tokenize_prompt",
"Pi05Pipeline",
"get_pi05_post_process_func",
]
+471
View File
@@ -0,0 +1,471 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Config surface for the π0.5 VLA model in vllm-omni.
Deliberately shaped exactly like ``pi0/config.py``: a small dataclass that
consumes the raw LeRobot ``config.json`` (the field surface of
``lerobot.policies.pi05.PI05Config``) and keeps only the runtime-relevant
fields. Transformer dimensions are derived from ``paligemma_variant`` /
``action_expert_variant`` inside the model via ``get_gemma_config``.
What π0.5 adds on top of the π0 config surface:
* ``tokenizer_max_length = 200`` (π0 uses 48).
* ``state_num_bins`` — state is discretized into language tokens instead of
going through a ``state_proj`` layer.
* ``use_relative_actions`` / ``relative_exclude_joints`` /
``action_feature_names`` — the relative-action contract. See
``processor_pi05.Pi05RelativeActions``.
* Quantile normalization stats. LeRobot's π0.5 defaults ``STATE`` and
``ACTION`` to ``NormalizationMode.QUANTILES`` where π0 uses ``MEAN_STD``.
**Checkpoint boundary rule.** A capability that the checkpoint *declares* but
this implementation does not *consume* must raise, not be silently dropped.
π0.5 checkpoints can declare MEM (short-horizon observation memory) and RTC
(real-time chunking); neither is supported here, and serving such a checkpoint
anyway would produce plausible-looking wrong actions. See
``_reject_unsupported_capabilities``.
"""
from __future__ import annotations
import json
import logging
from collections.abc import Callable
from dataclasses import dataclass, field
from dataclasses import fields as dataclass_fields
from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
# Serving dtypes, by name. Kept in sync with ``Pi05Pipeline.SUPPORTED_DTYPES``,
# which guards the path that performs the actual cast. Defined here rather than
# imported to keep config.py free of a pipeline import cycle.
SUPPORTED_DTYPE_NAMES = frozenset({"float32", "bfloat16"})
# LeRobot / OpenPI observation key conventions.
ACTION = "action"
OBS_STR = "observation"
OBS_STATE = OBS_STR + ".state"
OBS_IMAGES = OBS_STR + ".images"
class UnsupportedCheckpointCapabilityError(ValueError):
"""A checkpoint declares a capability this implementation does not consume.
Raised at load time rather than silently ignored: every one of these
capabilities changes what a *correct* action chunk looks like, and none of
them is visible in the weights alone.
"""
def resolve_excluded_action_indices(
exclude_joints: list[str] | None,
action_names: list[str] | None,
) -> list[int]:
"""Map ``relative_exclude_joints`` names onto action-vector indices.
Matching is exact name first, then substring (a checkpoint may name the
gripper dimension ``gripper_position`` while the config just says
``gripper``). Single source of truth for both the config-time validation
and the runtime mask in ``processor_pi05.Pi05RelativeActions``.
Returns an empty list when there is nothing to exclude. Raises when a name
cannot be resolved — an unresolvable exclusion would otherwise silently
become "make this dimension relative too".
"""
if not [name for name in (exclude_joints or []) if name]:
return []
if not action_names:
raise UnsupportedCheckpointCapabilityError(
f"Cannot resolve relative_exclude_joints={exclude_joints!r} without action_feature_names."
)
# LeRobot walks the action names and excludes each one any token equals or is
# contained in, both lowercased. Walking the tokens instead and stopping at the
# first exact hit misses a second name the token is a substring of.
tokens = [str(name).lower() for name in exclude_joints if name]
lowered = [str(name).lower() for name in action_names]
indices = [i for i, name in enumerate(lowered) if any(t == name or t in name for t in tokens)]
unresolved = [t for t in tokens if not any(t == name or t in name for name in lowered)]
if unresolved:
raise UnsupportedCheckpointCapabilityError(
f"relative_exclude_joints entries {unresolved!r} match no entry in action_feature_names={action_names!r}."
)
return sorted(set(indices))
@dataclass
class Pi05Config:
"""π0.5 VLA config (dataclass, not an HF ``PretrainedConfig``)."""
# Backbone variants — mapped to Gemma dimensions by ``get_gemma_config``.
paligemma_variant: str = "gemma_2b"
action_expert_variant: str = "gemma_300m"
# Action chunk shape.
chunk_size: int = 50
# The stateless OpenPI endpoint returns one complete predicted chunk.
n_action_steps: int = 50
max_action_dim: int = 32
max_state_dim: int = 32
# Flow-matching denoising schedule.
num_inference_steps: int = 10
# Sinusoidal timestep embedding periods (must match OpenPI/LeRobot).
min_period: float = 4e-3
max_period: float = 4.0
# Image preprocessing. π0.5/SigLIP only support square inputs.
image_resolution: tuple[int, int] = (224, 224)
# π0.5 pads text to 200 tokens (π0 uses 48). The prompt now also carries the
# serialized state, which is why it is so much longer.
tokenizer_max_length: int = 200
# Number of camera slots the model attends to (real + padded).
max_cameras: int = 3
# Bins the normalized state is discretized into before it enters the prompt.
# Ref: openpi PaliGemmaTokenizer.tokenize().
state_num_bins: int = 256
# Weight dtype the checkpoint was saved in.
dtype: str = "float32"
# ── Relative actions ──────────────────────────────────────────────
# True when the checkpoint was trained on actions relative to the current
# state. Its ``norm_stats`` are then in relative space, so serving it without
# the transform silently yields wrong actions — the weights look identical
# either way.
use_relative_actions: bool = False
# Joint names kept absolute (gripper open/close is an absolute quantity).
relative_exclude_joints: list[str] = field(default_factory=lambda: ["gripper"])
# Needed to resolve ``relative_exclude_joints``; there is no dataset to
# fall back on at serving time.
action_feature_names: list[str] | None = None
# Per-dataset normalization stats (schema matches LeRobot's
# ``NormalizerProcessorStep``). ``None`` means identity / pass-through.
# π0.5 defaults to quantile mode; see ``processor_pi05.build_norm_stats``.
norm_stats: dict | None = None
# Ordered camera-slot identities. Missing keys retain their slot and are
# represented by an empty image with a false mask during preprocessing.
image_feature_keys: list[str] | None = None
# Optional map from raw OpenPI obs keys → ``image_feature_keys`` entries.
image_key_map: dict[str, str] = field(default_factory=dict)
# Checkpoint feature schemas. The input schema determines camera order and
# the state width serialized into the prompt; the output schema determines
# the unpadded action width returned on the wire.
input_features: dict[str, Any] = field(default_factory=dict)
output_features: dict[str, Any] = field(default_factory=dict)
# OpenPI handshake metadata from the deploy config. Construction validates
# it against the resolved checkpoint contract.
policy_server_config: dict[str, Any] = field(default_factory=dict)
# Derived from output_features[ACTION].shape; never accepted as a second
# source of truth in config.json.
action_dim: int = field(init=False)
# Derived from input_features[OBS_STATE].shape — the number of values the
# prompt serializes, not a padding target. See processor_pi05.as_state_vector.
state_dim: int = field(init=False)
def __post_init__(self) -> None:
# Coerce list → tuple (JSON has no tuples). Squareness is a real
# constraint: SigLIP only takes square inputs.
res = self.image_resolution
if not isinstance(res, (tuple, list)) or len(res) != 2 or res[0] != res[1]:
raise ValueError(f"π0.5 expects a square image_resolution (H == W); got {res!r}.")
self.image_resolution = (int(res[0]), int(res[1]))
if self.n_action_steps != self.chunk_size:
raise UnsupportedCheckpointCapabilityError(
"The stateless OpenPI serving path returns one complete action chunk and "
f"does not support n_action_steps={self.n_action_steps} with "
f"chunk_size={self.chunk_size}."
)
# Mirrors Pi05Pipeline.SUPPORTED_DTYPES. This field records what the
# *checkpoint* declares; the dtype the weights are actually cast to comes
# from the top-level OmniDiffusionConfig and is validated there.
if self.dtype not in SUPPORTED_DTYPE_NAMES:
raise ValueError(f"dtype must be one of {sorted(SUPPORTED_DTYPE_NAMES)}, got {self.dtype!r}.")
# Derive the camera order from input_features if not given explicitly.
if self.image_feature_keys is None and self.input_features:
self.image_feature_keys = [key for key in self.input_features if key.startswith(OBS_IMAGES + ".")]
if self.max_cameras < 1:
raise ValueError(f"max_cameras must be at least 1, got {self.max_cameras!r}.")
if self.num_inference_steps < 1:
# ``dt = -1 / num_steps`` in the Euler loop.
raise ValueError(f"num_inference_steps must be at least 1, got {self.num_inference_steps!r}.")
self._derive_widths()
self._validate_norm_stats()
self._validate_policy_server_config()
self._validate_relative_actions()
def _validate_norm_stats(self) -> None:
"""Statistics have to cover the widths the checkpoint declares."""
for key, width in (("state", self.state_dim), ("action", self.action_dim)):
for name, value in (self.norm_stats or {}).get(key, {}).items():
if name != "mode" and len(value) != width:
raise ValueError(f"norm_stats[{key}][{name}] has {len(value)} entries, expected {width}.")
# ------------------------------------------------------------------
# Validation
# ------------------------------------------------------------------
def _derive_widths(self) -> None:
"""Read the real state and action widths off the checkpoint schema.
π0.5 serializes the state into the prompt at its real width, so a 7-joint
checkpoint must not be padded out to ``max_state_dim``. The action chunk
is cropped to ``action_dim`` on the way out.
"""
state = self.input_features.get(OBS_STATE) or {}
action = self.output_features.get(ACTION) or {}
if state.get("type", "STATE").upper() != "STATE":
raise ValueError(f"input_features[{OBS_STATE!r}].type must be STATE, got {state['type']!r}.")
if action.get("type", "ACTION").upper() != "ACTION":
raise ValueError(f"output_features[{ACTION!r}].type must be ACTION, got {action['type']!r}.")
self.state_dim = int(state["shape"][0]) if state else self.max_state_dim
self.action_dim = int(action["shape"][0]) if action else self.max_action_dim
if self.state_dim > self.max_state_dim or self.action_dim > self.max_action_dim:
raise ValueError(
f"Checkpoint declares state_dim={self.state_dim} / action_dim={self.action_dim}, "
f"over max_state_dim={self.max_state_dim} / max_action_dim={self.max_action_dim}."
)
def _validate_policy_server_config(self) -> None:
"""The OpenPI handshake has to advertise the resolved contract."""
expected = {
"action_horizon": self.chunk_size,
"action_dim": self.action_dim,
"max_action_dim": self.max_action_dim,
"max_cameras": self.max_cameras,
"image_resolution": list(self.image_resolution),
}
for key, value in expected.items():
declared = (self.policy_server_config or {}).get(key)
if declared is None:
continue
if key == "image_resolution":
declared = list(declared)
if declared != value:
raise ValueError(
f"policy_server_config.{key}={declared!r} does not match the resolved value {value!r}."
)
def _validate_relative_actions(self) -> None:
"""Resolve the excluded joints at load, so a bad name fails before serving."""
if not self.use_relative_actions or not self.relative_exclude_joints:
return
if not self.action_feature_names:
raise UnsupportedCheckpointCapabilityError(
f"relative_exclude_joints={self.relative_exclude_joints!r} needs action_feature_names, "
"which the checkpoint does not carry."
)
resolve_excluded_action_indices(self.relative_exclude_joints, self.action_feature_names)
# ------------------------------------------------------------------
# Constructors
# ------------------------------------------------------------------
@classmethod
def from_pretrained(cls, checkpoint_dir: str | Path) -> Pi05Config:
"""Build from a checkpoint directory's ``config.json``.
Normalization stats are *not* in ``config.json``. LeRobot keeps them in
the processor sidecar, so they are loaded separately and backfilled
here — see :func:`load_lerobot_norm_stats`.
"""
checkpoint_dir = Path(checkpoint_dir)
config_path = checkpoint_dir / "config.json"
if not config_path.exists():
raise FileNotFoundError(f"π0.5 checkpoint is missing required config: {config_path}.")
with open(config_path, encoding="utf-8") as f:
raw = json.load(f)
config = cls.from_model_config(raw)
if config.norm_stats is None:
stats = load_lerobot_norm_stats(checkpoint_dir)
if stats:
config.norm_stats = stats
config._validate_norm_stats()
return config
@classmethod
def from_model_config(cls, model_config: dict[str, Any] | None) -> Pi05Config:
"""Build from a config dict (LeRobot ``config.json`` or deploy yaml)."""
if not model_config:
return cls()
raw = dict(model_config)
_reject_unsupported_capabilities(raw)
model_type = raw.pop("type", "pi05")
if model_type != "pi05":
raise ValueError(f"Expected a π0.5 checkpoint (type='pi05'), got type={model_type!r}.")
if "image_resolution" in raw:
raw["image_resolution"] = tuple(raw["image_resolution"])
# A config.json carries the whole training recipe; none of it reaches
# inference. Capabilities we cannot serve are rejected above instead.
allowed = {item.name for item in dataclass_fields(cls) if item.init}
filtered = {key: value for key, value in raw.items() if key in allowed}
dropped = sorted(set(raw) - allowed)
if dropped:
logger.debug("π0.5 config: ignoring %d non-runtime key(s): %s", len(dropped), dropped)
return cls(**filtered)
# ----------------------------------------------------------------------
# LeRobot normalization-stats sidecar
# ----------------------------------------------------------------------
# Stats live beside config.json: ``policy_preprocessor.json`` names a
# safetensors file per stateful step, keyed ``"<feature_name>.<stat_name>"``.
_PREPROCESSOR_JSON = "policy_preprocessor.json"
# The mode must come from ``norm_map``: a state_dict carries all of
# mean/std/min/max/q01/q99 regardless, so guessing from the present keys would
# read a QUANTILES checkpoint as mean_std and apply a wrong affine map.
_NORM_MODE_FROM_LEROBOT: dict[str, tuple[str, str, str] | None] = {
"IDENTITY": None,
"MEAN_STD": ("mean_std", "mean", "std"),
"MIN_MAX": ("min_max", "min", "max"),
"QUANTILES": ("quantile", "q01", "q99"),
}
# Renaming happens in an earlier processor step, so these names are canonical
# here. VISUAL is absent by design: images are normalized in the processor.
_NORM_STATS_FEATURES = {OBS_STATE: ("STATE", "state"), ACTION: ("ACTION", "action")}
def load_lerobot_norm_stats(checkpoint_dir: str | Path) -> dict[str, dict[str, Any]] | None:
"""Load normalization stats from a LeRobot checkpoint's processor sidecar.
Returns a ``norm_stats``-shaped dict (``{"state": {...}, "action": {...}}``)
carrying an **explicit** ``mode``, or ``None`` when the checkpoint ships no
stats. ``lerobot/pi05_base`` is the latter case: its normalizer step has no
``state_file``, i.e. normalization is identity and the client is expected to
send an already-normalized state.
Raises on a mode we cannot reproduce rather than serving the checkpoint with
the wrong transform, which fails silently — a wrongly normalized state still
yields a plausible-looking action chunk.
"""
checkpoint_dir = Path(checkpoint_dir)
preprocessor_path = checkpoint_dir / _PREPROCESSOR_JSON
if not preprocessor_path.exists():
return None
with open(preprocessor_path, encoding="utf-8") as f:
steps = json.load(f).get("steps", [])
step = next((s for s in steps if s.get("registry_name") == "normalizer_processor"), {})
state_file = step.get("state_file")
if not state_file:
logger.info(
"π0.5 config: %s declares no normalizer state file; the state passes through.",
_PREPROCESSOR_JSON,
)
return None
state_path = checkpoint_dir / state_file
if not state_path.exists():
raise FileNotFoundError(f"{preprocessor_path} declares normalizer state {state_file!r}, which is missing.")
norm_map = {str(k).upper(): str(v).upper() for k, v in ((step.get("config") or {}).get("norm_map") or {}).items()}
import safetensors.torch
flat = safetensors.torch.load_file(str(state_path))
stats: dict[str, dict[str, Any]] = {}
for feature_name, (feature_type, stats_key) in _NORM_STATS_FEATURES.items():
lerobot_mode = norm_map.get(feature_type, "IDENTITY")
if lerobot_mode not in _NORM_MODE_FROM_LEROBOT:
raise ValueError(
f"π0.5 cannot reproduce normalization mode {lerobot_mode!r} for {feature_type}. "
f"Expected one of {sorted(_NORM_MODE_FROM_LEROBOT)}."
)
selected = _NORM_MODE_FROM_LEROBOT[lerobot_mode]
if selected is None:
continue
mode, *stat_names = selected
missing = [name for name in stat_names if f"{feature_name}.{name}" not in flat]
if missing:
raise ValueError(
f"{feature_type} declares {lerobot_mode} normalization but the state file is missing {missing}."
)
stats[stats_key] = {"mode": mode} | {name: flat[f"{feature_name}.{name}"].tolist() for name in stat_names}
if not stats:
return None
logger.info(
"π0.5 config: loaded normalization stats from %s — %s.",
state_file,
", ".join(f"{key}={value['mode']}" for key, value in sorted(stats.items())),
)
return stats
# ----------------------------------------------------------------------
# Checkpoint-boundary rule
# ----------------------------------------------------------------------
# Each entry: config key → (is this value *enabled*?, why we cannot serve it).
# Every capability here changes what a *correct* action chunk looks like, and
# none is visible in the weights, so a checkpoint that enables one is refused
# rather than served plausibly wrong. See recipes/lerobot/Pi05.md for the
# longer explanations.
#
# The predicate is per key because these are not all flags: ``n_obs_steps`` is
# a count whose supported value is 1, and an empty ``rtc_config`` still selects
# RTC — LeRobot's ``RTCConfig`` defaults ``enabled=True``.
_UNSUPPORTED: dict[str, tuple[Callable[[Any], bool], str]] = {
"use_peft": (bool, "adapter-aware loading; this loader takes a merged checkpoint only"),
"empty_cameras": (bool, "mutates the input schema; declare camera features explicitly instead"),
"use_visual_memory": (bool, "MEM needs a per-session observation history, which this path does not keep"),
"use_proprioceptive_memory": (
bool,
"MEM sends the state as a projected token, not the discretized prompt built here",
),
"rtc_config": (
lambda value: value is not None,
"RTC needs prefix guidance in the denoising loop and per-request chunk carry-over",
),
"n_obs_steps": (
lambda value: bool(value) and value > 1,
"an observation history; this path is first-order Markov",
),
}
def _reject_unsupported_capabilities(raw: dict[str, Any]) -> None:
"""Raise if the checkpoint enables something we do not consume.
Scope note: this validates that we correctly consume *the checkpoint we were
handed*. Choosing which checkpoint to load belongs to the caller.
"""
problems = [
f" - {key}={raw[key]!r}: {why}"
for key, (is_enabled, why) in _UNSUPPORTED.items()
if key in raw and is_enabled(raw[key])
]
if problems:
raise UnsupportedCheckpointCapabilityError(
"This checkpoint declares capabilities the vllm-omni π0.5 implementation "
"does not support:\n" + "\n".join(problems) + "\nServing it anyway would "
"produce plausible-looking but wrong actions."
)
# Not an error: it records that the checkpoint was trained with clean action
# prefixes sampled in, which is a property of training rather than a request
# to run RTC. Such a checkpoint is still correct to serve without RTC.
delay = raw.get("rtc_training_max_delay")
if delay:
logger.info(
"π0.5 config: checkpoint was trained with rtc_training_max_delay=%s. "
"Real-Time Chunking is not implemented here; serving proceeds without it.",
delay,
)
@@ -0,0 +1,898 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Inference-only π0.5 VLA math kernel for vllm-omni.
Only the math that turns a robot observation into an action chunk; no serving or
request glue. Deliberately shaped like ``models/pi0/modeling_pi0.py`` so the two
can later be factored into a shared Pi-family module (RFC step 2) on a
"behaviour unchanged" review.
π0.5 = PaliGemma (SigLIP vision + Gemma 2B LM) prefix + Gemma 300M action expert
suffix + flow-matching head. Where π0 projects the robot state through
``state_proj``, π0.5 discretizes it into prompt tokens — so there is no
``state_proj`` layer, ``sample_actions`` takes no ``state`` argument, and the
suffix is action tokens only, which drops π0's leading state-token boundary from
the suffix attention mask and leaves ``[1] + [0] * (horizon - 1)``.
π0.5 is nonetheless the *larger* model: the 37 AdaRMS ``dense`` projections add
~116M parameters against the ~8K that ``state_proj`` saves. (LeRobot's README
says otherwise; the checkpoint disagrees.)
Reference implementations:
- OpenPI: openpi/src/openpi/models_pytorch/pi0_pytorch.py, gemma_pytorch.py
- LeRobot: lerobot/src/lerobot/policies/pi05/modeling_pi05.py
"""
from __future__ import annotations
import logging
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.models.auto import CONFIG_MAPPING
from transformers.models.gemma.modeling_gemma import (
GemmaForCausalLM,
apply_rotary_pos_emb,
)
from transformers.models.paligemma.modeling_paligemma import (
PaliGemmaForConditionalGeneration,
)
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
logger = logging.getLogger(__name__)
# ──────────────────────────────────────────────────────────────────────
# Constants
# ──────────────────────────────────────────────────────────────────────
DEFAULT_ACTION_DIM = 32
DEFAULT_ACTION_HORIZON = 50
DEFAULT_MAX_TOKEN_LEN = 200 # π0 uses 48
DEFAULT_NUM_INFERENCE_STEPS = 10
DEFAULT_IMAGE_RESOLUTION = (224, 224) # openpi/models/model.py IMAGE_RESOLUTION
DEFAULT_STATE_NUM_BINS = 256 # openpi PaliGemmaTokenizer.tokenize()
# Large negative value to fill masked-out positions in a float attention mask.
# Matches OpenPI's constant exactly so that numerics line up during parity.
# Ref: openpi/src/openpi/models/gemma.py
OPENPI_ATTENTION_MASK_VALUE = -2.3819763e38
# ──────────────────────────────────────────────────────────────────────
# Gemma variant configs (matches openpi/models/gemma.py get_config)
# ──────────────────────────────────────────────────────────────────────
class GemmaVariantConfig:
def __init__(self, width, depth, mlp_dim, num_heads, num_kv_heads, head_dim):
self.width = width
self.depth = depth
self.mlp_dim = mlp_dim
self.num_heads = num_heads
self.num_kv_heads = num_kv_heads
self.head_dim = head_dim
def get_gemma_config(variant: str) -> GemmaVariantConfig:
if variant == "gemma_2b":
return GemmaVariantConfig(2048, 18, 16384, 8, 1, 256)
elif variant == "gemma_300m":
return GemmaVariantConfig(1024, 18, 4096, 8, 1, 256)
else:
raise ValueError(f"Unknown variant: {variant}")
# ──────────────────────────────────────────────────────────────────────
# Utility functions (match openpi/models_pytorch/pi0_pytorch.py)
# ──────────────────────────────────────────────────────────────────────
def create_sinusoidal_pos_embedding(
time: torch.Tensor,
dimension: int,
min_period: float = 4e-3,
max_period: float = 4.0,
device: torch.device = None,
) -> torch.Tensor:
"""Compute a sine/cosine positional embedding for scalar timesteps.
Ref: openpi/models_pytorch/pi0_pytorch.py create_sinusoidal_pos_embedding
"""
if dimension % 2 != 0:
raise ValueError(f"dimension ({dimension}) must be divisible by 2")
if time.ndim != 1:
raise ValueError("time tensor must be 1-D (batch_size,)")
if device is None:
device = time.device
# Use float64 for the log-linear sweep and for the inner products, to
# match the reference implementation's numerical behaviour exactly.
dtype = torch.float64
fraction = torch.linspace(0.0, 1.0, dimension // 2, dtype=dtype, device=device)
period = min_period * (max_period / min_period) ** fraction
scaling_factor = 1.0 / period * 2 * math.pi
sin_input = scaling_factor[None, :] * time[:, None].to(dtype)
return torch.cat([torch.sin(sin_input), torch.cos(sin_input)], dim=1)
def make_att_2d_masks(pad_masks: torch.Tensor, att_masks: torch.Tensor) -> torch.Tensor:
"""Build a 2D attention mask from a padding mask and an autoregressive mask.
Ref: openpi/models_pytorch/pi0_pytorch.py make_att_2d_masks
"""
if att_masks.ndim != 2:
raise ValueError(f"att_masks must be 2-D, got {att_masks.ndim}-D")
if pad_masks.ndim != 2:
raise ValueError(f"pad_masks must be 2-D, got {pad_masks.ndim}-D")
cumsum = torch.cumsum(att_masks, dim=1)
att_2d_masks = cumsum[:, None, :] <= cumsum[:, :, None]
pad_2d_masks = pad_masks[:, None, :] * pad_masks[:, :, None]
return att_2d_masks & pad_2d_masks
def prepare_attention_masks_4d(att_2d_masks: torch.Tensor) -> torch.Tensor:
"""Convert ``(B, S, S)`` bool masks to ``(B, 1, S, S)`` float masks.
``True`` → 0.0 (attend), ``False`` → ``OPENPI_ATTENTION_MASK_VALUE``.
"""
att_2d_masks_4d = att_2d_masks[:, None, :, :]
return torch.where(att_2d_masks_4d, 0.0, OPENPI_ATTENTION_MASK_VALUE)
class Pi05AdaRMSNorm(nn.Module):
"""Adaptive RMSNorm conditioned on the flow-matching timestep.
π0 conditions on time by *concatenating* a time embedding onto each action
embedding. π0.5 instead feeds the time embedding into every action-expert
norm, which produces a per-layer ``(scale, shift, gate)`` triple::
y = norm(x) * (1 + scale) + shift
out = residual + gate * sublayer(y)
``dense`` is zero-initialized, so an untrained model starts as the identity
modulation with a closed gate — matching OpenPI's parameterization.
Note the shape of the unconditioned branch: ``normed * (1 + weight)`` with
``weight`` zero-initialized, which is exactly ``transformers``'
``GemmaRMSNorm``. That equivalence is why only the *expert* norms need
replacing here and the PaliGemma prefix can keep stock Gemma layers.
"""
def __init__(self, dim: int, eps: float = 1e-6, cond_dim: int | None = None):
super().__init__()
self.eps = eps
self.dim = dim
self.cond_dim = cond_dim
if cond_dim is not None:
self.dense = nn.Linear(cond_dim, dim * 3, bias=True)
nn.init.zeros_(self.dense.weight)
nn.init.zeros_(self.dense.bias)
self.weight = None
else:
self.weight = nn.Parameter(torch.zeros(dim))
self.dense = None
def _norm(self, x: torch.Tensor) -> torch.Tensor:
var = torch.mean(torch.square(x.float()), dim=-1, keepdim=True)
return x.float() * torch.rsqrt(var + self.eps)
def forward(
self,
x: torch.Tensor,
cond: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""Return ``(normed, gate)``; ``gate`` is ``None`` in the unconditioned case."""
dtype = x.dtype
normed = self._norm(x)
if self.dense is None:
normed = normed * (1.0 + self.weight.float())
return normed.to(dtype), None
if cond is None:
# A conditioned norm silently falling back to an unconditioned one
# would drop the entire timestep signal and still return a
# well-shaped, finite tensor.
raise ValueError(
"Pi05AdaRMSNorm was built with cond_dim="
f"{self.cond_dim} but called without an AdaRMS conditioning vector."
)
if cond.shape[-1] != self.cond_dim:
raise ValueError(f"Expected AdaRMS cond dim {self.cond_dim}, got {cond.shape[-1]}")
modulation = self.dense(cond.to(self.dense.weight.dtype))
if x.ndim == 3:
# (B, 3*dim) → (B, 1, 3*dim), broadcast across the token axis: the
# timestep is a per-sample scalar, identical for every action token.
modulation = modulation.unsqueeze(1)
scale, shift, gate = modulation.chunk(3, dim=-1)
normed = normed * (1.0 + scale.float()) + shift.float()
return normed.to(dtype), gate.to(dtype)
def _gated_residual(residual: torch.Tensor, out: torch.Tensor, gate: torch.Tensor | None) -> torch.Tensor:
if gate is None:
return residual + out
return residual + gate * out
# ──────────────────────────────────────────────────────────────────────
# Dual-backbone: PaliGemma + AdaRMS action expert
# ──────────────────────────────────────────────────────────────────────
def _repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""Repeat KV heads for grouped-query attention.
``(B, num_kv_heads, S, D) → (B, num_kv_heads * n_rep, S, D)``.
"""
if n_rep == 1:
return hidden_states
b, nh, s, d = hidden_states.shape
hidden_states = hidden_states[:, :, None, :, :].expand(b, nh, n_rep, s, d)
return hidden_states.reshape(b, nh * n_rep, s, d)
def _attend(query_states, key_states, value_states, attention_mask, num_kv_groups, scaling):
"""Manual eager attention: ``softmax(Q Kᵀ · scale + mask) · V``.
The mask is sliced to ``key_states.shape[-2]`` so the same
``(B, 1, Q, prefix+suffix)`` mask works in both the prefix pass (K length =
prefix) and the suffix pass (K length = prefix + suffix).
"""
k = _repeat_kv(key_states, num_kv_groups)
v = _repeat_kv(value_states, num_kv_groups)
attn_weights = torch.matmul(query_states, k.transpose(2, 3)) * scaling
if attention_mask is not None:
attn_weights = attn_weights + attention_mask[:, :, :, : k.shape[-2]]
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
return torch.matmul(attn_weights, v)
def _match(tensor: torch.Tensor, module: nn.Module) -> torch.Tensor:
"""Cast ``tensor`` to the dtype ``module``'s weight expects."""
return tensor.to(module.weight.dtype) if tensor.dtype != module.weight.dtype else tensor
def _compute_layer_prefix_only(layer_idx, hidden_states, attention_mask, position_ids, paligemma):
"""Run one PaliGemma LM layer on the prefix, returning the layer output and
the post-RoPE ``(k, v)`` for the suffix pass.
Identical to π0: the prefix backbone is unchanged in π0.5 (no AdaRMS —
there is no timestep in the prefix).
"""
model = paligemma.model.language_model
layer = model.layers[layer_idx]
residual = hidden_states
x = _match(layer.input_layernorm(hidden_states), layer.self_attn.q_proj)
hidden_shape = (*x.shape[:-1], -1, layer.self_attn.head_dim)
q = layer.self_attn.q_proj(x).view(hidden_shape).transpose(1, 2)
k = layer.self_attn.k_proj(x).view(hidden_shape).transpose(1, 2)
v = layer.self_attn.v_proj(x).view(hidden_shape).transpose(1, 2)
cos, sin = model.rotary_emb(v, position_ids)
q, k = apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1)
att = _attend(
q,
k,
v,
attention_mask,
num_kv_groups=layer.self_attn.num_key_value_groups,
scaling=1.0 / math.sqrt(layer.self_attn.head_dim),
)
att = att.transpose(1, 2).reshape(q.shape[0], -1, q.shape[1] * layer.self_attn.head_dim)
out = layer.self_attn.o_proj(_match(att, layer.self_attn.o_proj)) + residual
after_resid = out
normed = layer.post_attention_layernorm(out)
out = layer.mlp(_match(normed, layer.mlp.up_proj)) + after_resid
return out, (k, v)
def _compute_layer_suffix_only(
layer_idx,
hidden_states,
prefix_kv,
attention_mask,
position_ids,
gemma_expert,
adarms_cond,
):
"""Run one action-expert layer on the suffix with AdaRMS conditioning.
This is where π0.5 diverges from π0. Both norms are
:class:`Pi05AdaRMSNorm` and each returns a gate that scales its sublayer's
contribution to the residual stream.
"""
layer = gemma_expert.model.layers[layer_idx]
residual = hidden_states
x, gate = layer.input_layernorm(hidden_states, adarms_cond)
x = _match(x, layer.self_attn.q_proj)
hidden_shape = (*x.shape[:-1], -1, layer.self_attn.head_dim)
q = layer.self_attn.q_proj(x).view(hidden_shape).transpose(1, 2)
k_suf = layer.self_attn.k_proj(x).view(hidden_shape).transpose(1, 2)
v_suf = layer.self_attn.v_proj(x).view(hidden_shape).transpose(1, 2)
# RoPE frequencies are shared between PaliGemma and the expert.
cos, sin = gemma_expert.model.rotary_emb(v_suf, position_ids)
q, k_suf = apply_rotary_pos_emb(q, k_suf, cos, sin, unsqueeze_dim=1)
# Concatenate cached prefix K/V (possibly different dtype) with suffix K/V.
k_prefix, v_prefix = prefix_kv
k = torch.cat([k_prefix.to(k_suf.dtype), k_suf], dim=2)
v = torch.cat([v_prefix.to(v_suf.dtype), v_suf], dim=2)
att = _attend(
q,
k,
v,
attention_mask,
num_kv_groups=layer.self_attn.num_key_value_groups,
scaling=1.0 / math.sqrt(layer.self_attn.head_dim),
)
att = att.transpose(1, 2).reshape(q.shape[0], -1, q.shape[1] * layer.self_attn.head_dim)
hidden_states = _gated_residual(residual, layer.self_attn.o_proj(_match(att, layer.self_attn.o_proj)), gate)
residual = hidden_states
x, gate = layer.post_attention_layernorm(hidden_states, adarms_cond)
return _gated_residual(residual, layer.mlp(_match(x, layer.mlp.up_proj)), gate)
class PaliGemmaWithActionExpertPi05(nn.Module):
"""Dual-backbone transformer: PaliGemma (Gemma 2B) + AdaRMS expert (300M).
Same two-mode dispatch as π0 (``prefix_only`` / ``suffix_only``), with one
structural change: after building a stock ``GemmaForCausalLM`` expert, every
norm in it is swapped for a :class:`Pi05AdaRMSNorm` carrying a ``dense``
conditioning projection.
Swapping in place — rather than subclassing ``GemmaModel`` as #4419 does —
keeps the module tree, and therefore the checkpoint key layout, identical to
the expert's stock layout apart from the norms themselves.
"""
def __init__(self, vlm_config, action_expert_config):
super().__init__()
# PaliGemma prefix: identical to π0. It sees no timestep, so no AdaRMS.
vlm_config_hf = CONFIG_MAPPING["paligemma"]()
vlm_config_hf._vocab_size = 257152
vlm_config_hf.image_token_index = 257152
vlm_config_hf.text_config.hidden_size = vlm_config.width
vlm_config_hf.text_config.intermediate_size = vlm_config.mlp_dim
vlm_config_hf.text_config.num_attention_heads = vlm_config.num_heads
vlm_config_hf.text_config.head_dim = vlm_config.head_dim
vlm_config_hf.text_config.num_hidden_layers = vlm_config.depth
vlm_config_hf.text_config.num_key_value_heads = vlm_config.num_kv_heads
vlm_config_hf.text_config.hidden_activation = "gelu_pytorch_tanh"
vlm_config_hf.text_config.dtype = "float32"
vlm_config_hf.text_config.vocab_size = 257152
vlm_config_hf.vision_config.intermediate_size = 4304
vlm_config_hf.vision_config.projection_dim = 2048
vlm_config_hf.vision_config.projector_hidden_act = "gelu_fast"
vlm_config_hf.vision_config.dtype = "float32"
action_expert_config_hf = CONFIG_MAPPING["gemma"](
head_dim=action_expert_config.head_dim,
hidden_size=action_expert_config.width,
intermediate_size=action_expert_config.mlp_dim,
num_attention_heads=action_expert_config.num_heads,
num_hidden_layers=action_expert_config.depth,
num_key_value_heads=action_expert_config.num_kv_heads,
vocab_size=257152,
hidden_activation="gelu_pytorch_tanh",
dtype="float32",
)
self.paligemma = PaliGemmaForConditionalGeneration(config=vlm_config_hf)
self.gemma_expert = GemmaForCausalLM(config=action_expert_config_hf)
# The action expert doesn't embed tokens — it only consumes the
# suffix action embeddings we feed in.
self.gemma_expert.model.embed_tokens = None
self.adarms_cond_dim = action_expert_config.width
self._install_adarms_norms(action_expert_config)
def _install_adarms_norms(self, action_expert_config) -> None:
"""Replace every action-expert RMSNorm with a conditioned AdaRMS norm."""
expert = self.gemma_expert.model
eps = getattr(self.gemma_expert.config, "rms_norm_eps", 1e-6)
width = action_expert_config.width
for layer in expert.layers:
layer.input_layernorm = Pi05AdaRMSNorm(width, eps=eps, cond_dim=self.adarms_cond_dim)
layer.post_attention_layernorm = Pi05AdaRMSNorm(width, eps=eps, cond_dim=self.adarms_cond_dim)
expert.norm = Pi05AdaRMSNorm(width, eps=eps, cond_dim=self.adarms_cond_dim)
def embed_image(self, pixel_values: torch.Tensor) -> torch.Tensor:
"""Encode images with SigLIP vision tower + PaliGemma projector.
The two steps are run explicitly rather than via
``PaliGemmaModel.get_image_features`` because that helper divides the
projector output by ``sqrt(text_hidden_size)``. Being explicit keeps the
scale unambiguous and matches π0 exactly (SigLIP is unchanged in π0.5).
"""
# Shapes: pixel_values (B, 3, 224, 224) → SigLIP (B, 256, 1152)
# → projector (B, 256, 2048)
vision_outputs = self.paligemma.model.vision_tower(pixel_values)
image_features = vision_outputs.last_hidden_state
return self.paligemma.model.multi_modal_projector(image_features)
def embed_language_tokens(self, tokens: torch.Tensor) -> torch.Tensor:
"""Embed language tokens, returning the ``* sqrt(hidden)``-scaled embedding.
The scaling location moved across transformers releases: at ≤5.3 the
normalizer lives inside ``GemmaModel.forward`` (which we bypass), and at
≥5.4 ``GemmaTextScaledWordEmbedding`` self-applies it. Detect and avoid
double-scaling.
"""
embed_tokens = self.paligemma.model.language_model.embed_tokens
lang_emb = embed_tokens(tokens)
if getattr(embed_tokens, "embed_scale", None) is None:
lang_emb = lang_emb * math.sqrt(lang_emb.shape[-1])
return lang_emb
def forward(
self,
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_values=None,
inputs_embeds: list[torch.Tensor | None] | None = None,
use_cache: bool = False,
adarms_cond: torch.Tensor | None = None,
):
"""Dispatch to prefix_only / suffix_only and return
``([prefix_out, suffix_out], past_key_values_or_None)``.
"""
num_layers = self.paligemma.config.text_config.num_hidden_layers
pali_lm = self.paligemma.model.language_model
expert_lm = self.gemma_expert.model
if inputs_embeds[1] is None:
hidden_states = inputs_embeds[0]
kv_list: list[tuple[torch.Tensor, torch.Tensor]] = []
for layer_idx in range(num_layers):
hidden_states, kv = _compute_layer_prefix_only(
layer_idx,
hidden_states,
attention_mask,
position_ids,
paligemma=self.paligemma,
)
kv_list.append(kv)
hidden_states = pali_lm.norm(hidden_states)
return [hidden_states, None], (kv_list if use_cache else None)
if inputs_embeds[0] is not None:
raise ValueError(
"PaliGemmaWithActionExpertPi05.forward only supports prefix-only "
"or suffix-only dispatch; got both inputs_embeds populated."
)
if not isinstance(past_key_values, list):
raise TypeError(
"suffix_only forward expects past_key_values to be the "
"list[(k, v)] produced by a previous prefix_only forward; "
f"got {type(past_key_values)}"
)
hidden_states = inputs_embeds[1]
for layer_idx in range(num_layers):
hidden_states = _compute_layer_suffix_only(
layer_idx,
hidden_states,
past_key_values[layer_idx],
attention_mask,
position_ids,
gemma_expert=self.gemma_expert,
adarms_cond=adarms_cond,
)
hidden_states, _ = expert_lm.norm(hidden_states, adarms_cond)
return [None, hidden_states], None
# ──────────────────────────────────────────────────────────────────────
# Main π0.5 Model
# ──────────────────────────────────────────────────────────────────────
class Pi05ForActionPrediction(nn.Module):
"""π0.5 VLA model for robot action prediction via flow matching.
Inference flow:
1. Embed prefix (images + language, where the language already carries the
discretized state) → prefix tokens.
2. Forward prefix through PaliGemma → layer-wise KV cache.
3. For each denoising step ``t = 1.0, 1-dt, ..., 0``:
a. Embed the timestep → an AdaRMS conditioning vector.
b. Embed the suffix (action tokens only).
c. Forward the suffix through the AdaRMS action expert.
d. ``x_t = x_t + dt * v_t`` (Euler integration).
4. Return ``x_0`` as the predicted action chunk.
"""
def __init__(self, config, quant_config=None, prefix: str = ""):
super().__init__()
# ``quant_config`` is accepted for interface compatibility but unused —
# quant_config is not plumbed through; the weight dtype comes from the pipeline.
del quant_config
self.config = config
self.action_dim = getattr(config, "max_action_dim", DEFAULT_ACTION_DIM)
self.max_state_dim = getattr(config, "max_state_dim", self.action_dim)
self.action_horizon = getattr(config, "chunk_size", DEFAULT_ACTION_HORIZON)
self.num_inference_steps = getattr(config, "num_inference_steps", DEFAULT_NUM_INFERENCE_STEPS)
paligemma_variant = getattr(config, "paligemma_variant", "gemma_2b")
action_expert_variant = getattr(config, "action_expert_variant", "gemma_300m")
vlm_config = get_gemma_config(paligemma_variant)
expert_config = get_gemma_config(action_expert_variant)
self.vlm_width = vlm_config.width
self.expert_width = expert_config.width
# Dual backbone
self.paligemma_with_expert = PaliGemmaWithActionExpertPi05(vlm_config, expert_config)
# Action chunk projections.
self.action_in_proj = nn.Linear(self.action_dim, self.expert_width)
self.action_out_proj = nn.Linear(self.expert_width, self.action_dim)
# π0.5 timestep MLP: (W → W → W) with SiLU, feeding AdaRMS.
# π0 instead has action_time_mlp_{in,out} of shape (2W → W → W) because
# it concatenates the time embedding onto the action embedding.
# NOTE: there is deliberately **no** ``state_proj`` here — that is the
# π0-only continuous-state path.
self.time_mlp_in = nn.Linear(self.expert_width, self.expert_width)
self.time_mlp_out = nn.Linear(self.expert_width, self.expert_width)
# ── Prefix embedding ─────────────────────────────────────────────
def embed_prefix(
self,
images: list[torch.Tensor],
image_masks: list[torch.Tensor],
lang_tokens: torch.Tensor,
lang_masks: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Build prefix embeddings, per-token padding mask, and AR mask.
Prefix tokens form ``[img_cam_0..., ..., lang_tokens...]`` with fully
bidirectional attention (all-zero ``att_masks``). Identical to π0 — the
state is inside ``lang_tokens``, so nothing here changes shape-wise.
Cameras are embedded one at a time; each call is ``(B, 3, 224, 224)``.
The number of slots is fixed by ``config.max_cameras`` for the deployed
model; missing cameras occupy their slot with a false image mask.
"""
num_views = len(images)
if len(image_masks) != num_views:
raise ValueError(
f"images and image_masks must contain the same number of views, got {num_views} and {len(image_masks)}."
)
max_cameras = int(self.config.max_cameras)
if num_views != max_cameras:
raise ValueError(f"Expected exactly max_cameras={max_cameras} image views, got {num_views}.")
embs: list[torch.Tensor] = []
pad_masks: list[torch.Tensor] = []
att_masks: list[int] = []
for img, img_mask in zip(images, image_masks):
img_emb = self.paligemma_with_expert.embed_image(img)
bsize, num_img_embs = img_emb.shape[:2]
embs.append(img_emb)
pad_masks.append(img_mask[:, None].expand(bsize, num_img_embs))
att_masks += [0] * num_img_embs
lang_emb = self.paligemma_with_expert.embed_language_tokens(lang_tokens)
embs.append(lang_emb)
pad_masks.append(lang_masks)
att_masks += [0] * lang_emb.shape[1]
embs = torch.cat(embs, dim=1)
pad_masks = torch.cat(pad_masks, dim=1)
att_masks = torch.tensor(att_masks, dtype=torch.bool, device=embs.device)
att_masks = att_masks[None, :].expand(pad_masks.shape[0], -1)
return embs, pad_masks, att_masks
# ── Timestep + suffix embedding ──────────────────────────────────
def embed_timestep(self, timestep: torch.Tensor) -> torch.Tensor:
"""Timestep → AdaRMS conditioning vector ``(B, expert_width)``.
``silu(time_mlp_out(silu(time_mlp_in(sinusoid(t)))))``. The trailing
SiLU is part of the reference implementation — dropping it is a silent
numerical error, not a crash.
"""
model_dtype = self.action_in_proj.weight.dtype
time_emb = create_sinusoidal_pos_embedding(
timestep,
self.action_in_proj.out_features,
min_period=getattr(self.config, "min_period", 4e-3),
max_period=getattr(self.config, "max_period", 4.0),
device=timestep.device,
).to(dtype=model_dtype)
time_cond = self.time_mlp_in(time_emb)
time_cond = F.silu(time_cond)
time_cond = self.time_mlp_out(time_cond)
return F.silu(time_cond)
def embed_suffix(
self,
noisy_actions: torch.Tensor,
timestep: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Build the suffix: **action tokens only**, plus the AdaRMS condition.
π0's suffix is ``[state_token, action_tokens×H]`` with an AR mask of
``[1, 1, 0...]``. π0.5 has no state token, so the suffix is
``[action_tokens×H]`` and the mask is ``[1] + [0]*(H-1)``: the first
action token opens a causal block and the rest attend bidirectionally
within it.
"""
model_dtype = self.action_in_proj.weight.dtype
noisy_actions = noisy_actions.to(dtype=model_dtype)
time_cond = self.embed_timestep(timestep)
action_emb = self.action_in_proj(noisy_actions) # (B, H, W)
bsize, action_len = action_emb.shape[:2]
pad_masks = torch.ones(bsize, action_len, dtype=torch.bool, device=action_emb.device)
att_masks = torch.tensor(
[1] + [0] * (self.action_horizon - 1),
dtype=action_emb.dtype,
device=action_emb.device,
)[None, :].expand(bsize, -1)
return action_emb, pad_masks, att_masks, time_cond
# ── Denoising step ───────────────────────────────────────────────
def denoise_step(
self,
prefix_pad_masks: torch.Tensor,
past_key_values,
x_t: torch.Tensor,
timestep: torch.Tensor,
) -> torch.Tensor:
"""Apply one flow-matching denoising step: predict ``v_t`` from ``x_t``.
Signature differs from π0's by exactly one argument: no ``state``.
"""
suffix_embs, suffix_pad_masks, suffix_att_masks, time_cond = self.embed_suffix(x_t, timestep)
batch_size = prefix_pad_masks.shape[0]
suffix_len = suffix_pad_masks.shape[1]
prefix_len = prefix_pad_masks.shape[1]
prefix_pad_2d_masks = prefix_pad_masks[:, None, :].expand(batch_size, suffix_len, prefix_len)
suffix_att_2d_masks = make_att_2d_masks(suffix_pad_masks, suffix_att_masks)
full_att_2d_masks = torch.cat([prefix_pad_2d_masks, suffix_att_2d_masks], dim=2)
# Position IDs continue from where the prefix's last valid token left off.
prefix_offsets = torch.sum(prefix_pad_masks, dim=-1)[:, None]
position_ids = prefix_offsets + torch.cumsum(suffix_pad_masks, dim=1) - 1
full_att_2d_masks_4d = prepare_attention_masks_4d(full_att_2d_masks)
outputs_embeds, _ = self.paligemma_with_expert.forward(
attention_mask=full_att_2d_masks_4d,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=[None, suffix_embs],
use_cache=False,
adarms_cond=time_cond,
)
# Every suffix token is an action token in π0.5 (no state token to drop).
suffix_out = outputs_embeds[1][:, -self.action_horizon :]
suffix_out = suffix_out.to(dtype=self.action_out_proj.weight.dtype)
return self.action_out_proj(suffix_out)
# ── Full action generation ───────────────────────────────────────
@torch.no_grad()
def sample_actions(
self,
images: list[torch.Tensor],
image_masks: list[torch.Tensor],
lang_tokens: torch.Tensor,
lang_masks: torch.Tensor,
noise: torch.Tensor | None = None,
num_steps: int | None = None,
generator: torch.Generator | list[torch.Generator] | None = None,
) -> torch.Tensor:
"""Generate an action chunk via iterative flow-matching denoising.
Convention: ``t=1`` is noise, ``t=0`` is the target — opposite of the
published π0 paper but matching both OpenPI and LeRobot.
Takes no ``state``: π0.5's state rides inside ``lang_tokens``.
"""
if num_steps is None:
num_steps = self.num_inference_steps
bsize = lang_tokens.shape[0]
device = lang_tokens.device
if noise is None:
noise_shape = (self.action_horizon, self.action_dim)
if isinstance(generator, list):
if len(generator) != bsize:
raise ValueError(f"Expected {bsize} generators, got {len(generator)}.")
noise = torch.stack(
[torch.randn(noise_shape, dtype=torch.float32, device=device, generator=item) for item in generator]
)
else:
noise = torch.randn(
bsize,
*noise_shape,
dtype=torch.float32,
device=device,
generator=generator,
)
# 1. Prefix embeddings + mask building.
prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix(
images, image_masks, lang_tokens, lang_masks
)
prefix_att_2d_masks = make_att_2d_masks(prefix_pad_masks, prefix_att_masks)
prefix_position_ids = torch.cumsum(prefix_pad_masks, dim=1) - 1
prefix_att_2d_masks_4d = prepare_attention_masks_4d(prefix_att_2d_masks)
# 2. Forward prefix through PaliGemma LM, producing a list[(k, v)] cache.
_, past_key_values = self.paligemma_with_expert.forward(
attention_mask=prefix_att_2d_masks_4d,
position_ids=prefix_position_ids,
past_key_values=None,
inputs_embeds=[prefix_embs, None],
use_cache=True,
)
# 3. Euler-integrated denoising from t=1 down to t=0.
dt = -1.0 / num_steps
x_t = noise
for step in range(num_steps):
t = 1.0 + step * dt
time_tensor = torch.full((bsize,), t, dtype=torch.float32, device=device)
v_t = self.denoise_step(
prefix_pad_masks=prefix_pad_masks,
past_key_values=past_key_values,
x_t=x_t,
timestep=time_tensor,
)
x_t = x_t + dt * v_t
return x_t
# ── Weight loading ───────────────────────────────────────────────
def load_weights(
self,
weights: Iterable[tuple[str, torch.Tensor]],
*,
strict: bool = True,
):
"""Load and audit a LeRobot π0.5 safetensors checkpoint.
Same remap rules as π0 (strip the ``model.`` prefix, flatten→nested
PaliGemma submodules, tied ``lm_head`` → ``embed_tokens``, version-robust
SigLIP nesting), plus two π0.5-specific ones:
* ``action_time_mlp_{in,out}`` → ``time_mlp_{in,out}``: some
checkpoints were exported under the π0 parameter names.
* ``state_proj.*`` is reported, not silently dropped. A π0.5
checkpoint should not contain it; its presence usually means a π0
checkpoint was pointed at the π0.5 model class, which would
otherwise run happily with a randomly-initialized action expert.
The action-expert norms are AdaRMS here, so they expose ``dense.weight``
/ ``dense.bias`` and no plain ``weight``. A checkpoint that carries a
plain expert-norm ``weight`` is a π0-shaped checkpoint; that too is
rejected rather than skipped. ``strict=False`` exists only for focused
remapping unit tests that intentionally provide a partial state dict;
the serving path always uses the strict default.
"""
params_dict = dict(self.named_parameters())
buffers_dict = dict(self.named_buffers())
_PALIGEMMA_SUBMODULES = ("vision_tower", "multi_modal_projector", "language_model")
_EXPERT_PREFIX = "paligemma_with_expert.gemma_expert.model."
def _remap(name: str) -> str:
# Strip the leading "model." that LeRobot's PI05Policy wrapper adds.
if name.startswith("model."):
name = name[len("model.") :]
# π0-style timestep MLP names → π0.5 names.
if name.startswith("action_time_mlp_in."):
name = "time_mlp_in." + name[len("action_time_mlp_in.") :]
elif name.startswith("action_time_mlp_out."):
name = "time_mlp_out." + name[len("action_time_mlp_out.") :]
# Nested PaliGemma layout.
for sub in _PALIGEMMA_SUBMODULES:
flat = f"paligemma_with_expert.paligemma.{sub}."
nested = f"paligemma_with_expert.paligemma.model.{sub}."
if name.startswith(flat) and not name.startswith(nested):
return nested + name[len(flat) :]
if name == "paligemma_with_expert.paligemma.lm_head.weight":
return "paligemma_with_expert.paligemma.model.language_model.embed_tokens.weight"
return name
def _fix_vision_tower(name: str) -> str:
"""Reconcile SigLIP nesting across transformers versions (≤5.3 wraps
the encoder in ``vision_tower.vision_model.*``; ≥5.4 flattens it)."""
vt = "paligemma_with_expert.paligemma.model.vision_tower."
if not name.startswith(vt):
return name
rest = name[len(vt) :]
if name in params_dict or name in buffers_dict:
return name
if rest.startswith("vision_model."):
candidate = vt + rest[len("vision_model.") :]
else:
candidate = vt + "vision_model." + rest
return candidate if (candidate in params_dict or candidate in buffers_dict) else name
loaded = 0
skipped: list[str] = []
pi0_shaped: list[str] = []
filled_params: set = set()
for name, loaded_weight in weights:
mapped = _fix_vision_tower(_remap(name))
# Diagnose π0-shaped keys instead of dropping them quietly.
is_expert_norm_weight = mapped.startswith(_EXPERT_PREFIX) and (
mapped.endswith("input_layernorm.weight")
or mapped.endswith("post_attention_layernorm.weight")
or mapped == _EXPERT_PREFIX + "norm.weight"
)
if mapped.startswith("state_proj.") or is_expert_norm_weight:
pi0_shaped.append(mapped)
continue
if mapped in params_dict:
param = params_dict[mapped]
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, loaded_weight)
loaded += 1
filled_params.add(mapped)
elif mapped in buffers_dict:
buffers_dict[mapped].copy_(loaded_weight)
loaded += 1
filled_params.add(mapped)
else:
skipped.append(mapped)
# LeRobot stores PaliGemma's tied text embedding as lm_head.weight; keep
# lm_head filled so the tied-weight state stays consistent.
embed_key = "paligemma_with_expert.paligemma.model.language_model.embed_tokens.weight"
lm_head_key = "paligemma_with_expert.paligemma.lm_head.weight"
if embed_key in filled_params and lm_head_key in params_dict and lm_head_key not in filled_params:
params_dict[lm_head_key].data.copy_(params_dict[embed_key].data)
filled_params.add(lm_head_key)
# Reverse audit: any model param that got no checkpoint tensor at all
# would be running with random init.
missing_params: list[str] = []
for pname in params_dict:
if pname in filled_params:
continue
if "rotary_emb" in pname or pname.endswith(".inv_freq"):
continue
missing_params.append(pname)
parts: list[str] = []
if pi0_shaped:
parts.append(
f"{len(pi0_shaped)} checkpoint key(s) are π0-shaped, not π0.5-shaped (first 5: {pi0_shaped[:5]})"
)
if skipped:
parts.append(f"{len(skipped)} checkpoint key(s) had no model target (first 5: {skipped[:5]})")
if missing_params:
parts.append(f"{len(missing_params)} model param(s) received no weight (first 5: {missing_params[:5]})")
if parts and strict:
raise RuntimeError("Incomplete or incompatible π0.5 checkpoint: " + "; ".join(parts))
if parts:
logger.debug("π0.5 partial test load: %d tensors loaded — %s.", loaded, "; ".join(parts))
else:
logger.info("π0.5 load_weights: %d tensors loaded, 0 skipped, 0 missing.", loaded)
return filled_params
EntryClass = Pi05ForActionPrediction
@@ -0,0 +1,311 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""π0.5 VLA pipeline for vllm-omni.
Entry point for ``DiffusionEngine.step() → pipeline.forward(req)``. Mirrors the
DreamZero contract and the π0 pipeline: the pipeline owns ALL preprocessing. It
reads the raw robot observation from
``req.sampling_params.extra_args["robot_obs"]`` (delivered by the OpenPI
realtime serving layer), builds model inputs, runs flow-matching denoising, and
returns ``DiffusionOutput(output={"actions": ndarray})``.
π0.5 is stateless across calls (no KV reuse, first-order Markov), so
``session_id`` / ``reset`` from the OpenPI protocol are accepted but ignored.
The post-processing order is load-bearing and matches LeRobot::
unnormalize → absolute actions → to_cpu
``AbsoluteActionsProcessorStep`` must run *after* unnormalization, because a
relative-action checkpoint's ``norm_stats`` are computed in relative space.
"""
from __future__ import annotations
import json
import os
from dataclasses import fields as dataclass_fields
import numpy as np
import torch
from torch import nn
from vllm.logger import init_logger
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.models.pi05.config import SUPPORTED_DTYPE_NAMES, Pi05Config
from vllm_omni.diffusion.models.pi05.modeling_pi05 import Pi05ForActionPrediction
from vllm_omni.diffusion.models.pi05.processor_pi05 import Pi05Processor
from vllm_omni.diffusion.models.pi05_pipeline_config import PI05_PIPELINE as PI05_PIPELINE
from vllm_omni.diffusion.request import OmniDiffusionRequest
logger = init_logger(__name__)
# π0.5 pins the PaliGemma tokenizer (LeRobot hardcodes it too).
DEFAULT_PI05_TOKENIZER = "google/paligemma-3b-pt-224"
# float16 is absent deliberately, not by oversight: nothing here has been
# validated against it. The float32/bfloat16 trade-off is in the deploy config
# and recipes/lerobot/Pi05.md.
SUPPORTED_DTYPES = (torch.float32, torch.bfloat16)
# The two lists guard different entry points — what the checkpoint declares
# versus the dtype actually cast to — so they must not drift apart.
assert {str(dtype).split(".")[-1] for dtype in SUPPORTED_DTYPES} == set(SUPPORTED_DTYPE_NAMES)
def _checkpoint_declared_keys(model_dir: str) -> set[str]:
"""The keys the checkpoint's config.json actually carries."""
path = os.path.join(model_dir, "config.json")
if not os.path.exists(path):
return set()
with open(path, encoding="utf-8") as f:
return set(json.load(f))
def _comparable(value):
"""Compare yaml and checkpoint values without tripping on list/tuple."""
return list(value) if isinstance(value, (list, tuple)) else value
def _pi05_post_process(x):
"""Module-level identity post-process (picklable across the orchestrator's
multiprocess boundary — a local closure is not)."""
return x
def get_pi05_post_process_func(od_config: OmniDiffusionConfig):
"""π0.5 returns actions directly; post-processing is identity."""
del od_config
return _pi05_post_process
_LEROBOT_FLOAT32_IN_BFLOAT16 = (
"vision_tower",
"multi_modal_projector",
"input_layernorm",
"post_attention_layernorm",
"model.norm",
)
def _to_bfloat16_for_inference(model: Pi05ForActionPrediction) -> None:
"""Apply LeRobot's mixed-precision inference layout explicitly."""
inner_model = model.paligemma_with_expert
for name, param in inner_model.named_parameters():
target_dtype = (
torch.float32 if any(selector in name for selector in _LEROBOT_FLOAT32_IN_BFLOAT16) else torch.bfloat16
)
param.data = param.data.to(dtype=target_dtype)
for buffer in inner_model.buffers():
if buffer.is_floating_point():
buffer.data = buffer.data.to(dtype=torch.bfloat16)
for name, param in model.named_parameters():
if not name.startswith("paligemma_with_expert."):
param.data = param.data.to(dtype=torch.float32)
for name, buffer in model.named_buffers():
if not name.startswith("paligemma_with_expert.") and buffer.is_floating_point():
buffer.data = buffer.data.to(dtype=torch.float32)
def _set_inference_dtype(model: Pi05ForActionPrediction, dtype: torch.dtype) -> None:
if dtype == torch.float32:
model.to(dtype=torch.float32)
elif dtype == torch.bfloat16:
_to_bfloat16_for_inference(model)
else:
raise ValueError(f"Unsupported π0.5 inference dtype: {dtype!r}.")
class Pi05Pipeline(nn.Module):
"""π0.5 VLA pipeline: raw robot obs → continuous action chunk.
Registered as ``"Pi05Pipeline"`` in the diffusion registry.
"""
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
super().__init__()
self.od_config = od_config
self.prefix = prefix
self.model_dir = self._resolve_model_dir(od_config.model)
self.config = self._build_config(od_config)
custom_args = od_config.custom_pipeline_args or {}
self.tokenizer_source = str(custom_args.get("tokenizer", self._resolve_tokenizer_source()))
self._torch_dtype = self._resolve_dtype(od_config)
self._device = self._resolve_device(od_config)
self.tokenizer = self._load_tokenizer()
self.model = self._initialize_model()
self.processor = Pi05Processor(self.config, self.tokenizer, self._device)
# ------------------------------------------------------------------
# Construction helpers
# ------------------------------------------------------------------
@staticmethod
def _resolve_model_dir(model: str | None) -> str | None:
"""Return a local directory for ``model``; download an HF repo id if needed."""
if not model:
return None
if os.path.isdir(model):
return model
# Via repo_utils' shared HfApi rather than huggingface_hub directly, so
# the download carries vLLM-Omni's user agent like every other repo access.
from vllm_omni.transformers_utils.repo_utils import hf_api
return hf_api().snapshot_download(
repo_id=model,
allow_patterns=["*.json", "*.safetensors", "*.model", "tokenizer*"],
)
def _build_config(self, od_config: OmniDiffusionConfig) -> Pi05Config:
"""Read the config from the checkpoint, then let the deploy yaml override it."""
checkpoint_config = Pi05Config.from_pretrained(self.model_dir) if self.model_dir else None
if checkpoint_config is None:
return Pi05Config.from_model_config(od_config.model_config)
if not od_config.model_config:
return checkpoint_config
resolved = {
item.name: getattr(checkpoint_config, item.name) for item in dataclass_fields(Pi05Config) if item.init
}
# Only a key the checkpoint actually declares can disagree with the yaml.
# Comparing against the dataclass default instead would report every
# serving-only field, such as policy_server_config, on every start.
declared_keys = _checkpoint_declared_keys(self.model_dir)
for key, value in od_config.model_config.items():
if key in resolved and key in declared_keys and _comparable(value) != _comparable(resolved[key]):
logger.warning(
"Pi05Pipeline: the deploy config sets %s=%r, overriding %r from the checkpoint.",
key,
value,
resolved[key],
)
resolved.update(od_config.model_config)
return Pi05Config.from_model_config(resolved)
def _resolve_tokenizer_source(self) -> str:
"""Prefer the checkpoint dir if it ships tokenizer files; else PaliGemma."""
if self.model_dir and os.path.isdir(self.model_dir):
if os.path.exists(os.path.join(self.model_dir, "tokenizer_config.json")):
return self.model_dir
return DEFAULT_PI05_TOKENIZER
@staticmethod
def _resolve_dtype(od_config: OmniDiffusionConfig) -> torch.dtype:
"""Resolve the dtype the weights are actually cast to.
This is the load-bearing check, not ``Pi05Config.dtype``: the cast in
:meth:`_initialize_model` reads the *top-level* ``OmniDiffusionConfig``
field, so a guard on the model config alone would let an unsupported
dtype through. See :data:`SUPPORTED_DTYPES` for why float16 is excluded.
"""
dt = od_config.dtype
resolved = dt if isinstance(dt, torch.dtype) else getattr(torch, str(dt).split(".")[-1], None)
if resolved not in SUPPORTED_DTYPES:
raise ValueError(
f"Unsupported π0.5 dtype: {dt!r}. Supported: "
f"{', '.join(sorted(str(d).split('.')[-1] for d in SUPPORTED_DTYPES))}."
)
return resolved
@staticmethod
def _resolve_device(od_config: OmniDiffusionConfig) -> torch.device:
from vllm_omni.diffusion.distributed.utils import get_local_device
try:
return get_local_device()
except Exception: # noqa: BLE001
return torch.device("cuda" if torch.cuda.is_available() else "cpu")
def _load_tokenizer(self):
from transformers import AutoTokenizer
# padding_side="right" is part of the π0.5 spec: the prefix is a fixed
# 200-token block whose live tokens must start at index 0.
return AutoTokenizer.from_pretrained(self.tokenizer_source, padding_side="right")
def has_real_checkpoint(self) -> bool:
return bool(self.model_dir) and os.path.exists(os.path.join(self.model_dir, "model.safetensors"))
def _initialize_model(self) -> Pi05ForActionPrediction:
if not self.has_real_checkpoint():
expected = os.path.join(self.model_dir or "<missing-model-dir>", "model.safetensors")
raise FileNotFoundError(f"π0.5 serving requires checkpoint weights at {expected}.")
model = Pi05ForActionPrediction(self.config)
_set_inference_dtype(model, self._torch_dtype)
model.to(device=self._device)
self._load_checkpoint(model)
model.eval()
return model
def _load_checkpoint(self, model: Pi05ForActionPrediction) -> None:
import safetensors.torch
path = os.path.join(self.model_dir, "model.safetensors")
logger.info("Pi05Pipeline: loading π0.5 weights from %s", path)
try:
state = safetensors.torch.load_file(path)
model.load_weights(state.items())
except Exception as exc:
raise RuntimeError(f"Failed to load complete π0.5 checkpoint {path}: {exc}") from exc
# ------------------------------------------------------------------
# Framework weight-loading hook
# ------------------------------------------------------------------
def load_weights(self, weights=()): # noqa: D401
"""No-op for the diffusion loader: π0.5 self-loads its checkpoint."""
for _ in weights:
pass
return None
# ------------------------------------------------------------------
# Inference
# ------------------------------------------------------------------
@torch.inference_mode()
def forward(self, req: OmniDiffusionRequest, **kwargs) -> DiffusionOutput:
extra_args = getattr(req.sampling_params, "extra_args", None) or {}
robot_obs = extra_args.get("robot_obs")
if robot_obs is None:
# Dummy warmup path (no obs): return zeros so engine warmup/capture
# doesn't crash. Mirrors DreamZero's dummy-run handling.
first_prompt = req.prompts[0] if req.prompts else ""
prompt = first_prompt if isinstance(first_prompt, str) else (first_prompt.get("prompt") or "")
num_steps = getattr(req.sampling_params, "num_inference_steps", None)
if prompt == "dummy run" or num_steps == 1:
logger.info("Pi05Pipeline: dummy warmup request without robot_obs — returning zeros.")
return DiffusionOutput(
output={
"actions": np.zeros(
(self.config.chunk_size, self.config.action_dim),
dtype=np.float32,
)
},
)
return DiffusionOutput(
error="Pi05Pipeline.forward requires sampling_params.extra_args['robot_obs'].",
)
images, image_masks, lang_tokens, lang_masks = self.processor.build_model_inputs(robot_obs)
num_steps = getattr(req.sampling_params, "num_inference_steps", None)
if num_steps is not None and (
isinstance(num_steps, bool) or not isinstance(num_steps, (int, np.integer)) or int(num_steps) < 1
):
raise ValueError(f"num_inference_steps must be a positive integer, got {num_steps!r}.")
if num_steps is not None:
num_steps = int(num_steps)
actions = self.model.sample_actions(
images=images,
image_masks=image_masks,
lang_tokens=lang_tokens,
lang_masks=lang_masks,
num_steps=num_steps,
generator=req.sampling_params.generator,
)
return DiffusionOutput(output={"actions": self.processor.build_model_outputs(actions, robot_obs)})
@@ -0,0 +1,568 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
r"""Preprocessing for the π0.5 VLA model.
Converts a raw robot observation (multi-camera images + language instruction +
proprioceptive state) into the tensors ``Pi05ForActionPrediction.sample_actions``
consumes.
**The defining π0.5 difference:** the state is not projected by a ``state_proj``
layer. It is normalized to ``[-1, 1]``, discretized into ``state_num_bins`` bins,
and serialized into the language prompt::
"Task: <instruction>, State: <b0> <b1> ... <bN>;\nAction: "
so ``sample_actions`` receives no state tensor at all.
**Normalization must precede discretization.** The discretizer bins over
``[-1, 1]`` and assumes the state is already in that range. Reversed, every bin
index is wrong and nothing raises.
Reference:
- OpenPI: openpi/src/openpi/shared/image_tools.py (resize_with_pad)
- OpenPI: openpi/src/openpi/models/pi0_config.py (PaliGemmaTokenizer.tokenize)
- LeRobot: lerobot/src/lerobot/policies/pi05/processor_pi05.py
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from vllm.logger import init_logger
from vllm_omni.diffusion.models.pi05.config import resolve_excluded_action_indices
from vllm_omni.diffusion.models.pi05.modeling_pi05 import (
DEFAULT_IMAGE_RESOLUTION,
DEFAULT_MAX_TOKEN_LEN,
DEFAULT_STATE_NUM_BINS,
)
logger = init_logger(__name__)
# LeRobot NormalizerProcessorStep.eps.
NORM_EPS = 1e-8
# ──────────────────────────────────────────────────────────────────────
# Image preprocessing (identical to π0 — SigLIP is unchanged in π0.5)
# ──────────────────────────────────────────────────────────────────────
def resize_with_pad(
images: torch.Tensor,
target_height: int,
target_width: int,
mode: str = "bilinear",
) -> torch.Tensor:
"""Resize ``(B, C, H, W)`` images to the target shape, preserving aspect
ratio with -1 padding on the short side.
Matches openpi ``image_tools.resize_with_pad_torch`` — the clamp to
[-1, 1] is what lets the padded region blend with SigLIP-normalized
pixels without adding signal at the boundary.
"""
if images.ndim != 4:
raise ValueError(f"Expected 4-D (B,C,H,W), got {images.ndim}-D")
_, _, cur_h, cur_w = images.shape
ratio = max(cur_w / target_width, cur_h / target_height)
rh, rw = int(cur_h / ratio), int(cur_w / ratio)
align_corners = False if mode == "bilinear" else None
resized = F.interpolate(images, size=(rh, rw), mode=mode, align_corners=align_corners)
resized = resized.clamp(-1.0, 1.0)
ph, rem_h = divmod(target_height - rh, 2)
pw, rem_w = divmod(target_width - rw, 2)
return F.pad(resized, (pw, pw + rem_w, ph, ph + rem_h), value=-1.0)
def pil_image_to_tensor(image: Image.Image) -> torch.Tensor:
"""PIL → ``(1, C, H, W)`` float32 in ``[-1, 1]`` (SigLIP normalization)."""
if image.mode != "RGB":
image = image.convert("RGB")
arr = np.array(image, dtype=np.float32) / 255.0 * 2.0 - 1.0
return torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0)
class Pi05ImageProcessor:
"""Minimal image preprocessor: image → normalized + padded ``[-1,1]`` tensor."""
def __init__(self, image_size: int = DEFAULT_IMAGE_RESOLUTION[0]):
self.image_size = image_size
def preprocess_single(self, image: Any) -> torch.Tensor:
"""Convert one LeRobot-domain image to a normalized model tensor.
PIL and uint8 inputs have domain ``[0, 255]``. Floating ndarray/tensor
inputs must be finite and in ``[0, 1]``. Values are converted
deterministically to ``[-1, 1]``; the pixel content is never used to
guess its input domain.
"""
t = self._to_tensor(image)
if t.shape[2] != self.image_size or t.shape[3] != self.image_size:
t = resize_with_pad(t, self.image_size, self.image_size)
return t
def _to_tensor(self, image: Any) -> torch.Tensor:
if isinstance(image, Image.Image):
return pil_image_to_tensor(image)
if isinstance(image, np.ndarray):
if image.ndim != 3 or image.shape[-1] != 3:
raise ValueError(f"Expected an HWC ndarray with 3 channels, got shape {image.shape}.")
t = torch.from_numpy(np.ascontiguousarray(image)).permute(2, 0, 1).unsqueeze(0)
elif isinstance(image, torch.Tensor):
t = image.unsqueeze(0) if image.ndim == 3 else image
if t.ndim != 4 or t.shape[0] != 1 or t.shape[1] != 3:
raise ValueError(f"Expected a CHW tensor (optionally batched once), got shape {tuple(t.shape)}.")
else:
raise TypeError(f"Unsupported image type for π0.5 preprocessing: {type(image)}")
if t.dtype == torch.uint8:
return t.to(dtype=torch.float32) / 255.0 * 2.0 - 1.0
if not t.is_floating_point():
raise TypeError(f"π0.5 images must use uint8 or floating dtype, got {t.dtype}.")
if not torch.isfinite(t).all():
raise ValueError("Floating π0.5 image contains NaN or Inf.")
low, high = float(t.amin()), float(t.amax())
if low < 0.0 or high > 1.0:
raise ValueError(f"Floating π0.5 images must be in [0, 1]; observed min={low}, max={high}.")
return t.to(dtype=torch.float32) * 2.0 - 1.0
def make_empty_image(self) -> torch.Tensor:
"""Fill tensor for an unused camera slot — pure -1, matches OpenPI/LeRobot."""
return torch.full((1, 3, self.image_size, self.image_size), -1.0)
# ──────────────────────────────────────────────────────────────────────
# Normalization (LeRobot NormalizerProcessorStep)
# ──────────────────────────────────────────────────────────────────────
@dataclass(frozen=True)
class NormStats:
"""The affine map a checkpoint's statistics define.
``mean_std`` carries mean and std; the two range modes carry the lower and
upper bound (``min``/``max``, or the ``q01``/``q99`` quantiles π0.5 ships).
"""
mode: str
lower: torch.Tensor
upper: torch.Tensor
def build_norm_stats(norm_stats: dict | None, key: str) -> NormStats | None:
"""Read ``norm_stats[key]`` into tensors, or ``None`` when it carries none.
The mode comes from the entry. A LeRobot state_dict ships mean, std, min,
max, q01 and q99 at once, so the statistic names present cannot select it.
Missing modes default to quantile, which is what LeRobot defaults π0.5's
STATE and ACTION to (π0 defaults to mean_std).
"""
entry = (norm_stats or {}).get(key)
if not entry:
return None
mode = str(entry.get("mode", "quantile")).lower()
if mode == "mean_std":
names = ("mean", "std")
elif mode == "min_max":
names = ("min", "max")
elif mode == "quantile":
mode, names = "min_max", ("q01", "q99")
else:
raise ValueError(f"Unsupported normalization mode for {key!r}: {mode!r}.")
bounds = [entry.get(name) for name in names]
if any(bound is None for bound in bounds):
raise ValueError(f"Normalization mode {mode!r} for {key!r} requires {names[0]!r} and {names[1]!r}.")
lower, upper = (torch.as_tensor(bound, dtype=torch.float32) for bound in bounds)
return NormStats(mode=mode, lower=lower, upper=upper)
def apply_norm(x: torch.Tensor, stats: NormStats | None, *, inverse: bool = False) -> torch.Tensor:
"""Map raw units to the model's normalized space, or back with ``inverse``.
Actions are padded to ``max_action_dim`` while the statistics cover only the
real width, so the tail passes through untouched. The eps rules are
LeRobot's: ``mean_std`` always divides by ``std + eps``, and the range modes
substitute ``eps`` only for an exactly zero range.
"""
if stats is None:
return x
lower = stats.lower.to(device=x.device, dtype=x.dtype)
upper = stats.upper.to(device=x.device, dtype=x.dtype)
valid = lower.shape[0]
head = x[..., :valid]
if stats.mode == "mean_std":
head = head * upper + lower if inverse else (head - lower) / (upper + NORM_EPS)
else:
span = upper - lower
span = torch.where(span == 0, NORM_EPS, span)
head = (head + 1.0) * 0.5 * span + lower if inverse else 2.0 * (head - lower) / span - 1.0
if valid == x.shape[-1]:
return head
return torch.cat([head, x[..., valid:]], dim=-1)
# ──────────────────────────────────────────────────────────────────────
# State: normalize → discretize → prompt (π0.5's defining path)
# ──────────────────────────────────────────────────────────────────────
def _pad_or_truncate(raw_state: Any, width: int) -> np.ndarray:
"""Zero-pad / truncate a vector to ``(width,)`` float32."""
if raw_state is None:
return np.zeros((width,), dtype=np.float32)
if isinstance(raw_state, torch.Tensor):
raw_state = raw_state.detach().cpu().numpy()
state = np.asarray(raw_state, dtype=np.float32).reshape(-1)
if state.shape[0] < width:
state = np.pad(state, (0, width - state.shape[0]))
elif state.shape[0] > width:
state = state[:width]
return state.astype(np.float32)
def as_state_vector(raw_state: Any, state_dim: int) -> np.ndarray:
"""Coerce a request's raw state to ``(state_dim,)`` float32, or raise.
LeRobot's ``Pi05PrepareStateTokenizerProcessorStep`` discretizes whatever
width it is handed and never pads to ``max_state_dim``, so zero-filling a
7-dim state up to 32 would append 25 state tokens the checkpoint never saw
in training.
"""
if raw_state is None:
raise ValueError("π0.5 requires a state; there is no default to fall back on.")
if isinstance(raw_state, torch.Tensor):
raw_state = raw_state.detach().cpu().numpy()
state = np.asarray(raw_state, dtype=np.float32)
if state.ndim == 2 and state.shape[0] == 1:
state = state[0]
if state.ndim != 1:
raise ValueError(f"π0.5 state must be shaped (D,) or (1, D); got {tuple(state.shape)}.")
if not np.isfinite(state).all():
raise ValueError("π0.5 state contains NaN or Inf.")
if state.shape[0] != state_dim:
raise ValueError(
f"π0.5 state has {state.shape[0]} dimension(s), but the checkpoint declares "
f"{state_dim}. The state is serialized into the prompt at its real width, so "
"padding or truncating it would change the tokens the model sees."
)
return state
def discretize_state(state: np.ndarray, *, num_bins: int = DEFAULT_STATE_NUM_BINS) -> np.ndarray:
"""Discretize a ``[-1, 1]`` state into ``num_bins`` integer bins.
Byte-for-byte LeRobot's ``processor_pi05.py``::
np.digitize(state_np, bins=np.linspace(-1, 1, 256 + 1)[:-1]) - 1
A state below ``-1`` lands in bin ``-1``, and that negative bin is part of
the contract: the checkpoint was trained with ``" -1"`` in the state prompt
for those dimensions. Clipping it to ``0`` changes the tokens the model
sees, so this must not clip.
``bins`` stays float64, matching LeRobot's default ``linspace`` dtype, so
boundary values fall on the same side.
**Assumes the state is already normalized** — see the module docstring.
"""
bins = np.linspace(-1.0, 1.0, num_bins + 1)[:-1]
return (np.digitize(np.asarray(state, dtype=np.float32), bins=bins) - 1).astype(np.int64)
def build_pi05_prompt(
*,
task: str,
normalized_state: np.ndarray,
state_num_bins: int = DEFAULT_STATE_NUM_BINS,
) -> str:
"""Build the π0.5 prompt: instruction + serialized discretized state.
Matches LeRobot's ``Pi05PrepareStateTokenizerProcessorStep``, including the
task cleanup (``strip``, ``_`` → space, newline → space), the exact template
and the state values it serializes. The template already ends in a newline,
so — unlike π0 — there is no separate newline-appending step.
``normalized_state`` comes from ``Pi05ForActionPrediction._normalize_state``.
"""
cleaned_task = (task or "").strip().replace("_", " ").replace("\n", " ")
bins = discretize_state(normalized_state, num_bins=state_num_bins)
state_str = " ".join(str(int(x)) for x in bins.tolist())
return f"Task: {cleaned_task}, State: {state_str};\nAction: "
def tokenize_prompt(tokenizer, text: str, max_token_len: int = DEFAULT_MAX_TOKEN_LEN):
"""Return ``(input_ids, attention_mask)`` lists, length exactly ``max_token_len``.
``padding="max_length"`` is what makes the prefix a constant shape: the text
segment is always ``max_token_len`` tokens regardless of the instruction, so
only ``attention_mask.sum()`` varies per request.
"""
enc = tokenizer(
text,
padding="max_length",
max_length=max_token_len,
truncation=True,
add_special_tokens=True,
return_tensors=None,
)
return list(enc["input_ids"]), list(enc["attention_mask"])
# ──────────────────────────────────────────────────────────────────────
# Relative actions
# ──────────────────────────────────────────────────────────────────────
class Pi05RelativeActions:
"""The relative/absolute action transform, as a single paired object.
LeRobot builds one ``RelativeActionsProcessorStep`` and hands *the same
instance* to ``AbsoluteActionsProcessorStep``; the two directions must
agree on ``enabled`` and on which dimensions are excluded, so they are one
object here too.
**Deviation from LeRobot, on purpose.** LeRobot's step keeps the reference
state on ``self`` between the pre- and post-pass. That is safe for a
single-threaded training loop and unsafe for a server: two in-flight
requests would share one reference state and silently corrupt each other's
actions. Here the state is passed explicitly to :meth:`to_absolute`, so the
object stays immutable after construction and is safe to share across
requests.
Transform (LeRobot / OpenPI): ``relative = action - state`` on the way in,
``absolute = relative + state`` on the way out, applied only to the
dimensions *not* named in ``exclude_joints``. Gripper open/close is an
absolute command, which is why it is excluded by default.
"""
def __init__(
self,
*,
enabled: bool,
exclude_joints: list[str] | None = None,
action_names: list[str] | None = None,
max_action_dim: int = 32,
):
self.enabled = bool(enabled)
self.exclude_joints = list(exclude_joints or [])
self.action_names = list(action_names) if action_names else None
self.max_action_dim = int(max_action_dim)
# Boolean mask over action dims: True = this dim is relative to state.
mask = np.ones((self.max_action_dim,), dtype=bool)
if self.enabled:
for idx in resolve_excluded_action_indices(self.exclude_joints, self.action_names):
if 0 <= idx < self.max_action_dim:
mask[idx] = False
# Padding beyond the real action dimensions carries no signal;
# leaving it "relative" would add state noise into dead channels.
if self.action_names:
mask[len(self.action_names) :] = False
else:
mask[:] = False
self.relative_mask = mask
@property
def num_relative_dims(self) -> int:
return int(self.relative_mask.sum())
def _state_row(self, state: Any, device, dtype) -> torch.Tensor:
"""Raw state → ``(B, max_action_dim)`` aligned with the action dims.
Accepts one state for the whole batch (``(D,)``, the serving path,
where the pipeline runs B=1) or one state per sample (``(B, D)``).
LeRobot caches the batched state and shifts each sample by its own row,
so the per-sample form has to be honoured: ``_pad_or_truncate``
flattens, which would silently reduce ``(B, D)`` to sample 0's state and
apply it to every sample — wrong answers, no error.
"""
if isinstance(state, torch.Tensor):
state = state.detach().cpu().numpy()
arr = np.asarray(0.0 if state is None else state, dtype=np.float32)
if arr.ndim > 2:
raise ValueError(f"Expected state shaped (D,) or (B, D), got {tuple(arr.shape)}")
rows = arr if arr.ndim == 2 else arr[None, :]
padded = np.stack([_pad_or_truncate(row, self.max_action_dim) for row in rows])
return torch.as_tensor(padded, device=device, dtype=dtype)
def to_relative(self, actions: torch.Tensor, state: Any) -> torch.Tensor:
"""``absolute → relative``. Input side (step 3).
Not used on the inference path — there are no input actions to convert
at serving time — but it is what the transform *means*, and the parity
test exercises it as the inverse of :meth:`to_absolute`.
"""
if not self.enabled:
return actions
return self._shift(actions, state, sign=-1.0)
def to_absolute(self, actions: torch.Tensor, state: Any) -> torch.Tensor:
"""``relative → absolute``. Output side (step 2 of the post-pipeline).
``state`` must be the **raw** state — the same one the model was given
before normalization — because relative actions live in raw action space.
"""
if not self.enabled:
return actions
return self._shift(actions, state, sign=+1.0)
def _shift(self, actions: torch.Tensor, state: Any, *, sign: float) -> torch.Tensor:
if actions.ndim != 3:
raise ValueError(f"Expected actions shaped (B, horizon, action_dim), got {tuple(actions.shape)}")
action_dim = actions.shape[-1]
if action_dim != self.max_action_dim:
raise ValueError(
f"Action dim {action_dim} does not match max_action_dim={self.max_action_dim}; "
"the relative mask would be misaligned."
)
state_row = self._state_row(state, actions.device, actions.dtype) # (1, D)
mask = torch.as_tensor(self.relative_mask, device=actions.device)
delta = torch.where(mask, state_row, torch.zeros_like(state_row))
# Broadcast over the action horizon: every step of the chunk is
# expressed relative to the same current state.
return actions + sign * delta[:, None, :]
# ──────────────────────────────────────────────────────────────────────
# Model input assembly
# ──────────────────────────────────────────────────────────────────────
def _extract_images(robot_obs: dict, config) -> dict[str, Any]:
"""Pull a ``{feature_key: image}`` map out of a raw robot obs.
This is functional step 1 (``rename_observations``): keys are translated
through ``config.image_key_map`` so serving wire names map onto the
checkpoint's ``input_features`` identities.
"""
images = robot_obs.get("images")
if not isinstance(images, dict):
images = {k: v for k, v in robot_obs.items() if _is_image_like(v)}
key_map = config.image_key_map or {}
return {key_map.get(k, k): v for k, v in images.items() if _is_image_like(v)}
def _is_image_like(value: Any) -> bool:
if isinstance(value, (Image.Image, torch.Tensor)):
return True
if isinstance(value, np.ndarray):
return value.ndim >= 3
if isinstance(value, (list, tuple)):
try:
return np.asarray(value).ndim >= 3
except Exception: # noqa: BLE001
return False
return False
def _assemble_model_inputs(robot_obs: dict, config, tokenizer, device: torch.device, state_norm: NormStats | None):
"""Convert a raw robot observation into ``sample_actions`` inputs.
Returns ``(images, image_masks, lang_tokens, lang_masks)`` — note there is
**no state tensor**: π0.5 carries the state inside ``lang_tokens``.
Camera slots follow ``config.image_feature_keys`` order. A missing key keeps
its semantic slot and receives an empty image with a false mask. The output
always contains exactly ``max_cameras`` slots for the deployed model.
"""
image_size = int(config.image_resolution[0])
img_proc = Pi05ImageProcessor(image_size=image_size)
max_cameras = config.max_cameras
feature_keys = config.image_feature_keys or []
obs_images = _extract_images(robot_obs, config)
if not feature_keys:
# No declared camera order — fall back to whatever the obs provides,
# preserving insertion order.
feature_keys = list(obs_images.keys())[:max_cameras]
camera_keys = feature_keys[:max_cameras]
if all(obs_images.get(key) is None for key in camera_keys):
raise ValueError("π0.5 observation must provide at least one configured camera image.")
if not config.image_feature_keys and len(obs_images) > max_cameras:
raise ValueError(
f"π0.5 observation provides {len(obs_images)} cameras, which exceeds max_cameras={max_cameras}."
)
images: list[torch.Tensor] = []
image_masks: list[torch.Tensor] = []
for key in camera_keys:
image = obs_images.get(key)
if image is None:
tensor = img_proc.make_empty_image().to(device=device)
mask = False
else:
tensor = img_proc.preprocess_single(image).to(device=device)
mask = True
images.append(tensor)
image_masks.append(torch.tensor([mask], dtype=torch.bool, device=device))
# A checkpoint may declare fewer named slots than the serving graph.
while len(images) < max_cameras:
images.append(img_proc.make_empty_image().to(device=device))
image_masks.append(torch.tensor([False], dtype=torch.bool, device=device))
# Normalize and serialize the state into the tokenized prompt.
raw_state = as_state_vector(robot_obs.get("state"), config.state_dim)
normalized_state = apply_norm(torch.from_numpy(raw_state), state_norm).numpy()
prompt = build_pi05_prompt(
task=robot_obs.get("prompt", "") or "",
normalized_state=normalized_state,
state_num_bins=config.state_num_bins,
)
ids, attn = tokenize_prompt(tokenizer, prompt, config.tokenizer_max_length)
lang_tokens = torch.tensor([ids], dtype=torch.long, device=device)
lang_masks = torch.tensor([attn], dtype=torch.bool, device=device)
return images, image_masks, lang_tokens, lang_masks
# ──────────────────────────────────────────────────────────────────────
# The interface the pipeline uses
# ──────────────────────────────────────────────────────────────────────
class Pi05Processor:
"""Everything between the OpenPI wire and the model.
Owns the normalization statistics and the relative-action transform, so the
pipeline holds no preprocessing state of its own.
"""
def __init__(self, config, tokenizer, device: torch.device):
self.config = config
self.tokenizer = tokenizer
self.device = device
self._state_norm = build_norm_stats(config.norm_stats, "state")
self._action_norm = build_norm_stats(config.norm_stats, "action")
self.relative_actions = Pi05RelativeActions(
enabled=config.use_relative_actions,
exclude_joints=config.relative_exclude_joints,
action_names=config.action_feature_names,
max_action_dim=config.max_action_dim,
)
if self._action_norm is None:
logger.info("π0.5: no action normalization stats; returned actions stay in normalized space.")
if self.relative_actions.enabled:
logger.info(
"π0.5: relative actions enabled — %d of %d action dims are state-relative (excluded joints: %s).",
self.relative_actions.num_relative_dims,
config.max_action_dim,
config.relative_exclude_joints,
)
def build_model_inputs(self, robot_obs: dict):
"""Raw observation → ``sample_actions`` inputs.
No state tensor comes back: π0.5 carries the state inside ``lang_tokens``.
"""
return _assemble_model_inputs(robot_obs, self.config, self.tokenizer, self.device, self._state_norm)
def build_model_outputs(self, actions: torch.Tensor, robot_obs: dict) -> np.ndarray:
"""Model output → the action chunk the robot receives.
``AbsoluteActionsProcessorStep`` runs after unnormalization, because a
relative-action checkpoint's statistics are computed in relative space.
The raw state is the one the prompt encoded, before normalization.
"""
actions = apply_norm(actions, self._action_norm, inverse=True)
if self.relative_actions.enabled:
actions = self.relative_actions.to_absolute(actions, robot_obs.get("state"))
return actions.squeeze(0)[..., : self.config.action_dim].float().cpu().numpy()
@@ -0,0 +1,30 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Lightweight pipeline topology for π0.5."""
from vllm_omni.config.stage_config import (
PipelineConfig,
StageExecutionType,
StagePipelineConfig,
)
# π0.5 is one diffusion stage (robot observation -> action chunk via flow
# matching). It is registered in ``OMNI_PIPELINES`` because π0.5 is online-served
# via ``vllm serve --deploy-config pi05.yaml``. Keep this topology outside the
# ``pi05`` package: importing a package submodule executes ``pi05.__init__``,
# which imports the runtime pipeline and ``diffusion.data``.
PI05_PIPELINE = PipelineConfig(
model_type="pi05",
model_arch="Pi05Pipeline",
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="diffusion",
execution_type=StageExecutionType.DIFFUSION,
input_sources=(),
final_output=True,
final_output_type="action",
model_arch="Pi05Pipeline",
),
),
)
@@ -337,14 +337,20 @@ class QwenImagePipeline(
del visual_owner.visual
else:
logger.warning("Qwen-Image: vision tower not found on text encoder; skipping drop")
self.text_encoder = self.text_encoder.to(self.device)
# Under model-level CPU offload, keep the BF16 encoder/VAE on CPU so they
# do not share VRAM with DiT construction (#7555). The DiT follows the
# loader's default-device context (CUDA for online / AutoRound INT under
# offload, CPU for layerwise / unquantized HSDP defer).
cpu_offload = bool(getattr(self.od_config, "enable_cpu_offload", False))
enc_vae_device = torch.device("cpu") if cpu_offload else self.device
self.text_encoder = self.text_encoder.to(enc_vae_device)
self.vae = from_pretrained_with_prefetch(
DistributedAutoencoderKLQwenImage.from_pretrained,
model,
subfolder="vae",
prefetch_list=qwen_subfolders,
local_files_only=local_files_only,
).to(self.device)
).to(enc_vae_device)
transformer_kwargs = get_transformer_config_kwargs(od_config.tf_model_config, QwenImageTransformer2DModel)
self.transformer = QwenImageTransformer2DModel(
od_config=od_config,
@@ -374,51 +374,6 @@ class QwenImageEditPipeline(
return split_result
def _get_qwen_prompt_embeds(
self,
prompt: str | list[str] = None,
image: torch.Tensor | None = None,
dtype: torch.dtype | None = None,
):
dtype = dtype or self.text_encoder.dtype
prompt = [prompt] if isinstance(prompt, str) else prompt
template = self.prompt_template_encode
drop_idx = self.prompt_template_encode_start_idx
txt = [template.format(e) for e in prompt]
model_inputs = self.processor(
text=txt,
images=image,
padding=True,
return_tensors="pt",
).to(self.device)
outputs = self.text_encoder(
input_ids=model_inputs.input_ids,
attention_mask=model_inputs.attention_mask,
pixel_values=model_inputs.pixel_values,
image_grid_thw=model_inputs.image_grid_thw,
output_hidden_states=True,
)
hidden_states = outputs.hidden_states[-1]
split_hidden_states = self._extract_masked_hidden(hidden_states, model_inputs.attention_mask)
split_hidden_states = [e[drop_idx:] for e in split_hidden_states]
attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states]
max_seq_len = max([e.size(0) for e in split_hidden_states])
prompt_embeds = torch.stack(
[torch.cat([u, u.new_zeros(max_seq_len - u.size(0), u.size(1))]) for u in split_hidden_states]
)
encoder_attention_mask = torch.stack(
[torch.cat([u, u.new_zeros(max_seq_len - u.size(0))]) for u in attn_mask_list]
)
prompt_embeds = prompt_embeds.to(dtype=dtype, device=self.device)
return prompt_embeds, encoder_attention_mask
def _get_qwen_prompt_embeds(
self,
prompt: str | list[str] = None,
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
@@ -45,20 +45,61 @@ from vllm_omni.diffusion.distributed.sp_plan import (
)
from vllm_omni.diffusion.forward_context import get_forward_context
from vllm_omni.diffusion.layers.adalayernorm import AdaLayerNorm
from vllm_omni.diffusion.layers.fused_qk_norm_rope import (
_fused_cuda_supported,
fused_qk_norm_rope,
)
from vllm_omni.diffusion.layers.qwen_select01_modulation import (
can_use_qwen_select01_triton,
fused_layernorm_select01,
fused_residual_layernorm_select01,
select01_modulation_native,
)
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
logger = init_logger(__name__)
def _apply_qwen_image_rotary_emb(x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
"""Rotate interleaved pairs before rounding back to the activation dtype.
def _qwen_image_qk_norm_rope(
q: torch.Tensor,
k: torch.Tensor,
norm_q: nn.Module,
norm_k: nn.Module,
freqs: torch.Tensor,
rope: RotaryEmbedding,
eps: float,
*,
use_fused: bool = True,
) -> tuple[torch.Tensor, torch.Tensor]:
head_dim = q.shape[-1]
rotary_dim = freqs.shape[-1] * 2
if use_fused and _fused_cuda_supported(q, k, head_dim, rotary_dim, interleaved=True):
batch, seq_len, num_heads, _ = q.shape
num_kv_heads = k.shape[2]
rope_table = torch.cat((freqs.real, freqs.imag), dim=-1)
rope_table = rope_table.unsqueeze(0).expand(batch, -1, -1).reshape(batch * seq_len, rotary_dim)
fused_q, fused_k = fused_qk_norm_rope(
q.reshape(batch * seq_len, num_heads, head_dim),
k.reshape(batch * seq_len, num_kv_heads, head_dim),
norm_q.weight,
norm_k.weight,
rope_table,
eps,
interleaved=True,
)
return (
fused_q.reshape(batch, seq_len, num_heads, head_dim),
fused_k.reshape(batch, seq_len, num_kv_heads, head_dim),
)
Qwen-Image's reference uses complex FP32 multiplication. Rounding the
frequencies to BF16 before rotation loses positional precision; those
errors accumulate across the denoising steps.
"""
paired = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
return torch.view_as_real(paired * freqs.unsqueeze(1)).flatten(3).to(x.dtype)
# Eager path: BF16/activation-dtype RotaryEmbedding on every device.
# CUDA used to call FP32 complex multiply here; that matches the Diffusers
# helper in unit tests but drops Omni vs Diffusers pipeline PSNR (#7494).
q = norm_q(q)
k = norm_k(k)
cos = torch.real(freqs).to(q.dtype)
sin = torch.imag(freqs).to(q.dtype)
return rope(q, cos, sin), rope(k, cos, sin)
def _normalize_qwen_image_weight_name(name: str) -> str:
@@ -648,28 +689,25 @@ class QwenImageCrossAttention(nn.Module):
txt_key = txt_key.unflatten(-1, (self.add_kv_num_heads, self.head_dim))
txt_value = txt_value.unflatten(-1, (self.add_kv_num_heads, self.head_dim))
img_query = self.norm_q(img_query)
img_key = self.norm_k(img_key)
txt_query = self.norm_added_q(txt_query)
txt_key = self.norm_added_k(txt_key)
if img_query.device.type == "cuda":
img_query = _apply_qwen_image_rotary_emb(img_query, vid_freqs)
img_key = _apply_qwen_image_rotary_emb(img_key, vid_freqs)
txt_query = _apply_qwen_image_rotary_emb(txt_query, txt_freqs)
txt_key = _apply_qwen_image_rotary_emb(txt_key, txt_freqs)
else:
# Retain the platform-specific kernels on other accelerators,
# which may not support complex tensors.
img_cos = torch.real(vid_freqs).to(img_query.dtype)
img_sin = torch.imag(vid_freqs).to(img_query.dtype)
txt_cos = torch.real(txt_freqs).to(txt_query.dtype)
txt_sin = torch.imag(txt_freqs).to(txt_query.dtype)
img_query = self.rope(img_query, img_cos, img_sin)
img_key = self.rope(img_key, img_cos, img_sin)
txt_query = self.rope(txt_query, txt_cos, txt_sin)
txt_key = self.rope(txt_key, txt_cos, txt_sin)
img_query, img_key = _qwen_image_qk_norm_rope(
img_query,
img_key,
self.norm_q,
self.norm_k,
vid_freqs,
self.rope,
self.eps,
use_fused=self.qk_norm,
)
txt_query, txt_key = _qwen_image_qk_norm_rope(
txt_query,
txt_key,
self.norm_added_q,
self.norm_added_k,
txt_freqs,
self.rope,
self.eps,
)
seq_len_txt = encoder_hidden_states.shape[1]
joint_query = torch.cat([txt_query, img_query], dim=1)
@@ -807,41 +845,11 @@ class QwenImageTransformerBlock(nn.Module):
self.zero_cond_t = zero_cond_t
def _modulate(self, mod_params, index=None):
def _modulate(self, mod_params):
"""Apply modulation to input tensor"""
# shift: b d, scale: b d, gate: b d
shift, scale, gate = mod_params.chunk(3, dim=-1)
if index is not None:
# Assuming mod_params batch dim is 2*actual_batch (chunked into 2 parts)
# So shift, scale, gate have shape [2*actual_batch, d]
actual_batch = shift.size(0) // 2
shift_0, shift_1 = shift[:actual_batch], shift[actual_batch:] # each: [actual_batch, d]
scale_0, scale_1 = scale[:actual_batch], scale[actual_batch:]
gate_0, gate_1 = gate[:actual_batch], gate[actual_batch:]
# index: [b, l] where b is actual batch size
# Expand to [b, l, 1] to match feature dimension
index_expanded = index.unsqueeze(-1) # [b, l, 1]
# Expand chunks to [b, 1, d] then broadcast to [b, l, d]
shift_0_exp = shift_0.unsqueeze(1) # [b, 1, d]
shift_1_exp = shift_1.unsqueeze(1) # [b, 1, d]
scale_0_exp = scale_0.unsqueeze(1)
scale_1_exp = scale_1.unsqueeze(1)
gate_0_exp = gate_0.unsqueeze(1)
gate_1_exp = gate_1.unsqueeze(1)
# Use torch.where to select based on index
shift_result = torch.where(index_expanded == 0, shift_0_exp, shift_1_exp)
scale_result = torch.where(index_expanded == 0, scale_0_exp, scale_1_exp)
gate_result = torch.where(index_expanded == 0, gate_0_exp, gate_1_exp)
else:
shift_result = shift.unsqueeze(1)
scale_result = scale.unsqueeze(1)
gate_result = gate.unsqueeze(1)
return scale_result, shift_result, gate_result
return scale.unsqueeze(1), shift.unsqueeze(1), gate.unsqueeze(1)
def forward(
self,
@@ -867,8 +875,22 @@ class QwenImageTransformerBlock(nn.Module):
txt_mod1, txt_mod2 = txt_mod_params.chunk(2, dim=-1) # Each [B, 3*dim]
# Process image stream - norm1 + modulation
img_scale1, img_shift1, img_gate1 = self._modulate(img_mod1, modulate_index)
img_modulated = self.img_norm1(hidden_states, img_scale1, img_shift1)
use_fused_select01 = modulate_index is not None and can_use_qwen_select01_triton(hidden_states)
if use_fused_select01:
img_modulated, img_gate1 = fused_layernorm_select01(
hidden_states,
img_mod1,
modulate_index,
self.img_norm1.eps,
self.img_norm1.layernorm.weight,
self.img_norm1.layernorm.bias,
)
elif modulate_index is not None:
img_scale1, img_shift1, img_gate1 = select01_modulation_native(img_mod1, modulate_index)
img_modulated = self.img_norm1(hidden_states, img_scale1, img_shift1)
else:
img_scale1, img_shift1, img_gate1 = self._modulate(img_mod1)
img_modulated = self.img_norm1(hidden_states, img_scale1, img_shift1)
# Process text stream - norm1 + modulation
txt_scale1, txt_shift1, txt_gate1 = self._modulate(txt_mod1)
@@ -893,12 +915,29 @@ class QwenImageTransformerBlock(nn.Module):
img_attn_output, txt_attn_output = attn_output
# Apply attention gates and add residual (like in Megatron)
hidden_states = hidden_states + img_gate1 * img_attn_output
hidden_states_before_attn = hidden_states
if not use_fused_select01:
hidden_states = hidden_states + img_gate1 * img_attn_output
encoder_hidden_states = encoder_hidden_states + txt_gate1 * txt_attn_output
# Process image stream - norm2 + MLP
img_scale2, img_shift2, img_gate2 = self._modulate(img_mod2, modulate_index)
img_modulated2 = self.img_norm2(hidden_states, img_scale2, img_shift2)
if use_fused_select01:
img_modulated2, hidden_states, img_gate2 = fused_residual_layernorm_select01(
img_attn_output,
hidden_states_before_attn,
img_gate1,
img_mod2,
modulate_index,
self.img_norm2.eps,
self.img_norm2.layernorm.weight,
self.img_norm2.layernorm.bias,
)
elif modulate_index is not None:
img_scale2, img_shift2, img_gate2 = select01_modulation_native(img_mod2, modulate_index)
img_modulated2 = self.img_norm2(hidden_states, img_scale2, img_shift2)
else:
img_scale2, img_shift2, img_gate2 = self._modulate(img_mod2)
img_modulated2 = self.img_norm2(hidden_states, img_scale2, img_shift2)
img_mlp_output = self.img_mlp(img_modulated2)
hidden_states = hidden_states + img_gate2 * img_mlp_output
+59
View File
@@ -5,12 +5,14 @@ from __future__ import annotations
import json
import os
from collections.abc import Sequence
from typing import TYPE_CHECKING, Literal
import torch
import torch.nn as nn
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
LinearBase,
ReplicatedLinear,
RowParallelLinear,
)
@@ -124,6 +126,28 @@ def recursive_replace_linear(model: nn.Module, od_config: OmniDiffusionConfig):
_recursive_replace(model, prefix="")
def recursive_replace_linear_with_quantization_config(
model: nn.Module,
quant_config: QuantizationConfig | None,
prefix: str = "",
skip_modules: Sequence[str] = (),
) -> None:
for child_name, child_module in model.named_children():
qual_name = maybe_prefix(prefix, child_name)
if any(qual_name == path or qual_name.startswith(path + ".") for path in skip_modules):
continue
if isinstance(child_module, nn.Linear):
setattr(
model,
child_name,
replace_linear_class(child_module, quant_config=quant_config, prefix=qual_name),
)
else:
recursive_replace_linear_with_quantization_config(
child_module, quant_config, prefix=qual_name, skip_modules=skip_modules
)
def init_parameters(
module: nn.Module,
dtype: torch.dtype | None,
@@ -144,6 +168,24 @@ def init_parameters(
init_parameters(child, dtype, device)
def init_parameters_preserving_vllm_linear(
module: nn.Module,
dtype: torch.dtype | None,
device: torch.device | None = None,
) -> None:
if isinstance(module, LinearBase):
return
for name, param in module.named_parameters(recurse=False):
if param.is_meta:
setattr(
module,
name,
nn.Parameter(torch.empty_like(param, dtype=dtype, device=device), requires_grad=param.requires_grad),
)
for child in module.children():
init_parameters_preserving_vllm_linear(child, dtype, device)
def create_transformers_model(
auto_cls: _BaseAutoModelClass,
od_config: OmniDiffusionConfig,
@@ -161,6 +203,23 @@ def create_transformers_model(
return model
def create_transformers_model_with_vllm_linears(
auto_cls: _BaseAutoModelClass,
hf_config: PretrainedConfig,
quant_config: QuantizationConfig | None,
dtype: torch.dtype,
device: torch.device,
prefix: str = "",
skip_modules: Sequence[str] = (),
) -> PreTrainedModel:
"""Build a Transformers model with vLLM linears."""
with init_on_device_without_buffers("meta"):
model = auto_cls.from_config(hf_config, dtype=dtype)
recursive_replace_linear_with_quantization_config(model, quant_config, prefix=prefix, skip_modules=skip_modules)
init_parameters_preserving_vllm_linear(model, dtype=dtype, device=device)
return model
def _load_json(model_path: str, filename: str, local_files_only: bool = True) -> dict:
"""Load a JSON config file from a local path or HuggingFace Hub repo."""
if local_files_only:
@@ -0,0 +1,87 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Worker-side MP4 encoding for Wan VAE temporal chunks."""
from __future__ import annotations
from typing import Any
from vllm_omni.diffusion.utils.media_utils import normalize_preencode_batch_frames, normalize_video_codec_options
# Matches the fallback the video serving layer applies when a request omits fps,
# so the bytes the worker encodes carry the rate the response advertises.
WAN_DEFAULT_OUTPUT_FPS = 24
# Keep worker-side encoding consistent with the one-shot serving encoder when
# a request does not choose codec options explicitly.
WAN_DEFAULT_VIDEO_CODEC_OPTIONS = {"preset": "ultrafast", "threads": "0"}
# Wan publishes one latent frame group per callback, which is far finer than one
# host transfer is worth. 17 frames matches MiniMax-H3's native clip size.
WAN_DEFAULT_BATCH_FRAMES = 17
def wan_preencoded_mp4_payload(video: Any) -> dict[str, Any] | None:
"""Return a post-process payload when the worker already encoded the MP4.
Returns ``None`` for the ordinary frame-tensor output so callers fall
through to their existing post-processing.
No fps is reported here: :func:`resolve_wan_output_fps` mirrors the fallback
the serving layer applies, so the rate the response advertises already
matches the rate these bytes were encoded at.
"""
if isinstance(video, (bytes, bytearray, memoryview)):
video = [video]
if not isinstance(video, list) or not all(isinstance(item, (bytes, bytearray, memoryview)) for item in video):
return None
return {"payload": {"video": [bytes(item) for item in video]}, "metadata": {}}
def resolve_wan_preencode_mp4(sampling_params: Any, *, output_type: str) -> bool:
"""Return whether this request wants the worker to pre-encode the MP4.
Reject rather than silently downgrade the combinations the pre-encoded path
cannot serve: it emits MP4 bytes, so nothing downstream can interpolate
frames or hand back an array.
"""
extra_args = getattr(sampling_params, "extra_args", None) or {}
if not extra_args.get("preencode_mp4", False):
return False
if getattr(sampling_params, "enable_frame_interpolation", False):
raise ValueError(
"preencode_mp4 cannot be combined with enable_frame_interpolation: interpolation "
"needs the decoded frames that the pre-encoded path no longer materializes"
)
if output_type != "np":
raise ValueError(f"preencode_mp4 returns MP4 bytes and cannot serve output_type={output_type!r}")
return True
def resolve_wan_preencode_batch_frames(sampling_params: Any, *, default: int = WAN_DEFAULT_BATCH_FRAMES) -> int:
"""Read the MP4 batching threshold before starting expensive generation."""
extra_args = getattr(sampling_params, "extra_args", None) or {}
return normalize_preencode_batch_frames(extra_args.get("preencode_batch_frames", default))
def resolve_wan_video_codec_options(sampling_params: Any) -> dict[str, str] | None:
"""Read the request's encoder options, preserving serving defaults.
An absent key inherits the one-shot serving encoder's defaults. Explicit
``None`` and an empty mapping remain distinct caller choices.
"""
extra_args = getattr(sampling_params, "extra_args", None) or {}
return normalize_video_codec_options(extra_args.get("video_codec_options", WAN_DEFAULT_VIDEO_CODEC_OPTIONS))
def resolve_wan_output_fps(sampling_params: Any) -> int:
"""Resolve the fps the worker encodes with.
The serving layer resolves output fps from the request's ``fps`` field, not
from ``frame_rate``, so pre-encoding has to read the same field or the bytes
would carry a rate the response does not advertise.
"""
fps = getattr(sampling_params, "fps", None)
if isinstance(fps, list):
fps = fps[0] if fps else None
return int(fps) if fps else WAN_DEFAULT_OUTPUT_FPS
+81
View File
@@ -0,0 +1,81 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Normalization layer used by the Wan VAE patch."""
import torch
import torch.nn as nn
import torch.nn.functional as F
from vllm_omni.diffusion.layers.custom_op import CustomOp
class RMSNormVAE(CustomOp):
"""Root Mean Square Layer Normalization for Channel-First or Last"""
def __init__(
self,
dim: int,
channel_first: bool = True,
images: bool = True,
bias: bool = False,
epsilon: float = 1e-6,
) -> None:
super().__init__()
broadcastable_dims = (1, 1, 1) if not images else (1, 1)
shape = (dim, *broadcastable_dims) if channel_first else (dim,)
self.channel_first = channel_first
self.scale = dim**0.5
self.gamma = nn.Parameter(torch.ones(shape))
self.bias = nn.Parameter(torch.zeros(shape)) if bias else None
self.epsilon = epsilon
self.gamma_rmsnorm = None
def forward_cuda(
self,
x: torch.Tensor,
) -> torch.Tensor:
return self.forward_native(x)
def forward_hip(
self,
x: torch.Tensor,
) -> torch.Tensor:
return self.forward_native(x)
def forward_npu(
self,
x: torch.Tensor,
) -> torch.Tensor:
import torch_npu
if self.gamma_rmsnorm is None:
self.gamma_rmsnorm = self.gamma.reshape(-1)
if self.channel_first:
x = x.transpose(1, -1)
out = torch_npu.npu_rms_norm(x, self.gamma_rmsnorm, epsilon=self.epsilon)[0].transpose(1, -1)
else:
out = torch_npu.npu_rms_norm(x, self.gamma_rmsnorm, epsilon=self.epsilon)[0]
if self.bias is not None:
out = out + self.bias
return out
def forward_native(
self,
x: torch.Tensor,
) -> torch.Tensor:
out = (
F.normalize(
x,
dim=(1 if self.channel_first else -1),
eps=self.epsilon,
)
* self.scale
* self.gamma
)
if self.bias is not None:
out = out + self.bias
return out
@@ -1,9 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import sys
from vllm_omni.diffusion.layers.norm import RMSNormVAE
from vllm_omni.diffusion.models.wan2_2.norm import RMSNormVAE
def patch_wan_rms_norm():
@@ -26,18 +26,34 @@ from vllm_omni.diffusion.distributed.pipeline_parallel import AsyncLatents, Pipe
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.forward_context import DenoiseProgressMixin
from vllm_omni.diffusion.lora.loader import WanLoraLoaderMixin
from vllm_omni.diffusion.media import (
DiffusionMediaOutput,
VideoMediaOutput,
VideoTensorEncoding,
VideoTensorLayout,
VideoTensorSpec,
VideoValueRange,
)
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch, prefetch_subfolders
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
from vllm_omni.diffusion.models.interface import SupportsComponentDiscovery
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin, _is_rank_zero
from vllm_omni.diffusion.models.schedulers import FlowUniPCMultistepScheduler
from vllm_omni.diffusion.models.wan2_2.chunked_mp4 import (
resolve_wan_output_fps,
resolve_wan_preencode_batch_frames,
resolve_wan_preencode_mp4,
resolve_wan_video_codec_options,
wan_preencoded_mp4_payload,
)
from vllm_omni.diffusion.models.wan2_2.scheduling_wan_euler import WanEulerScheduler
from vllm_omni.diffusion.models.wan2_2.wan2_2_transformer import WanSelfAttention, WanTransformer3DModel
from vllm_omni.diffusion.offloader import OffloadPlan
from vllm_omni.diffusion.postprocess import interpolate_video_tensor
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.diffusion.utils.chunked_video import decode_to_mp4
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch, split_diffusion_output_by_request
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniTextPrompt
from vllm_omni.platforms import current_omni_platform
@@ -51,9 +67,11 @@ FASTWAN_DMD_SCHEDULER_SHIFT = 8.0
def build_wan_scheduler(sample_solver: str, flow_shift: float) -> Any:
if sample_solver == "unipc":
# Keep native Wan's unshifted training endpoints; set_timesteps applies
# the requested shift to the interpolated inference sigmas.
return FlowUniPCMultistepScheduler(
num_train_timesteps=1000,
shift=flow_shift,
shift=1.0,
prediction_type="flow_prediction",
)
if sample_solver == "euler":
@@ -169,8 +187,36 @@ def load_transformer_config(model_path: str, subfolder: str = "transformer", loc
return {}
def resolve_wan_transformer_quant_config(
config: dict, quant_config: QuantizationConfig | None, component: str
) -> QuantizationConfig | None:
"""Resolve the expert before applying its checkpoint's storage contract."""
from vllm_omni.quantization.component_config import ComponentQuantizationConfig
from vllm_omni.quantization.factory import resolve_quant_config_from_disk
# Wan experts are siblings: "transformer_2" must not inherit "transformer"
# through the generic layer-prefix resolver. Select the whole expert name.
component_quant_config = (
quant_config.component_configs.get(component, quant_config.default_config)
if isinstance(quant_config, ComponentQuantizationConfig)
else quant_config
)
quantization_disabled = isinstance(quant_config, ComponentQuantizationConfig) and component_quant_config is None
resolved_quant_config = resolve_quant_config_from_disk(component_quant_config, config.get("quantization_config"))
if quantization_disabled and resolved_quant_config is not None:
raise ValueError(
f"Quantization is disabled for component {component!r}, but its checkpoint declares quantization. "
"Use a BF16 checkpoint for this component or enable its matching quantization method."
)
return resolved_quant_config
def create_transformer_from_config(
config: dict, quant_config: QuantizationConfig | None = None, prefix: str = ""
config: dict,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
*,
component: str = "transformer",
) -> WanTransformer3DModel:
"""Create WanTransformer3DModel from config dict."""
kwargs: dict = {}
@@ -206,11 +252,7 @@ def create_transformer_from_config(
if "pos_embed_seq_len" in config:
kwargs["pos_embed_seq_len"] = config["pos_embed_seq_len"]
if "quantization_config" in config:
from vllm_omni.quantization.factory import resolve_quant_config_from_disk
quant_config = resolve_quant_config_from_disk(quant_config, config["quantization_config"])
quant_config = resolve_wan_transformer_quant_config(config, quant_config, component)
if quant_config is not None:
kwargs["quant_config"] = quant_config
if prefix:
@@ -235,6 +277,9 @@ def get_wan22_post_process_func(
output_type = sampling_params.output_type
if output_type == "latent":
return video
encoded = wan_preencoded_mp4_payload(video)
if encoded is not None:
return encoded
video_metadata = {}
if sampling_params is not None and getattr(sampling_params, "enable_frame_interpolation", False):
video, multiplier = interpolate_video_tensor(
@@ -450,13 +495,13 @@ class Wan22Pipeline(
# Initialize transformers with correct config (weights loaded via load_weights)
if load_transformer:
transformer_config = load_transformer_config(model, "transformer", local_files_only)
self.transformer = self._create_transformer(transformer_config)
self.transformer = self._create_transformer(transformer_config, component="transformer")
else:
self.transformer = None
if load_transformer_2:
transformer_2_config = load_transformer_config(model, "transformer_2", local_files_only)
self.transformer_2 = self._create_transformer(transformer_2_config)
self.transformer_2 = self._create_transformer(transformer_2_config, component="transformer_2")
else:
self.transformer_2 = None
@@ -494,10 +539,17 @@ class Wan22Pipeline(
enable_diffusion_pipeline_profiler=self.od_config.enable_diffusion_pipeline_profiler
)
def _create_transformer(self, config: dict) -> WanTransformer3DModel:
def _create_transformer(self, config: dict, component: str = "transformer") -> WanTransformer3DModel:
"""Create a transformer from a config dict. Respects od_config.quantization_config."""
quant_config = getattr(self.od_config, "quantization_config", None)
return create_transformer_from_config(config, quant_config=quant_config)
# Startup metadata describes the first expert, not a user policy for both.
if getattr(self.od_config, "quantization_config_is_auto_detected", False):
quant_config = None
return create_transformer_from_config(
config,
quant_config=quant_config,
component=component,
)
@property
def guidance_scale(self):
@@ -670,6 +722,8 @@ class Wan22Pipeline(
num_steps = 40 if common.num_inference_steps is None else common.num_inference_steps
output_type = common.output_type or "np"
preencode_mp4 = resolve_wan_preencode_mp4(common, output_type=output_type)
preencode_batch_frames = resolve_wan_preencode_batch_frames(common) if preencode_mp4 else 17
num_outputs_per_prompt = common.num_outputs_per_prompt or 1
attention_kwargs: dict | None = None
@@ -766,7 +820,10 @@ class Wan22Pipeline(
self._sample_solver = sample_solver
self._flow_shift = flow_shift
self.scheduler.set_timesteps(num_steps, device=device)
if sample_solver == "unipc":
self.scheduler.set_timesteps(num_steps, device=device, shift=flow_shift)
else:
self.scheduler.set_timesteps(num_steps, device=device)
timesteps = self.scheduler.timesteps
self._num_timesteps = len(timesteps)
boundary_timestep = None
@@ -907,6 +964,7 @@ class Wan22Pipeline(
if DEBUG_PERF:
_t_decode_start = time.perf_counter()
media = None
if output_type == "latent":
output = latents
else:
@@ -920,7 +978,36 @@ class Wan22Pipeline(
latents.device, latents.dtype
)
latents = latents / latents_std + latents_mean
output = self.vae.decode(latents, return_dict=False)[0]
if preencode_mp4:
output = decode_to_mp4(
self.vae,
latents,
fps=resolve_wan_output_fps(common),
batch_frames=preencode_batch_frames,
video_codec_options=resolve_wan_video_codec_options(common),
)
else:
decoded = self.vae.decode(latents, return_dict=False)[0]
# Distributed VAE decode uses broadcast_result=False, so only the
# output-owning rank receives the full [B, C, T, H, W] video; other
# ranks get an empty placeholder. Emit typed media only from the
# owning rank and keep the placeholder on the legacy output field, so
# the media batch-dimension check in split_diffusion_output_by_request
# does not trip on every non-owner rank.
if decoded.dim() == 5:
output = None
media = DiffusionMediaOutput(
video=VideoMediaOutput(
tensor=decoded,
spec=VideoTensorSpec(
layout=VideoTensorLayout.BCTHW,
encoding=VideoTensorEncoding.NORMALIZED_FLOAT,
value_range=VideoValueRange.NEGATIVE_ONE_TO_ONE,
),
)
)
else:
output = decoded
if DEBUG_PERF:
current_omni_platform.synchronize()
@@ -947,6 +1034,7 @@ class Wan22Pipeline(
return split_diffusion_output_by_request(
DiffusionOutput(
output=output,
media=media,
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
),
req,
@@ -31,6 +31,13 @@ from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
from vllm_omni.diffusion.models.interface import SupportImageInput, SupportsComponentDiscovery
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin, _is_rank_zero
from vllm_omni.diffusion.models.utils import _load_json
from vllm_omni.diffusion.models.wan2_2.chunked_mp4 import (
resolve_wan_output_fps,
resolve_wan_preencode_batch_frames,
resolve_wan_preencode_mp4,
resolve_wan_video_codec_options,
wan_preencoded_mp4_payload,
)
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
_WAN_TEXT_ENCODER_OFFLOAD_PLAN,
build_wan_scheduler,
@@ -46,6 +53,7 @@ from vllm_omni.diffusion.models.wan2_2.wan2_2_transformer import WanTransformer3
from vllm_omni.diffusion.postprocess import interpolate_video_tensor
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.diffusion.utils.chunked_video import decode_to_mp4
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch, split_diffusion_output_by_request
from vllm_omni.inputs.data import OmniTextPrompt
from vllm_omni.platforms import current_omni_platform
@@ -70,6 +78,9 @@ def get_wan22_i2v_post_process_func(
output_type = sampling_params.output_type
if output_type == "latent":
return video
encoded = wan_preencoded_mp4_payload(video)
if encoded is not None:
return encoded
video_metadata = {}
if sampling_params is not None and getattr(sampling_params, "enable_frame_interpolation", False):
video, multiplier = interpolate_video_tensor(
@@ -304,25 +315,10 @@ class Wan22I2VPipeline(
# Transformers (weights loaded via load_weights)
# Load config from model directory or HF Hub to get correct in_channels for I2V models
transformer_config = load_transformer_config(model, "transformer", local_files_only)
self.transformer = create_transformer_from_config(
transformer_config,
quant_config=od_config.quantization_config,
)
self.transformer = self._create_transformer(transformer_config, component="transformer")
if self.has_transformer_2:
transformer_2_config = load_transformer_config(model, "transformer_2", local_files_only)
t2_quant = transformer_2_config.get("quantization_config")
if isinstance(t2_quant, dict) and "quant_method" in t2_quant:
from vllm_omni.quantization.factory import build_quant_config
method = t2_quant["quant_method"]
kwargs = {k: v for k, v in t2_quant.items() if k != "quant_method"}
t2_quant = build_quant_config(method, **kwargs)
else:
t2_quant = None
self.transformer_2 = create_transformer_from_config(
transformer_2_config,
quant_config=t2_quant,
)
self.transformer_2 = self._create_transformer(transformer_2_config, component="transformer_2")
else:
self.transformer_2 = None
@@ -462,10 +458,13 @@ class Wan22I2VPipeline(
image_embeds = self.image_encoder(pixel_values, output_hidden_states=True)
return image_embeds.hidden_states[-2]
def _create_transformer(self, config: dict) -> WanTransformer3DModel:
def _create_transformer(self, config: dict, component: str = "transformer") -> WanTransformer3DModel:
"""Create a transformer from a config dict. Respects od_config.quantization_config."""
quant_config = getattr(self.od_config, "quantization_config", None)
return create_transformer_from_config(config, quant_config=quant_config)
# Startup metadata describes the first expert, not a user policy for both.
if getattr(self.od_config, "quantization_config_is_auto_detected", False):
quant_config = None
return create_transformer_from_config(config, quant_config=quant_config, component=component)
def forward(self, req: DiffusionRequestBatch) -> list[DiffusionOutput]:
sampling_params_list = req.sampling_params_list
@@ -519,6 +518,8 @@ class Wan22I2VPipeline(
num_steps = 40 if common.num_inference_steps is None else common.num_inference_steps
output_type = common.output_type or "np"
preencode_mp4 = resolve_wan_preencode_mp4(common, output_type=output_type)
preencode_batch_frames = resolve_wan_preencode_batch_frames(common) if preencode_mp4 else 17
num_outputs_per_prompt = common.num_outputs_per_prompt or 1
attention_kwargs: dict | None = None
@@ -629,7 +630,10 @@ class Wan22I2VPipeline(
self._flow_shift = flow_shift
# Timesteps
self.scheduler.set_timesteps(num_steps, device=device)
if sample_solver == "unipc":
self.scheduler.set_timesteps(num_steps, device=device, shift=flow_shift)
else:
self.scheduler.set_timesteps(num_steps, device=device)
timesteps = self.scheduler.timesteps
self._num_timesteps = len(timesteps)
@@ -745,7 +749,16 @@ class Wan22I2VPipeline(
latents.device, latents.dtype
)
latents = latents / latents_std + latents_mean
output = self.vae.decode(latents, return_dict=False)[0]
if preencode_mp4:
output = decode_to_mp4(
self.vae,
latents,
fps=resolve_wan_output_fps(common),
batch_frames=preencode_batch_frames,
video_codec_options=resolve_wan_video_codec_options(common),
)
else:
output = self.vae.decode(latents, return_dict=False)[0]
if DEBUG_PERF:
current_omni_platform.synchronize()
@@ -33,6 +33,11 @@ from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineL
from vllm_omni.diffusion.models.interface import SupportAudioInput, SupportImageInput
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
from vllm_omni.diffusion.models.schedulers import FlowUniPCMultistepScheduler
from vllm_omni.diffusion.models.wan2_2.chunked_mp4 import (
resolve_wan_preencode_batch_frames,
resolve_wan_preencode_mp4,
resolve_wan_video_codec_options,
)
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
load_transformer_config,
load_wan_weights_with_optional_gate,
@@ -44,6 +49,7 @@ from vllm_omni.diffusion.models.wan2_2.wan2_2_s2v_transformer import (
from vllm_omni.diffusion.offloader.config import DIT_COMPONENT, selected_offload_components
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.diffusion.utils.chunked_video import ChunkedVideoMP4Session
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch, split_diffusion_output_by_request
from vllm_omni.inputs.data import OmniTextPrompt
from vllm_omni.platforms import current_omni_platform
@@ -63,6 +69,10 @@ _S2V_DEFAULT_NEG_PROMPT = (
_AUDIO_VIDEO_RATE = 30
# S2V generates at a fixed rate; the worker-side encoder and the post-process
# payload must report the same one.
S2V_OUTPUT_FPS = 16
def _s2v_audio_condition_key(audio: str | np.ndarray | None) -> tuple[Any, ...]:
if isinstance(audio, str):
@@ -280,6 +290,10 @@ def get_wan22_s2v_post_process_func(
if output_type == "latent":
return video
if isinstance(video, list) and all(isinstance(item, (bytes, bytearray, memoryview)) for item in video):
# The worker already muxed the audio into these bytes.
return {"video": [bytes(item) for item in video], "audio": None, "fps": S2V_OUTPUT_FPS}
processed_video = video_processor.postprocess_video(video, output_type=output_type)
if audio_waveform is not None:
@@ -287,7 +301,7 @@ def get_wan22_s2v_post_process_func(
"video": processed_video,
"audio": audio_waveform,
"audio_sample_rate": audio_sr,
"fps": 16,
"fps": S2V_OUTPUT_FPS,
}
return processed_video
@@ -545,10 +559,10 @@ class Wan22S2VPipeline(
self._init_original_format(model_path, dtype)
# -- Scheduler --
flow_shift = od_config.flow_shift if od_config.flow_shift is not None else 3.0 # S2V default
self._flow_shift = od_config.flow_shift if od_config.flow_shift is not None else 3.0 # S2V default
self.scheduler = FlowUniPCMultistepScheduler(
num_train_timesteps=1000,
shift=flow_shift,
shift=1.0,
prediction_type="flow_prediction",
)
@@ -1177,6 +1191,13 @@ class Wan22S2VPipeline(
)
num_steps = common.num_inference_steps or num_inference_steps
num_outputs_per_prompt = common.num_outputs_per_prompt or 1
# The request's output_type is what serving honours downstream; the keyword
# argument only carries a default for direct callers. Reading it here is what
# lets pre-encoding reject pil, pt, and latent instead of returning MP4 bytes
# to a caller that asked for frames.
output_type = common.output_type or output_type or "np"
preencode_mp4 = resolve_wan_preencode_mp4(common, output_type=output_type)
preencode_batch_frames = resolve_wan_preencode_batch_frames(common, default=1) if preencode_mp4 else 1
if common.guidance_scale_provided:
guidance_scale = common.guidance_scale
@@ -1315,170 +1336,207 @@ class Wan22S2VPipeline(
# ---- 6. Multi-clip autoregressive denoising ----
clips: list[torch.Tensor] = []
# Encode each finished clip while the next one denoises, instead of
# concatenating the whole video first.
mp4_session = (
ChunkedVideoMP4Session(
value_range=self.vae.chunk_value_range,
audio_waveforms=[raw_audio_waveforms[index // num_outputs_per_prompt] for index in range(batch_size)],
audio_sample_rate=raw_audio_sr,
fps=S2V_OUTPUT_FPS,
batch_frames=preencode_batch_frames,
video_codec_options=resolve_wan_video_codec_options(common),
)
if preencode_mp4
else None
)
# Keep a pixel-space buffer of the trailing motion_frames for the
# autoregressive connection between clips.
videos_last_frames = torch.zeros([batch_size, 3, motion_frames, height, width], dtype=dtype, device=device)
for r in range(num_repeat):
clip_generators = _make_clip_generators(seeds, generators, r, device)
# -- Noise --
if r == 0 and request_latents is not None:
latents = request_latents.to(device=device, dtype=dtype)
else:
latents = torch.stack(
[
self.prepare_latents(
infer_frames=infer_frames,
height=height,
width=width,
motion_frames=motion_frames,
lat_motion_frames=lat_motion_frames,
dtype=dtype,
device=device,
generator=clip_generator,
)
for clip_generator in clip_generators
]
try:
for r in range(num_repeat):
clip_generators = _make_clip_generators(seeds, generators, r, device)
# -- Noise --
if r == 0 and request_latents is not None:
latents = request_latents.to(device=device, dtype=dtype)
else:
latents = torch.stack(
[
self.prepare_latents(
infer_frames=infer_frames,
height=height,
width=width,
motion_frames=motion_frames,
lat_motion_frames=lat_motion_frames,
dtype=dtype,
device=device,
generator=clip_generator,
)
for clip_generator in clip_generators
]
)
# -- Scheduler --
self.scheduler.set_timesteps(num_steps, device=device, shift=self._flow_shift)
timesteps = self.scheduler.timesteps
self._num_timesteps = len(timesteps)
# -- Slice audio for this clip --
left_idx = r * infer_frames
right_idx = left_idx + infer_frames
audio_input = audio_emb[..., left_idx:right_idx]
# -- Pose condition for this clip --
# Default: zero condition (no pose driving)
# Shape: [B, C=16, T, H, W]
lat_h = height // self.vae_scale_factor_spatial
lat_w = width // self.vae_scale_factor_spatial
lat_target_frames = (infer_frames + 3 + motion_frames) // 4 - lat_motion_frames
cond_latents = torch.zeros(
[batch_size, 16, lat_target_frames, lat_h, lat_w], dtype=dtype, device=device
)
# -- Scheduler --
self.scheduler.set_timesteps(num_steps, device=device)
timesteps = self.scheduler.timesteps
self._num_timesteps = len(timesteps)
# -- Clone motion latents for this clip --
input_motion_latents = motion_latents.clone()
# -- Slice audio for this clip --
left_idx = r * infer_frames
right_idx = left_idx + infer_frames
audio_input = audio_emb[..., left_idx:right_idx]
# Max sequence length for the transformer
max_seq_len = int(np.prod([lat_target_frames, lat_h, lat_w]) // 4)
# -- Pose condition for this clip --
# Default: zero condition (no pose driving)
# Shape: [B, C=16, T, H, W]
lat_h = height // self.vae_scale_factor_spatial
lat_w = width // self.vae_scale_factor_spatial
lat_target_frames = (infer_frames + 3 + motion_frames) // 4 - lat_motion_frames
cond_latents = torch.zeros([batch_size, 16, lat_target_frames, lat_h, lat_w], dtype=dtype, device=device)
# -- Clone motion latents for this clip --
input_motion_latents = motion_latents.clone()
# Max sequence length for the transformer
max_seq_len = int(np.prod([lat_target_frames, lat_h, lat_w]) // 4)
# -- Precompute audio embeddings once per clip --
mf = [motion_frames, lat_motion_frames]
# When CPU offload is active the transformer lives on CPU until
# its __call__ hook fires. encode_audio() bypasses __call__,
# so move the audio sub-module to GPU explicitly.
_audio_enc = getattr(self.transformer, "casual_audio_encoder", None)
_audio_on_cpu = _audio_enc is not None and next(_audio_enc.parameters()).device.type == "cpu"
if _audio_on_cpu:
_audio_enc.to(device)
param_dtype = next(self.transformer.parameters()).dtype
with torch.amp.autocast(device.type, dtype=param_dtype):
positive_audio_emb = self.transformer.encode_audio(audio_input, mf)
do_true_cfg = self.do_classifier_free_guidance and negative_prompt_embeds is not None
if do_true_cfg:
# -- Precompute audio embeddings once per clip --
mf = [motion_frames, lat_motion_frames]
# When CPU offload is active the transformer lives on CPU until
# its __call__ hook fires. encode_audio() bypasses __call__,
# so move the audio sub-module to GPU explicitly.
_audio_enc = getattr(self.transformer, "casual_audio_encoder", None)
_audio_on_cpu = _audio_enc is not None and next(_audio_enc.parameters()).device.type == "cpu"
if _audio_on_cpu:
_audio_enc.to(device)
param_dtype = next(self.transformer.parameters()).dtype
with torch.amp.autocast(device.type, dtype=param_dtype):
negative_audio_emb = self.transformer.encode_audio(0.0 * audio_input, mf)
else:
negative_audio_emb = None
if _audio_on_cpu:
_audio_enc.to("cpu")
positive_audio_emb = self.transformer.encode_audio(audio_input, mf)
do_true_cfg = self.do_classifier_free_guidance and negative_prompt_embeds is not None
if do_true_cfg:
with torch.amp.autocast(device.type, dtype=param_dtype):
negative_audio_emb = self.transformer.encode_audio(0.0 * audio_input, mf)
else:
negative_audio_emb = None
if _audio_on_cpu:
_audio_enc.to("cpu")
# -- Denoising loop --
latents = self.diffuse(
latents=latents,
timesteps=timesteps,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
guidance_scale=guidance_scale,
clip_generator=clip_generators,
dtype=dtype,
device=device,
max_seq_len=max_seq_len,
cond_latents=cond_latents,
input_motion_latents=input_motion_latents,
ref_latents=ref_latents,
motion_frames=mf,
drop_first_motion=drop_first_motion and r == 0,
positive_audio_emb=positive_audio_emb,
negative_audio_emb=negative_audio_emb,
)
# ---- Decode this clip ----
if self._should_release_dit_before_decode():
self.transformer.to("cpu")
current_omni_platform.empty_cache()
if not (drop_first_motion and r == 0):
decode_latents = torch.cat([motion_latents, latents], dim=2)
else:
decode_latents = torch.cat([ref_latents, latents], dim=2)
decode_latents = self._denormalize_latents(decode_latents)
decode_latents = decode_latents.to(self.vae.dtype)
clip_video = self.vae.decode(decode_latents, return_dict=False)[0] # [1, C, T, H, W]
# Handle VAE patch parallel: only rank 0 gets result, broadcast to all ranks
# This is needed for S2V's autoregressive loop where all ranks need the decoded frames
if clip_video.numel() == 0:
# Non-rank0 received empty tensor from patch parallel decode
# Use the same broadcast mechanism as the VAE patch parallel code
import torch.distributed as dist
total_frames = decode_latents.shape[2]
# Create buffer for broadcast
clip_video = torch.empty(
(batch_size, 3, total_frames, height, width),
device=decode_latents.device,
dtype=decode_latents.dtype,
# -- Denoising loop --
latents = self.diffuse(
latents=latents,
timesteps=timesteps,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
guidance_scale=guidance_scale,
clip_generator=clip_generators,
dtype=dtype,
device=device,
max_seq_len=max_seq_len,
cond_latents=cond_latents,
input_motion_latents=input_motion_latents,
ref_latents=ref_latents,
motion_frames=mf,
drop_first_motion=drop_first_motion and r == 0,
positive_audio_emb=positive_audio_emb,
negative_audio_emb=negative_audio_emb,
)
# Get the VAE's patch parallel group (same one used in decode)
vae_pp_group = getattr(self.vae, "_vae_pp_group", None)
if vae_pp_group is not None:
# Broadcast using the same group as VAE patch parallel
dist.broadcast(clip_video, src=0, group=vae_pp_group)
# ---- Decode this clip ----
if self._should_release_dit_before_decode():
self.transformer.to("cpu")
current_omni_platform.empty_cache()
# Trim to the infer_frames of interest
clip_video = clip_video[:, :, -infer_frames:]
if drop_first_motion and r == 0:
# Drop the first 3 frames (artifact from ref_latents prepend)
clip_video = clip_video[:, :, 3:]
if not (drop_first_motion and r == 0):
decode_latents = torch.cat([motion_latents, latents], dim=2)
else:
decode_latents = torch.cat([ref_latents, latents], dim=2)
# ---- Update motion for next clip (autoregressive) ----
overlap_frames_num = min(motion_frames, clip_video.shape[2])
videos_last_frames = torch.cat(
[videos_last_frames[:, :, overlap_frames_num:], clip_video[:, :, -overlap_frames_num:]],
dim=2,
decode_latents = self._denormalize_latents(decode_latents)
decode_latents = decode_latents.to(self.vae.dtype)
clip_video = self.vae.decode(decode_latents, return_dict=False)[0] # [1, C, T, H, W]
# Under VAE patch parallelism only the output-owning rank decodes a
# real clip; peers get an empty placeholder filled by the broadcast.
owns_output = clip_video.numel() > 0
# Handle VAE patch parallel: only rank 0 gets result, broadcast to all ranks
# This is needed for S2V's autoregressive loop where all ranks need the decoded frames
if clip_video.numel() == 0:
# Non-rank0 received empty tensor from patch parallel decode
# Use the same broadcast mechanism as the VAE patch parallel code
import torch.distributed as dist
total_frames = decode_latents.shape[2]
# Create buffer for broadcast
clip_video = torch.empty(
(batch_size, 3, total_frames, height, width),
device=decode_latents.device,
dtype=decode_latents.dtype,
)
# Get the VAE's patch parallel group (same one used in decode)
vae_pp_group = getattr(self.vae, "_vae_pp_group", None)
if vae_pp_group is not None:
# Broadcast using the same group as VAE patch parallel
dist.broadcast(clip_video, src=0, group=vae_pp_group)
# Trim to the infer_frames of interest
clip_video = clip_video[:, :, -infer_frames:]
if drop_first_motion and r == 0:
# Drop the first 3 frames (artifact from ref_latents prepend)
clip_video = clip_video[:, :, 3:]
# ---- Update motion for next clip (autoregressive) ----
overlap_frames_num = min(motion_frames, clip_video.shape[2])
videos_last_frames = torch.cat(
[videos_last_frames[:, :, overlap_frames_num:], clip_video[:, :, -overlap_frames_num:]],
dim=2,
)
videos_last_frames = videos_last_frames.to(dtype=dtype, device=device)
# Only prepare motion latents if there's another clip coming
if r < num_repeat - 1:
motion_latents = self.prepare_motion_latents(videos_last_frames, device=device).to(dtype=dtype)
if mp4_session is not None:
# Every rank needs the frames for the motion loop above, but the
# executor keeps only the owner's response, so a peer skips the
# encode and finishes with no containers, like T2V's non-owners.
if owns_output:
mp4_session.push(clip_video)
else:
clips.append(clip_video.cpu())
# Free VRAM between clips
if current_omni_platform.is_available():
current_omni_platform.empty_cache()
# ---- Assemble the output ----
if mp4_session is not None:
output = mp4_session.finish() # one progressive MP4 per batch entry
else:
output = torch.cat(clips, dim=2) # [B, C, T_total, H, W]
outputs = split_diffusion_output_by_request(
DiffusionOutput(
output=output,
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
),
req,
num_outputs_per_prompt=num_outputs_per_prompt,
)
videos_last_frames = videos_last_frames.to(dtype=dtype, device=device)
# Only prepare motion latents if there's another clip coming
if r < num_repeat - 1:
motion_latents = self.prepare_motion_latents(videos_last_frames, device=device).to(dtype=dtype)
clips.append(clip_video.cpu())
# Free VRAM between clips
if current_omni_platform.is_available():
current_omni_platform.empty_cache()
# ---- Concatenate all clips ----
output = torch.cat(clips, dim=2) # [B, C, T_total, H, W]
outputs = split_diffusion_output_by_request(
DiffusionOutput(
output=output,
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
),
req,
num_outputs_per_prompt=num_outputs_per_prompt,
)
for request_output, raw_audio_waveform in zip(outputs, raw_audio_waveforms):
request_output.output = (request_output.output, raw_audio_waveform, raw_audio_sr)
return outputs
if mp4_session is not None:
# The waveform is already muxed into each container.
return outputs
for request_output, raw_audio_waveform in zip(outputs, raw_audio_waveforms):
request_output.output = (request_output.output, raw_audio_waveform, raw_audio_sr)
return outputs
except BaseException:
if mp4_session is not None:
mp4_session.abort()
raise
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
return load_wan_weights_with_optional_gate(self, weights)
@@ -28,6 +28,7 @@ from vllm_omni.diffusion.models.interface import SupportImageInput
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
Wan22Pipeline,
load_wan_weights_with_optional_gate,
resolve_wan_transformer_quant_config,
retrieve_latents,
)
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
@@ -60,6 +61,8 @@ def create_vace_transformer_from_config(
config: dict,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
*,
component: str = "transformer",
) -> WanVACETransformer3DModel:
"""Create WanVACETransformer3DModel from config dict."""
kwargs = {}
@@ -97,6 +100,7 @@ def create_vace_transformer_from_config(
kwargs["vace_layers"] = config["vace_layers"]
if "vace_in_channels" in config:
kwargs["vace_in_channels"] = config["vace_in_channels"]
quant_config = resolve_wan_transformer_quant_config(config, quant_config, component)
if quant_config is not None:
kwargs["quant_config"] = quant_config
if prefix:
@@ -205,10 +209,13 @@ class Wan22VACEPipeline(Wan22Pipeline, SupportImageInput):
super().__init__(od_config=od_config, prefix=prefix)
def _create_transformer(self, config: dict) -> WanVACETransformer3DModel:
def _create_transformer(self, config: dict, component: str = "transformer") -> WanVACETransformer3DModel:
"""Build VACE transformer. Respects od_config.quantization_config."""
quant_config = getattr(self.od_config, "quantization_config", None)
return create_vace_transformer_from_config(config, quant_config=quant_config)
# Startup metadata describes the first expert, not a user policy for both.
if getattr(self.od_config, "quantization_config_is_auto_detected", False):
quant_config = None
return create_vace_transformer_from_config(config, quant_config=quant_config, component=component)
def diffuse(
self,
@@ -690,7 +697,10 @@ class Wan22VACEPipeline(Wan22Pipeline, SupportImageInput):
)
# Set up scheduler
self.scheduler.set_timesteps(num_inference_steps, device=device)
if self._sample_solver == "unipc":
self.scheduler.set_timesteps(num_inference_steps, device=device, shift=self._flow_shift)
else:
self.scheduler.set_timesteps(num_inference_steps, device=device)
timesteps = self.scheduler.timesteps
self._num_timesteps = len(timesteps)
+142
View File
@@ -0,0 +1,142 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Wan S2V rotary positional embedding layers."""
import torch
from vllm_omni.diffusion.layers.rope import RotaryEmbeddingWan
from vllm_omni.platforms import current_omni_platform
class WanS2VRotaryPosEmbed(torch.nn.Module):
"""Precompute complex-valued RoPE embeddings for S2V multi-grid positions.
Owns the base frequency buffer and provides forward() to compute position
embeddings given hidden_states (for shape) and grid_sizes.
"""
def __init__(self, num_heads: int, head_dim: int, max_seq_len: int = 1024):
super().__init__()
self.num_heads = num_heads
self.head_dim = head_dim
d = head_dim
freqs = torch.cat(
[
self._rope_params(max_seq_len, d - 4 * (d // 6)),
self._rope_params(max_seq_len, 2 * (d // 6)),
self._rope_params(max_seq_len, 2 * (d // 6)),
],
dim=1,
)
self.register_buffer("freqs", freqs.to(torch.complex64), persistent=False)
@staticmethod
@torch.amp.autocast(current_omni_platform.device_type, enabled=False)
def _rope_params(max_seq_len, dim, theta=10000):
if dim % 2 != 0:
raise ValueError(f"dim ({dim}) must be even")
freqs = torch.outer(
torch.arange(max_seq_len), 1.0 / torch.pow(theta, torch.arange(0, dim, 2).to(torch.float64).div(dim))
)
return torch.polar(torch.ones_like(freqs), freqs)
def forward(
self,
hidden_states: torch.Tensor,
grid_sizes: list,
trainable_freqs: torch.Tensor | None = None,
) -> torch.Tensor:
"""Precompute RoPE embeddings for the given grid layout.
Args:
hidden_states: Tensor [B, S, ...] (used for batch/seq shape and device)
grid_sizes: Grid specification (list of [offsets, sizes, totals])
trainable_freqs: Optional trainable frequency overrides for t_f < 0
Returns:
Complex tensor [B, S, 1, head_dim//2] of precomputed position embeddings
"""
b, s = hidden_states.shape[0], hidden_states.shape[1]
c = self.head_dim // 2
device = hidden_states.device
freqs = self.freqs.to(device)
if trainable_freqs is not None:
freqs_input = [freqs, trainable_freqs]
else:
freqs_input = freqs
if isinstance(freqs_input, list):
trainable_f = freqs_input[1]
freqs_split = freqs_input[0]
else:
trainable_f = None
freqs_split = freqs_input
freqs_split = freqs_split.split([c - 2 * (c // 3), c // 3, c // 3], dim=1)
output = torch.empty((b, s, 1, c), device=device, dtype=torch.complex64)
seq_bucket = [0]
if not isinstance(grid_sizes, list):
grid_sizes = [grid_sizes]
for g in grid_sizes:
if not isinstance(g, list):
g = [torch.zeros_like(g), g]
batch_size = g[0].shape[0]
for i in range(batch_size):
f_o, h_o, w_o = g[0][i]
f, h, w = g[1][i]
t_f, t_h, t_w = g[2][i]
seq_f, seq_h, seq_w = f - f_o, h - h_o, w - w_o
seq_len = int(seq_f * seq_h * seq_w)
if seq_len > 0:
if t_f > 0:
assert f_o * f >= 0 and h_o * h >= 0 and w_o * w >= 0
seq_f_int = int(seq_f)
seq_h_int = int(seq_h)
seq_w_int = int(seq_w)
if f_o >= 0:
f_sam = torch.linspace(int(f_o), int(t_f + f_o) - 1, seq_f_int, device=device).long()
else:
f_sam = torch.linspace(int(-f_o), int(-t_f - f_o) + 1, seq_f_int, device=device).long()
h_sam = torch.linspace(int(h_o), int(t_h + h_o) - 1, seq_h_int, device=device).long()
w_sam = torch.linspace(int(w_o), int(t_w + w_o) - 1, seq_w_int, device=device).long()
freqs_0 = torch.index_select(freqs_split[0] if f_o >= 0 else freqs_split[0].conj(), 0, f_sam)
freqs_0 = freqs_0.view(seq_f_int, 1, 1, -1)
freqs_i = torch.cat(
[
freqs_0.expand(seq_f_int, seq_h_int, seq_w_int, -1),
torch.index_select(freqs_split[1], 0, h_sam)
.view(1, seq_h_int, 1, -1)
.expand(seq_f_int, seq_h_int, seq_w_int, -1),
torch.index_select(freqs_split[2], 0, w_sam)
.view(1, 1, seq_w_int, -1)
.expand(seq_f_int, seq_h_int, seq_w_int, -1),
],
dim=-1,
).reshape(seq_len, 1, -1)
elif t_f < 0:
freqs_i = trainable_f.unsqueeze(1)
output[i, seq_bucket[-1] : seq_bucket[-1] + seq_len] = freqs_i
seq_bucket.append(seq_bucket[-1] + seq_len)
return output
class RotaryEmbeddingWanS2V(RotaryEmbeddingWan):
"""Apply RoPE using precomputed complex freqs for Wan S2V main transformer.
Converts complex freqs (from WanS2VRotaryPosEmbed) to cos/sin and delegates
to RotaryEmbeddingWan for platform-optimized application (float32 kernel).
Under TP, freqs has 1 head — broadcasts automatically via cos/sin.
"""
def __init__(self) -> None:
super().__init__(is_neox_style=False, half_head_dim=True)
def forward(self, x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
freqs_sliced = freqs[:, : x.size(1)]
cos = freqs_sliced.real.to(x.dtype)
sin = freqs_sliced.imag.to(x.dtype)
return super().forward(x, cos, sin)
@@ -32,7 +32,8 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelInput, SequenceParallelOutput
from vllm_omni.diffusion.layers.rope import RotaryEmbeddingS2VGrid, RotaryEmbeddingWanS2V, WanS2VRotaryPosEmbed
from vllm_omni.diffusion.layers.rope import RotaryEmbeddingS2VGrid
from vllm_omni.diffusion.models.wan2_2.rope import RotaryEmbeddingWanS2V, WanS2VRotaryPosEmbed
from vllm_omni.platforms import current_omni_platform
from .wan2_2_transformer import DistributedRMSNorm, WanFeedForward
@@ -18,7 +18,7 @@ from vllm.distributed import (
)
from vllm.logger import init_logger
from vllm.model_executor.layers.conv import Conv3dLayer
from vllm.model_executor.layers.linear import ColumnParallelLinear, QKVParallelLinear, RowParallelLinear
from vllm.model_executor.layers.linear import ColumnParallelLinear, LinearBase, QKVParallelLinear, RowParallelLinear
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.models.utils import (
@@ -29,7 +29,7 @@ from vllm.model_executor.models.utils import (
)
from vllm.sequence import IntermediateTensors
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata, VideoTokenLayout
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.distributed.parallel_state import (
get_pipeline_parallel_world_size,
@@ -45,6 +45,7 @@ from vllm_omni.diffusion.layers.adalayernorm import AdaLayerNorm
from vllm_omni.diffusion.layers.norm import LayerNorm, RMSNorm
from vllm_omni.diffusion.layers.rope import RotaryEmbeddingWan
from vllm_omni.platforms import current_omni_platform
from vllm_omni.quantization.mxfp4_config import NPUMxfp4LinearMethod
logger = init_logger(__name__)
@@ -416,6 +417,7 @@ class WanSelfAttention(nn.Module):
softmax_scale=1.0 / (head_dim**0.5),
causal=False,
role="self",
qkv_layout="BSND",
prefix=prefix,
)
@@ -608,8 +610,8 @@ class WanCrossAttention(nn.Module):
qkv_layout="BSND",
prefix=prefix,
skip_sequence_parallel=True,
# Wan2.2 cross-attn operates on short text-encoder sequences; per-block
# FP8 quant offers no perf win and degrades quality. Opt out until a
# Wan2.2 cross-attn operates on short text-encoder sequences; runtime
# Q/K/V quantization offers no perf win and degrades quality. Opt out until a
# dedicated quant backend handles this case.
disable_kv_quant=True,
)
@@ -763,7 +765,15 @@ class WanTransformerBlock(nn.Module):
self_attn_extra["vsa_dit_seq_shape"] = vsa_dit_seq_shape
if preserve_vsa_all_blocks:
self_attn_extra["preserve_vsa_all_blocks"] = True
self_attn_metadata = AttentionMetadata(attn_mask=hidden_states_mask, extra=self_attn_extra)
video_layout = None
if vsa_dit_seq_shape is not None:
grid = tuple(int(dim) for dim in vsa_dit_seq_shape)
# Publish geometry independently of backend selection. Do not add
# partial cu_seqlens/max_seqlen metadata to dense CUDA attention.
video_layout = VideoTokenLayout(prefix_len=0, latent_grid=grid, used_len=math.prod(grid))
self_attn_metadata = AttentionMetadata(
attn_mask=hidden_states_mask, extra=self_attn_extra, video_layout=video_layout
)
attn_output = self.attn1(norm_hidden_states, rotary_emb, self_attn_metadata)
hidden_states = (hidden_states + attn_output * gate_msa).type_as(hidden_states)
@@ -985,6 +995,68 @@ class WanTransformer3DModel(nn.Module):
# ROPE helper
self._cached_rope_emb = None
self._cached_rope_resolution = None
self._validate_w4a8_fallback_layers(quant_config)
def _validate_w4a8_fallback_layers(self, quant_config: QuantizationConfig | None) -> None:
"""Reject checkpoint aliases/typos before loading weights or running inference."""
requested = tuple(getattr(quant_config, "w4a8_fallback_layers", []))
self._w4a8_fallback_layers = requested
self._local_w4a8_fallback_layers: tuple[str, ...] = ()
if not requested:
return
modules = dict(self.named_modules())
missing_pp_prefixes = [name for name, module in modules.items() if isinstance(module, PPMissingLayer)]
local_layers = [
name for name in requested if not any(name.startswith(prefix + ".") for prefix in missing_pp_prefixes)
]
self._local_w4a8_fallback_layers = tuple(local_layers)
invalid = [name for name in local_layers if not isinstance(modules.get(name), LinearBase)]
if invalid:
raise ValueError(
"w4a8_fallback_layers requires exact runtime Linear paths relative to each Wan transformer; "
f"unknown/non-Linear paths: {invalid}. Use attn1.to_qkv for fused self-attention, "
"not checkpoint attn1.to_q/to_k/to_v names."
)
def _log_w4a8_fallback_load_summary(self, component_name: str) -> None:
"""Log post-load transforms/cache readiness, not numerical acceptance."""
requested = self._w4a8_fallback_layers
if not requested:
return
modules = dict(self.named_modules())
local_layers = self._local_w4a8_fallback_layers
selected_layers = [
name for name in local_layers if getattr(modules[name].quant_method, "is_w4a8_fallback_layer", False)
]
bf16_overrides = [name for name in local_layers if name not in selected_layers]
processed = [
name
for name in selected_layers
if getattr(modules[name], "_already_called_process_weights_after_loading", False)
]
if not selected_layers:
processing_state = "not-required"
elif len(processed) == len(selected_layers):
processing_state = "ready"
else:
processing_state = "not-ready"
def qualified(names: Iterable[str]) -> list[str]:
return [f"{component_name}.{name}" for name in names]
logger.info(
"Wan W4A8 post-load summary: component=%s; selected=%d %s; BF16 overrides=%d %s; "
"weight/A8 processing state=%s (%d/%d selected layers processed); other PP ranks=%d",
component_name,
len(selected_layers),
qualified(selected_layers),
len(bf16_overrides),
qualified(bf16_overrides),
processing_state,
len(processed),
len(selected_layers),
len(requested) - len(local_layers),
)
@property
def dtype(self) -> torch.dtype:
@@ -1155,7 +1227,22 @@ class WanTransformer3DModel(nn.Module):
}
params_dict = dict(self.named_parameters())
single_scale_prefixes = {
name
for name, module in self.named_modules()
if isinstance(getattr(module, "quant_method", None), NPUMxfp4LinearMethod)
}
def reject_dualscale_tensor(name: str) -> None:
if name.endswith(".weight_dual_scale") and name.rsplit(".", 1)[0] in single_scale_prefixes:
raise ValueError(
f"Single-scale mxfp4 cannot load DualScale tensor {name}; "
"changing quant_method does not convert a checkpoint."
)
loaded_params: set[str] = set()
loaded_qkv_shards: dict[str, set[str]] = {}
qkv_smooth_scales: dict[str, torch.Tensor] = {}
for name, loaded_weight in weights:
name = weight_name_remapping.get(name, name)
@@ -1166,15 +1253,32 @@ class WanTransformer3DModel(nn.Module):
# Pre-fused to_qkv tensors (from offline MXFP8 merged checkpoint) fall
# through to the else branch and are loaded directly.
for param_name, weight_name, shard_id in stacked_params_mapping:
if weight_name not in original_name:
if f"{weight_name}." not in original_name:
continue
lookup_name = original_name.replace(weight_name, param_name)
lookup_name = original_name.replace(f"{weight_name}.", f"{param_name}.", 1)
reject_dualscale_tensor(lookup_name)
# Skip weights that belong to PP stages other than this one
if is_pp_missing_parameter(lookup_name, self) or lookup_name not in params_dict:
break
param = params_dict[lookup_name]
if lookup_name.endswith(".mul_scale"):
previous_scale = qkv_smooth_scales.get(lookup_name)
if previous_scale is not None and not torch.equal(previous_scale, loaded_weight):
raise ValueError(f"Fused Q/K/V must share the same Smooth tensor: {lookup_name}")
if previous_scale is None:
qkv_smooth_scales[lookup_name] = loaded_weight.clone()
weight_loader = param.weight_loader
weight_loader(param, loaded_weight, shard_id)
loaded_params.add(original_name)
if getattr(param, "output_dim", None) is None and not getattr(param, "needs_scalar_to_array", False):
# Shared input-channel Smooth is a complete tensor even
# when supplied under a single Q/K/V source name.
loaded_params.add(lookup_name)
else:
shards = loaded_qkv_shards.setdefault(lookup_name, set())
shards.add(shard_id)
if shards == {"q", "k", "v"}:
loaded_params.add(lookup_name)
break
else:
# diffusers: ffn.net.0.proj.weight -> our: ffn.net_0.proj.weight
@@ -1198,6 +1302,7 @@ class WanTransformer3DModel(nn.Module):
if is_pp_missing_parameter(lookup_name, self):
continue
reject_dualscale_tensor(lookup_name)
if lookup_name not in params_dict:
logger.warning(f"Skipping weight {original_name} -> {lookup_name}")
continue
@@ -1222,8 +1327,6 @@ class WanTransformer3DModel(nn.Module):
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, loaded_weight)
loaded_params.add(original_name)
loaded_params.add(lookup_name)
loaded_params.update((original_name, lookup_name))
return loaded_params
@@ -612,6 +612,15 @@ class ZImageTransformer2DModel(CachedTransformer):
Note: Our "Sequence Parallelism" (SP) corresponds to "Context Parallelism" (CP) in diffusers.
"""
# Fused projections and their checkpoint shard names (mirrors
# stacked_params_mapping in load_weights). ``w13`` is the Z-Image FFN
# fusion of ``w1``/``w3``; declared here so quantized-checkpoint adapters
# can resolve shard keys without a framework-level default entry.
packed_modules_mapping = {
"to_qkv": ["to_q", "to_k", "to_v"],
"w13": ["w1", "w3"],
}
_repeated_blocks = ["ZImageTransformerBlock"]
_layerwise_offload_blocks_attrs = ["layers"]