[Model] Add circlestone-labs/Anima (#4083)
Signed-off-by: akshatvishu <akshatnayak197@gmail.com>
This commit is contained in:
1 parent
698f716012
commit
415005be22
33 files changed
+3127
-46
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
|
||||
Reference in new issue
Block a user