[Feature] Add official LTX multimodal guidance and precision guard (#5148)
Signed-off-by: mglyn <1203789601@qq.com>
This commit is contained in:
1 parent
66a9b0c84f
commit
12d75cf63a
51 files changed
+4547
-3062
No files matched your search
@@ -9,28 +9,16 @@ from vllm_omni.diffusion.models.ltx2.ltx2_components import (
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_transformer import LTX2VideoTransformer3DModel
|
||||
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2 import (
|
||||
LTX2I2VDMD2Pipeline,
|
||||
LTX2ImageToVideoPipeline,
|
||||
LTX2Pipeline,
|
||||
LTX2T2VDMD2Pipeline,
|
||||
LTX23ImageToVideoPipeline,
|
||||
LTX23Pipeline,
|
||||
)
|
||||
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_latent_upsample import LTX2LatentUpsamplePipeline
|
||||
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_two_stage import (
|
||||
LTX2ImageToVideoTwoStagesPipeline,
|
||||
LTX2TwoStagesPipeline,
|
||||
)
|
||||
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_two_stage import LTX2DistilledPipeline
|
||||
|
||||
__all__ = [
|
||||
"LTX2Pipeline",
|
||||
"LTX2T2VDMD2Pipeline",
|
||||
"LTX2ImageToVideoPipeline",
|
||||
"LTX2I2VDMD2Pipeline",
|
||||
"LTX2LatentUpsamplePipeline",
|
||||
"LTX2TwoStagesPipeline",
|
||||
"LTX2ImageToVideoTwoStagesPipeline",
|
||||
"LTX23Pipeline",
|
||||
"LTX23ImageToVideoPipeline",
|
||||
"LTX2DistilledPipeline",
|
||||
"get_ltx2_post_process_func",
|
||||
"load_transformer_config",
|
||||
"create_transformer_from_config",
|
||||
|
||||
@@ -7,6 +7,7 @@ from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any
|
||||
@@ -14,11 +15,14 @@ from typing import TYPE_CHECKING, Any
|
||||
import torch
|
||||
from diffusers import AutoencoderKLLTX2Audio, AutoencoderKLLTX2Video, FlowMatchEulerDiscreteScheduler
|
||||
from diffusers.pipelines.ltx2 import LTX2TextConnectors
|
||||
from diffusers.pipelines.ltx2.latent_upsampler import LTX2LatentUpsamplerModel
|
||||
from diffusers.pipelines.ltx2.vocoder import LTX2Vocoder
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
from huggingface_hub import hf_hub_download
|
||||
from transformers import AutoTokenizer, Gemma3ForConditionalGeneration
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.layer import Attention as OmniAttention
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_ltx2 import DistributedAutoencoderKLLTX2Video
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
@@ -28,7 +32,12 @@ from vllm_omni.diffusion.offloader.module_collector import ModuleDiscovery
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
|
||||
from .ltx2_transformer import LTX2VideoTransformer3DModel
|
||||
from .ltx2_transformer import (
|
||||
LTX2VideoTransformer3DModel,
|
||||
apply_interleaved_rotary_emb,
|
||||
apply_split_rotary_emb,
|
||||
to_ltx_padding_mask,
|
||||
)
|
||||
|
||||
try:
|
||||
from diffusers.pipelines.ltx2.vocoder import LTX2VocoderWithBWE
|
||||
@@ -44,7 +53,9 @@ _LTX_COMPONENT_SUBFOLDERS = (
|
||||
"audio_vae",
|
||||
"vocoder",
|
||||
"scheduler",
|
||||
"latent_upsampler",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -81,6 +92,164 @@ LTX23_COMPONENT_PROFILE = LTXComponentProfile(
|
||||
vocoder_fallback_cls=LTX2Vocoder,
|
||||
)
|
||||
|
||||
LTX2_DISTILLED_COMPONENT_PROFILE = LTXComponentProfile(
|
||||
name="ltx2_distilled",
|
||||
dit_modules=("transformer",),
|
||||
encoder_modules=("text_encoder", "connectors"),
|
||||
vae_modules=("vae", "audio_vae"),
|
||||
resident_modules=("vocoder", "latent_upsampler"),
|
||||
video_vae_cls=DistributedAutoencoderKLLTX2Video,
|
||||
)
|
||||
|
||||
|
||||
_COMPONENT_PROFILES: dict[tuple[str, str], LTXComponentProfile] = {
|
||||
("one_stage", "2"): LTX2_COMPONENT_PROFILE,
|
||||
("one_stage", "2.3"): LTX23_COMPONENT_PROFILE,
|
||||
("distilled_two_stage", "2"): LTX2_DISTILLED_COMPONENT_PROFILE,
|
||||
("dmd2", "2"): LTX2_COMPONENT_PROFILE,
|
||||
("dmd2", "2.3"): LTX23_COMPONENT_PROFILE,
|
||||
}
|
||||
|
||||
|
||||
def resolve_ltx_component_profile(pipeline_kind: str, model_version: str) -> LTXComponentProfile:
|
||||
"""Resolve component construction independently from execution recipes."""
|
||||
try:
|
||||
return _COMPONENT_PROFILES[(pipeline_kind, model_version)]
|
||||
except KeyError as exc:
|
||||
raise ValueError(f"Unsupported LTX component kind/version: {pipeline_kind!r}/{model_version!r}.") from exc
|
||||
|
||||
|
||||
def _load_ltx_metadata_json(model: str, filename: str) -> dict[str, Any]:
|
||||
"""Load small checkpoint metadata without relying on repository names."""
|
||||
if os.path.isdir(model):
|
||||
path = os.path.join(model, filename)
|
||||
if not os.path.isfile(path):
|
||||
return {}
|
||||
else:
|
||||
try:
|
||||
path = hf_hub_download(repo_id=model, filename=filename)
|
||||
except Exception:
|
||||
return {}
|
||||
try:
|
||||
with open(path) as config_file:
|
||||
value = json.load(config_file)
|
||||
except (OSError, TypeError, ValueError):
|
||||
return {}
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def detect_ltx_model_version(model: str) -> str:
|
||||
"""Detect LTX-2 versus LTX-2.3 from checkpoint component metadata.
|
||||
|
||||
Official checkpoints use ``model_version`` metadata. Diffusers repositories
|
||||
expose the equivalent distinction through the BWE vocoder introduced by
|
||||
LTX-2.3. Unknown conversions retain the official LTX-2 fallback.
|
||||
"""
|
||||
model_index = _load_ltx_metadata_json(model, "model_index.json")
|
||||
if str(model_index.get("model_version", "")).startswith("2.3"):
|
||||
return "2.3"
|
||||
|
||||
vocoder_entry = model_index.get("vocoder")
|
||||
if isinstance(vocoder_entry, (list, tuple)) and vocoder_entry:
|
||||
vocoder_class = str(vocoder_entry[-1])
|
||||
elif isinstance(vocoder_entry, dict):
|
||||
vocoder_class = str(vocoder_entry.get("_class_name", ""))
|
||||
else:
|
||||
vocoder_class = ""
|
||||
if vocoder_class == "LTX2VocoderWithBWE":
|
||||
return "2.3"
|
||||
|
||||
vocoder_config = _load_ltx_metadata_json(model, "vocoder/config.json")
|
||||
if str(vocoder_config.get("model_version", "")).startswith("2.3"):
|
||||
return "2.3"
|
||||
if vocoder_config.get("_class_name") == "LTX2VocoderWithBWE":
|
||||
return "2.3"
|
||||
|
||||
logger.info("Using LTX-2 defaults for checkpoint %s", model)
|
||||
return "2"
|
||||
|
||||
|
||||
class _LTXConnectorAttnProcessor:
|
||||
"""Preserve official connector math around Omni attention dispatch."""
|
||||
|
||||
def __init__(self, *, has_learned_registers: bool) -> None:
|
||||
self.has_learned_registers = has_learned_registers
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
attn: Any,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
query_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
key_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> torch.Tensor:
|
||||
encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
|
||||
gate_logits = attn.to_gate_logits(hidden_states) if attn.to_gate_logits is not None else None
|
||||
|
||||
query = attn.norm_q(attn.to_q(hidden_states))
|
||||
key = attn.norm_k(attn.to_k(encoder_hidden_states))
|
||||
value = attn.to_v(encoder_hidden_states)
|
||||
|
||||
if query_rotary_emb is not None:
|
||||
key_rotary_emb = key_rotary_emb if key_rotary_emb is not None else query_rotary_emb
|
||||
if attn.rope_type == "interleaved":
|
||||
query = apply_interleaved_rotary_emb(query, query_rotary_emb)
|
||||
key = apply_interleaved_rotary_emb(key, key_rotary_emb)
|
||||
elif attn.rope_type == "split":
|
||||
query = apply_split_rotary_emb(query, query_rotary_emb, head_dim=attn.head_dim)
|
||||
key = apply_split_rotary_emb(key, key_rotary_emb, head_dim=attn.head_dim)
|
||||
else:
|
||||
raise ValueError(f"Unsupported LTX connector RoPE type: {attn.rope_type}")
|
||||
|
||||
batch_size, _, inner_dim = query.shape
|
||||
head_dim = inner_dim // attn.heads
|
||||
kv_heads = attn.inner_kv_dim // attn.head_dim
|
||||
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)
|
||||
|
||||
# The connector replaces padding tokens with learned registers before
|
||||
# entering its blocks, so every key is valid and the old padding mask
|
||||
# becomes an all-keep no-op.
|
||||
if self.has_learned_registers:
|
||||
attention_mask = None
|
||||
elif attention_mask is not None and attn.omni_attention.attn_backend.get_name().upper() == "FLASH_ATTN":
|
||||
attention_mask = to_ltx_padding_mask(attention_mask)
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
|
||||
hidden_states = attn.omni_attention(query, key, value, attn_metadata)
|
||||
hidden_states = hidden_states.reshape(batch_size, -1, inner_dim)
|
||||
|
||||
if gate_logits is not None:
|
||||
hidden_states = hidden_states.unflatten(2, (attn.heads, -1))
|
||||
hidden_states = hidden_states * (2.0 * torch.sigmoid(gate_logits)).unsqueeze(-1)
|
||||
hidden_states = hidden_states.flatten(2, 3)
|
||||
|
||||
hidden_states = attn.to_out[0](hidden_states)
|
||||
return attn.to_out[1](hidden_states)
|
||||
|
||||
|
||||
def _install_connector_attention(connectors: LTX2TextConnectors) -> None:
|
||||
for connector_name in ("video_connector", "audio_connector"):
|
||||
connector = getattr(connectors, connector_name, None)
|
||||
has_learned_registers = getattr(connector, "learnable_registers", None) is not None
|
||||
for block_index, block in enumerate(getattr(connector, "transformer_blocks", ())):
|
||||
attention = getattr(block, "attn1", None)
|
||||
if attention is not None:
|
||||
attention.omni_attention = OmniAttention(
|
||||
num_heads=attention.heads,
|
||||
head_size=attention.head_dim,
|
||||
num_kv_heads=attention.inner_kv_dim // attention.head_dim,
|
||||
softmax_scale=1.0 / (attention.head_dim**0.5),
|
||||
causal=False,
|
||||
prefix=f"connectors.{connector_name}.transformer_blocks.{block_index}.attn1",
|
||||
role="ltx2.connector",
|
||||
role_category="self",
|
||||
skip_sequence_parallel=True,
|
||||
disable_kv_quant=True,
|
||||
)
|
||||
attention.set_processor(_LTXConnectorAttnProcessor(has_learned_registers=has_learned_registers))
|
||||
|
||||
|
||||
def _detect_vocoder_output_sample_rate(model: str) -> int | None:
|
||||
"""Read the generated waveform sample rate from the vocoder config."""
|
||||
@@ -188,6 +357,7 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
|
||||
local_files_only=local_files_only,
|
||||
dtype=dtype,
|
||||
)
|
||||
_install_connector_attention(pipeline.connectors)
|
||||
pipeline.vae = _load_component(
|
||||
profile.video_vae_cls,
|
||||
model,
|
||||
@@ -221,6 +391,18 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
|
||||
dtype=dtype,
|
||||
)
|
||||
|
||||
if "latent_upsampler" in profile.resident_modules:
|
||||
# BlurDownsample constructs an integer kernel that must be initialized
|
||||
# on CPU; component placement is handled uniformly after construction.
|
||||
with torch.device("cpu"):
|
||||
pipeline.latent_upsampler = _load_component(
|
||||
LTX2LatentUpsamplerModel,
|
||||
model,
|
||||
"latent_upsampler",
|
||||
local_files_only=local_files_only,
|
||||
dtype=dtype,
|
||||
)
|
||||
|
||||
transformer_config = load_transformer_config(model, "transformer", local_files_only)
|
||||
quant_config = getattr(od_config, "quantization_config", None)
|
||||
pipeline.transformer = create_transformer_from_config(transformer_config, quant_config=quant_config)
|
||||
@@ -249,8 +431,6 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
|
||||
tokenizer_max_length = getattr(encoder_config, "max_seq_len", None)
|
||||
pipeline.tokenizer_max_length = int(tokenizer_max_length or 1024)
|
||||
|
||||
pipeline._guidance_scale = None
|
||||
pipeline._guidance_rescale = None
|
||||
pipeline._interrupt = False
|
||||
|
||||
|
||||
@@ -262,22 +442,15 @@ def load_transformer_config(
|
||||
"""Load an LTX transformer config from a local model or the HF Hub."""
|
||||
if local_files_only:
|
||||
config_path = os.path.join(model_path, subfolder, "config.json")
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path) as config_file:
|
||||
return json.load(config_file)
|
||||
if not os.path.exists(config_path):
|
||||
raise FileNotFoundError(f"LTX transformer config not found: {config_path}")
|
||||
else:
|
||||
try:
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
config_path = hf_hub_download(
|
||||
repo_id=model_path,
|
||||
filename=f"{subfolder}/config.json",
|
||||
)
|
||||
with open(config_path) as config_file:
|
||||
return json.load(config_file)
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
config_path = hf_hub_download(
|
||||
repo_id=model_path,
|
||||
filename=f"{subfolder}/config.json",
|
||||
)
|
||||
with open(config_path) as config_file:
|
||||
return json.load(config_file)
|
||||
|
||||
|
||||
def create_transformer_from_config(
|
||||
|
||||
@@ -5,17 +5,20 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import numpy as np
|
||||
import PIL.Image
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img import retrieve_latents
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
|
||||
from . import ltx2_latents as latent_ops
|
||||
from .ltx2_denoise import I2VVideoAudioScheduler
|
||||
from .ltx2_guidance import euler_step_from_velocity
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .ltx2_denoise import LTXDenoiseContext, LTXForwardContext
|
||||
@@ -44,6 +47,41 @@ def _repeat_prompt_tensor_for_outputs(tensor: torch.Tensor, num_outputs: int) ->
|
||||
return tensor.repeat_interleave(num_outputs, dim=0)
|
||||
|
||||
|
||||
def _preprocess_i2v_pil_images(
|
||||
images: PIL.Image.Image | list[PIL.Image.Image],
|
||||
*,
|
||||
height: int,
|
||||
width: int,
|
||||
device: torch.device | None = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Match official LTX aspect-preserving resize and center crop."""
|
||||
image_list = images if isinstance(images, list) else [images]
|
||||
processed = []
|
||||
for image in image_list:
|
||||
pixels = (
|
||||
torch.from_numpy(np.array(image.convert("RGB"), copy=True))
|
||||
.permute(2, 0, 1)
|
||||
.unsqueeze(0)
|
||||
.to(device=device, dtype=torch.float32)
|
||||
)
|
||||
source_height, source_width = pixels.shape[-2:]
|
||||
scale = max(height / source_height, width / source_width)
|
||||
resized_height = math.ceil(source_height * scale)
|
||||
resized_width = math.ceil(source_width * scale)
|
||||
pixels = F.interpolate(
|
||||
pixels,
|
||||
size=(resized_height, resized_width),
|
||||
mode="bilinear",
|
||||
align_corners=False,
|
||||
)
|
||||
crop_top = (resized_height - height) // 2
|
||||
crop_left = (resized_width - width) // 2
|
||||
pixels = pixels[:, :, crop_top : crop_top + height, crop_left : crop_left + width]
|
||||
processed.append((pixels / 127.5 - 1.0).to(dtype=dtype))
|
||||
return torch.cat(processed, dim=0)
|
||||
|
||||
|
||||
class LTXTextConditioningMixin:
|
||||
"""Shared Gemma encoding and text connector orchestration."""
|
||||
|
||||
@@ -113,21 +151,64 @@ class LTXTextConditioningMixin:
|
||||
batch_size = len(prompt) if prompt is not None else prompt_embeds.shape[0]
|
||||
negative_prompt_embeds_provided = negative_prompt_embeds is not None
|
||||
|
||||
if prompt_embeds is None:
|
||||
prompt_embeds, prompt_attention_mask = self._get_gemma_prompt_embeds(
|
||||
prompt=prompt,
|
||||
num_videos_per_prompt=num_videos_per_prompt,
|
||||
if do_classifier_free_guidance and prompt_embeds is None and negative_prompt_embeds is None:
|
||||
negative_prompt = negative_prompt or ""
|
||||
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
||||
if prompt is not None and type(prompt) is not type(negative_prompt):
|
||||
raise TypeError(
|
||||
f"`negative_prompt` should be the same type as `prompt`, but got {type(negative_prompt)} !="
|
||||
f" {type(prompt)}."
|
||||
)
|
||||
if isinstance(negative_prompt, list) and batch_size != len(negative_prompt):
|
||||
raise ValueError(
|
||||
f"`negative_prompt` has batch size {len(negative_prompt)}, but `prompt` has batch size"
|
||||
f" {batch_size}."
|
||||
)
|
||||
|
||||
# Official LTX encodes positive and negative prompts in one Gemma batch;
|
||||
# separate bf16 GEMMs produce a different conditioning trajectory.
|
||||
combined_embeds, combined_mask = self._get_gemma_prompt_embeds(
|
||||
prompt=prompt + negative_prompt,
|
||||
num_videos_per_prompt=1,
|
||||
max_sequence_length=max_sequence_length,
|
||||
scale_factor=scale_factor,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
elif num_videos_per_prompt > 1:
|
||||
prompt_embeds = _repeat_prompt_tensor_for_outputs(prompt_embeds, num_videos_per_prompt)
|
||||
prompt_attention_mask = _repeat_prompt_tensor_for_outputs(
|
||||
prompt_attention_mask,
|
||||
num_videos_per_prompt,
|
||||
)
|
||||
prompt_embeds = combined_embeds[:batch_size]
|
||||
negative_prompt_embeds = combined_embeds[batch_size:]
|
||||
prompt_attention_mask = combined_mask[:batch_size]
|
||||
negative_prompt_attention_mask = combined_mask[batch_size:]
|
||||
if num_videos_per_prompt > 1:
|
||||
prompt_embeds = _repeat_prompt_tensor_for_outputs(prompt_embeds, num_videos_per_prompt)
|
||||
negative_prompt_embeds = _repeat_prompt_tensor_for_outputs(
|
||||
negative_prompt_embeds,
|
||||
num_videos_per_prompt,
|
||||
)
|
||||
prompt_attention_mask = _repeat_prompt_tensor_for_outputs(
|
||||
prompt_attention_mask,
|
||||
num_videos_per_prompt,
|
||||
)
|
||||
negative_prompt_attention_mask = _repeat_prompt_tensor_for_outputs(
|
||||
negative_prompt_attention_mask,
|
||||
num_videos_per_prompt,
|
||||
)
|
||||
else:
|
||||
if prompt_embeds is None:
|
||||
prompt_embeds, prompt_attention_mask = self._get_gemma_prompt_embeds(
|
||||
prompt=prompt,
|
||||
num_videos_per_prompt=num_videos_per_prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
scale_factor=scale_factor,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
elif num_videos_per_prompt > 1:
|
||||
prompt_embeds = _repeat_prompt_tensor_for_outputs(prompt_embeds, num_videos_per_prompt)
|
||||
prompt_attention_mask = _repeat_prompt_tensor_for_outputs(
|
||||
prompt_attention_mask,
|
||||
num_videos_per_prompt,
|
||||
)
|
||||
|
||||
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
||||
negative_prompt = negative_prompt or ""
|
||||
@@ -243,9 +324,10 @@ class LTXTextConditioningMixin:
|
||||
|
||||
|
||||
class LTXI2VConditioningMixin:
|
||||
"""First-frame conditioning behavior common to LTX2 and LTX2.3."""
|
||||
"""First-frame conditioning with optional unified T2V/I2V dispatch."""
|
||||
|
||||
support_image_input = True
|
||||
unified_text_image_entry = False
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
@@ -254,10 +336,6 @@ class LTXI2VConditioningMixin:
|
||||
resample="bilinear",
|
||||
)
|
||||
|
||||
def forward(self, req: Any, image: Any | None = None, *args: Any, **kwargs: Any) -> Any:
|
||||
"""Preserve the public I2V positional API while sharing the T2V runner."""
|
||||
return super().forward(req, *args, image=image, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def _resolve_single_prompt_image(raw_image: Any) -> Any:
|
||||
if isinstance(raw_image, list):
|
||||
@@ -283,11 +361,12 @@ class LTXI2VConditioningMixin:
|
||||
image: Any | None,
|
||||
request_inputs: LTXRequestInputs,
|
||||
) -> Any | None:
|
||||
if image is not None or not req.prompts:
|
||||
prompts = getattr(req, "prompts", None)
|
||||
if image is not None or not prompts:
|
||||
return image
|
||||
|
||||
raw_images = []
|
||||
for prompt_item in req.prompts:
|
||||
for prompt_item in prompts:
|
||||
if isinstance(prompt_item, str):
|
||||
raw_image = None
|
||||
else:
|
||||
@@ -300,8 +379,12 @@ class LTXI2VConditioningMixin:
|
||||
raw_image = PIL.Image.open(raw_image).convert("RGB")
|
||||
raw_images.append(raw_image)
|
||||
|
||||
if all(raw_image is None for raw_image in raw_images) and self.unified_text_image_entry:
|
||||
return None
|
||||
if any(raw_image is None for raw_image in raw_images) and request_inputs.latents is None:
|
||||
raise ValueError("Image is required for LTX I2V generation.")
|
||||
if not self.unified_text_image_entry:
|
||||
raise ValueError("Image is required for LTX I2V generation.")
|
||||
raise ValueError("LTX request batches cannot mix text-to-video and image-to-video prompts.")
|
||||
if len(raw_images) == 1:
|
||||
return raw_images[0]
|
||||
return raw_images or image
|
||||
@@ -311,75 +394,19 @@ class LTXI2VConditioningMixin:
|
||||
request_inputs: LTXRequestInputs,
|
||||
image: Any | None = None,
|
||||
) -> None:
|
||||
if image is None and request_inputs.latents is None:
|
||||
if not self.unified_text_image_entry and image is None and request_inputs.latents is None:
|
||||
raise ValueError("Provide either `image` or `latents`. Cannot leave both undefined.")
|
||||
super()._check_forward_inputs(request_inputs, image=image)
|
||||
|
||||
def prepare_latents(
|
||||
def _encode_i2v_image_latents(
|
||||
self,
|
||||
image: torch.Tensor | None = None,
|
||||
batch_size: int = 1,
|
||||
num_channels_latents: int = 128,
|
||||
height: int = 512,
|
||||
width: int = 768,
|
||||
num_frames: int = 121,
|
||||
noise_scale: float = 0.0,
|
||||
dtype: torch.dtype | None = None,
|
||||
device: torch.device | None = None,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
num_frames, height, width = latent_ops.resolve_video_latent_shape(
|
||||
height,
|
||||
width,
|
||||
num_frames,
|
||||
vae_spatial_compression_ratio=self.vae_spatial_compression_ratio,
|
||||
vae_temporal_compression_ratio=self.vae_temporal_compression_ratio,
|
||||
)
|
||||
shape = (batch_size, num_channels_latents, num_frames, height, width)
|
||||
mask_shape = (batch_size, 1, num_frames, height, width)
|
||||
|
||||
if latents is not None:
|
||||
if latents.ndim == 5:
|
||||
batch_size, _, num_frames, height, width = latents.shape
|
||||
mask_shape = (batch_size, 1, num_frames, height, width)
|
||||
conditioning_mask = latents.new_zeros(mask_shape)
|
||||
conditioning_mask[:, :, 0] = 1.0
|
||||
latents = latent_ops.normalize_latents(
|
||||
latents,
|
||||
self.vae.latents_mean,
|
||||
self.vae.latents_std,
|
||||
self.vae.config.scaling_factor,
|
||||
)
|
||||
latents = latent_ops.create_noised_state(
|
||||
latents,
|
||||
noise_scale * (1 - conditioning_mask),
|
||||
generator,
|
||||
)
|
||||
latents = latent_ops.pack_latents(
|
||||
latents,
|
||||
self.transformer_spatial_patch_size,
|
||||
self.transformer_temporal_patch_size,
|
||||
)
|
||||
else:
|
||||
conditioning_mask = latents.new_zeros(mask_shape)
|
||||
conditioning_mask[:, :, 0] = 1.0
|
||||
|
||||
conditioning_mask = latent_ops.pack_latents(
|
||||
conditioning_mask,
|
||||
self.transformer_spatial_patch_size,
|
||||
self.transformer_temporal_patch_size,
|
||||
).squeeze(-1)
|
||||
if latents.ndim != 3 or latents.shape[:2] != conditioning_mask.shape:
|
||||
raise ValueError(
|
||||
"Provided `latents` tensor has shape"
|
||||
f" {latents.shape}, but the expected shape is {conditioning_mask.shape + (num_channels_latents,)}."
|
||||
)
|
||||
return latents.to(device=device, dtype=dtype), conditioning_mask
|
||||
|
||||
if image is None:
|
||||
raise ValueError("`image` must be provided when `latents` is None.")
|
||||
|
||||
image: torch.Tensor,
|
||||
*,
|
||||
batch_size: int,
|
||||
generator: torch.Generator | list[torch.Generator] | None,
|
||||
dtype: torch.dtype | None,
|
||||
) -> torch.Tensor:
|
||||
"""Encode one conditioning frame per prompt into normalized latents."""
|
||||
image_batch_size = image.shape[0]
|
||||
if image_batch_size == 0:
|
||||
raise ValueError("`image` batch is empty.")
|
||||
@@ -415,38 +442,173 @@ class LTXI2VConditioningMixin:
|
||||
for img in image
|
||||
]
|
||||
|
||||
init_latents = torch.cat(init_latents, dim=0).to(dtype)
|
||||
init_latents = torch.cat(init_latents, dim=0).to(dtype=dtype)
|
||||
if num_videos_per_prompt > 1:
|
||||
init_latents = init_latents.repeat_interleave(num_videos_per_prompt, dim=0)
|
||||
init_latents = latent_ops.normalize_latents(
|
||||
return latent_ops.normalize_latents(
|
||||
init_latents,
|
||||
self.vae.latents_mean,
|
||||
self.vae.latents_std,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _replace_first_latent_frame(
|
||||
latents: torch.Tensor,
|
||||
image_latents: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
expected_shape = (latents.shape[0], latents.shape[1], 1, latents.shape[3], latents.shape[4])
|
||||
if tuple(image_latents.shape) != expected_shape:
|
||||
raise ValueError(
|
||||
f"Encoded LTX conditioning image has shape {tuple(image_latents.shape)}, expected {expected_shape}."
|
||||
)
|
||||
latents = latents.clone()
|
||||
latents[:, :, :1] = image_latents
|
||||
return latents
|
||||
|
||||
def prepare_latents(
|
||||
self,
|
||||
image: torch.Tensor | None = None,
|
||||
batch_size: int = 1,
|
||||
num_channels_latents: int = 128,
|
||||
height: int = 512,
|
||||
width: int = 768,
|
||||
num_frames: int = 121,
|
||||
noise_scale: float = 0.0,
|
||||
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 | tuple[torch.Tensor, torch.Tensor]:
|
||||
if image is None and self.unified_text_image_entry:
|
||||
return super().prepare_latents(
|
||||
batch_size=batch_size,
|
||||
num_channels_latents=num_channels_latents,
|
||||
height=height,
|
||||
width=width,
|
||||
num_frames=num_frames,
|
||||
noise_scale=noise_scale,
|
||||
dtype=dtype,
|
||||
device=device,
|
||||
generator=generator,
|
||||
latents=latents,
|
||||
)
|
||||
|
||||
num_frames, height, width = latent_ops.resolve_video_latent_shape(
|
||||
height,
|
||||
width,
|
||||
num_frames,
|
||||
vae_spatial_compression_ratio=self.vae_spatial_compression_ratio,
|
||||
vae_temporal_compression_ratio=self.vae_temporal_compression_ratio,
|
||||
)
|
||||
mask_shape = (batch_size, 1, num_frames, height, width)
|
||||
|
||||
if latents is not None:
|
||||
unpacked_latents = latents.ndim == 5
|
||||
if latents.ndim == 5:
|
||||
expected_shape = (batch_size, num_channels_latents, num_frames, height, width)
|
||||
if tuple(latents.shape) != expected_shape:
|
||||
raise ValueError(
|
||||
f"Provided unpacked `latents` have shape {tuple(latents.shape)}, expected {expected_shape}."
|
||||
)
|
||||
conditioning_mask = latents.new_zeros(mask_shape)
|
||||
conditioning_mask[:, :, 0] = 1.0
|
||||
latents = latent_ops.normalize_latents(
|
||||
latents,
|
||||
self.vae.latents_mean,
|
||||
self.vae.latents_std,
|
||||
self.vae.config.scaling_factor,
|
||||
)
|
||||
if image is not None:
|
||||
image_latents = self._encode_i2v_image_latents(
|
||||
image,
|
||||
batch_size=batch_size,
|
||||
generator=generator,
|
||||
dtype=dtype,
|
||||
)
|
||||
# Official distilled Stage 2 starts from the upsampled Stage 1
|
||||
# state, then reapplies the source image at final resolution.
|
||||
latents = self._replace_first_latent_frame(latents, image_latents)
|
||||
latents = latent_ops.pack_latents(
|
||||
latents,
|
||||
self.transformer_spatial_patch_size,
|
||||
self.transformer_temporal_patch_size,
|
||||
)
|
||||
else:
|
||||
conditioning_mask = latents.new_zeros(mask_shape)
|
||||
conditioning_mask[:, :, 0] = 1.0
|
||||
|
||||
conditioning_mask = latent_ops.pack_latents(
|
||||
conditioning_mask,
|
||||
self.transformer_spatial_patch_size,
|
||||
self.transformer_temporal_patch_size,
|
||||
).squeeze(-1)
|
||||
if latents.ndim != 3 or latents.shape[:2] != conditioning_mask.shape:
|
||||
raise ValueError(
|
||||
"Provided `latents` tensor has shape"
|
||||
f" {latents.shape}, but the expected shape is {conditioning_mask.shape + (num_channels_latents,)}."
|
||||
)
|
||||
if unpacked_latents:
|
||||
# Official LTX patchifies the latent state before drawing noise.
|
||||
# Sampling the packed shape preserves its seed-to-output contract.
|
||||
latents = latent_ops.create_noised_state(
|
||||
latents,
|
||||
noise_scale * (1 - conditioning_mask).unsqueeze(-1),
|
||||
generator,
|
||||
)
|
||||
elif image is not None:
|
||||
image_latents = self._encode_i2v_image_latents(
|
||||
image,
|
||||
batch_size=batch_size,
|
||||
generator=generator,
|
||||
dtype=dtype,
|
||||
)
|
||||
unpacked = latent_ops.unpack_latents(
|
||||
latents,
|
||||
num_frames,
|
||||
height,
|
||||
width,
|
||||
self.transformer_spatial_patch_size,
|
||||
self.transformer_temporal_patch_size,
|
||||
)
|
||||
unpacked = self._replace_first_latent_frame(unpacked, image_latents)
|
||||
latents = latent_ops.pack_latents(
|
||||
unpacked,
|
||||
self.transformer_spatial_patch_size,
|
||||
self.transformer_temporal_patch_size,
|
||||
)
|
||||
return latents.to(device=device, dtype=dtype), conditioning_mask
|
||||
|
||||
if image is None:
|
||||
raise ValueError("`image` must be provided when `latents` is None.")
|
||||
init_latents = self._encode_i2v_image_latents(
|
||||
image,
|
||||
batch_size=batch_size,
|
||||
generator=generator,
|
||||
dtype=dtype,
|
||||
)
|
||||
init_latents = init_latents.repeat(1, 1, num_frames, 1, 1)
|
||||
|
||||
conditioning_mask = torch.zeros(mask_shape, device=device, dtype=dtype)
|
||||
conditioning_mask[:, :, 0] = 1.0
|
||||
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
||||
latents = init_latents * conditioning_mask + noise * (1 - conditioning_mask)
|
||||
|
||||
init_latents = latent_ops.pack_latents(
|
||||
init_latents,
|
||||
self.transformer_spatial_patch_size,
|
||||
self.transformer_temporal_patch_size,
|
||||
)
|
||||
conditioning_mask = latent_ops.pack_latents(
|
||||
conditioning_mask,
|
||||
self.transformer_spatial_patch_size,
|
||||
self.transformer_temporal_patch_size,
|
||||
).squeeze(-1)
|
||||
latents = latent_ops.pack_latents(
|
||||
latents,
|
||||
self.transformer_spatial_patch_size,
|
||||
self.transformer_temporal_patch_size,
|
||||
)
|
||||
noise = randn_tensor(init_latents.shape, generator=generator, device=device, dtype=dtype)
|
||||
latents = init_latents * conditioning_mask.unsqueeze(-1) + noise * (1 - conditioning_mask).unsqueeze(-1)
|
||||
return latents, conditioning_mask
|
||||
|
||||
def _step_video_latents_i2v(
|
||||
self,
|
||||
noise_pred_video: torch.Tensor,
|
||||
latents: torch.Tensor,
|
||||
timestep: torch.Tensor,
|
||||
step_index: int,
|
||||
latent_num_frames: int,
|
||||
latent_height: int,
|
||||
latent_width: int,
|
||||
@@ -469,12 +631,14 @@ class LTXI2VConditioningMixin:
|
||||
)
|
||||
noise_pred_video = noise_pred_video[:, :, 1:]
|
||||
noise_latents = latents_unpacked[:, :, 1:]
|
||||
pred_latents = self.scheduler.step(
|
||||
noise_pred_video,
|
||||
timestep,
|
||||
# Official LTX advances the unconditioned frames directly on the
|
||||
# sigma trajectory; the first frame remains fixed conditioning.
|
||||
pred_latents = euler_step_from_velocity(
|
||||
noise_latents,
|
||||
return_dict=False,
|
||||
)[0]
|
||||
noise_pred_video,
|
||||
self.scheduler.sigmas,
|
||||
step_index,
|
||||
)
|
||||
latents_unpacked = torch.cat([latents_unpacked[:, :, :1], pred_latents], dim=2)
|
||||
return latent_ops.pack_latents(
|
||||
latents_unpacked,
|
||||
@@ -491,12 +655,31 @@ class LTXI2VConditioningMixin:
|
||||
noise_scale: float,
|
||||
image: Any | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
if request_inputs.latents is None:
|
||||
if image is None and self.unified_text_image_entry:
|
||||
return super()._prepare_video_latents_stage(
|
||||
request_inputs,
|
||||
prompt_context,
|
||||
device=device,
|
||||
noise_scale=noise_scale,
|
||||
image=None,
|
||||
)
|
||||
|
||||
if image is not None:
|
||||
if isinstance(image, torch.Tensor):
|
||||
if image.ndim == 3:
|
||||
image = image.unsqueeze(0)
|
||||
elif isinstance(image, list) and image and isinstance(image[0], torch.Tensor):
|
||||
image = torch.stack(image, dim=0)
|
||||
elif isinstance(image, PIL.Image.Image) or (
|
||||
isinstance(image, list) and image and isinstance(image[0], PIL.Image.Image)
|
||||
):
|
||||
image = _preprocess_i2v_pil_images(
|
||||
image,
|
||||
height=request_inputs.height,
|
||||
width=request_inputs.width,
|
||||
device=device,
|
||||
dtype=prompt_context.positive_connector_prompt_embeds.dtype,
|
||||
)
|
||||
else:
|
||||
image = self.video_processor.preprocess(
|
||||
image,
|
||||
@@ -509,32 +692,17 @@ class LTXI2VConditioningMixin:
|
||||
)
|
||||
|
||||
return self.prepare_latents(
|
||||
image,
|
||||
prompt_context.batch_size * request_inputs.num_videos_per_prompt,
|
||||
self.transformer.config.in_channels,
|
||||
request_inputs.height,
|
||||
request_inputs.width,
|
||||
request_inputs.num_frames,
|
||||
noise_scale,
|
||||
torch.float32,
|
||||
device,
|
||||
request_inputs.generator,
|
||||
request_inputs.latents,
|
||||
)
|
||||
|
||||
def _make_video_audio_scheduler(
|
||||
self,
|
||||
audio_scheduler: Any,
|
||||
latent_num_frames: int,
|
||||
latent_height: int,
|
||||
latent_width: int,
|
||||
) -> Any:
|
||||
return I2VVideoAudioScheduler(
|
||||
self,
|
||||
audio_scheduler,
|
||||
latent_num_frames,
|
||||
latent_height,
|
||||
latent_width,
|
||||
image=image,
|
||||
batch_size=prompt_context.batch_size * request_inputs.num_videos_per_prompt,
|
||||
num_channels_latents=self.transformer.config.in_channels,
|
||||
height=request_inputs.height,
|
||||
width=request_inputs.width,
|
||||
num_frames=request_inputs.num_frames,
|
||||
noise_scale=noise_scale,
|
||||
dtype=prompt_context.positive_connector_prompt_embeds.dtype,
|
||||
device=device,
|
||||
generator=request_inputs.generator,
|
||||
latents=request_inputs.latents,
|
||||
)
|
||||
|
||||
def _prepare_denoise_context_for_cfg(
|
||||
@@ -544,6 +712,8 @@ class LTXI2VConditioningMixin:
|
||||
) -> LTXDenoiseContext:
|
||||
denoise_ctx = super()._prepare_denoise_context_for_cfg(forward_ctx, denoise_ctx)
|
||||
if denoise_ctx.conditioning_mask is None:
|
||||
if self.unified_text_image_entry:
|
||||
return denoise_ctx
|
||||
raise ValueError("LTX I2V denoising requires a conditioning mask.")
|
||||
|
||||
mask_batch = denoise_ctx.conditioning_mask.shape[0]
|
||||
@@ -564,15 +734,46 @@ class LTXI2VConditioningMixin:
|
||||
ts: torch.Tensor,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
*,
|
||||
video_token_count: int,
|
||||
audio_token_count: int,
|
||||
) -> dict[str, torch.Tensor]:
|
||||
kwargs = super()._denoise_timestep_kwargs(ts, forward_ctx, denoise_ctx)
|
||||
if denoise_ctx.conditioning_mask is None:
|
||||
if self.unified_text_image_entry:
|
||||
return super()._denoise_timestep_kwargs(
|
||||
ts,
|
||||
forward_ctx,
|
||||
denoise_ctx,
|
||||
video_token_count=video_token_count,
|
||||
audio_token_count=audio_token_count,
|
||||
)
|
||||
raise ValueError("LTX I2V denoising requires a conditioning mask.")
|
||||
kwargs = super()._denoise_timestep_kwargs(
|
||||
ts,
|
||||
forward_ctx,
|
||||
denoise_ctx,
|
||||
video_token_count=video_token_count,
|
||||
audio_token_count=audio_token_count,
|
||||
)
|
||||
conditioning_mask = (
|
||||
denoise_ctx.conditioning_mask if forward_ctx.cfg_parallel_ready else denoise_ctx.conditioning_mask_for_model
|
||||
)
|
||||
if conditioning_mask is None:
|
||||
raise ValueError("LTX I2V denoising requires a conditioning mask.")
|
||||
kwargs.update(
|
||||
timestep=ts.unsqueeze(-1) * (1 - conditioning_mask),
|
||||
audio_timestep=ts,
|
||||
timestep=ts.reshape(-1, 1) * (1 - conditioning_mask),
|
||||
)
|
||||
return kwargs
|
||||
|
||||
def _video_guidance_model_sigma(
|
||||
self,
|
||||
sigma: torch.Tensor,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> torch.Tensor:
|
||||
if denoise_ctx.conditioning_mask is None:
|
||||
if self.unified_text_image_entry:
|
||||
return super()._video_guidance_model_sigma(sigma, denoise_ctx)
|
||||
raise ValueError("LTX I2V guidance requires a conditioning mask.")
|
||||
# The conditioned tokens are evaluated at timestep zero by the model,
|
||||
# so velocity-to-x0 guidance must use that same per-token sigma.
|
||||
return sigma.reshape(-1, 1, 1) * (1 - denoise_ctx.conditioning_mask).unsqueeze(-1)
|
||||
@@ -6,20 +6,22 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import math
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any, Protocol
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import retrieve_timesteps
|
||||
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
|
||||
from .ltx2_latents import LTXAVState
|
||||
from .ltx2_guidance import euler_step_from_velocity
|
||||
from .ltx2_latents import LTXAVState, unpack_audio_latents, unpad_audio_latents
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .ltx2_conditioning import LTXPromptContext
|
||||
from .ltx2_recipes import LTXPhaseRecipe
|
||||
from .ltx2_request import LTXRequestInputs
|
||||
|
||||
|
||||
@@ -41,7 +43,7 @@ class LTXForwardContext:
|
||||
padded_audio_num_frames: int
|
||||
timesteps: torch.Tensor
|
||||
audio_scheduler: Any
|
||||
video_audio_scheduler: Any
|
||||
video_audio_step_adapter: Any
|
||||
|
||||
@property
|
||||
def batch_size(self) -> int:
|
||||
@@ -71,6 +73,7 @@ class LTXPhaseResult:
|
||||
forward_context: LTXForwardContext
|
||||
video: torch.Tensor
|
||||
audio: torch.Tensor
|
||||
audio_for_next_phase: torch.Tensor | None = None
|
||||
|
||||
|
||||
class LTXDenoisePipeline(Protocol):
|
||||
@@ -122,61 +125,81 @@ def calculate_shift(
|
||||
return image_seq_len * slope + intercept
|
||||
|
||||
|
||||
class VideoAudioScheduler:
|
||||
"""Composite scheduler dispatching video and audio updates."""
|
||||
class LTXVideoAudioStepAdapter:
|
||||
"""Expose the shared LTX Euler update through the distributed scheduler API."""
|
||||
|
||||
def __init__(self, video_scheduler, audio_scheduler):
|
||||
self.video_scheduler = video_scheduler
|
||||
self.audio_scheduler = audio_scheduler
|
||||
|
||||
def step(self, noise_pred, t, latents, return_dict=False, generator=None):
|
||||
video_out = self.video_scheduler.step(
|
||||
noise_pred[0],
|
||||
t[0],
|
||||
latents[0],
|
||||
return_dict=False,
|
||||
generator=generator,
|
||||
)[0]
|
||||
audio_out = self.audio_scheduler.step(
|
||||
noise_pred[1],
|
||||
t[1],
|
||||
latents[1],
|
||||
return_dict=False,
|
||||
generator=generator,
|
||||
)[0]
|
||||
return ((video_out, audio_out),)
|
||||
|
||||
|
||||
class I2VVideoAudioScheduler:
|
||||
"""Update the unconditioned video frames and the full audio state."""
|
||||
|
||||
def __init__(self, pipeline, audio_scheduler, latent_num_frames, latent_height, latent_width):
|
||||
self.video_scheduler = pipeline.scheduler
|
||||
self.audio_scheduler = audio_scheduler
|
||||
def __init__(
|
||||
self,
|
||||
pipeline: Any,
|
||||
audio_scheduler: Any,
|
||||
latent_num_frames: int,
|
||||
latent_height: int,
|
||||
latent_width: int,
|
||||
*,
|
||||
image_conditioned: bool,
|
||||
) -> None:
|
||||
self._pipeline = pipeline
|
||||
self._audio_scheduler = audio_scheduler
|
||||
self._latent_num_frames = latent_num_frames
|
||||
self._latent_height = latent_height
|
||||
self._latent_width = latent_width
|
||||
self._image_conditioned = image_conditioned
|
||||
self._step_index = 0
|
||||
|
||||
def step(self, noise_pred, t, latents, return_dict=False, generator=None):
|
||||
video_out = self._pipeline._step_video_latents_i2v(
|
||||
noise_pred[0],
|
||||
latents[0],
|
||||
t[0],
|
||||
self._latent_num_frames,
|
||||
self._latent_height,
|
||||
self._latent_width,
|
||||
)
|
||||
audio_out = self.audio_scheduler.step(
|
||||
noise_pred[1],
|
||||
t[1],
|
||||
del t, return_dict, generator
|
||||
if self._image_conditioned:
|
||||
video_out = self._pipeline._step_video_latents_i2v(
|
||||
noise_pred[0],
|
||||
latents[0],
|
||||
self._step_index,
|
||||
self._latent_num_frames,
|
||||
self._latent_height,
|
||||
self._latent_width,
|
||||
)
|
||||
else:
|
||||
video_out = euler_step_from_velocity(
|
||||
latents[0],
|
||||
noise_pred[0],
|
||||
self._pipeline.scheduler.sigmas,
|
||||
self._step_index,
|
||||
)
|
||||
audio_out = euler_step_from_velocity(
|
||||
latents[1],
|
||||
return_dict=False,
|
||||
generator=generator,
|
||||
)[0]
|
||||
noise_pred[1],
|
||||
self._audio_scheduler.sigmas,
|
||||
self._step_index,
|
||||
)
|
||||
self._step_index += 1
|
||||
return ((video_out, audio_out),)
|
||||
|
||||
|
||||
def _official_ltx_sigmas(scheduler: Any, steps: int, device: torch.device) -> torch.Tensor:
|
||||
"""Build the official LTX one-stage sigma schedule in torch fp32."""
|
||||
config = scheduler.config
|
||||
base_anchor = config.get("base_image_seq_len", 1024)
|
||||
max_anchor = config.get("max_image_seq_len", 4096)
|
||||
base_shift = config.get("base_shift", 0.95)
|
||||
max_shift = config.get("max_shift", 2.05)
|
||||
|
||||
sigmas = torch.linspace(1.0, 0.0, steps + 1)
|
||||
slope = (max_shift - base_shift) / (max_anchor - base_anchor)
|
||||
# Official LTX2 one-stage intentionally uses the max sequence anchor, so the shift stays at max_shift.
|
||||
sigma_shift = max_anchor * slope + (base_shift - slope * base_anchor)
|
||||
exp_shift = math.exp(sigma_shift)
|
||||
sigmas = torch.where(sigmas != 0, exp_shift / (exp_shift + (1 / sigmas - 1)), 0)
|
||||
|
||||
# Official non-distilled checkpoints explicitly set this to 0.1. Missing
|
||||
# or None means the loaded scheduler disabled terminal stretching.
|
||||
terminal = config.get("shift_terminal")
|
||||
if terminal is not None:
|
||||
non_zero = sigmas != 0
|
||||
one_minus_sigmas = 1.0 - sigmas[non_zero]
|
||||
scale = one_minus_sigmas[-1] / (1.0 - terminal)
|
||||
sigmas[non_zero] = 1.0 - one_minus_sigmas / scale
|
||||
return sigmas.to(dtype=torch.float32, device=device)
|
||||
|
||||
|
||||
def _set_scheduler_sigmas(scheduler: Any, sigmas: torch.Tensor) -> torch.Tensor:
|
||||
sigmas = sigmas.to(torch.float32)
|
||||
timesteps = sigmas[:-1] * scheduler.config.get("num_train_timesteps", 1000)
|
||||
@@ -198,16 +221,20 @@ def prepare_scheduler_stage(
|
||||
latent_num_frames: int,
|
||||
latent_height: int,
|
||||
latent_width: int,
|
||||
use_official_sigma_schedule: bool,
|
||||
image_conditioned: bool = False,
|
||||
) -> tuple[Any, Any, torch.Tensor]:
|
||||
if sigmas is not None and timesteps is not None:
|
||||
raise ValueError("Only one of `sigmas` or `timesteps` may be provided.")
|
||||
|
||||
audio_scheduler = copy.deepcopy(pipeline.scheduler)
|
||||
video_audio_scheduler = pipeline._make_video_audio_scheduler(
|
||||
video_audio_step_adapter = LTXVideoAudioStepAdapter(
|
||||
pipeline,
|
||||
audio_scheduler,
|
||||
latent_num_frames,
|
||||
latent_height,
|
||||
latent_width,
|
||||
image_conditioned=image_conditioned,
|
||||
)
|
||||
if sigmas is not None:
|
||||
scheduler_sigmas = torch.as_tensor(sigmas, dtype=torch.float32, device=device)
|
||||
@@ -217,12 +244,14 @@ def prepare_scheduler_stage(
|
||||
scheduler_sigmas = torch.cat([scheduler_sigmas, scheduler_sigmas.new_zeros(1)])
|
||||
timesteps_tensor = _set_scheduler_sigmas(pipeline.scheduler, scheduler_sigmas)
|
||||
_set_scheduler_sigmas(audio_scheduler, scheduler_sigmas.clone())
|
||||
return audio_scheduler, video_audio_scheduler, timesteps_tensor
|
||||
return audio_scheduler, video_audio_step_adapter, timesteps_tensor
|
||||
|
||||
if sigmas is None and timesteps is None and use_official_sigma_schedule:
|
||||
scheduler_sigmas = _official_ltx_sigmas(pipeline.scheduler, request_inputs.num_inference_steps, device)
|
||||
timesteps_tensor = _set_scheduler_sigmas(pipeline.scheduler, scheduler_sigmas)
|
||||
_set_scheduler_sigmas(audio_scheduler, scheduler_sigmas.clone())
|
||||
return audio_scheduler, video_audio_step_adapter, timesteps_tensor
|
||||
|
||||
sigmas = np.linspace(1.0, 1 / request_inputs.num_inference_steps, request_inputs.num_inference_steps)
|
||||
# Official LTX2 one-stage omits the latent, so mu stays at max_shift across resolutions.
|
||||
# Mu varies with latent token count only when the scheduler receives a latent, as in official HQ two-stage;
|
||||
# explicit sigma schedules bypass mu entirely.
|
||||
mu = calculate_shift(
|
||||
pipeline.scheduler.config.get("max_image_seq_len", 4096),
|
||||
pipeline.scheduler.config.get("base_image_seq_len", 1024),
|
||||
@@ -246,7 +275,7 @@ def prepare_scheduler_stage(
|
||||
sigmas=sigmas,
|
||||
mu=mu,
|
||||
)
|
||||
return audio_scheduler, video_audio_scheduler, timesteps_tensor
|
||||
return audio_scheduler, video_audio_step_adapter, timesteps_tensor
|
||||
|
||||
|
||||
def prepare_rope_coords_stage(
|
||||
@@ -283,15 +312,25 @@ def build_transformer_kwargs(
|
||||
encoder_attention_mask: torch.Tensor | None,
|
||||
audio_encoder_attention_mask: torch.Tensor | None,
|
||||
ts: torch.Tensor,
|
||||
attention_kwargs: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
del encoder_attention_mask, audio_encoder_attention_mask
|
||||
return {
|
||||
"hidden_states": hidden_states,
|
||||
"audio_hidden_states": audio_hidden_states,
|
||||
"encoder_hidden_states": encoder_hidden_states,
|
||||
"audio_encoder_hidden_states": audio_encoder_hidden_states,
|
||||
**pipeline._denoise_timestep_kwargs(ts, forward_ctx, denoise_ctx),
|
||||
"encoder_attention_mask": encoder_attention_mask,
|
||||
"audio_encoder_attention_mask": audio_encoder_attention_mask,
|
||||
**pipeline._denoise_timestep_kwargs(
|
||||
ts,
|
||||
forward_ctx,
|
||||
denoise_ctx,
|
||||
video_token_count=hidden_states.shape[1],
|
||||
audio_token_count=audio_hidden_states.shape[1],
|
||||
),
|
||||
# This is valid only because LTX connectors replace every padding token
|
||||
# with a learned register, making all output context tokens valid.
|
||||
"encoder_attention_mask": None,
|
||||
"audio_encoder_attention_mask": None,
|
||||
"num_frames": forward_ctx.latent_num_frames,
|
||||
"height": forward_ctx.latent_height,
|
||||
"width": forward_ctx.latent_width,
|
||||
@@ -299,7 +338,7 @@ def build_transformer_kwargs(
|
||||
"audio_num_frames": forward_ctx.padded_audio_num_frames,
|
||||
"video_coords": denoise_ctx.video_coords,
|
||||
"audio_coords": denoise_ctx.audio_coords,
|
||||
"attention_kwargs": forward_ctx.attention_kwargs,
|
||||
"attention_kwargs": forward_ctx.attention_kwargs if attention_kwargs is None else attention_kwargs,
|
||||
"return_dict": False,
|
||||
}
|
||||
|
||||
@@ -317,7 +356,7 @@ def step_denoised_latents(
|
||||
(timestep, timestep),
|
||||
(denoise_ctx.latents, denoise_ctx.audio_latents),
|
||||
do_true_cfg=pipeline.do_classifier_free_guidance,
|
||||
per_request_scheduler=forward_ctx.video_audio_scheduler,
|
||||
per_request_scheduler=forward_ctx.video_audio_step_adapter,
|
||||
)
|
||||
return pipeline._synchronize_cfg_parallel_step_output(
|
||||
latents,
|
||||
@@ -338,11 +377,12 @@ class LTXPhaseExecutor:
|
||||
sigmas: list[float] | None,
|
||||
timesteps: list[int] | None,
|
||||
attention_kwargs: dict[str, Any] | None,
|
||||
phase_recipe: LTXPhaseRecipe,
|
||||
image: Any | None = None,
|
||||
prompt_context: LTXPromptContext | None = None,
|
||||
) -> LTXPhaseResult:
|
||||
pipeline._check_forward_inputs(request_inputs, image=image)
|
||||
cfg_parallel_ready = pipeline._setup_forward_runtime(request_inputs, attention_kwargs)
|
||||
cfg_parallel_ready = pipeline._setup_forward_runtime(req, request_inputs, attention_kwargs)
|
||||
device = pipeline.device
|
||||
if prompt_context is None:
|
||||
prompt_context = pipeline._prepare_prompt_context(
|
||||
@@ -372,7 +412,7 @@ class LTXPhaseExecutor:
|
||||
noise_scale=noise_scale,
|
||||
)
|
||||
)
|
||||
audio_scheduler, video_audio_scheduler, timesteps_tensor = prepare_scheduler_stage(
|
||||
audio_scheduler, video_audio_step_adapter, timesteps_tensor = prepare_scheduler_stage(
|
||||
pipeline,
|
||||
request_inputs,
|
||||
device=device,
|
||||
@@ -381,6 +421,8 @@ class LTXPhaseExecutor:
|
||||
latent_num_frames=latent_num_frames,
|
||||
latent_height=latent_height,
|
||||
latent_width=latent_width,
|
||||
use_official_sigma_schedule=phase_recipe.use_official_sigma_schedule,
|
||||
image_conditioned=conditioning_mask is not None,
|
||||
)
|
||||
forward_ctx = LTXForwardContext(
|
||||
req=req,
|
||||
@@ -397,7 +439,7 @@ class LTXPhaseExecutor:
|
||||
padded_audio_num_frames=padded_audio_num_frames,
|
||||
timesteps=timesteps_tensor,
|
||||
audio_scheduler=audio_scheduler,
|
||||
video_audio_scheduler=video_audio_scheduler,
|
||||
video_audio_step_adapter=video_audio_step_adapter,
|
||||
)
|
||||
video_coords, audio_coords = prepare_rope_coords_stage(pipeline, forward_ctx, latents, audio_latents)
|
||||
denoise_ctx = LTXDenoiseContext(
|
||||
@@ -427,4 +469,13 @@ class LTXPhaseExecutor:
|
||||
state.video,
|
||||
state.audio,
|
||||
)
|
||||
return LTXPhaseResult(forward_context=forward_ctx, video=latents, audio=audio_latents)
|
||||
normalized_audio = unpack_audio_latents(
|
||||
unpad_audio_latents(state.audio, forward_ctx.original_audio_num_frames),
|
||||
num_mel_bins=forward_ctx.latent_mel_bins,
|
||||
)
|
||||
return LTXPhaseResult(
|
||||
forward_context=forward_ctx,
|
||||
video=latents,
|
||||
audio=audio_latents,
|
||||
audio_for_next_phase=normalized_audio,
|
||||
)
|
||||
@@ -1,16 +1,16 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Guidance strategies for the LTX model family."""
|
||||
"""Official multi-modal guidance for the LTX model family."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any, Protocol
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import rescale_noise_cfg
|
||||
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
get_cfg_group,
|
||||
get_classifier_free_guidance_rank,
|
||||
@@ -22,358 +22,409 @@ if TYPE_CHECKING:
|
||||
from .ltx2_latents import LTXAVState
|
||||
|
||||
|
||||
class LTXGuidanceStrategy(Protocol):
|
||||
"""Model-version guidance behavior consumed by the shared pipeline."""
|
||||
@dataclass(frozen=True)
|
||||
class LTXModalityGuidance:
|
||||
"""Guidance parameters applied to one LTX output modality."""
|
||||
|
||||
def validate_cfg_world_size(self, cfg_world_size: int) -> None: ...
|
||||
cfg_scale: float = 1.0
|
||||
stg_scale: float = 0.0
|
||||
modality_scale: float = 1.0
|
||||
rescale_scale: float = 0.0
|
||||
stg_blocks: tuple[int, ...] = ()
|
||||
|
||||
def prepare_denoise_context(
|
||||
self,
|
||||
pipeline: Any,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> LTXDenoiseContext: ...
|
||||
@property
|
||||
def do_cfg(self) -> bool:
|
||||
return not math.isclose(self.cfg_scale, 1.0)
|
||||
|
||||
def timestep_kwargs(
|
||||
self,
|
||||
ts: torch.Tensor,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> dict[str, torch.Tensor]: ...
|
||||
@property
|
||||
def do_stg(self) -> bool:
|
||||
return not math.isclose(self.stg_scale, 0.0) and bool(self.stg_blocks)
|
||||
|
||||
def combine_cfg_noise(
|
||||
self,
|
||||
pipeline: Any,
|
||||
positive_noise_pred: tuple[torch.Tensor, torch.Tensor],
|
||||
negative_noise_pred: tuple[torch.Tensor, torch.Tensor],
|
||||
true_cfg_scale: float,
|
||||
cfg_normalize: bool,
|
||||
context: dict[str, Any],
|
||||
) -> tuple[torch.Tensor, torch.Tensor]: ...
|
||||
|
||||
def predict_noise(
|
||||
self,
|
||||
pipeline: Any,
|
||||
index: int,
|
||||
timestep: torch.Tensor,
|
||||
state: LTXAVState,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]: ...
|
||||
@property
|
||||
def do_modality_guidance(self) -> bool:
|
||||
return not math.isclose(self.modality_scale, 1.0)
|
||||
|
||||
|
||||
class _LTXGuidanceStrategyBase:
|
||||
def validate_cfg_world_size(self, cfg_world_size: int) -> None:
|
||||
del cfg_world_size
|
||||
@dataclass(frozen=True)
|
||||
class LTXGuidanceSpec:
|
||||
"""Video and audio guidance requested for one denoise phase."""
|
||||
|
||||
def prepare_denoise_context(
|
||||
self,
|
||||
pipeline: Any,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> LTXDenoiseContext:
|
||||
del pipeline, forward_ctx
|
||||
return denoise_ctx
|
||||
video: LTXModalityGuidance = LTXModalityGuidance()
|
||||
audio: LTXModalityGuidance = LTXModalityGuidance()
|
||||
|
||||
def timestep_kwargs(
|
||||
self,
|
||||
ts: torch.Tensor,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> dict[str, torch.Tensor]:
|
||||
del forward_ctx, denoise_ctx
|
||||
return {"timestep": ts}
|
||||
@classmethod
|
||||
def positive_only(cls) -> LTXGuidanceSpec:
|
||||
return cls()
|
||||
|
||||
@property
|
||||
def do_cfg(self) -> bool:
|
||||
return self.video.do_cfg or self.audio.do_cfg
|
||||
|
||||
@property
|
||||
def do_stg(self) -> bool:
|
||||
return self.video.do_stg or self.audio.do_stg
|
||||
|
||||
@property
|
||||
def do_modality_guidance(self) -> bool:
|
||||
return self.video.do_modality_guidance or self.audio.do_modality_guidance
|
||||
|
||||
@property
|
||||
def do_rescale(self) -> bool:
|
||||
return self.video.rescale_scale != 0.0 or self.audio.rescale_scale != 0.0
|
||||
|
||||
|
||||
def combine_velocity_via_x0(
|
||||
@dataclass(frozen=True)
|
||||
class LTXDenoisePass:
|
||||
"""One conditioned Transformer evaluation in a guidance batch."""
|
||||
|
||||
name: str
|
||||
negative_video_context: bool = False
|
||||
negative_audio_context: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LTXGuidancePlan:
|
||||
"""Concrete Transformer passes derived from a guidance specification."""
|
||||
|
||||
spec: LTXGuidanceSpec
|
||||
passes: tuple[LTXDenoisePass, ...]
|
||||
|
||||
@classmethod
|
||||
def build(cls, spec: LTXGuidanceSpec) -> LTXGuidancePlan:
|
||||
passes = [LTXDenoisePass("cond")]
|
||||
if spec.do_cfg:
|
||||
passes.append(
|
||||
LTXDenoisePass(
|
||||
"uncond",
|
||||
negative_video_context=spec.video.do_cfg,
|
||||
negative_audio_context=spec.audio.do_cfg,
|
||||
)
|
||||
)
|
||||
if spec.do_stg:
|
||||
passes.append(LTXDenoisePass("ptb"))
|
||||
if spec.do_modality_guidance:
|
||||
passes.append(LTXDenoisePass("mod"))
|
||||
return cls(spec=spec, passes=tuple(passes))
|
||||
|
||||
@property
|
||||
def names(self) -> tuple[str, ...]:
|
||||
return tuple(item.name for item in self.passes)
|
||||
|
||||
@property
|
||||
def cfg_parallel_compatible(self) -> bool:
|
||||
return self.names == ("cond", "uncond") and not self.spec.do_rescale
|
||||
|
||||
|
||||
def x0_from_velocity(sample: torch.Tensor, velocity: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
|
||||
"""Convert velocity to x0 using the official fp32 arithmetic order."""
|
||||
sigma = sigma.to(torch.float32)
|
||||
return (sample.to(torch.float32) - velocity.to(torch.float32) * sigma).to(sample.dtype)
|
||||
|
||||
|
||||
def velocity_from_x0(sample: torch.Tensor, x0: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
|
||||
"""Convert x0 back to velocity using the official fp32 arithmetic order."""
|
||||
sigma = sigma.to(torch.float32)
|
||||
return ((sample.to(torch.float32) - x0.to(torch.float32)) / sigma).to(sample.dtype)
|
||||
|
||||
|
||||
def euler_step_from_velocity(
|
||||
sample: torch.Tensor,
|
||||
positive_velocity: torch.Tensor,
|
||||
negative_velocity: torch.Tensor,
|
||||
sigma: torch.Tensor,
|
||||
guidance_scale: float,
|
||||
velocity: torch.Tensor,
|
||||
sigmas: torch.Tensor,
|
||||
step_index: int,
|
||||
) -> torch.Tensor:
|
||||
"""Apply CFG in x0 space and convert the result back to velocity."""
|
||||
x0_cond = sample - positive_velocity * sigma
|
||||
x0_uncond = sample - negative_velocity * sigma
|
||||
x0_guided = x0_cond + (guidance_scale - 1) * (x0_cond - x0_uncond)
|
||||
return (sample - x0_guided) / sigma
|
||||
sigma = sigmas[step_index].to(torch.float32)
|
||||
sigma_next = sigmas[step_index + 1].to(torch.float32)
|
||||
return (sample.float() + velocity.float() * (sigma_next - sigma)).to(sample.dtype)
|
||||
|
||||
|
||||
class LTXLegacyVelocityGuidance(_LTXGuidanceStrategyBase):
|
||||
"""Existing LTX2 Diffusers-style velocity-space CFG behavior."""
|
||||
|
||||
def combine_cfg_noise(
|
||||
self,
|
||||
pipeline: Any,
|
||||
positive_noise_pred: tuple[torch.Tensor, torch.Tensor],
|
||||
negative_noise_pred: tuple[torch.Tensor, torch.Tensor],
|
||||
true_cfg_scale: float,
|
||||
cfg_normalize: bool,
|
||||
context: dict[str, Any],
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
del context
|
||||
video_pos, audio_pos = positive_noise_pred
|
||||
video_neg, audio_neg = negative_noise_pred
|
||||
video_combined = CFGParallelMixin.combine_cfg_noise(
|
||||
pipeline,
|
||||
video_pos,
|
||||
video_neg,
|
||||
true_cfg_scale,
|
||||
cfg_normalize,
|
||||
)
|
||||
audio_combined = CFGParallelMixin.combine_cfg_noise(
|
||||
pipeline,
|
||||
audio_pos,
|
||||
audio_neg,
|
||||
true_cfg_scale,
|
||||
cfg_normalize,
|
||||
)
|
||||
if pipeline.guidance_rescale and pipeline.guidance_rescale > 0:
|
||||
video_combined = rescale_noise_cfg(
|
||||
video_combined,
|
||||
video_pos,
|
||||
guidance_rescale=pipeline.guidance_rescale,
|
||||
)
|
||||
audio_combined = rescale_noise_cfg(
|
||||
audio_combined,
|
||||
audio_pos,
|
||||
guidance_rescale=pipeline.guidance_rescale,
|
||||
)
|
||||
return video_combined, audio_combined
|
||||
|
||||
def predict_noise(
|
||||
self,
|
||||
pipeline: Any,
|
||||
index: int,
|
||||
timestep: torch.Tensor,
|
||||
state: LTXAVState,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
del index
|
||||
prompt_context = forward_ctx.prompt_context
|
||||
video_input = state.video.to(prompt_context.positive_connector_prompt_embeds.dtype)
|
||||
audio_input = state.audio.to(prompt_context.positive_connector_prompt_embeds.dtype)
|
||||
expanded_timestep = timestep.expand(video_input.shape[0])
|
||||
positive_kwargs = pipeline._build_transformer_kwargs(
|
||||
forward_ctx,
|
||||
denoise_ctx,
|
||||
hidden_states=video_input,
|
||||
audio_hidden_states=audio_input,
|
||||
encoder_hidden_states=prompt_context.positive_connector_prompt_embeds,
|
||||
audio_encoder_hidden_states=prompt_context.positive_connector_audio_prompt_embeds,
|
||||
encoder_attention_mask=prompt_context.positive_connector_attention_mask,
|
||||
audio_encoder_attention_mask=prompt_context.positive_connector_attention_mask,
|
||||
ts=expanded_timestep,
|
||||
)
|
||||
negative_kwargs = (
|
||||
{
|
||||
**positive_kwargs,
|
||||
"encoder_hidden_states": prompt_context.negative_connector_prompt_embeds,
|
||||
"audio_encoder_hidden_states": prompt_context.negative_connector_audio_prompt_embeds,
|
||||
"encoder_attention_mask": prompt_context.negative_connector_attention_mask,
|
||||
"audio_encoder_attention_mask": prompt_context.negative_connector_attention_mask,
|
||||
}
|
||||
if pipeline.do_classifier_free_guidance
|
||||
else None
|
||||
)
|
||||
return pipeline.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=pipeline.do_classifier_free_guidance,
|
||||
true_cfg_scale=forward_ctx.request_inputs.guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
)
|
||||
def combine_guided_x0(
|
||||
*,
|
||||
cond: torch.Tensor,
|
||||
uncond_text: torch.Tensor | float,
|
||||
uncond_perturbed: torch.Tensor | float,
|
||||
uncond_modality: torch.Tensor | float,
|
||||
guidance: LTXModalityGuidance,
|
||||
) -> torch.Tensor:
|
||||
dtype = cond.dtype
|
||||
cond = cond.float()
|
||||
uncond_text = uncond_text.float() if isinstance(uncond_text, torch.Tensor) else uncond_text
|
||||
uncond_perturbed = uncond_perturbed.float() if isinstance(uncond_perturbed, torch.Tensor) else uncond_perturbed
|
||||
uncond_modality = uncond_modality.float() if isinstance(uncond_modality, torch.Tensor) else uncond_modality
|
||||
pred = cond + (guidance.cfg_scale - 1) * (cond - uncond_text)
|
||||
if guidance.do_stg:
|
||||
pred = pred + guidance.stg_scale * (cond - uncond_perturbed)
|
||||
pred = pred + (guidance.modality_scale - 1) * (cond - uncond_modality)
|
||||
if guidance.rescale_scale != 0.0:
|
||||
# The pinned official one-stage entry runs one generated sample and
|
||||
# uses its full-tensor standard deviation. In Omni, dimension 0 may
|
||||
# instead contain independently scheduled requests. Reduce each item
|
||||
# separately so its result cannot depend on unrelated co-batched work.
|
||||
reduce_dims = tuple(range(1, pred.ndim))
|
||||
cond_std = cond.std(dim=reduce_dims, keepdim=True)
|
||||
pred_std = pred.std(dim=reduce_dims, keepdim=True)
|
||||
eps = torch.finfo(pred.dtype).eps
|
||||
factor = cond_std / pred_std.clamp_min(eps)
|
||||
factor = torch.where(pred_std > eps, factor, torch.ones_like(factor))
|
||||
factor = guidance.rescale_scale * factor + (1 - guidance.rescale_scale)
|
||||
pred = pred * factor
|
||||
return pred.to(dtype)
|
||||
|
||||
|
||||
class LTXOfficialX0Guidance(_LTXGuidanceStrategyBase):
|
||||
"""Official LTX x0-space CFG behavior currently used by LTX2.3."""
|
||||
def _repeat_batch(tensor: torch.Tensor, repeats: int) -> torch.Tensor:
|
||||
return tensor.repeat((repeats,) + (1,) * (tensor.ndim - 1))
|
||||
|
||||
def validate_cfg_world_size(self, cfg_world_size: int) -> None:
|
||||
if cfg_world_size not in (1, 2):
|
||||
raise ValueError(
|
||||
f"LTX x0 guidance supports CFG parallelism with cfg_parallel_size 1 or 2, but got {cfg_world_size}."
|
||||
)
|
||||
|
||||
def _mask_for_pass(
|
||||
pass_count: int,
|
||||
batch_size: int,
|
||||
pass_index: int,
|
||||
reference: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
mask = reference.new_ones((pass_count * batch_size, 1, 1))
|
||||
start = pass_index * batch_size
|
||||
mask[start : start + batch_size] = 0
|
||||
return mask
|
||||
|
||||
|
||||
def build_perturbation_kwargs(
|
||||
plan: LTXGuidancePlan,
|
||||
batch_size: int,
|
||||
reference: torch.Tensor,
|
||||
) -> dict[str, Any]:
|
||||
kwargs: dict[str, Any] = {}
|
||||
if "ptb" in plan.names:
|
||||
mask = _mask_for_pass(len(plan.passes), batch_size, plan.names.index("ptb"), reference)
|
||||
if plan.spec.video.do_stg:
|
||||
kwargs["video_self_attention_mask"] = mask
|
||||
kwargs["video_self_attention_blocks"] = plan.spec.video.stg_blocks
|
||||
if plan.spec.audio.do_stg:
|
||||
kwargs["audio_self_attention_mask"] = mask
|
||||
kwargs["audio_self_attention_blocks"] = plan.spec.audio.stg_blocks
|
||||
if "mod" in plan.names:
|
||||
mask = _mask_for_pass(len(plan.passes), batch_size, plan.names.index("mod"), reference)
|
||||
kwargs["a2v_cross_attention_mask"] = mask
|
||||
kwargs["v2a_cross_attention_mask"] = mask
|
||||
return kwargs
|
||||
|
||||
|
||||
class LTXGuidanceExecutor:
|
||||
"""Build and execute official LTX multi-guidance Transformer passes."""
|
||||
|
||||
@staticmethod
|
||||
def validate_cfg_world_size(plan: LTXGuidancePlan, cfg_world_size: int) -> None:
|
||||
if cfg_world_size == 1:
|
||||
return
|
||||
if cfg_world_size != 2:
|
||||
raise ValueError(f"LTX CFG parallelism supports cfg_parallel_size 1 or 2, got {cfg_world_size}.")
|
||||
if not plan.cfg_parallel_compatible:
|
||||
raise ValueError("LTX CFG parallelism only supports CFG-only guidance without rescale.")
|
||||
|
||||
@staticmethod
|
||||
def prepare_denoise_context(
|
||||
self,
|
||||
pipeline: Any,
|
||||
forward_ctx: LTXForwardContext,
|
||||
plan: LTXGuidancePlan,
|
||||
cfg_parallel_ready: bool,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> LTXDenoiseContext:
|
||||
if pipeline.do_classifier_free_guidance and not forward_ctx.cfg_parallel_ready:
|
||||
denoise_ctx.video_coords = denoise_ctx.video_coords.repeat(
|
||||
(2,) + (1,) * (denoise_ctx.video_coords.ndim - 1)
|
||||
)
|
||||
denoise_ctx.audio_coords = denoise_ctx.audio_coords.repeat(
|
||||
(2,) + (1,) * (denoise_ctx.audio_coords.ndim - 1)
|
||||
)
|
||||
if len(plan.passes) > 1 and not cfg_parallel_ready:
|
||||
denoise_ctx.video_coords = _repeat_batch(denoise_ctx.video_coords, len(plan.passes))
|
||||
denoise_ctx.audio_coords = _repeat_batch(denoise_ctx.audio_coords, len(plan.passes))
|
||||
return denoise_ctx
|
||||
|
||||
@staticmethod
|
||||
def timestep_kwargs(
|
||||
self,
|
||||
ts: torch.Tensor,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
video_token_count: int,
|
||||
audio_token_count: int,
|
||||
) -> dict[str, torch.Tensor]:
|
||||
del forward_ctx, denoise_ctx
|
||||
return {"timestep": ts, "sigma": ts}
|
||||
return {
|
||||
"timestep": ts.reshape(-1, 1).expand(-1, video_token_count),
|
||||
"audio_timestep": ts.reshape(-1, 1).expand(-1, audio_token_count),
|
||||
"sigma": ts,
|
||||
"audio_sigma": ts,
|
||||
}
|
||||
|
||||
def combine_cfg_noise(
|
||||
self,
|
||||
pipeline: Any,
|
||||
positive_noise_pred: tuple[torch.Tensor, torch.Tensor],
|
||||
negative_noise_pred: tuple[torch.Tensor, torch.Tensor],
|
||||
true_cfg_scale: float,
|
||||
cfg_normalize: bool,
|
||||
context: dict[str, Any],
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
required = ("video_latents", "audio_latents", "video_sigma", "audio_sigma")
|
||||
if any(context.get(name) is None for name in required):
|
||||
raise ValueError("LTX x0-space CFG requires video/audio latents and sigmas.")
|
||||
|
||||
video_pos, audio_pos = positive_noise_pred
|
||||
video_neg, audio_neg = negative_noise_pred
|
||||
video_combined = combine_velocity_via_x0(
|
||||
context["video_latents"],
|
||||
video_pos,
|
||||
video_neg,
|
||||
context["video_sigma"],
|
||||
true_cfg_scale,
|
||||
@staticmethod
|
||||
def combine_cfg_velocity(
|
||||
sample: torch.Tensor,
|
||||
positive_velocity: torch.Tensor,
|
||||
negative_velocity: torch.Tensor,
|
||||
sigma: torch.Tensor,
|
||||
guidance_scale: float,
|
||||
*,
|
||||
model_sigma: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
guidance = LTXModalityGuidance(cfg_scale=guidance_scale)
|
||||
model_sigma = sigma if model_sigma is None else model_sigma
|
||||
guided_x0 = combine_guided_x0(
|
||||
cond=x0_from_velocity(sample, positive_velocity, model_sigma),
|
||||
uncond_text=x0_from_velocity(sample, negative_velocity, model_sigma),
|
||||
uncond_perturbed=0.0,
|
||||
uncond_modality=0.0,
|
||||
guidance=guidance,
|
||||
)
|
||||
audio_combined = combine_velocity_via_x0(
|
||||
context["audio_latents"],
|
||||
audio_pos,
|
||||
audio_neg,
|
||||
context["audio_sigma"],
|
||||
true_cfg_scale,
|
||||
)
|
||||
if cfg_normalize:
|
||||
video_combined = pipeline.cfg_normalize_function(video_pos, video_combined)
|
||||
audio_combined = pipeline.cfg_normalize_function(audio_pos, audio_combined)
|
||||
return video_combined, audio_combined
|
||||
return velocity_from_x0(sample, guided_x0, sigma)
|
||||
|
||||
def predict_parallel_cfg(
|
||||
self,
|
||||
pipeline: Any,
|
||||
true_cfg_scale: float,
|
||||
positive_kwargs: dict[str, Any],
|
||||
negative_kwargs: dict[str, Any],
|
||||
cfg_normalize: bool = True,
|
||||
output_slice: int | None = None,
|
||||
**context: Any,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
def maybe_slice(pred: tuple[torch.Tensor, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if output_slice is None:
|
||||
return pred
|
||||
return pred[0][:, :output_slice], pred[1][:, :output_slice]
|
||||
|
||||
cfg_world_size = get_classifier_free_guidance_world_size()
|
||||
self.validate_cfg_world_size(cfg_world_size)
|
||||
if cfg_world_size != 2:
|
||||
raise ValueError(f"Parallel LTX x0 guidance requires cfg_parallel_size 2, but got {cfg_world_size}.")
|
||||
|
||||
cfg_rank = get_classifier_free_guidance_rank()
|
||||
branch_kwargs = positive_kwargs if cfg_rank == 0 else negative_kwargs
|
||||
local_video_pred, local_audio_pred = maybe_slice(pipeline.predict_noise(**branch_kwargs))
|
||||
cfg_group = get_cfg_group()
|
||||
gathered_video = cfg_group.all_gather(local_video_pred, separate_tensors=True)
|
||||
gathered_audio = cfg_group.all_gather(local_audio_pred, separate_tensors=True)
|
||||
return self.combine_cfg_noise(
|
||||
pipeline,
|
||||
(gathered_video[0], gathered_audio[0]),
|
||||
(gathered_video[1], gathered_audio[1]),
|
||||
true_cfg_scale,
|
||||
cfg_normalize,
|
||||
context,
|
||||
)
|
||||
|
||||
def predict_noise(
|
||||
self,
|
||||
pipeline: Any,
|
||||
plan: LTXGuidancePlan,
|
||||
index: int,
|
||||
timestep: torch.Tensor,
|
||||
state: LTXAVState,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
prompt_context = forward_ctx.prompt_context
|
||||
guidance_scale = forward_ctx.request_inputs.guidance_scale
|
||||
audio_scheduler = forward_ctx.audio_scheduler
|
||||
if forward_ctx.cfg_parallel_ready:
|
||||
video_input = state.video.to(prompt_context.positive_connector_prompt_embeds.dtype)
|
||||
audio_input = state.audio.to(prompt_context.positive_connector_prompt_embeds.dtype)
|
||||
ts = timestep.expand(video_input.shape[0])
|
||||
positive_kwargs = pipeline._build_transformer_kwargs(
|
||||
forward_ctx,
|
||||
denoise_ctx,
|
||||
hidden_states=video_input,
|
||||
audio_hidden_states=audio_input,
|
||||
encoder_hidden_states=prompt_context.positive_connector_prompt_embeds,
|
||||
audio_encoder_hidden_states=prompt_context.positive_connector_audio_prompt_embeds,
|
||||
encoder_attention_mask=prompt_context.positive_connector_attention_mask,
|
||||
audio_encoder_attention_mask=prompt_context.positive_connector_attention_mask,
|
||||
ts=ts,
|
||||
)
|
||||
negative_kwargs = {
|
||||
**positive_kwargs,
|
||||
"encoder_hidden_states": prompt_context.negative_connector_prompt_embeds,
|
||||
"audio_encoder_hidden_states": prompt_context.negative_connector_audio_prompt_embeds,
|
||||
"encoder_attention_mask": prompt_context.negative_connector_attention_mask,
|
||||
"audio_encoder_attention_mask": prompt_context.negative_connector_attention_mask,
|
||||
}
|
||||
return self.predict_parallel_cfg(
|
||||
pipeline,
|
||||
true_cfg_scale=guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
video_latents=state.video,
|
||||
audio_latents=state.audio,
|
||||
video_sigma=pipeline.scheduler.sigmas[index],
|
||||
audio_sigma=audio_scheduler.sigmas[index],
|
||||
)
|
||||
|
||||
video_input = torch.cat([state.video] * 2) if pipeline.do_classifier_free_guidance else state.video
|
||||
video_input = video_input.to(prompt_context.connector_prompt_embeds.dtype)
|
||||
audio_input = torch.cat([state.audio] * 2) if pipeline.do_classifier_free_guidance else state.audio
|
||||
audio_input = audio_input.to(prompt_context.connector_prompt_embeds.dtype)
|
||||
ts = timestep.expand(video_input.shape[0])
|
||||
transformer_kwargs = pipeline._build_transformer_kwargs(
|
||||
self.validate_cfg_world_size(plan, get_classifier_free_guidance_world_size())
|
||||
prompt = forward_ctx.prompt_context
|
||||
negative = get_classifier_free_guidance_rank() == 1
|
||||
video_context = (
|
||||
prompt.negative_connector_prompt_embeds
|
||||
if negative and plan.spec.video.do_cfg
|
||||
else prompt.positive_connector_prompt_embeds
|
||||
)
|
||||
audio_context = (
|
||||
prompt.negative_connector_audio_prompt_embeds
|
||||
if negative and plan.spec.audio.do_cfg
|
||||
else prompt.positive_connector_audio_prompt_embeds
|
||||
)
|
||||
if video_context is None or audio_context is None:
|
||||
raise ValueError("Negative prompt context is required when LTX CFG is enabled.")
|
||||
video_input = state.video.to(prompt.positive_connector_prompt_embeds.dtype)
|
||||
audio_input = state.audio.to(prompt.positive_connector_audio_prompt_embeds.dtype)
|
||||
kwargs = pipeline._build_transformer_kwargs(
|
||||
forward_ctx,
|
||||
denoise_ctx,
|
||||
hidden_states=video_input,
|
||||
audio_hidden_states=audio_input,
|
||||
encoder_hidden_states=prompt_context.connector_prompt_embeds,
|
||||
audio_encoder_hidden_states=prompt_context.connector_audio_prompt_embeds,
|
||||
encoder_attention_mask=prompt_context.connector_attention_mask,
|
||||
audio_encoder_attention_mask=prompt_context.connector_attention_mask,
|
||||
ts=ts,
|
||||
encoder_hidden_states=video_context,
|
||||
audio_encoder_hidden_states=audio_context,
|
||||
encoder_attention_mask=None,
|
||||
audio_encoder_attention_mask=None,
|
||||
ts=timestep.expand(video_input.shape[0]),
|
||||
)
|
||||
with pipeline._transformer_cache_context("cond_uncond"):
|
||||
video_pred, audio_pred = pipeline.transformer(**transformer_kwargs)
|
||||
video_pred = video_pred.float()
|
||||
audio_pred = audio_pred.float()
|
||||
|
||||
if pipeline.do_classifier_free_guidance:
|
||||
video_uncond, video_cond = video_pred.chunk(2)
|
||||
video_pred = combine_velocity_via_x0(
|
||||
local_video, local_audio = pipeline.predict_noise(**kwargs)
|
||||
group = get_cfg_group()
|
||||
video = group.all_gather(local_video, separate_tensors=True)
|
||||
audio = group.all_gather(local_audio, separate_tensors=True)
|
||||
video_sigma = pipeline.scheduler.sigmas[index]
|
||||
return (
|
||||
self.combine_cfg_velocity(
|
||||
state.video,
|
||||
video_cond,
|
||||
video_uncond,
|
||||
pipeline.scheduler.sigmas[index],
|
||||
guidance_scale,
|
||||
)
|
||||
audio_uncond, audio_cond = audio_pred.chunk(2)
|
||||
audio_pred = combine_velocity_via_x0(
|
||||
video[0],
|
||||
video[1],
|
||||
video_sigma,
|
||||
plan.spec.video.cfg_scale,
|
||||
model_sigma=pipeline._video_guidance_model_sigma(video_sigma, denoise_ctx),
|
||||
),
|
||||
self.combine_cfg_velocity(
|
||||
state.audio,
|
||||
audio_cond,
|
||||
audio_uncond,
|
||||
audio_scheduler.sigmas[index],
|
||||
guidance_scale,
|
||||
audio[0],
|
||||
audio[1],
|
||||
forward_ctx.audio_scheduler.sigmas[index],
|
||||
plan.spec.audio.cfg_scale,
|
||||
),
|
||||
)
|
||||
|
||||
def predict_noise(
|
||||
self,
|
||||
pipeline: Any,
|
||||
plan: LTXGuidancePlan,
|
||||
index: int,
|
||||
timestep: torch.Tensor,
|
||||
state: LTXAVState,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if forward_ctx.cfg_parallel_ready:
|
||||
return self.predict_parallel_cfg(pipeline, plan, index, timestep, state, forward_ctx, denoise_ctx)
|
||||
|
||||
prompt = forward_ctx.prompt_context
|
||||
video_contexts: list[torch.Tensor] = []
|
||||
audio_contexts: list[torch.Tensor] = []
|
||||
for denoise_pass in plan.passes:
|
||||
video_context = (
|
||||
prompt.negative_connector_prompt_embeds
|
||||
if denoise_pass.negative_video_context
|
||||
else prompt.positive_connector_prompt_embeds
|
||||
)
|
||||
return video_pred, audio_pred
|
||||
audio_context = (
|
||||
prompt.negative_connector_audio_prompt_embeds
|
||||
if denoise_pass.negative_audio_context
|
||||
else prompt.positive_connector_audio_prompt_embeds
|
||||
)
|
||||
if video_context is None or audio_context is None:
|
||||
raise ValueError("Negative prompt context is required when LTX CFG is enabled.")
|
||||
video_contexts.append(video_context)
|
||||
audio_contexts.append(audio_context)
|
||||
|
||||
pass_count = len(plan.passes)
|
||||
video_input = _repeat_batch(state.video, pass_count).to(prompt.positive_connector_prompt_embeds.dtype)
|
||||
audio_input = _repeat_batch(state.audio, pass_count).to(prompt.positive_connector_audio_prompt_embeds.dtype)
|
||||
attention_kwargs = dict(forward_ctx.attention_kwargs or {})
|
||||
perturbations = build_perturbation_kwargs(plan, state.video.shape[0], video_input)
|
||||
if perturbations:
|
||||
attention_kwargs["ltx_perturbation_kwargs"] = perturbations
|
||||
kwargs = pipeline._build_transformer_kwargs(
|
||||
forward_ctx,
|
||||
denoise_ctx,
|
||||
hidden_states=video_input,
|
||||
audio_hidden_states=audio_input,
|
||||
encoder_hidden_states=torch.cat(video_contexts),
|
||||
audio_encoder_hidden_states=torch.cat(audio_contexts),
|
||||
encoder_attention_mask=None,
|
||||
audio_encoder_attention_mask=None,
|
||||
ts=timestep.expand(video_input.shape[0]),
|
||||
attention_kwargs=attention_kwargs,
|
||||
)
|
||||
with pipeline._transformer_cache_context("guided"):
|
||||
video_velocity, audio_velocity = pipeline.transformer(**kwargs)
|
||||
video_splits = dict(zip(plan.names, video_velocity.chunk(pass_count), strict=True))
|
||||
audio_splits = dict(zip(plan.names, audio_velocity.chunk(pass_count), strict=True))
|
||||
|
||||
def guide_modality(
|
||||
sample: torch.Tensor,
|
||||
splits: dict[str, torch.Tensor],
|
||||
sigma: torch.Tensor,
|
||||
guidance: LTXModalityGuidance,
|
||||
*,
|
||||
model_sigma: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
model_sigma = sigma if model_sigma is None else model_sigma
|
||||
# Official guidance reduces contiguous BSC tensors. The fused
|
||||
# transformer output may be channel-major after splitting, which
|
||||
# changes fp32 reduction order and can cross bf16 rounding bounds.
|
||||
x0 = {name: x0_from_velocity(sample, value, model_sigma).contiguous() for name, value in splits.items()}
|
||||
guided = combine_guided_x0(
|
||||
cond=x0["cond"],
|
||||
uncond_text=x0.get("uncond", 0.0),
|
||||
uncond_perturbed=x0.get("ptb", 0.0),
|
||||
uncond_modality=x0.get("mod", 0.0),
|
||||
guidance=guidance,
|
||||
)
|
||||
return velocity_from_x0(sample, guided, sigma)
|
||||
|
||||
return (
|
||||
guide_modality(
|
||||
state.video,
|
||||
video_splits,
|
||||
pipeline.scheduler.sigmas[index],
|
||||
plan.spec.video,
|
||||
model_sigma=pipeline._video_guidance_model_sigma(
|
||||
pipeline.scheduler.sigmas[index],
|
||||
denoise_ctx,
|
||||
),
|
||||
),
|
||||
guide_modality(
|
||||
state.audio,
|
||||
audio_splits,
|
||||
forward_ctx.audio_scheduler.sigmas[index],
|
||||
plan.spec.audio,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
LTX_LEGACY_VELOCITY_GUIDANCE = LTXLegacyVelocityGuidance()
|
||||
LTX_OFFICIAL_X0_GUIDANCE = LTXOfficialX0Guidance()
|
||||
LTX_GUIDANCE_EXECUTOR = LTXGuidanceExecutor()
|
||||
|
||||
# Kept as a narrow compatibility helper for CFG-parallel tests and extensions.
|
||||
combine_velocity_via_x0 = LTXGuidanceExecutor.combine_cfg_velocity
|
||||
@@ -120,45 +120,14 @@ def create_noised_state(
|
||||
return noise_scale * noise + (1 - noise_scale) * latents
|
||||
|
||||
|
||||
def pack_audio_latents(
|
||||
latents: torch.Tensor,
|
||||
patch_size: int | None = None,
|
||||
patch_size_t: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
if patch_size is not None and patch_size_t is not None:
|
||||
batch_size, _, latent_length, latent_mel_bins = latents.shape
|
||||
post_patch_latent_length = latent_length / patch_size_t
|
||||
post_patch_mel_bins = latent_mel_bins / patch_size
|
||||
latents = latents.reshape(
|
||||
batch_size,
|
||||
-1,
|
||||
post_patch_latent_length,
|
||||
patch_size_t,
|
||||
post_patch_mel_bins,
|
||||
patch_size,
|
||||
)
|
||||
return latents.permute(0, 2, 4, 1, 3, 5).flatten(3, 5).flatten(1, 2)
|
||||
def pack_audio_latents(latents: torch.Tensor) -> torch.Tensor:
|
||||
return latents.transpose(1, 2).flatten(2, 3)
|
||||
|
||||
|
||||
def unpack_audio_latents(
|
||||
latents: torch.Tensor,
|
||||
latent_length: int,
|
||||
num_mel_bins: int,
|
||||
patch_size: int | None = None,
|
||||
patch_size_t: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
if patch_size is not None and patch_size_t is not None:
|
||||
batch_size = latents.size(0)
|
||||
latents = latents.reshape(
|
||||
batch_size,
|
||||
latent_length,
|
||||
num_mel_bins,
|
||||
-1,
|
||||
patch_size_t,
|
||||
patch_size,
|
||||
)
|
||||
return latents.permute(0, 3, 1, 4, 2, 5).flatten(4, 5).flatten(2, 3)
|
||||
return latents.unflatten(2, (-1, num_mel_bins)).transpose(1, 2)
|
||||
|
||||
|
||||
@@ -224,18 +193,19 @@ def prepare_video_latents(
|
||||
vae_spatial_compression_ratio=pipeline.vae_spatial_compression_ratio,
|
||||
vae_temporal_compression_ratio=pipeline.vae_temporal_compression_ratio,
|
||||
)
|
||||
shape = (batch_size, num_channels_latents, num_frames, height, width)
|
||||
spatial_patch_size = pipeline.transformer_spatial_patch_size
|
||||
temporal_patch_size = pipeline.transformer_temporal_patch_size
|
||||
shape = (
|
||||
batch_size,
|
||||
(num_frames // temporal_patch_size) * (height // spatial_patch_size) * (width // spatial_patch_size),
|
||||
num_channels_latents * temporal_patch_size * spatial_patch_size * spatial_patch_size,
|
||||
)
|
||||
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."
|
||||
)
|
||||
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
||||
return pack_latents(
|
||||
latents,
|
||||
pipeline.transformer_spatial_patch_size,
|
||||
pipeline.transformer_temporal_patch_size,
|
||||
)
|
||||
return randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
||||
|
||||
|
||||
def prepare_audio_latents(
|
||||
@@ -249,6 +219,7 @@ def prepare_audio_latents(
|
||||
device: torch.device | None = None,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
latents_normalized: bool = False,
|
||||
) -> tuple[torch.Tensor, int, int]:
|
||||
original_latent_length = audio_latent_length
|
||||
latent_mel_bins = num_mel_bins // pipeline.audio_vae_mel_compression_ratio
|
||||
@@ -260,11 +231,12 @@ def prepare_audio_latents(
|
||||
latents = pack_audio_latents(latents)
|
||||
if latents.ndim != 3:
|
||||
raise ValueError(f"Provided `latents` has shape {latents.shape}, expected [batch, seq, features].")
|
||||
latents = normalize_audio_latents(
|
||||
latents,
|
||||
pipeline.audio_vae.latents_mean,
|
||||
pipeline.audio_vae.latents_std,
|
||||
)
|
||||
if not latents_normalized:
|
||||
latents = normalize_audio_latents(
|
||||
latents,
|
||||
pipeline.audio_vae.latents_mean,
|
||||
pipeline.audio_vae.latents_std,
|
||||
)
|
||||
latents = create_noised_state(latents, noise_scale, generator)
|
||||
|
||||
if latents.shape[1] not in {original_latent_length, padded_latent_length}:
|
||||
@@ -283,11 +255,11 @@ def prepare_audio_latents(
|
||||
latents = torch.cat([latents, padding], dim=1)
|
||||
return latents.to(device=device, dtype=dtype), original_latent_length, padded_latent_length
|
||||
|
||||
shape = (batch_size, num_channels_latents, padded_latent_length, latent_mel_bins)
|
||||
shape = (batch_size, padded_latent_length, num_channels_latents * latent_mel_bins)
|
||||
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."
|
||||
)
|
||||
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
||||
return pack_audio_latents(latents), original_latent_length, padded_latent_length
|
||||
return latents, original_latent_length, padded_latent_length
|
||||
@@ -1,20 +1,175 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""User-visible one-stage defaults for the LTX model family."""
|
||||
"""Declarative execution recipes for the LTX model family."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
from .ltx2_guidance import LTXGuidanceSpec, LTXModalityGuidance
|
||||
|
||||
LTX_DEFAULT_NEGATIVE_PROMPT = (
|
||||
"blurry, out of focus, overexposed, underexposed, low contrast, washed out colors, excessive noise, "
|
||||
"grainy texture, poor lighting, flickering, motion blur, distorted proportions, unnatural skin tones, "
|
||||
"deformed facial features, asymmetrical face, missing facial features, extra limbs, disfigured hands, "
|
||||
"wrong hand count, artifacts around text, inconsistent perspective, camera shake, incorrect depth of "
|
||||
"field, background too sharp, background clutter, distracting reflections, harsh shadows, inconsistent "
|
||||
"lighting direction, color banding, cartoonish rendering, 3D CGI look, unrealistic materials, uncanny "
|
||||
"valley effect, incorrect ethnicity, wrong gender, exaggerated expressions, wrong gaze direction, "
|
||||
"mismatched lip sync, silent or muted audio, distorted voice, robotic voice, echo, background noise, "
|
||||
"off-sync audio, incorrect dialogue, added dialogue, repetitive speech, jittery movement, awkward "
|
||||
"pauses, incorrect timing, unnatural transitions, inconsistent framing, tilted camera, flat lighting, "
|
||||
"inconsistent tone, cinematic oversaturation, stylized filters, or AI artifacts."
|
||||
)
|
||||
|
||||
LTX_DISTILLED_SIGMAS = (1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725, 0.421875, 0.0)
|
||||
LTX_STAGE_2_DISTILLED_SIGMAS = (0.909375, 0.725, 0.421875, 0.0)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LTXOneStageRecipe:
|
||||
class LTXPhaseRecipe:
|
||||
"""One denoise phase and the transition used to construct its input."""
|
||||
|
||||
name: str
|
||||
guidance: LTXGuidanceSpec
|
||||
spatial_downscale: int = 1
|
||||
sigmas: tuple[float, ...] | None = None
|
||||
noise_scale: float = 0.0
|
||||
input_transform: Literal["initial", "spatial_upsample"] = "initial"
|
||||
allow_guidance_override: bool = True
|
||||
use_official_sigma_schedule: bool = True
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.spatial_downscale < 1:
|
||||
raise ValueError("LTX phase spatial_downscale must be positive.")
|
||||
if self.sigmas is not None and len(self.sigmas) < 2:
|
||||
raise ValueError("An explicit LTX sigma schedule must contain at least two denoise sigmas.")
|
||||
|
||||
@property
|
||||
def num_inference_steps(self) -> int | None:
|
||||
return None if self.sigmas is None else len(self.sigmas) - 1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LTXPipelineRecipe:
|
||||
"""Request defaults, ordered phases, output routing, and request capabilities."""
|
||||
|
||||
phases: tuple[LTXPhaseRecipe, ...]
|
||||
height: int = 512
|
||||
width: int = 768
|
||||
num_frames: int = 121
|
||||
frame_rate: float = 24.0
|
||||
num_inference_steps: int = 40
|
||||
guidance_scale: float = 4.0
|
||||
negative_prompt: str = LTX_DEFAULT_NEGATIVE_PROMPT
|
||||
video_output_phase: int = -1
|
||||
audio_output_phase: int = -1
|
||||
allow_request_sigmas: bool = True
|
||||
allow_request_latents: bool = True
|
||||
allow_negative_prompt: bool = True
|
||||
fixed_num_inference_steps: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.phases:
|
||||
raise ValueError("An LTX pipeline recipe must contain at least one phase.")
|
||||
if self.phases[0].input_transform != "initial":
|
||||
raise ValueError("The first LTX phase must use the initial request input.")
|
||||
phase_count = len(self.phases)
|
||||
for output_phase in (self.video_output_phase, self.audio_output_phase):
|
||||
if not -phase_count <= output_phase < phase_count:
|
||||
raise ValueError(f"LTX output phase {output_phase} is outside a {phase_count}-phase recipe.")
|
||||
|
||||
@property
|
||||
def request_guidance(self) -> LTXGuidanceSpec:
|
||||
return self.phases[0].guidance
|
||||
|
||||
@property
|
||||
def max_spatial_downscale(self) -> int:
|
||||
return max(phase.spatial_downscale for phase in self.phases)
|
||||
|
||||
|
||||
LTX2_ONE_STAGE_RECIPE = LTXOneStageRecipe()
|
||||
LTX23_ONE_STAGE_RECIPE = LTXOneStageRecipe()
|
||||
def _official_guidance(stg_block: int) -> LTXGuidanceSpec:
|
||||
return LTXGuidanceSpec(
|
||||
video=LTXModalityGuidance(
|
||||
cfg_scale=3.0,
|
||||
stg_scale=1.0,
|
||||
modality_scale=3.0,
|
||||
rescale_scale=0.7,
|
||||
stg_blocks=(stg_block,),
|
||||
),
|
||||
audio=LTXModalityGuidance(
|
||||
cfg_scale=7.0,
|
||||
stg_scale=1.0,
|
||||
modality_scale=3.0,
|
||||
rescale_scale=0.7,
|
||||
stg_blocks=(stg_block,),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
LTX2_ONE_STAGE_RECIPE = LTXPipelineRecipe(
|
||||
phases=(LTXPhaseRecipe(name="generate", guidance=_official_guidance(29)),),
|
||||
)
|
||||
LTX23_ONE_STAGE_RECIPE = LTXPipelineRecipe(
|
||||
num_inference_steps=30,
|
||||
phases=(LTXPhaseRecipe(name="generate", guidance=_official_guidance(28)),),
|
||||
)
|
||||
LTX_POSITIVE_ONLY_RECIPE = LTXPipelineRecipe(
|
||||
phases=(
|
||||
LTXPhaseRecipe(
|
||||
name="generate",
|
||||
guidance=LTXGuidanceSpec.positive_only(),
|
||||
use_official_sigma_schedule=False,
|
||||
),
|
||||
),
|
||||
)
|
||||
LTX2_DISTILLED_TWO_STAGE_RECIPE = LTXPipelineRecipe(
|
||||
# Official distilled arguments describe the final output. Stage 1 applies
|
||||
# spatial_downscale=2 and therefore runs at 512x768.
|
||||
height=1024,
|
||||
width=1536,
|
||||
num_inference_steps=len(LTX_DISTILLED_SIGMAS) - 1,
|
||||
negative_prompt="",
|
||||
phases=(
|
||||
LTXPhaseRecipe(
|
||||
name="generate_lowres",
|
||||
guidance=LTXGuidanceSpec.positive_only(),
|
||||
spatial_downscale=2,
|
||||
sigmas=LTX_DISTILLED_SIGMAS,
|
||||
noise_scale=1.0,
|
||||
allow_guidance_override=False,
|
||||
use_official_sigma_schedule=False,
|
||||
),
|
||||
LTXPhaseRecipe(
|
||||
name="refine",
|
||||
guidance=LTXGuidanceSpec.positive_only(),
|
||||
sigmas=LTX_STAGE_2_DISTILLED_SIGMAS,
|
||||
noise_scale=LTX_STAGE_2_DISTILLED_SIGMAS[0],
|
||||
input_transform="spatial_upsample",
|
||||
allow_guidance_override=False,
|
||||
use_official_sigma_schedule=False,
|
||||
),
|
||||
),
|
||||
video_output_phase=1,
|
||||
audio_output_phase=1,
|
||||
allow_request_sigmas=False,
|
||||
allow_request_latents=False,
|
||||
allow_negative_prompt=False,
|
||||
fixed_num_inference_steps=True,
|
||||
)
|
||||
|
||||
|
||||
_PIPELINE_RECIPES: dict[tuple[str, str], LTXPipelineRecipe] = {
|
||||
("one_stage", "2"): LTX2_ONE_STAGE_RECIPE,
|
||||
("one_stage", "2.3"): LTX23_ONE_STAGE_RECIPE,
|
||||
("distilled_two_stage", "2"): LTX2_DISTILLED_TWO_STAGE_RECIPE,
|
||||
("dmd2", "2"): LTX_POSITIVE_ONLY_RECIPE,
|
||||
("dmd2", "2.3"): LTX_POSITIVE_ONLY_RECIPE,
|
||||
}
|
||||
|
||||
|
||||
def resolve_ltx_pipeline_recipe(pipeline_kind: str, model_version: str) -> LTXPipelineRecipe:
|
||||
"""Resolve execution independently from component loading."""
|
||||
try:
|
||||
return _PIPELINE_RECIPES[(pipeline_kind, model_version)]
|
||||
except KeyError as exc:
|
||||
raise ValueError(f"Unsupported LTX pipeline kind/version: {pipeline_kind!r}/{model_version!r}.") from exc
|
||||
@@ -1,17 +1,21 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Request normalization shared by LTX pipeline variants."""
|
||||
"""Request normalization and validation shared by LTX pipeline variants."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
|
||||
from .ltx2_guidance import LTXGuidanceSpec, LTXModalityGuidance
|
||||
from .ltx2_recipes import LTXPipelineRecipe
|
||||
|
||||
|
||||
@dataclass
|
||||
class LTXRequestInputs:
|
||||
@@ -24,8 +28,7 @@ class LTXRequestInputs:
|
||||
num_frames: int
|
||||
frame_rate: float
|
||||
num_inference_steps: int
|
||||
guidance_scale: float
|
||||
guidance_rescale: float
|
||||
guidance: LTXGuidanceSpec
|
||||
num_videos_per_prompt: int
|
||||
generator: torch.Generator | list[torch.Generator] | None
|
||||
latents: torch.Tensor | None
|
||||
@@ -38,6 +41,65 @@ class LTXRequestInputs:
|
||||
decode_noise_scale: float | list[float] | None
|
||||
output_type: str
|
||||
max_sequence_length: int
|
||||
audio_latents_normalized: bool = False
|
||||
|
||||
@property
|
||||
def guidance_scale(self) -> float:
|
||||
"""Compatibility view for callers that only understand video CFG."""
|
||||
return self.guidance.video.cfg_scale
|
||||
|
||||
|
||||
def validate_pipeline_request(
|
||||
request_inputs: LTXRequestInputs,
|
||||
*,
|
||||
pipeline_recipe: LTXPipelineRecipe,
|
||||
vae_spatial_compression_ratio: int,
|
||||
vae_temporal_compression_ratio: int,
|
||||
pipeline_name: str,
|
||||
request_sigmas: list[float] | None = None,
|
||||
) -> None:
|
||||
"""Validate the request capabilities declared by an execution recipe."""
|
||||
alignment = vae_spatial_compression_ratio * pipeline_recipe.max_spatial_downscale
|
||||
if request_inputs.height % alignment != 0 or request_inputs.width % alignment != 0:
|
||||
raise ValueError(
|
||||
f"{pipeline_name} resolution must be divisible by {alignment}, got "
|
||||
f"{request_inputs.width}x{request_inputs.height}."
|
||||
)
|
||||
|
||||
if request_inputs.num_frames < 1 or (request_inputs.num_frames - 1) % vae_temporal_compression_ratio != 0:
|
||||
raise ValueError(
|
||||
f"{pipeline_name} `num_frames` must be {vae_temporal_compression_ratio} * k + 1, "
|
||||
f"got {request_inputs.num_frames}."
|
||||
)
|
||||
|
||||
if not pipeline_recipe.allow_request_latents and (
|
||||
request_inputs.latents is not None or request_inputs.audio_latents is not None
|
||||
):
|
||||
raise ValueError(f"{pipeline_name} does not accept request-provided video or audio latents.")
|
||||
|
||||
if not pipeline_recipe.allow_request_sigmas and request_sigmas is not None:
|
||||
raise ValueError(f"{pipeline_name} uses fixed phase sigma schedules.")
|
||||
|
||||
if pipeline_recipe.fixed_num_inference_steps and (
|
||||
request_inputs.num_inference_steps != pipeline_recipe.num_inference_steps
|
||||
):
|
||||
raise ValueError(
|
||||
f"{pipeline_name} uses {pipeline_recipe.num_inference_steps} fixed Stage 1 denoise steps; "
|
||||
f"got {request_inputs.num_inference_steps}."
|
||||
)
|
||||
|
||||
negative_prompt = request_inputs.negative_prompt
|
||||
has_negative_prompt = (
|
||||
any(bool(value) for value in negative_prompt) if isinstance(negative_prompt, list) else bool(negative_prompt)
|
||||
)
|
||||
if not pipeline_recipe.allow_negative_prompt and (
|
||||
has_negative_prompt or request_inputs.negative_prompt_embeds is not None
|
||||
):
|
||||
raise ValueError(f"{pipeline_name} uses positive-only guidance and does not accept negative conditioning.")
|
||||
|
||||
first_phase = pipeline_recipe.phases[0]
|
||||
if not first_phase.allow_guidance_override and request_inputs.guidance != first_phase.guidance:
|
||||
raise ValueError(f"{pipeline_name} uses fixed positive-only guidance and cannot override it.")
|
||||
|
||||
|
||||
def _unwrap_request_tensor(value: Any) -> Any:
|
||||
@@ -65,11 +127,187 @@ def _get_audio_latents_from_sampling(sampling: Any) -> torch.Tensor | None:
|
||||
return sampling.extra_args.get("audio_latents")
|
||||
|
||||
|
||||
def _get_extra_arg(sampling: Any, *names: str) -> Any:
|
||||
extra_args = sampling.extra_args or {}
|
||||
for name in names:
|
||||
value = extra_args.get(name)
|
||||
if value is not None:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_stg_blocks(value: Any, default: tuple[int, ...]) -> tuple[int, ...]:
|
||||
if value is None:
|
||||
return default
|
||||
if isinstance(value, int):
|
||||
return (value,)
|
||||
if not isinstance(value, (list, tuple)):
|
||||
raise ValueError(f"STG blocks must be an integer or a list of integers, got {value!r}.")
|
||||
return tuple(int(item) for item in value)
|
||||
|
||||
|
||||
def _resolve_negative_prompts(
|
||||
prompts: list[Any],
|
||||
fallback: str | list[str],
|
||||
) -> str | list[str]:
|
||||
if not prompts:
|
||||
return fallback
|
||||
if isinstance(fallback, list) and len(fallback) != len(prompts):
|
||||
raise ValueError(
|
||||
f"`negative_prompt` has batch size {len(fallback)}, but the request batch has size {len(prompts)}."
|
||||
)
|
||||
|
||||
resolved = []
|
||||
for index, item in enumerate(prompts):
|
||||
request_value = None if isinstance(item, str) else item.get("negative_prompt")
|
||||
if request_value is not None:
|
||||
resolved.append(request_value)
|
||||
else:
|
||||
resolved.append(fallback[index] if isinstance(fallback, list) else fallback)
|
||||
return resolved
|
||||
|
||||
|
||||
def _resolve_modality_guidance(
|
||||
sampling: Any,
|
||||
modality: str,
|
||||
default: LTXModalityGuidance,
|
||||
) -> LTXModalityGuidance:
|
||||
cfg_aliases = (f"{modality}_cfg_scale", f"{modality}_cfg_guidance_scale")
|
||||
stg_aliases = (f"{modality}_stg_scale", f"{modality}_stg_guidance_scale")
|
||||
modality_aliases = (
|
||||
("video_modality_scale", "a2v_guidance_scale")
|
||||
if modality == "video"
|
||||
else ("audio_modality_scale", "v2a_guidance_scale")
|
||||
)
|
||||
cfg_scale = _get_extra_arg(sampling, *cfg_aliases)
|
||||
stg_scale = _get_extra_arg(sampling, *stg_aliases)
|
||||
modality_scale = _get_extra_arg(sampling, *modality_aliases)
|
||||
rescale_scale = _get_extra_arg(sampling, f"{modality}_rescale_scale")
|
||||
stg_blocks = _get_extra_arg(sampling, f"{modality}_stg_blocks")
|
||||
return replace(
|
||||
default,
|
||||
cfg_scale=default.cfg_scale if cfg_scale is None else float(cfg_scale),
|
||||
stg_scale=default.stg_scale if stg_scale is None else float(stg_scale),
|
||||
modality_scale=default.modality_scale if modality_scale is None else float(modality_scale),
|
||||
rescale_scale=default.rescale_scale if rescale_scale is None else float(rescale_scale),
|
||||
stg_blocks=_normalize_stg_blocks(stg_blocks, default.stg_blocks),
|
||||
)
|
||||
|
||||
|
||||
def _resolve_guidance_spec(
|
||||
sampling: Any,
|
||||
default: LTXGuidanceSpec,
|
||||
*,
|
||||
guidance_scale: float | None,
|
||||
) -> LTXGuidanceSpec:
|
||||
video = _resolve_modality_guidance(sampling, "video", default.video)
|
||||
audio = _resolve_modality_guidance(sampling, "audio", default.audio)
|
||||
|
||||
common_cfg = sampling.guidance_scale if sampling.guidance_scale_provided else guidance_scale
|
||||
if common_cfg is not None:
|
||||
video = replace(video, cfg_scale=float(common_cfg))
|
||||
audio = replace(audio, cfg_scale=float(common_cfg))
|
||||
|
||||
return LTXGuidanceSpec(video=video, audio=audio)
|
||||
|
||||
|
||||
class LTXRequestMixin:
|
||||
"""Normalize serving requests without coupling them to a model version."""
|
||||
|
||||
supports_request_batch = False
|
||||
supports_guidance_rescale = False
|
||||
|
||||
@staticmethod
|
||||
def _validate_forward_options(
|
||||
*,
|
||||
timesteps: list[int] | None,
|
||||
guidance_rescale: float | None,
|
||||
noise_scale: float,
|
||||
return_dict: bool,
|
||||
attention_kwargs: dict[str, Any] | None,
|
||||
) -> None:
|
||||
if timesteps is not None:
|
||||
raise ValueError("LTX does not support `timesteps`; use `sigmas` for a custom schedule.")
|
||||
if guidance_rescale not in (None, 0.0):
|
||||
raise ValueError(
|
||||
"LTX does not support the common `guidance_rescale`; use `video_rescale_scale` and "
|
||||
"`audio_rescale_scale`."
|
||||
)
|
||||
if noise_scale != 0.0:
|
||||
raise ValueError("LTX only supports `noise_scale=0.0`.")
|
||||
if return_dict is not True:
|
||||
raise ValueError("LTX only supports `return_dict=True`.")
|
||||
if attention_kwargs is not None:
|
||||
raise ValueError("LTX does not support public `attention_kwargs`.")
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
*,
|
||||
image: Any | None = None,
|
||||
prompt: str | list[str] | None = None,
|
||||
negative_prompt: str | list[str] | None = None,
|
||||
height: int | None = None,
|
||||
width: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
frame_rate: float | None = None,
|
||||
num_inference_steps: int | None = None,
|
||||
sigmas: list[float] | None = None,
|
||||
timesteps: list[int] | None = None,
|
||||
guidance_scale: float | None = None,
|
||||
guidance_rescale: float | None = None,
|
||||
noise_scale: float = 0.0,
|
||||
num_videos_per_prompt: int | None = 1,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
audio_latents: torch.Tensor | None = None,
|
||||
prompt_embeds: torch.Tensor | None = None,
|
||||
negative_prompt_embeds: torch.Tensor | None = None,
|
||||
prompt_attention_mask: torch.Tensor | None = None,
|
||||
negative_prompt_attention_mask: torch.Tensor | None = None,
|
||||
decode_timestep: float | list[float] = 0.0,
|
||||
decode_noise_scale: float | list[float] | None = None,
|
||||
output_type: str = "np",
|
||||
return_dict: bool = True,
|
||||
attention_kwargs: dict[str, Any] | None = None,
|
||||
max_sequence_length: int | None = None,
|
||||
) -> DiffusionOutput | list[DiffusionOutput]:
|
||||
"""Validate and normalize the public LTX request surface."""
|
||||
self._validate_forward_options(
|
||||
timesteps=timesteps,
|
||||
guidance_rescale=guidance_rescale,
|
||||
noise_scale=noise_scale,
|
||||
return_dict=return_dict,
|
||||
attention_kwargs=attention_kwargs,
|
||||
)
|
||||
if image is not None and not self.support_image_input:
|
||||
raise ValueError(f"{self.__class__.__name__} does not support `image` input.")
|
||||
|
||||
return self._forward_request(
|
||||
req,
|
||||
image=image,
|
||||
prompt=prompt,
|
||||
negative_prompt=negative_prompt,
|
||||
height=height,
|
||||
width=width,
|
||||
num_frames=num_frames,
|
||||
frame_rate=frame_rate,
|
||||
num_inference_steps=num_inference_steps,
|
||||
sigmas=sigmas,
|
||||
guidance_scale=guidance_scale,
|
||||
num_videos_per_prompt=num_videos_per_prompt,
|
||||
generator=generator,
|
||||
latents=latents,
|
||||
audio_latents=audio_latents,
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
prompt_attention_mask=prompt_attention_mask,
|
||||
negative_prompt_attention_mask=negative_prompt_attention_mask,
|
||||
decode_timestep=decode_timestep,
|
||||
decode_noise_scale=decode_noise_scale,
|
||||
output_type=output_type,
|
||||
max_sequence_length=max_sequence_length,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _resolve_request_sigmas(
|
||||
@@ -128,8 +366,7 @@ class LTXRequestMixin:
|
||||
num_frames: int | None,
|
||||
frame_rate: float | None,
|
||||
num_inference_steps: int | None,
|
||||
timesteps: list[int] | None,
|
||||
guidance_scale: float,
|
||||
guidance_scale: float | None,
|
||||
num_videos_per_prompt: int | None,
|
||||
generator: torch.Generator | list[torch.Generator] | None,
|
||||
latents: torch.Tensor | None,
|
||||
@@ -142,38 +379,55 @@ class LTXRequestMixin:
|
||||
decode_noise_scale: float | list[float] | None,
|
||||
output_type: str,
|
||||
max_sequence_length: int | None,
|
||||
guidance_rescale: float = 0.0,
|
||||
) -> LTXRequestInputs:
|
||||
sampling_params_list = req.sampling_params_list
|
||||
sampling = sampling_params_list[0]
|
||||
prompt = [item if isinstance(item, str) else (item.get("prompt") or "") for item in req.prompts] or prompt
|
||||
if all(isinstance(item, str) or item.get("negative_prompt") is None for item in req.prompts):
|
||||
negative_prompt = None
|
||||
elif req.prompts:
|
||||
negative_prompt = [
|
||||
"" if isinstance(item, str) else (item.get("negative_prompt") or "") for item in req.prompts
|
||||
]
|
||||
for sampling in sampling_params_list:
|
||||
if sampling.timesteps is not None:
|
||||
raise ValueError("LTX does not support `timesteps`; use `sigmas` for a custom schedule.")
|
||||
if sampling.guidance_rescale:
|
||||
raise ValueError(
|
||||
"LTX does not support the common `guidance_rescale`; use `video_rescale_scale` and "
|
||||
"`audio_rescale_scale`."
|
||||
)
|
||||
if _get_extra_arg(sampling, "flow_shift") is not None:
|
||||
raise ValueError("LTX does not support `flow_shift`; use `sigmas` for a custom schedule.")
|
||||
|
||||
height = sampling.height or height or self.one_stage_recipe.height
|
||||
width = sampling.width or width or self.one_stage_recipe.width
|
||||
num_frames = sampling.num_frames or num_frames or self.one_stage_recipe.num_frames
|
||||
frame_rate = sampling.resolved_frame_rate or frame_rate or self.one_stage_recipe.frame_rate
|
||||
num_inference_steps = (
|
||||
sampling.num_inference_steps or num_inference_steps or self.one_stage_recipe.num_inference_steps
|
||||
sampling = sampling_params_list[0]
|
||||
is_dummy_run = req.is_dummy_run()
|
||||
prompt = [item if isinstance(item, str) else (item.get("prompt") or "") for item in req.prompts] or prompt
|
||||
negative_prompt = _resolve_negative_prompts(
|
||||
req.prompts,
|
||||
negative_prompt if negative_prompt is not None else self.pipeline_recipe.negative_prompt,
|
||||
)
|
||||
if timesteps is None:
|
||||
num_inference_steps = max(int(num_inference_steps), 2)
|
||||
elif len(timesteps) < 2:
|
||||
raise ValueError("`timesteps` must contain at least 2 values for FlowMatchEulerDiscreteScheduler.")
|
||||
|
||||
height = sampling.height or height or self.pipeline_recipe.height
|
||||
width = sampling.width or width or self.pipeline_recipe.width
|
||||
num_frames = sampling.num_frames or num_frames or self.pipeline_recipe.num_frames
|
||||
frame_rate = sampling.resolved_frame_rate or frame_rate or self.pipeline_recipe.frame_rate
|
||||
num_inference_steps = (
|
||||
sampling.num_inference_steps or num_inference_steps or self.pipeline_recipe.num_inference_steps
|
||||
)
|
||||
if is_dummy_run and self.pipeline_recipe.fixed_num_inference_steps:
|
||||
num_inference_steps = self.pipeline_recipe.num_inference_steps
|
||||
num_inference_steps = max(int(num_inference_steps), 2)
|
||||
|
||||
num_videos_per_prompt = (
|
||||
sampling.num_outputs_per_prompt if sampling.num_outputs_per_prompt > 0 else num_videos_per_prompt or 1
|
||||
)
|
||||
max_sequence_length = sampling.max_sequence_length or max_sequence_length or self.tokenizer_max_length
|
||||
if sampling.guidance_scale_provided:
|
||||
guidance_scale = sampling.guidance_scale
|
||||
if self.supports_guidance_rescale and sampling.guidance_rescale is not None:
|
||||
guidance_rescale = sampling.guidance_rescale
|
||||
guidance_specs = [
|
||||
_resolve_guidance_spec(
|
||||
item,
|
||||
self.pipeline_recipe.request_guidance,
|
||||
guidance_scale=guidance_scale,
|
||||
)
|
||||
for item in sampling_params_list
|
||||
]
|
||||
guidance = guidance_specs[0]
|
||||
if is_dummy_run and not self.pipeline_recipe.phases[0].allow_guidance_override:
|
||||
guidance = self.pipeline_recipe.request_guidance
|
||||
if any(item != guidance for item in guidance_specs[1:]):
|
||||
raise ValueError("Batched LTX requests must use identical video/audio guidance parameters.")
|
||||
|
||||
if self.supports_request_batch:
|
||||
if generator is None:
|
||||
@@ -235,6 +489,10 @@ class LTXRequestMixin:
|
||||
]
|
||||
if any(value is not None for value in request_negative_masks):
|
||||
negative_prompt_attention_mask = torch.stack(request_negative_masks) # type: ignore[arg-type]
|
||||
if prompt_embeds is not None:
|
||||
prompt = None
|
||||
if negative_prompt_embeds is not None:
|
||||
negative_prompt = None
|
||||
|
||||
if sampling.decode_timestep is not None:
|
||||
decode_timestep = sampling.decode_timestep
|
||||
@@ -251,8 +509,7 @@ class LTXRequestMixin:
|
||||
num_frames=int(num_frames),
|
||||
frame_rate=float(frame_rate),
|
||||
num_inference_steps=int(num_inference_steps),
|
||||
guidance_scale=guidance_scale,
|
||||
guidance_rescale=guidance_rescale,
|
||||
guidance=guidance,
|
||||
num_videos_per_prompt=int(num_videos_per_prompt),
|
||||
generator=generator,
|
||||
latents=latents,
|
||||
|
||||
+305
-65
@@ -1,12 +1,13 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Shared runtime surface for LTX pipeline variants."""
|
||||
"""Shared recipe-driven runtime for LTX pipeline variants."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from contextlib import nullcontext
|
||||
from dataclasses import replace
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import torch
|
||||
@@ -21,22 +22,41 @@ from vllm_omni.diffusion.models.interface import SupportsComponentDiscovery
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch, split_diffusion_output_by_request
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
from . import ltx2_latents as latent_ops
|
||||
from .ltx2_components import LTXComponentProfile, initialize_pipeline_components
|
||||
from .ltx2_components import (
|
||||
LTXComponentProfile,
|
||||
detect_ltx_model_version,
|
||||
initialize_pipeline_components,
|
||||
resolve_ltx_component_profile,
|
||||
)
|
||||
from .ltx2_conditioning import LTXPromptContext, LTXTextConditioningMixin
|
||||
from .ltx2_denoise import (
|
||||
LTXDenoiseContext,
|
||||
LTXForwardContext,
|
||||
LTXPhaseExecutor,
|
||||
LTXPhaseResult,
|
||||
VideoAudioScheduler,
|
||||
build_transformer_kwargs,
|
||||
step_denoised_latents,
|
||||
)
|
||||
from .ltx2_guidance import LTXGuidanceStrategy
|
||||
from .ltx2_recipes import LTXOneStageRecipe
|
||||
from .ltx2_request import LTXRequestInputs, LTXRequestMixin
|
||||
from .ltx2_guidance import (
|
||||
LTX_GUIDANCE_EXECUTOR,
|
||||
LTXGuidanceExecutor,
|
||||
LTXGuidancePlan,
|
||||
LTXGuidanceSpec,
|
||||
LTXModalityGuidance,
|
||||
)
|
||||
from .ltx2_recipes import (
|
||||
LTXPhaseRecipe,
|
||||
LTXPipelineRecipe,
|
||||
resolve_ltx_pipeline_recipe,
|
||||
)
|
||||
from .ltx2_request import (
|
||||
LTXRequestInputs,
|
||||
LTXRequestMixin,
|
||||
validate_pipeline_request,
|
||||
)
|
||||
|
||||
|
||||
def _expand_per_prompt_decode_value(
|
||||
@@ -92,7 +112,7 @@ def _prepare_decode_timestep_conditioning(
|
||||
)
|
||||
|
||||
|
||||
class LTXPipelineRuntime(
|
||||
class LTXRuntime(
|
||||
LTXRequestMixin,
|
||||
LTXTextConditioningMixin,
|
||||
nn.Module,
|
||||
@@ -101,27 +121,146 @@ class LTXPipelineRuntime(
|
||||
SupportsComponentDiscovery,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
):
|
||||
"""Shared Omni runtime for explicitly composed LTX denoise phases."""
|
||||
"""Shared Omni runtime for recipe-driven LTX denoise phases."""
|
||||
|
||||
pipeline_kind: ClassVar[str] = "one_stage"
|
||||
component_profile: ClassVar[LTXComponentProfile]
|
||||
guidance_strategy: ClassVar[LTXGuidanceStrategy]
|
||||
one_stage_recipe: ClassVar[LTXOneStageRecipe]
|
||||
pipeline_recipe: ClassVar[LTXPipelineRecipe]
|
||||
guidance_executor: ClassVar[LTXGuidanceExecutor] = LTX_GUIDANCE_EXECUTOR
|
||||
supports_request_batch = False
|
||||
connector_batches_cfg = False
|
||||
distributed_video_decode = True
|
||||
support_image_input = False
|
||||
dummy_run_num_frames = 2
|
||||
dummy_run_num_frames = 1
|
||||
preserve_sp_padded_audio_duration = False
|
||||
reports_stage_durations = False
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = "") -> None:
|
||||
del prefix
|
||||
self.model_version = detect_ltx_model_version(od_config.model)
|
||||
self.component_profile = resolve_ltx_component_profile(self.pipeline_kind, self.model_version)
|
||||
self.pipeline_recipe = resolve_ltx_pipeline_recipe(self.pipeline_kind, self.model_version)
|
||||
self._dit_modules = list(self.component_profile.dit_modules)
|
||||
self._encoder_modules = list(self.component_profile.encoder_modules)
|
||||
self._vae_modules = list(self.component_profile.vae_modules)
|
||||
self._resident_modules = list(self.component_profile.resident_modules)
|
||||
if self.model_version == "2.3":
|
||||
self.preserve_sp_padded_audio_duration = True
|
||||
self.reports_stage_durations = True
|
||||
super().__init__()
|
||||
self._guidance_plan = LTXGuidancePlan.build(self.pipeline_recipe.request_guidance)
|
||||
initialize_pipeline_components(self, od_config)
|
||||
self.setup_diffusion_pipeline_profiler(
|
||||
enable_diffusion_pipeline_profiler=self.od_config.enable_diffusion_pipeline_profiler
|
||||
)
|
||||
|
||||
def _forward_request(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
*,
|
||||
image: Any | None = None,
|
||||
prompt: str | list[str] | None = None,
|
||||
negative_prompt: str | list[str] | None = None,
|
||||
height: int | None = None,
|
||||
width: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
frame_rate: float | None = None,
|
||||
num_inference_steps: int | None = None,
|
||||
sigmas: list[float] | None = None,
|
||||
guidance_scale: float | None = None,
|
||||
num_videos_per_prompt: int | None = 1,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
audio_latents: torch.Tensor | None = None,
|
||||
prompt_embeds: torch.Tensor | None = None,
|
||||
negative_prompt_embeds: torch.Tensor | None = None,
|
||||
prompt_attention_mask: torch.Tensor | None = None,
|
||||
negative_prompt_attention_mask: torch.Tensor | None = None,
|
||||
decode_timestep: float | list[float] = 0.0,
|
||||
decode_noise_scale: float | list[float] | None = None,
|
||||
output_type: str = "np",
|
||||
max_sequence_length: int | None = None,
|
||||
) -> DiffusionOutput | list[DiffusionOutput]:
|
||||
request_inputs = self._resolve_request_inputs(
|
||||
req,
|
||||
prompt=prompt,
|
||||
negative_prompt=negative_prompt,
|
||||
height=height,
|
||||
width=width,
|
||||
num_frames=num_frames,
|
||||
frame_rate=frame_rate,
|
||||
num_inference_steps=num_inference_steps,
|
||||
guidance_scale=guidance_scale,
|
||||
num_videos_per_prompt=num_videos_per_prompt,
|
||||
generator=generator,
|
||||
latents=latents,
|
||||
audio_latents=audio_latents,
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
prompt_attention_mask=prompt_attention_mask,
|
||||
negative_prompt_attention_mask=negative_prompt_attention_mask,
|
||||
decode_timestep=decode_timestep,
|
||||
decode_noise_scale=decode_noise_scale,
|
||||
output_type=output_type,
|
||||
max_sequence_length=max_sequence_length,
|
||||
)
|
||||
image = self._resolve_request_image(req, image, request_inputs)
|
||||
request_sigmas = self._resolve_request_sigmas(req, sigmas)
|
||||
validate_pipeline_request(
|
||||
request_inputs,
|
||||
pipeline_recipe=self.pipeline_recipe,
|
||||
vae_spatial_compression_ratio=self.vae_spatial_compression_ratio,
|
||||
vae_temporal_compression_ratio=self.vae_temporal_compression_ratio,
|
||||
pipeline_name=self.__class__.__name__,
|
||||
request_sigmas=request_sigmas,
|
||||
)
|
||||
return self._run_recipe(req, request_inputs, request_sigmas=request_sigmas, image=image)
|
||||
|
||||
def _run_recipe(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
request_inputs: LTXRequestInputs,
|
||||
*,
|
||||
request_sigmas: list[float] | None,
|
||||
image: Any | None = None,
|
||||
) -> DiffusionOutput | list[DiffusionOutput]:
|
||||
"""Execute one- and multi-phase recipes through the same control flow."""
|
||||
phase_results: list[LTXPhaseResult] = []
|
||||
prompt_context = None
|
||||
|
||||
for phase_recipe in self.pipeline_recipe.phases:
|
||||
self._enter_phase(phase_recipe)
|
||||
phase_inputs = self._build_phase_inputs(
|
||||
request_inputs,
|
||||
phase_recipe,
|
||||
phase_results[-1] if phase_results else None,
|
||||
)
|
||||
phase_result = self.run_phase(
|
||||
req,
|
||||
phase_inputs,
|
||||
noise_scale=phase_recipe.noise_scale,
|
||||
sigmas=list(phase_recipe.sigmas) if phase_recipe.sigmas is not None else request_sigmas,
|
||||
timesteps=None,
|
||||
attention_kwargs=None,
|
||||
phase_recipe=phase_recipe,
|
||||
image=image,
|
||||
prompt_context=prompt_context,
|
||||
)
|
||||
phase_results.append(phase_result)
|
||||
prompt_context = phase_result.forward_context.prompt_context
|
||||
|
||||
final_context = phase_results[-1].forward_context
|
||||
output_phase = LTXPhaseResult(
|
||||
forward_context=final_context,
|
||||
video=phase_results[self.pipeline_recipe.video_output_phase].video,
|
||||
audio=phase_results[self.pipeline_recipe.audio_output_phase].audio,
|
||||
)
|
||||
return self.decode_phase(output_phase)
|
||||
|
||||
def _enter_phase(self, phase: LTXPhaseRecipe) -> None:
|
||||
"""Hook for a future phase-weight strategy."""
|
||||
del phase
|
||||
|
||||
def prepare_latents(
|
||||
self,
|
||||
batch_size: int = 1,
|
||||
@@ -160,6 +299,7 @@ class LTXPipelineRuntime(
|
||||
device: torch.device | None = None,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
latents_normalized: bool = False,
|
||||
) -> tuple[torch.Tensor, int, int]:
|
||||
return latent_ops.prepare_audio_latents(
|
||||
self,
|
||||
@@ -172,19 +312,16 @@ class LTXPipelineRuntime(
|
||||
device,
|
||||
generator,
|
||||
latents,
|
||||
latents_normalized,
|
||||
)
|
||||
|
||||
@property
|
||||
def guidance_scale(self):
|
||||
return self._guidance_scale
|
||||
|
||||
@property
|
||||
def guidance_rescale(self):
|
||||
return self._guidance_rescale
|
||||
return self._guidance_plan.spec.video.cfg_scale
|
||||
|
||||
@property
|
||||
def do_classifier_free_guidance(self):
|
||||
return self._guidance_scale is not None and self._guidance_scale > 1.0
|
||||
return self._guidance_plan.spec.do_cfg
|
||||
|
||||
@property
|
||||
def interrupt(self):
|
||||
@@ -212,21 +349,29 @@ class LTXPipelineRuntime(
|
||||
):
|
||||
if kwargs is not None:
|
||||
context = {**kwargs, **context}
|
||||
return self.guidance_strategy.combine_cfg_noise(
|
||||
self,
|
||||
positive_noise_pred,
|
||||
negative_noise_pred,
|
||||
true_cfg_scale,
|
||||
cfg_normalize,
|
||||
context,
|
||||
del cfg_normalize
|
||||
required = ("video_latents", "audio_latents", "video_sigma", "audio_sigma")
|
||||
if any(context.get(name) is None for name in required):
|
||||
raise ValueError("LTX x0-space CFG requires video/audio latents and sigmas.")
|
||||
video_pos, audio_pos = positive_noise_pred
|
||||
video_neg, audio_neg = negative_noise_pred
|
||||
return (
|
||||
self.guidance_executor.combine_cfg_velocity(
|
||||
context["video_latents"],
|
||||
video_pos,
|
||||
video_neg,
|
||||
context["video_sigma"],
|
||||
true_cfg_scale,
|
||||
),
|
||||
self.guidance_executor.combine_cfg_velocity(
|
||||
context["audio_latents"],
|
||||
audio_pos,
|
||||
audio_neg,
|
||||
context["audio_sigma"],
|
||||
true_cfg_scale,
|
||||
),
|
||||
)
|
||||
|
||||
def predict_noise_with_parallel_cfg(self, *args, **kwargs):
|
||||
predict_parallel_cfg = getattr(self.guidance_strategy, "predict_parallel_cfg", None)
|
||||
if predict_parallel_cfg is None:
|
||||
raise NotImplementedError("The selected LTX guidance strategy does not implement parallel CFG.")
|
||||
return predict_parallel_cfg(self, *args, **kwargs)
|
||||
|
||||
def _synchronize_cfg_parallel_step_output(
|
||||
self,
|
||||
latents: tuple[torch.Tensor, torch.Tensor],
|
||||
@@ -238,23 +383,35 @@ class LTXPipelineRuntime(
|
||||
# CUDA async execution otherwise permits numerical drift to accumulate
|
||||
# across CFG-parallel denoise steps.
|
||||
latents = tuple(tensor.contiguous() for tensor in latents)
|
||||
device = next((tensor.device for tensor in latents if tensor.is_cuda), None)
|
||||
if device is not None:
|
||||
torch.cuda.current_stream(device).synchronize()
|
||||
current_omni_platform.synchronize()
|
||||
return latents
|
||||
|
||||
def _setup_forward_runtime(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
request_inputs: LTXRequestInputs,
|
||||
attention_kwargs: dict[str, Any] | None,
|
||||
) -> bool:
|
||||
self._guidance_scale = request_inputs.guidance_scale
|
||||
self._guidance_rescale = request_inputs.guidance_rescale
|
||||
self._guidance_plan = LTXGuidancePlan.build(request_inputs.guidance)
|
||||
del attention_kwargs
|
||||
self._interrupt = False
|
||||
cfg_world_size = get_classifier_free_guidance_world_size()
|
||||
if (
|
||||
req.is_dummy_run()
|
||||
and cfg_world_size == 2
|
||||
and self.do_classifier_free_guidance
|
||||
and not self._guidance_plan.cfg_parallel_compatible
|
||||
):
|
||||
# The single-device warmup follows the full recipe. CFG2 executes
|
||||
# the same per-modality CFG scales without STG/modality passes.
|
||||
self._guidance_plan = LTXGuidancePlan.build(
|
||||
LTXGuidanceSpec(
|
||||
video=LTXModalityGuidance(cfg_scale=self._guidance_plan.spec.video.cfg_scale),
|
||||
audio=LTXModalityGuidance(cfg_scale=self._guidance_plan.spec.audio.cfg_scale),
|
||||
)
|
||||
)
|
||||
if self.do_classifier_free_guidance:
|
||||
self.guidance_strategy.validate_cfg_world_size(cfg_world_size)
|
||||
self.guidance_executor.validate_cfg_world_size(self._guidance_plan, cfg_world_size)
|
||||
return self.do_classifier_free_guidance and cfg_world_size > 1
|
||||
|
||||
def _check_forward_inputs(
|
||||
@@ -325,11 +482,8 @@ class LTXPipelineRuntime(
|
||||
vae_decode_needs_all_ranks = False
|
||||
is_distributed_vae_enabled = getattr(self.vae, "is_distributed_enabled", None)
|
||||
if self.distributed_video_decode and dist_initialized and callable(is_distributed_vae_enabled):
|
||||
try:
|
||||
# Distributed tiled decode is collective, so every rank must enter it.
|
||||
vae_decode_needs_all_ranks = bool(is_distributed_vae_enabled())
|
||||
except Exception:
|
||||
pass
|
||||
# Distributed tiled decode is collective, so every rank must enter it.
|
||||
vae_decode_needs_all_ranks = bool(is_distributed_vae_enabled())
|
||||
|
||||
should_decode_video = not self.distributed_video_decode or is_output_rank or vae_decode_needs_all_ranks
|
||||
if should_decode_video:
|
||||
@@ -361,16 +515,16 @@ class LTXPipelineRuntime(
|
||||
image: Any | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
latents = self.prepare_latents(
|
||||
prompt_context.batch_size * request_inputs.num_videos_per_prompt,
|
||||
self.transformer.config.in_channels,
|
||||
request_inputs.height,
|
||||
request_inputs.width,
|
||||
request_inputs.num_frames,
|
||||
noise_scale,
|
||||
torch.float32,
|
||||
device,
|
||||
request_inputs.generator,
|
||||
request_inputs.latents,
|
||||
batch_size=prompt_context.batch_size * request_inputs.num_videos_per_prompt,
|
||||
num_channels_latents=self.transformer.config.in_channels,
|
||||
height=request_inputs.height,
|
||||
width=request_inputs.width,
|
||||
num_frames=request_inputs.num_frames,
|
||||
noise_scale=noise_scale,
|
||||
dtype=prompt_context.positive_connector_prompt_embeds.dtype,
|
||||
device=device,
|
||||
generator=request_inputs.generator,
|
||||
latents=request_inputs.latents,
|
||||
)
|
||||
return latents, None
|
||||
|
||||
@@ -416,10 +570,11 @@ class LTXPipelineRuntime(
|
||||
audio_latent_length=audio_num_frames,
|
||||
num_mel_bins=num_mel_bins,
|
||||
noise_scale=noise_scale,
|
||||
dtype=torch.float32,
|
||||
dtype=prompt_context.positive_connector_audio_prompt_embeds.dtype,
|
||||
device=device,
|
||||
generator=request_inputs.generator,
|
||||
latents=request_inputs.audio_latents,
|
||||
latents_normalized=request_inputs.audio_latents_normalized,
|
||||
)
|
||||
return audio_latents, original_num_frames, padded_num_frames, latent_mel_bins
|
||||
|
||||
@@ -439,29 +594,37 @@ class LTXPipelineRuntime(
|
||||
padded_length = latent_ops.get_sp_padded_audio_latent_length(requested_length, int(sp_size))
|
||||
return requested_length if provided_length in {requested_length, padded_length} else provided_length
|
||||
|
||||
def _make_video_audio_scheduler(
|
||||
self,
|
||||
audio_scheduler: Any,
|
||||
latent_num_frames: int,
|
||||
latent_height: int,
|
||||
latent_width: int,
|
||||
) -> Any:
|
||||
return VideoAudioScheduler(self.scheduler, audio_scheduler)
|
||||
|
||||
def _prepare_denoise_context_for_cfg(
|
||||
self,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> LTXDenoiseContext:
|
||||
return self.guidance_strategy.prepare_denoise_context(self, forward_ctx, denoise_ctx)
|
||||
return self.guidance_executor.prepare_denoise_context(
|
||||
self._guidance_plan,
|
||||
forward_ctx.cfg_parallel_ready,
|
||||
denoise_ctx,
|
||||
)
|
||||
|
||||
def _denoise_timestep_kwargs(
|
||||
self,
|
||||
ts: torch.Tensor,
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
*,
|
||||
video_token_count: int,
|
||||
audio_token_count: int,
|
||||
) -> dict[str, torch.Tensor]:
|
||||
return self.guidance_strategy.timestep_kwargs(ts, forward_ctx, denoise_ctx)
|
||||
del forward_ctx, denoise_ctx
|
||||
return self.guidance_executor.timestep_kwargs(ts, video_token_count, audio_token_count)
|
||||
|
||||
def _video_guidance_model_sigma(
|
||||
self,
|
||||
sigma: torch.Tensor,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> torch.Tensor:
|
||||
"""Return the video timestep used to convert velocity predictions to x0."""
|
||||
del denoise_ctx
|
||||
return sigma
|
||||
|
||||
def _build_transformer_kwargs(
|
||||
self,
|
||||
@@ -475,6 +638,7 @@ class LTXPipelineRuntime(
|
||||
encoder_attention_mask: torch.Tensor | None,
|
||||
audio_encoder_attention_mask: torch.Tensor | None,
|
||||
ts: torch.Tensor,
|
||||
attention_kwargs: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
return build_transformer_kwargs(
|
||||
self,
|
||||
@@ -487,6 +651,7 @@ class LTXPipelineRuntime(
|
||||
encoder_attention_mask=encoder_attention_mask,
|
||||
audio_encoder_attention_mask=audio_encoder_attention_mask,
|
||||
ts=ts,
|
||||
attention_kwargs=attention_kwargs,
|
||||
)
|
||||
|
||||
def _predict_noise_for_step(
|
||||
@@ -497,8 +662,9 @@ class LTXPipelineRuntime(
|
||||
forward_ctx: LTXForwardContext,
|
||||
denoise_ctx: LTXDenoiseContext,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return self.guidance_strategy.predict_noise(
|
||||
return self.guidance_executor.predict_noise(
|
||||
self,
|
||||
self._guidance_plan,
|
||||
index,
|
||||
timestep,
|
||||
state,
|
||||
@@ -562,7 +728,6 @@ class LTXPipelineRuntime(
|
||||
)
|
||||
audio_latents = latent_ops.unpack_audio_latents(
|
||||
audio_latents,
|
||||
forward_ctx.original_audio_num_frames,
|
||||
num_mel_bins=forward_ctx.latent_mel_bins,
|
||||
)
|
||||
return latents, audio_latents
|
||||
@@ -576,6 +741,7 @@ class LTXPipelineRuntime(
|
||||
sigmas: list[float] | None,
|
||||
timesteps: list[int] | None,
|
||||
attention_kwargs: dict[str, Any] | None,
|
||||
phase_recipe: LTXPhaseRecipe,
|
||||
image: Any | None = None,
|
||||
prompt_context: LTXPromptContext | None = None,
|
||||
) -> LTXPhaseResult:
|
||||
@@ -588,10 +754,84 @@ class LTXPipelineRuntime(
|
||||
sigmas=sigmas,
|
||||
timesteps=timesteps,
|
||||
attention_kwargs=attention_kwargs,
|
||||
phase_recipe=phase_recipe,
|
||||
image=image,
|
||||
prompt_context=prompt_context,
|
||||
)
|
||||
|
||||
def _build_phase_inputs(
|
||||
self,
|
||||
request_inputs: LTXRequestInputs,
|
||||
phase: LTXPhaseRecipe,
|
||||
previous_phase: LTXPhaseResult | None,
|
||||
) -> LTXRequestInputs:
|
||||
"""Resolve one phase from immutable request inputs and prior AV state."""
|
||||
divisor = phase.spatial_downscale
|
||||
if request_inputs.height % divisor != 0 or request_inputs.width % divisor != 0:
|
||||
raise ValueError(
|
||||
f"LTX phase {phase.name!r} cannot scale resolution "
|
||||
f"{request_inputs.width}x{request_inputs.height} by {divisor}."
|
||||
)
|
||||
height = request_inputs.height // divisor
|
||||
width = request_inputs.width // divisor
|
||||
latents = request_inputs.latents
|
||||
audio_latents = request_inputs.audio_latents
|
||||
audio_latents_normalized = request_inputs.audio_latents_normalized
|
||||
decode_timestep = request_inputs.decode_timestep
|
||||
decode_noise_scale = request_inputs.decode_noise_scale
|
||||
|
||||
if phase.input_transform == "spatial_upsample":
|
||||
if previous_phase is None:
|
||||
raise ValueError(f"LTX phase {phase.name!r} requires a previous phase to upsample.")
|
||||
if previous_phase.video.ndim != 5:
|
||||
raise ValueError(f"LTX spatial upsampling expects a 5D video latent, got {previous_phase.video.shape}.")
|
||||
latents = self._spatial_upsample_phase(previous_phase.video)
|
||||
if previous_phase.audio_for_next_phase is not None:
|
||||
audio_latents = previous_phase.audio_for_next_phase
|
||||
audio_latents_normalized = True
|
||||
else:
|
||||
audio_latents = previous_phase.audio
|
||||
audio_latents_normalized = False
|
||||
decode_timestep = 0.0
|
||||
decode_noise_scale = None
|
||||
|
||||
expected_shape = latent_ops.resolve_video_latent_shape(
|
||||
height,
|
||||
width,
|
||||
request_inputs.num_frames,
|
||||
vae_spatial_compression_ratio=self.vae_spatial_compression_ratio,
|
||||
vae_temporal_compression_ratio=self.vae_temporal_compression_ratio,
|
||||
)
|
||||
if latents.shape[2:] != expected_shape:
|
||||
raise ValueError(
|
||||
f"LTX phase {phase.name!r} upsampler produced {tuple(latents.shape[2:])}, expected "
|
||||
f"{expected_shape} for {width}x{height}."
|
||||
)
|
||||
elif phase.input_transform != "initial":
|
||||
raise ValueError(f"Unsupported LTX phase input transform: {phase.input_transform!r}.")
|
||||
|
||||
guidance = request_inputs.guidance if phase.allow_guidance_override else phase.guidance
|
||||
return replace(
|
||||
request_inputs,
|
||||
height=height,
|
||||
width=width,
|
||||
num_inference_steps=phase.num_inference_steps or request_inputs.num_inference_steps,
|
||||
guidance=guidance,
|
||||
latents=latents,
|
||||
audio_latents=audio_latents,
|
||||
audio_latents_normalized=audio_latents_normalized,
|
||||
decode_timestep=decode_timestep,
|
||||
decode_noise_scale=decode_noise_scale,
|
||||
)
|
||||
|
||||
def _spatial_upsample_phase(self, latents: torch.Tensor) -> torch.Tensor:
|
||||
"""Apply the recipe-managed spatial upsampler to unpacked latents."""
|
||||
latent_upsampler = getattr(self, "latent_upsampler", None)
|
||||
if latent_upsampler is None:
|
||||
raise RuntimeError("This LTX pipeline recipe requires a spatial latent upsampler.")
|
||||
dtype = getattr(latent_upsampler, "dtype", latents.dtype)
|
||||
return latent_upsampler(latents.to(device=self.device, dtype=dtype))
|
||||
|
||||
def decode_phase(self, phase: LTXPhaseResult) -> DiffusionOutput | list[DiffusionOutput]:
|
||||
"""Decode one completed phase and restore per-request outputs."""
|
||||
forward_ctx = phase.forward_context
|
||||
@@ -57,6 +57,9 @@ _RMSNORM_INIT_PARAMS = inspect.signature(RMSNorm.__init__).parameters
|
||||
|
||||
def _make_rms_norm(hidden_size: int, *, eps: float, elementwise_affine: bool) -> nn.Module:
|
||||
"""Bridge diffusers' RMSNorm API onto vLLM's `has_weight` variant."""
|
||||
if not elementwise_affine:
|
||||
return nn.RMSNorm(hidden_size, eps=eps, elementwise_affine=False)
|
||||
|
||||
kwargs: dict[str, Any] = {"eps": eps}
|
||||
if "elementwise_affine" in _RMSNORM_INIT_PARAMS:
|
||||
kwargs["elementwise_affine"] = elementwise_affine
|
||||
@@ -79,10 +82,14 @@ def _make_rms_norm(hidden_size: int, *, eps: float, elementwise_affine: bool) ->
|
||||
|
||||
def apply_interleaved_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
|
||||
cos, sin = freqs
|
||||
if cos.dtype != x.dtype:
|
||||
cos = cos.to(dtype=x.dtype)
|
||||
if sin.dtype != x.dtype:
|
||||
sin = sin.to(dtype=x.dtype)
|
||||
# Concrete pair count instead of -1 keeps SDPA shape static under torch.compile.
|
||||
x_real, x_imag = x.unflatten(2, (x.shape[2] // 2, 2)).unbind(-1) # [B, S, C // 2]
|
||||
x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(2)
|
||||
out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
|
||||
out = x * cos + x_rotated * sin
|
||||
return out
|
||||
|
||||
|
||||
@@ -94,6 +101,10 @@ def apply_split_rotary_emb(
|
||||
) -> torch.Tensor:
|
||||
# `head_dim` is plumbed in (not inferred via `-1`) so SDPA shape stays static under torch.compile.
|
||||
cos, sin = freqs
|
||||
if cos.dtype != x.dtype:
|
||||
cos = cos.to(dtype=x.dtype)
|
||||
if sin.dtype != x.dtype:
|
||||
sin = sin.to(dtype=x.dtype)
|
||||
|
||||
x_dtype = x.dtype
|
||||
needs_reshape = False
|
||||
@@ -112,7 +123,7 @@ def apply_split_rotary_emb(
|
||||
r = last // 2
|
||||
|
||||
# (..., 2, r)
|
||||
split_x = x.reshape(*x.shape[:-1], 2, r).float() # Explicitly upcast to float
|
||||
split_x = x.reshape(*x.shape[:-1], 2, r)
|
||||
first_x = split_x[..., :1, :] # (..., 1, r)
|
||||
second_x = split_x[..., 1:, :] # (..., 1, r)
|
||||
|
||||
@@ -327,6 +338,23 @@ class TensorParallelRMSNorm(nn.Module):
|
||||
return out.to(dtype=x_dtype)
|
||||
|
||||
|
||||
def to_ltx_padding_mask(attention_mask: torch.Tensor) -> torch.Tensor:
|
||||
"""Convert an additive/expanded LTX mask to a 2D padding mask."""
|
||||
if attention_mask.ndim > 2:
|
||||
if attention_mask.is_floating_point():
|
||||
valid = attention_mask >= 0
|
||||
else:
|
||||
valid = attention_mask.to(torch.bool)
|
||||
batch_size = valid.shape[0]
|
||||
key_length = valid.shape[-1]
|
||||
attention_mask = valid.reshape(batch_size, -1, key_length).all(dim=1)
|
||||
if attention_mask.is_floating_point():
|
||||
attention_mask = attention_mask >= 0
|
||||
if attention_mask.dtype != torch.bool:
|
||||
attention_mask = attention_mask.to(torch.bool)
|
||||
return attention_mask
|
||||
|
||||
|
||||
class LTX2AudioVideoAttnProcessor:
|
||||
r"""
|
||||
Processor for implementing attention (SDPA is used by default if you're using PyTorch 2.0) for the LTX-2.0 model.
|
||||
@@ -344,24 +372,6 @@ class LTX2AudioVideoAttnProcessor:
|
||||
"Please upgrade your PyTorch installation."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _to_padding_mask(attention_mask: torch.Tensor) -> torch.Tensor:
|
||||
# Convert additive/expanded masks into a 2D padding mask for flash-attn.
|
||||
if attention_mask.ndim > 2:
|
||||
if attention_mask.is_floating_point():
|
||||
valid = attention_mask >= 0
|
||||
else:
|
||||
valid = attention_mask.to(torch.bool)
|
||||
b = valid.shape[0]
|
||||
key_len = valid.shape[-1]
|
||||
valid = valid.reshape(b, -1, key_len).all(dim=1)
|
||||
attention_mask = valid
|
||||
if attention_mask.is_floating_point():
|
||||
attention_mask = attention_mask >= 0
|
||||
if attention_mask.dtype != torch.bool:
|
||||
attention_mask = attention_mask.to(torch.bool)
|
||||
return attention_mask
|
||||
|
||||
@staticmethod
|
||||
def _is_sp_enabled() -> bool:
|
||||
if not is_forward_context_available():
|
||||
@@ -390,12 +400,12 @@ class LTX2AudioVideoAttnProcessor:
|
||||
# For cross-attention, encoder sequence length != query length, so drop the mask.
|
||||
if encoder_hidden_states is not None and encoder_hidden_states.shape[1] != hidden_states.shape[1]:
|
||||
return None
|
||||
return self._to_padding_mask(attention_mask)
|
||||
return to_ltx_padding_mask(attention_mask)
|
||||
|
||||
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
||||
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
||||
if attn.attn.attn_backend.get_name().upper() == "FLASH_ATTN":
|
||||
attention_mask = self._to_padding_mask(attention_mask)
|
||||
attention_mask = to_ltx_padding_mask(attention_mask)
|
||||
return attention_mask
|
||||
|
||||
@staticmethod
|
||||
@@ -467,6 +477,7 @@ class LTX2AudioVideoAttnProcessor:
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
query_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
key_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
perturbation_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
is_self_attention = encoder_hidden_states is None
|
||||
batch_size, sequence_length, _ = hidden_states.shape if is_self_attention else encoder_hidden_states.shape
|
||||
@@ -509,17 +520,21 @@ class LTX2AudioVideoAttnProcessor:
|
||||
elif attn.rope_type == "split":
|
||||
query = apply_split_rotary_emb(query, query_rotary_emb, head_dim=attn.head_dim)
|
||||
key = apply_split_rotary_emb(
|
||||
key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb, head_dim=attn.head_dim
|
||||
key,
|
||||
key_rotary_emb if key_rotary_emb is not None else query_rotary_emb,
|
||||
head_dim=attn.head_dim,
|
||||
)
|
||||
|
||||
query = query.unflatten(2, (attn.heads, attn.head_dim))
|
||||
key = key.unflatten(2, (attn.heads, attn.head_dim))
|
||||
value = value.unflatten(2, (attn.heads, attn.head_dim))
|
||||
value_heads = value.unflatten(2, (attn.heads, attn.head_dim))
|
||||
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
|
||||
hidden_states = attn.attn(query, key, value, attn_metadata)
|
||||
hidden_states = attn.attn(query, key, value_heads, attn_metadata)
|
||||
hidden_states = hidden_states.flatten(2, 3)
|
||||
hidden_states = hidden_states.to(query.dtype)
|
||||
if perturbation_mask is not None:
|
||||
hidden_states = hidden_states * perturbation_mask + value * (1 - perturbation_mask)
|
||||
|
||||
# LTX-2.3: per-head gated attention
|
||||
if attn.to_gate_logits is not None:
|
||||
@@ -560,6 +575,7 @@ class LTX2Attention(torch.nn.Module):
|
||||
norm_elementwise_affine: bool = True,
|
||||
rope_type: str = "interleaved",
|
||||
apply_gated_attention: bool = False,
|
||||
pack_qkv: bool = True,
|
||||
processor=None,
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
prefix: str = "",
|
||||
@@ -591,7 +607,7 @@ class LTX2Attention(torch.nn.Module):
|
||||
self.to_q = None
|
||||
self.to_k = None
|
||||
self.to_v = None
|
||||
if cross_attention_dim is None:
|
||||
if cross_attention_dim is None and pack_qkv:
|
||||
self.to_qkv = QKVParallelLinear(
|
||||
hidden_size=query_dim,
|
||||
head_size=self.head_dim,
|
||||
@@ -847,6 +863,9 @@ class LTX2VideoTransformerBlock(nn.Module):
|
||||
qk_norm=qk_norm,
|
||||
rope_type=rope_type,
|
||||
apply_gated_attention=audio_gated_attn,
|
||||
# The official checkpoint evaluates audio Q/K/V separately. Fusing
|
||||
# the bf16 GEMMs changes denoise numerics enough to accumulate.
|
||||
pack_qkv=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.audio_attn1" if prefix else "audio_attn1",
|
||||
)
|
||||
@@ -992,8 +1011,10 @@ class LTX2VideoTransformerBlock(nn.Module):
|
||||
v2a_cross_attention_mask: torch.Tensor | None = None,
|
||||
use_a2v_cross_attention: bool = True,
|
||||
use_v2a_cross_attention: bool = True,
|
||||
perturbation_mask: torch.Tensor | None = None,
|
||||
all_perturbed: bool | None = None,
|
||||
video_self_attention_perturbation_mask: torch.Tensor | None = None,
|
||||
audio_self_attention_perturbation_mask: torch.Tensor | None = None,
|
||||
a2v_cross_attention_perturbation_mask: torch.Tensor | None = None,
|
||||
v2a_cross_attention_perturbation_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
batch_size = hidden_states.size(0)
|
||||
|
||||
@@ -1012,6 +1033,7 @@ class LTX2VideoTransformerBlock(nn.Module):
|
||||
encoder_hidden_states=None,
|
||||
query_rotary_emb=video_rotary_emb,
|
||||
attention_mask=self_attention_mask,
|
||||
perturbation_mask=video_self_attention_perturbation_mask,
|
||||
)
|
||||
hidden_states = hidden_states + attn_hidden_states * gate_msa
|
||||
|
||||
@@ -1031,6 +1053,7 @@ class LTX2VideoTransformerBlock(nn.Module):
|
||||
encoder_hidden_states=None,
|
||||
query_rotary_emb=audio_rotary_emb,
|
||||
attention_mask=audio_self_attention_mask,
|
||||
perturbation_mask=audio_self_attention_perturbation_mask,
|
||||
)
|
||||
audio_hidden_states = audio_hidden_states + attn_audio_hidden_states * audio_gate_msa
|
||||
|
||||
@@ -1123,6 +1146,8 @@ class LTX2VideoTransformerBlock(nn.Module):
|
||||
key_rotary_emb=ca_audio_rotary_emb,
|
||||
attention_mask=a2v_cross_attention_mask,
|
||||
)
|
||||
if a2v_cross_attention_perturbation_mask is not None:
|
||||
a2v_attn_hidden_states = a2v_attn_hidden_states * a2v_cross_attention_perturbation_mask
|
||||
hidden_states = hidden_states + a2v_gate * a2v_attn_hidden_states
|
||||
|
||||
# 3.3. Video-to-Audio Cross Attention: Q: Audio; K,V: Video
|
||||
@@ -1141,6 +1166,8 @@ class LTX2VideoTransformerBlock(nn.Module):
|
||||
key_rotary_emb=ca_video_rotary_emb,
|
||||
attention_mask=v2a_cross_attention_mask,
|
||||
)
|
||||
if v2a_cross_attention_perturbation_mask is not None:
|
||||
v2a_attn_hidden_states = v2a_attn_hidden_states * v2a_cross_attention_perturbation_mask
|
||||
audio_hidden_states = audio_hidden_states + v2a_gate * v2a_attn_hidden_states
|
||||
|
||||
# 4. Feedforward
|
||||
@@ -1345,7 +1372,10 @@ class LTX2AudioVideoRotaryPosEmbed(nn.Module):
|
||||
return self.prepare_audio_coords(*args, **kwargs)
|
||||
|
||||
def forward(
|
||||
self, coords: torch.Tensor, device: str | torch.device | None = None
|
||||
self,
|
||||
coords: torch.Tensor,
|
||||
device: str | torch.device | None = None,
|
||||
out_dtype: torch.dtype | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
device = device or coords.device
|
||||
|
||||
@@ -1421,6 +1451,9 @@ class LTX2AudioVideoRotaryPosEmbed(nn.Module):
|
||||
cos_freqs = torch.swapaxes(cos_freq, 1, 2) # (B,H,T,D//2)
|
||||
sin_freqs = torch.swapaxes(sin_freq, 1, 2) # (B,H,T,D//2)
|
||||
|
||||
if out_dtype is not None:
|
||||
cos_freqs = cos_freqs.to(out_dtype)
|
||||
sin_freqs = sin_freqs.to(out_dtype)
|
||||
return cos_freqs, sin_freqs
|
||||
|
||||
|
||||
@@ -1488,8 +1521,11 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
# Shard prompt embeds across sequence
|
||||
"encoder_hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
||||
"audio_encoder_hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
||||
# Shard video timestep when provided as (B, seq_len)
|
||||
# Keep per-token video/audio timestep embeddings aligned with
|
||||
# their corresponding latent sequence shards. Official LTX
|
||||
# multi-guidance supplies both tensors as (B, seq_len).
|
||||
"timestep": SequenceParallelInput(split_dim=1, expected_dims=2, split_output=False),
|
||||
"audio_timestep": SequenceParallelInput(split_dim=1, expected_dims=2, split_output=False),
|
||||
},
|
||||
"rope": {
|
||||
0: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True),
|
||||
@@ -1856,6 +1892,12 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
# Determine timestep for audio.
|
||||
audio_timestep = audio_timestep if audio_timestep is not None else timestep
|
||||
|
||||
def batch_step(step: torch.Tensor) -> torch.Tensor:
|
||||
return step[:, 0] if step.ndim > 1 else step
|
||||
|
||||
sigma = sigma if sigma is not None else batch_step(timestep)
|
||||
audio_sigma = audio_sigma if audio_sigma is not None else batch_step(audio_timestep)
|
||||
|
||||
# convert encoder_attention_mask to a bias the same way we do for attention_mask
|
||||
if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
|
||||
encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
|
||||
@@ -1877,12 +1919,22 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
batch_size, audio_num_frames, audio_hidden_states.device
|
||||
)
|
||||
|
||||
video_rotary_emb = self.rope(video_coords, device=hidden_states.device)
|
||||
audio_rotary_emb = self.audio_rope(audio_coords, device=audio_hidden_states.device)
|
||||
video_rotary_emb = self.rope(video_coords, device=hidden_states.device, out_dtype=hidden_states.dtype)
|
||||
audio_rotary_emb = self.audio_rope(
|
||||
audio_coords,
|
||||
device=audio_hidden_states.device,
|
||||
out_dtype=audio_hidden_states.dtype,
|
||||
)
|
||||
|
||||
video_cross_attn_rotary_emb = self.cross_attn_rope(video_coords[:, 0:1, :], device=hidden_states.device)
|
||||
video_cross_attn_rotary_emb = self.cross_attn_rope(
|
||||
video_coords[:, 0:1, :],
|
||||
device=hidden_states.device,
|
||||
out_dtype=hidden_states.dtype,
|
||||
)
|
||||
audio_cross_attn_rotary_emb = self.cross_attn_audio_rope(
|
||||
audio_coords[:, 0:1, :], device=audio_hidden_states.device
|
||||
audio_coords[:, 0:1, :],
|
||||
device=audio_hidden_states.device,
|
||||
out_dtype=audio_hidden_states.dtype,
|
||||
)
|
||||
|
||||
# 2. Patchify input projections
|
||||
@@ -1920,7 +1972,7 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
hidden_dtype=hidden_states.dtype,
|
||||
)
|
||||
video_cross_attn_a2v_gate, _ = self.av_cross_attn_video_a2v_gate(
|
||||
timestep.flatten() * timestep_cross_attn_gate_scale_factor,
|
||||
audio_sigma.flatten() * timestep_cross_attn_gate_scale_factor,
|
||||
batch_size=batch_size,
|
||||
hidden_dtype=hidden_states.dtype,
|
||||
)
|
||||
@@ -1935,7 +1987,7 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
hidden_dtype=audio_hidden_states.dtype,
|
||||
)
|
||||
audio_cross_attn_v2a_gate, _ = self.av_cross_attn_audio_v2a_gate(
|
||||
audio_timestep.flatten() * timestep_cross_attn_gate_scale_factor,
|
||||
sigma.flatten() * timestep_cross_attn_gate_scale_factor,
|
||||
batch_size=batch_size,
|
||||
hidden_dtype=audio_hidden_states.dtype,
|
||||
)
|
||||
@@ -1945,7 +1997,6 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
audio_cross_attn_v2a_gate = audio_cross_attn_v2a_gate.view(batch_size, -1, audio_cross_attn_v2a_gate.shape[-1])
|
||||
|
||||
# 3.3. LTX-2.3: Compute prompt modulation from sigma
|
||||
audio_sigma = audio_sigma if audio_sigma is not None else sigma
|
||||
if self.prompt_modulation and sigma is not None:
|
||||
temb_prompt, _ = self.prompt_adaln(sigma.flatten(), batch_size=batch_size, hidden_dtype=hidden_states.dtype)
|
||||
temb_prompt_audio, _ = self.audio_prompt_adaln(
|
||||
@@ -1967,8 +2018,17 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
audio_encoder_hidden_states = self.audio_caption_projection(audio_encoder_hidden_states)
|
||||
audio_encoder_hidden_states = audio_encoder_hidden_states.view(batch_size, -1, audio_hidden_states.size(-1))
|
||||
|
||||
perturbation_kwargs = (attention_kwargs or {}).get("ltx_perturbation_kwargs", {})
|
||||
|
||||
def perturbation_mask_for(name: str, block_idx: int) -> torch.Tensor | None:
|
||||
mask = perturbation_kwargs.get(f"{name}_mask")
|
||||
blocks = perturbation_kwargs.get(f"{name}_blocks")
|
||||
if mask is None or (blocks is not None and block_idx not in blocks):
|
||||
return None
|
||||
return mask
|
||||
|
||||
# 5. Run transformer blocks
|
||||
for block in self.transformer_blocks:
|
||||
for block_idx, block in enumerate(self.transformer_blocks):
|
||||
block_kwargs = {
|
||||
"temb": temb,
|
||||
"temb_audio": temb_audio,
|
||||
@@ -1984,6 +2044,10 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
"ca_audio_rotary_emb": audio_cross_attn_rotary_emb,
|
||||
"encoder_attention_mask": encoder_attention_mask,
|
||||
"audio_encoder_attention_mask": audio_encoder_attention_mask,
|
||||
"video_self_attention_perturbation_mask": perturbation_mask_for("video_self_attention", block_idx),
|
||||
"audio_self_attention_perturbation_mask": perturbation_mask_for("audio_self_attention", block_idx),
|
||||
"a2v_cross_attention_perturbation_mask": perturbation_mask_for("a2v_cross_attention", block_idx),
|
||||
"v2a_cross_attention_perturbation_mask": perturbation_mask_for("v2a_cross_attention", block_idx),
|
||||
}
|
||||
# NOTE: We intentionally pass the first 4 args here positionally,
|
||||
# because CacheDiT expects the first 2 args to be hidden_states
|
||||
@@ -2066,7 +2130,10 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
for param_name, weight_name, shard_id in stacked_params_mapping:
|
||||
if weight_name not in name:
|
||||
continue
|
||||
name = name.replace(weight_name, param_name)
|
||||
packed_name = name.replace(weight_name, param_name)
|
||||
if packed_name not in params_dict:
|
||||
continue
|
||||
name = packed_name
|
||||
param = params_dict[name]
|
||||
weight_loader = param.weight_loader
|
||||
weight_loader(param, loaded_weight, shard_id)
|
||||
|
||||
@@ -5,250 +5,56 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, ClassVar
|
||||
from typing import ClassVar
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
|
||||
from .ltx2_components import (
|
||||
LTX2_COMPONENT_PROFILE,
|
||||
LTX23_COMPONENT_PROFILE,
|
||||
LTXComponentProfile,
|
||||
)
|
||||
from .ltx2_components import LTX2_COMPONENT_PROFILE
|
||||
from .ltx2_components import (
|
||||
get_ltx2_post_process_func as get_ltx2_post_process_func, # noqa: F401
|
||||
)
|
||||
from .ltx2_conditioning import LTXI2VConditioningMixin
|
||||
from .ltx2_guidance import (
|
||||
LTX_LEGACY_VELOCITY_GUIDANCE,
|
||||
LTX_OFFICIAL_X0_GUIDANCE,
|
||||
from .ltx2_recipes import (
|
||||
LTX2_ONE_STAGE_RECIPE,
|
||||
LTX_POSITIVE_ONLY_RECIPE,
|
||||
)
|
||||
from .ltx2_pipeline_runtime import LTXPipelineRuntime
|
||||
from .ltx2_recipes import LTX2_ONE_STAGE_RECIPE, LTX23_ONE_STAGE_RECIPE, LTXOneStageRecipe
|
||||
from .ltx2_request import LTXRequestInputs
|
||||
from .ltx2_runtime import LTXRuntime
|
||||
|
||||
|
||||
class LTXOneStagePipeline(LTXPipelineRuntime):
|
||||
"""Single execution path configured by model-version and task entries."""
|
||||
class LTX2Pipeline(LTXI2VConditioningMixin, LTXRuntime):
|
||||
"""LTX-2 family one-stage entry, configured from checkpoint metadata."""
|
||||
|
||||
component_profile: ClassVar[LTXComponentProfile]
|
||||
one_stage_recipe: ClassVar[LTXOneStageRecipe]
|
||||
|
||||
supports_request_batch = True
|
||||
supports_guidance_rescale = False
|
||||
|
||||
def _forward_impl(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
request_inputs: LTXRequestInputs,
|
||||
*,
|
||||
noise_scale: float,
|
||||
sigmas: list[float] | None,
|
||||
timesteps: list[int] | None,
|
||||
attention_kwargs: dict[str, Any] | None,
|
||||
image: Any | None = None,
|
||||
) -> DiffusionOutput | list[DiffusionOutput]:
|
||||
phase = self.run_phase(
|
||||
req,
|
||||
request_inputs,
|
||||
noise_scale=noise_scale,
|
||||
sigmas=sigmas,
|
||||
timesteps=timesteps,
|
||||
attention_kwargs=attention_kwargs,
|
||||
image=image,
|
||||
)
|
||||
return self.decode_phase(phase)
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
prompt: str | list[str] | None = None,
|
||||
negative_prompt: str | list[str] | None = None,
|
||||
height: int | None = None,
|
||||
width: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
frame_rate: float | None = None,
|
||||
num_inference_steps: int | None = None,
|
||||
sigmas: list[float] | None = None,
|
||||
timesteps: list[int] | None = None,
|
||||
guidance_scale: float = 4.0,
|
||||
guidance_rescale: float = 0.0,
|
||||
noise_scale: float = 0.0,
|
||||
num_videos_per_prompt: int | None = 1,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
audio_latents: torch.Tensor | None = None,
|
||||
prompt_embeds: torch.Tensor | None = None,
|
||||
negative_prompt_embeds: torch.Tensor | None = None,
|
||||
prompt_attention_mask: torch.Tensor | None = None,
|
||||
negative_prompt_attention_mask: torch.Tensor | None = None,
|
||||
decode_timestep: float | list[float] = 0.0,
|
||||
decode_noise_scale: float | list[float] | None = None,
|
||||
output_type: str = "np",
|
||||
return_dict: bool = True,
|
||||
attention_kwargs: dict[str, Any] | None = None,
|
||||
max_sequence_length: int | None = None,
|
||||
*,
|
||||
image: Any | None = None,
|
||||
) -> DiffusionOutput | list[DiffusionOutput]:
|
||||
del return_dict
|
||||
sigmas = self._resolve_request_sigmas(req, sigmas)
|
||||
request_inputs = self._resolve_request_inputs(
|
||||
req,
|
||||
prompt=prompt,
|
||||
negative_prompt=negative_prompt,
|
||||
height=height,
|
||||
width=width,
|
||||
num_frames=num_frames,
|
||||
frame_rate=frame_rate,
|
||||
num_inference_steps=num_inference_steps,
|
||||
timesteps=timesteps,
|
||||
guidance_scale=self.one_stage_recipe.guidance_scale if guidance_scale is None else guidance_scale,
|
||||
guidance_rescale=guidance_rescale,
|
||||
num_videos_per_prompt=num_videos_per_prompt,
|
||||
generator=generator,
|
||||
latents=latents,
|
||||
audio_latents=audio_latents,
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
prompt_attention_mask=prompt_attention_mask,
|
||||
negative_prompt_attention_mask=negative_prompt_attention_mask,
|
||||
decode_timestep=decode_timestep,
|
||||
decode_noise_scale=decode_noise_scale,
|
||||
output_type=output_type,
|
||||
max_sequence_length=max_sequence_length,
|
||||
)
|
||||
image = self._resolve_request_image(req, image, request_inputs)
|
||||
forward_kwargs = {
|
||||
"noise_scale": noise_scale,
|
||||
"sigmas": sigmas,
|
||||
"timesteps": timesteps,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
}
|
||||
if self.support_image_input:
|
||||
forward_kwargs["image"] = image
|
||||
return self._forward_impl(
|
||||
req,
|
||||
request_inputs,
|
||||
**forward_kwargs,
|
||||
)
|
||||
|
||||
|
||||
class LTX2Pipeline(LTXOneStagePipeline):
|
||||
"""LTX2 one-stage text-to-video entry."""
|
||||
|
||||
supports_guidance_rescale = True
|
||||
pipeline_kind = "one_stage"
|
||||
unified_text_image_entry = True
|
||||
component_profile = LTX2_COMPONENT_PROFILE
|
||||
guidance_strategy = LTX_LEGACY_VELOCITY_GUIDANCE
|
||||
one_stage_recipe = LTX2_ONE_STAGE_RECIPE
|
||||
pipeline_recipe = LTX2_ONE_STAGE_RECIPE
|
||||
_dit_modules: ClassVar[list[str]] = list(component_profile.dit_modules)
|
||||
_encoder_modules: ClassVar[list[str]] = list(component_profile.encoder_modules)
|
||||
_vae_modules: ClassVar[list[str]] = list(component_profile.vae_modules)
|
||||
_resident_modules: ClassVar[list[str]] = list(component_profile.resident_modules)
|
||||
|
||||
|
||||
class LTX23Pipeline(LTXOneStagePipeline):
|
||||
"""LTX2.3 one-stage text-to-video entry."""
|
||||
|
||||
connector_batches_cfg = True
|
||||
preserve_sp_padded_audio_duration = True
|
||||
reports_stage_durations = True
|
||||
component_profile = LTX23_COMPONENT_PROFILE
|
||||
guidance_strategy = LTX_OFFICIAL_X0_GUIDANCE
|
||||
one_stage_recipe = LTX23_ONE_STAGE_RECIPE
|
||||
_dit_modules: ClassVar[list[str]] = list(component_profile.dit_modules)
|
||||
_encoder_modules: ClassVar[list[str]] = list(component_profile.encoder_modules)
|
||||
_vae_modules: ClassVar[list[str]] = list(component_profile.vae_modules)
|
||||
_resident_modules: ClassVar[list[str]] = list(component_profile.resident_modules)
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
prompt: str | list[str] | None = None,
|
||||
negative_prompt: str | list[str] | None = None,
|
||||
height: int | None = None,
|
||||
width: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
frame_rate: float | None = None,
|
||||
num_inference_steps: int | None = None,
|
||||
sigmas: list[float] | None = None,
|
||||
timesteps: list[int] | None = None,
|
||||
guidance_scale: float = 4.0,
|
||||
noise_scale: float = 0.0,
|
||||
num_videos_per_prompt: int | None = 1,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
audio_latents: torch.Tensor | None = None,
|
||||
prompt_embeds: torch.Tensor | None = None,
|
||||
negative_prompt_embeds: torch.Tensor | None = None,
|
||||
prompt_attention_mask: torch.Tensor | None = None,
|
||||
negative_prompt_attention_mask: torch.Tensor | None = None,
|
||||
decode_timestep: float | list[float] = 0.0,
|
||||
decode_noise_scale: float | list[float] | None = None,
|
||||
output_type: str = "np",
|
||||
return_dict: bool = True,
|
||||
attention_kwargs: dict[str, Any] | None = None,
|
||||
max_sequence_length: int | None = None,
|
||||
*,
|
||||
image: Any | None = None,
|
||||
) -> DiffusionOutput | list[DiffusionOutput]:
|
||||
"""Preserve the pre-refactor LTX2.3 positional argument order."""
|
||||
return super().forward(
|
||||
req,
|
||||
prompt=prompt,
|
||||
negative_prompt=negative_prompt,
|
||||
height=height,
|
||||
width=width,
|
||||
num_frames=num_frames,
|
||||
frame_rate=frame_rate,
|
||||
num_inference_steps=num_inference_steps,
|
||||
sigmas=sigmas,
|
||||
timesteps=timesteps,
|
||||
guidance_scale=guidance_scale,
|
||||
guidance_rescale=0.0,
|
||||
noise_scale=noise_scale,
|
||||
num_videos_per_prompt=num_videos_per_prompt,
|
||||
generator=generator,
|
||||
latents=latents,
|
||||
audio_latents=audio_latents,
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
prompt_attention_mask=prompt_attention_mask,
|
||||
negative_prompt_attention_mask=negative_prompt_attention_mask,
|
||||
decode_timestep=decode_timestep,
|
||||
decode_noise_scale=decode_noise_scale,
|
||||
output_type=output_type,
|
||||
return_dict=return_dict,
|
||||
attention_kwargs=attention_kwargs,
|
||||
max_sequence_length=max_sequence_length,
|
||||
image=image,
|
||||
)
|
||||
|
||||
|
||||
class LTX2ImageToVideoPipeline(LTXI2VConditioningMixin, LTX2Pipeline):
|
||||
"""LTX2 one-stage image-to-video entry."""
|
||||
|
||||
|
||||
class LTX23ImageToVideoPipeline(LTXI2VConditioningMixin, LTX23Pipeline):
|
||||
"""LTX2.3 one-stage image-to-video entry."""
|
||||
supports_request_batch = True
|
||||
|
||||
|
||||
class LTX2T2VDMD2Pipeline(DMD2PipelineMixin, LTX2Pipeline):
|
||||
"""LTX2 T2V entry for FastGen DMD2-distilled models."""
|
||||
|
||||
pipeline_kind = "dmd2"
|
||||
support_image_input = False
|
||||
pipeline_recipe = LTX_POSITIVE_ONLY_RECIPE
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
|
||||
super().__init__(od_config=od_config, prefix=prefix)
|
||||
self.__init_dmd2__()
|
||||
|
||||
|
||||
class LTX2I2VDMD2Pipeline(DMD2PipelineMixin, LTX2ImageToVideoPipeline):
|
||||
class LTX2I2VDMD2Pipeline(DMD2PipelineMixin, LTX2Pipeline):
|
||||
"""LTX2 I2V entry for FastGen DMD2-distilled models."""
|
||||
|
||||
pipeline_kind = "dmd2"
|
||||
unified_text_image_entry = False
|
||||
pipeline_recipe = LTX_POSITIVE_ONLY_RECIPE
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
|
||||
super().__init__(od_config=od_config, prefix=prefix)
|
||||
self.__init_dmd2__()
|
||||
@@ -1,262 +0,0 @@
|
||||
import os
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from diffusers import AutoencoderKLLTX2Video
|
||||
from diffusers.image_processor import PipelineImageInput
|
||||
from diffusers.pipelines.ltx2.latent_upsampler import LTX2LatentUpsamplerModel
|
||||
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img import retrieve_latents
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class LTX2LatentUpsamplePipeline(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
od_config: OmniDiffusionConfig,
|
||||
vae: AutoencoderKLLTX2Video,
|
||||
latent_upsampler: LTX2LatentUpsamplerModel = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
|
||||
if vae is None:
|
||||
raise ValueError("vae must be provided")
|
||||
self.vae = vae
|
||||
|
||||
self.device = get_local_device()
|
||||
model = od_config.model
|
||||
local_files_only = os.path.exists(model)
|
||||
|
||||
if latent_upsampler is None:
|
||||
# Use cpu context to create latent upsampler. The code k[:, None] @ k[None, :] in
|
||||
# diffuser's BlurDownsample is not supported on GPU as k is type of torch.Int64
|
||||
with torch.device("cpu"):
|
||||
latent_upsampler = LTX2LatentUpsamplerModel.from_pretrained(
|
||||
model,
|
||||
subfolder="latent_upsampler",
|
||||
torch_dtype=torch.bfloat16,
|
||||
local_files_only=local_files_only,
|
||||
).to(self.device)
|
||||
self.latent_upsampler = latent_upsampler
|
||||
|
||||
self.vae_spatial_compression_ratio = (
|
||||
self.vae.spatial_compression_ratio if getattr(self, "vae", None) is not None else 32
|
||||
)
|
||||
self.vae_temporal_compression_ratio = (
|
||||
self.vae.temporal_compression_ratio if getattr(self, "vae", None) is not None else 8
|
||||
)
|
||||
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_spatial_compression_ratio)
|
||||
|
||||
def prepare_latents(
|
||||
self,
|
||||
video: torch.Tensor | None = None,
|
||||
batch_size: int = 1,
|
||||
num_frames: int = 121,
|
||||
height: int = 512,
|
||||
width: int = 768,
|
||||
spatial_patch_size: int = 1,
|
||||
temporal_patch_size: int = 1,
|
||||
dtype: torch.dtype | None = None,
|
||||
device: torch.device | None = None,
|
||||
generator: torch.Generator | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
if latents is not None:
|
||||
if latents.ndim == 3:
|
||||
# Convert token seq [B, S, D] to latent video [B, C, F, H, W]
|
||||
latent_num_frames = (num_frames - 1) // self.vae_temporal_compression_ratio + 1
|
||||
latent_height = height // self.vae_spatial_compression_ratio
|
||||
latent_width = width // self.vae_spatial_compression_ratio
|
||||
latents = self._unpack_latents(
|
||||
latents, latent_num_frames, latent_height, latent_width, spatial_patch_size, temporal_patch_size
|
||||
)
|
||||
return latents.to(device=device, dtype=dtype)
|
||||
|
||||
video = video.to(device=device, dtype=self.vae.dtype)
|
||||
if isinstance(generator, list):
|
||||
if 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."
|
||||
)
|
||||
|
||||
init_latents = [
|
||||
retrieve_latents(self.vae.encode(video[i].unsqueeze(0)), generator[i]) for i in range(batch_size)
|
||||
]
|
||||
else:
|
||||
init_latents = [retrieve_latents(self.vae.encode(vid.unsqueeze(0)), generator) for vid in video]
|
||||
|
||||
init_latents = torch.cat(init_latents, dim=0).to(dtype)
|
||||
# NOTE: latent upsampler operates on the unnormalized latents, so don't normalize here
|
||||
# init_latents = self._normalize_latents(init_latents, self.vae.latents_mean, self.vae.latents_std)
|
||||
return init_latents
|
||||
|
||||
def adain_filter_latent(self, latents: torch.Tensor, reference_latents: torch.Tensor, factor: float = 1.0):
|
||||
result = latents.clone()
|
||||
|
||||
for i in range(latents.size(0)):
|
||||
for c in range(latents.size(1)):
|
||||
r_sd, r_mean = torch.std_mean(reference_latents[i, c], dim=None) # index by original dim order
|
||||
i_sd, i_mean = torch.std_mean(result[i, c], dim=None)
|
||||
|
||||
result[i, c] = ((result[i, c] - i_mean) / i_sd) * r_sd + r_mean
|
||||
|
||||
result = torch.lerp(latents, result, factor)
|
||||
return result
|
||||
|
||||
def tone_map_latents(self, latents: torch.Tensor, compression: float) -> torch.Tensor:
|
||||
# Remap [0-1] to [0-0.75] and apply sigmoid compression in one shot
|
||||
scale_factor = compression * 0.75
|
||||
abs_latents = torch.abs(latents)
|
||||
|
||||
# Sigmoid compression: sigmoid shifts large values toward 0.2, small values stay ~1.0
|
||||
# When scale_factor=0, sigmoid term vanishes, when scale_factor=0.75, full effect
|
||||
sigmoid_term = torch.sigmoid(4.0 * scale_factor * (abs_latents - 1.0))
|
||||
scales = 1.0 - 0.8 * scale_factor * sigmoid_term
|
||||
|
||||
filtered = latents * scales
|
||||
return filtered
|
||||
|
||||
@staticmethod
|
||||
# Copied from diffusers.pipelines.ltx2.pipeline_ltx2.LTX2Pipeline._denormalize_latents
|
||||
def _denormalize_latents(
|
||||
latents: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor, scaling_factor: float = 1.0
|
||||
) -> torch.Tensor:
|
||||
# Denormalize latents across the channel dimension [B, C, F, H, W]
|
||||
latents_mean = latents_mean.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
|
||||
latents_std = latents_std.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
|
||||
latents = latents * latents_std / scaling_factor + latents_mean
|
||||
return latents
|
||||
|
||||
@staticmethod
|
||||
# Copied from diffusers.pipelines.ltx2.pipeline_ltx2.LTX2Pipeline._unpack_latents
|
||||
def _unpack_latents(
|
||||
latents: torch.Tensor, num_frames: int, height: int, width: int, patch_size: int = 1, patch_size_t: int = 1
|
||||
) -> torch.Tensor:
|
||||
# Packed latents of shape [B, S, D] (S is the effective video sequence length, D is the effective feature dimensions) # noqa
|
||||
# are unpacked and reshaped into a video tensor of shape [B, C, F, H, W]. This is the inverse operation of
|
||||
# what happens in the `_pack_latents` method.
|
||||
batch_size = latents.size(0)
|
||||
latents = latents.reshape(batch_size, num_frames, height, width, -1, patch_size_t, patch_size, patch_size)
|
||||
latents = latents.permute(0, 4, 1, 5, 2, 6, 3, 7).flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
||||
return latents
|
||||
|
||||
def check_inputs(self, video, height, width, latents, tone_map_compression_ratio):
|
||||
if height % self.vae_spatial_compression_ratio != 0 or width % self.vae_spatial_compression_ratio != 0:
|
||||
raise ValueError(f"`height` and `width` have to be divisible by 32 but are {height} and {width}.")
|
||||
|
||||
if video is not None and latents is not None:
|
||||
raise ValueError("Only one of `video` or `latents` can be provided.")
|
||||
if video is None and latents is None:
|
||||
raise ValueError("One of `video` or `latents` has to be provided.")
|
||||
|
||||
if not (0 <= tone_map_compression_ratio <= 1):
|
||||
raise ValueError("`tone_map_compression_ratio` must be in the range [0, 1]")
|
||||
|
||||
def forward(
|
||||
self,
|
||||
video: list[PipelineImageInput] | None = None,
|
||||
height: int = 512,
|
||||
width: int = 768,
|
||||
num_frames: int = 121,
|
||||
spatial_patch_size: int = 1,
|
||||
temporal_patch_size: int = 1,
|
||||
latents: torch.Tensor | None = None,
|
||||
latents_normalized: bool = False,
|
||||
decode_timestep: float | list[float] = 0.0,
|
||||
decode_noise_scale: float | list[float] | None = None,
|
||||
adain_factor: float = 0.0,
|
||||
tone_map_compression_ratio: float = 0.0,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
output_type: str | None = "pil",
|
||||
return_dict: bool = True,
|
||||
):
|
||||
self.check_inputs(
|
||||
video=video,
|
||||
height=height,
|
||||
width=width,
|
||||
latents=latents,
|
||||
tone_map_compression_ratio=tone_map_compression_ratio,
|
||||
)
|
||||
|
||||
if video is not None:
|
||||
# Batched video input is not yet tested/supported. TODO: take a look later
|
||||
batch_size = 1
|
||||
else:
|
||||
batch_size = latents.shape[0]
|
||||
device = self.device
|
||||
|
||||
if video is not None:
|
||||
num_frames = len(video)
|
||||
if num_frames % self.vae_temporal_compression_ratio != 1:
|
||||
num_frames = num_frames // self.vae_temporal_compression_ratio * self.vae_temporal_compression_ratio + 1
|
||||
video = video[:num_frames]
|
||||
logger.warning(
|
||||
f"Video length expected to be of the form `k * {self.vae_temporal_compression_ratio} + 1` but is {len(video)}. Truncating to {num_frames} frames." # noqa
|
||||
)
|
||||
video = self.video_processor.preprocess_video(video, height=height, width=width)
|
||||
video = video.to(device=device, dtype=torch.float32)
|
||||
|
||||
latents_supplied = latents is not None
|
||||
latents = self.prepare_latents(
|
||||
video=video,
|
||||
batch_size=batch_size,
|
||||
num_frames=num_frames,
|
||||
height=height,
|
||||
width=width,
|
||||
spatial_patch_size=spatial_patch_size,
|
||||
temporal_patch_size=temporal_patch_size,
|
||||
dtype=torch.float32,
|
||||
device=device,
|
||||
generator=generator,
|
||||
latents=latents,
|
||||
)
|
||||
|
||||
if latents_supplied and latents_normalized:
|
||||
latents = self._denormalize_latents(
|
||||
latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor
|
||||
)
|
||||
latents = latents.to(self.latent_upsampler.dtype)
|
||||
latents_upsampled = self.latent_upsampler(latents)
|
||||
|
||||
if adain_factor > 0.0:
|
||||
latents = self.adain_filter_latent(latents_upsampled, latents, adain_factor)
|
||||
else:
|
||||
latents = latents_upsampled
|
||||
|
||||
if tone_map_compression_ratio > 0.0:
|
||||
latents = self.tone_map_latents(latents, tone_map_compression_ratio)
|
||||
|
||||
if output_type == "latent":
|
||||
video = latents
|
||||
else:
|
||||
if not self.vae.config.timestep_conditioning:
|
||||
timestep = None
|
||||
else:
|
||||
noise = randn_tensor(latents.shape, generator=generator, device=device, dtype=latents.dtype)
|
||||
if not isinstance(decode_timestep, list):
|
||||
decode_timestep = [decode_timestep] * batch_size
|
||||
if decode_noise_scale is None:
|
||||
decode_noise_scale = decode_timestep
|
||||
elif not isinstance(decode_noise_scale, list):
|
||||
decode_noise_scale = [decode_noise_scale] * batch_size
|
||||
|
||||
timestep = torch.tensor(decode_timestep, device=device, dtype=latents.dtype)
|
||||
decode_noise_scale = torch.tensor(decode_noise_scale, device=device, dtype=latents.dtype)[
|
||||
:, None, None, None, None
|
||||
]
|
||||
latents = (1 - decode_noise_scale) * latents + decode_noise_scale * noise
|
||||
|
||||
video = self.vae.decode(latents, timestep, return_dict=False)[0]
|
||||
video = self.video_processor.postprocess_video(video, output_type=output_type)
|
||||
|
||||
if not return_dict:
|
||||
return (video,)
|
||||
|
||||
return DiffusionOutput(output=(video,))
|
||||
@@ -1,207 +1,27 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Two-stage entry points for the LTX model family."""
|
||||
"""Distilled two-stage entry points for the LTX model family."""
|
||||
|
||||
from __future__ import annotations
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import torch
|
||||
from diffusers.pipelines.ltx2.utils import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
|
||||
from .ltx2_components import (
|
||||
LTX2_COMPONENT_PROFILE,
|
||||
)
|
||||
from .ltx2_components import LTX2_DISTILLED_COMPONENT_PROFILE
|
||||
from .ltx2_components import (
|
||||
get_ltx2_post_process_func as get_ltx2_post_process_func, # noqa: F401
|
||||
)
|
||||
from .ltx2_conditioning import LTXI2VConditioningMixin
|
||||
from .ltx2_guidance import LTX_LEGACY_VELOCITY_GUIDANCE
|
||||
from .ltx2_pipeline_runtime import LTXPipelineRuntime
|
||||
from .ltx2_recipes import LTX2_ONE_STAGE_RECIPE
|
||||
from .ltx2_request import LTXRequestInputs
|
||||
from .pipeline_ltx2_latent_upsample import LTX2LatentUpsamplePipeline
|
||||
from .ltx2_recipes import LTX2_DISTILLED_TWO_STAGE_RECIPE
|
||||
from .pipeline_ltx2 import LTX2Pipeline
|
||||
|
||||
|
||||
class LTX2TwoStagesPipeline(LTXPipelineRuntime):
|
||||
"""Legacy distilled-only LTX2 two-stage compatibility entry."""
|
||||
class LTX2DistilledPipeline(LTX2Pipeline):
|
||||
"""Unified LTX-2 distilled two-stage T2V/I2V entry."""
|
||||
|
||||
component_profile = LTX2_COMPONENT_PROFILE
|
||||
guidance_strategy = LTX_LEGACY_VELOCITY_GUIDANCE
|
||||
one_stage_recipe = LTX2_ONE_STAGE_RECIPE
|
||||
pipeline_kind = "distilled_two_stage"
|
||||
component_profile = LTX2_DISTILLED_COMPONENT_PROFILE
|
||||
pipeline_recipe = LTX2_DISTILLED_TWO_STAGE_RECIPE
|
||||
supports_request_batch = False
|
||||
support_image_input = False
|
||||
|
||||
_dit_modules: ClassVar[list[str]] = list(component_profile.dit_modules)
|
||||
_encoder_modules: ClassVar[list[str]] = list(component_profile.encoder_modules)
|
||||
_vae_modules: ClassVar[list[str]] = list(component_profile.vae_modules)
|
||||
_resident_modules: ClassVar[list[str]] = list(component_profile.resident_modules)
|
||||
support_image_input = True
|
||||
unified_text_image_entry = True
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
|
||||
model_path = od_config.model
|
||||
self.distilled = "distilled" in os.path.basename(os.path.normpath(model_path))
|
||||
if not self.distilled:
|
||||
raise NotImplementedError(f"{model_path} is not supported for {self.__class__.__name__}.")
|
||||
|
||||
super().__init__(od_config=od_config, prefix=prefix)
|
||||
self.upsample_pipe = LTX2LatentUpsamplePipeline(vae=self.vae, od_config=od_config)
|
||||
|
||||
def _run_two_stage(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
request_inputs: LTXRequestInputs,
|
||||
*,
|
||||
noise_scale: float,
|
||||
timesteps: list[int] | None,
|
||||
attention_kwargs: dict[str, Any] | None,
|
||||
image: Any | None = None,
|
||||
) -> DiffusionOutput | list[DiffusionOutput]:
|
||||
stage1 = self.run_phase(
|
||||
req,
|
||||
request_inputs,
|
||||
noise_scale=noise_scale,
|
||||
sigmas=DISTILLED_SIGMA_VALUES if self.distilled else None,
|
||||
timesteps=timesteps,
|
||||
attention_kwargs=attention_kwargs,
|
||||
image=image,
|
||||
)
|
||||
upscaled_video_latent = self.upsample_pipe(
|
||||
latents=stage1.video,
|
||||
output_type="latent",
|
||||
return_dict=False,
|
||||
)[0]
|
||||
|
||||
stage2_inputs = replace(
|
||||
request_inputs,
|
||||
num_inference_steps=3,
|
||||
guidance_scale=1.0,
|
||||
latents=upscaled_video_latent,
|
||||
audio_latents=stage1.audio,
|
||||
decode_timestep=0.0,
|
||||
decode_noise_scale=None,
|
||||
output_type="np",
|
||||
)
|
||||
stage2 = self.run_phase(
|
||||
req,
|
||||
stage2_inputs,
|
||||
noise_scale=STAGE_2_DISTILLED_SIGMA_VALUES[0],
|
||||
sigmas=STAGE_2_DISTILLED_SIGMA_VALUES,
|
||||
timesteps=None,
|
||||
attention_kwargs=attention_kwargs,
|
||||
prompt_context=stage1.forward_context.prompt_context,
|
||||
)
|
||||
return self.decode_phase(stage2)
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
prompt: str | list[str] | None = None,
|
||||
negative_prompt: str | list[str] | None = None,
|
||||
height: int | None = None,
|
||||
width: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
frame_rate: float | None = None,
|
||||
num_inference_steps: int | None = None,
|
||||
timesteps: list[int] | None = None,
|
||||
guidance_scale: float = 4.0,
|
||||
guidance_rescale: float = 0.0,
|
||||
noise_scale: float = 0.0,
|
||||
num_videos_per_prompt: int | None = 1,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
audio_latents: torch.Tensor | None = None,
|
||||
prompt_embeds: torch.Tensor | None = None,
|
||||
negative_prompt_embeds: torch.Tensor | None = None,
|
||||
prompt_attention_mask: torch.Tensor | None = None,
|
||||
negative_prompt_attention_mask: torch.Tensor | None = None,
|
||||
decode_timestep: float | list[float] = 0.0,
|
||||
decode_noise_scale: float | list[float] | None = None,
|
||||
output_type: str = "np",
|
||||
return_dict: bool = True,
|
||||
attention_kwargs: dict[str, Any] | None = None,
|
||||
max_sequence_length: int | None = None,
|
||||
*,
|
||||
image: Any | None = None,
|
||||
) -> DiffusionOutput | list[DiffusionOutput]:
|
||||
del return_dict
|
||||
request_inputs = self._resolve_request_inputs(
|
||||
req,
|
||||
prompt=prompt,
|
||||
negative_prompt=negative_prompt,
|
||||
height=height,
|
||||
width=width,
|
||||
num_frames=num_frames,
|
||||
frame_rate=frame_rate,
|
||||
num_inference_steps=num_inference_steps,
|
||||
timesteps=timesteps,
|
||||
guidance_scale=(
|
||||
getattr(getattr(self, "one_stage_recipe", None), "guidance_scale", 4.0)
|
||||
if guidance_scale is None
|
||||
else guidance_scale
|
||||
),
|
||||
guidance_rescale=guidance_rescale,
|
||||
num_videos_per_prompt=num_videos_per_prompt,
|
||||
generator=generator,
|
||||
latents=latents,
|
||||
audio_latents=audio_latents,
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
prompt_attention_mask=prompt_attention_mask,
|
||||
negative_prompt_attention_mask=negative_prompt_attention_mask,
|
||||
decode_timestep=decode_timestep,
|
||||
decode_noise_scale=decode_noise_scale,
|
||||
output_type=output_type,
|
||||
max_sequence_length=max_sequence_length,
|
||||
)
|
||||
if self.support_image_input:
|
||||
image = self._resolve_request_image(req, image, request_inputs)
|
||||
return self._run_two_stage(
|
||||
req,
|
||||
request_inputs,
|
||||
noise_scale=noise_scale,
|
||||
timesteps=timesteps,
|
||||
attention_kwargs=attention_kwargs,
|
||||
image=image,
|
||||
)
|
||||
|
||||
|
||||
class LTX2ImageToVideoTwoStagesPipeline(LTXI2VConditioningMixin, LTX2TwoStagesPipeline):
|
||||
"""LTX2 two-stage image-to-video entry."""
|
||||
|
||||
def forward(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
image: Any | None = None,
|
||||
prompt: str | list[str] | None = None,
|
||||
negative_prompt: str | list[str] | None = None,
|
||||
height: int | None = None,
|
||||
width: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
frame_rate: float | None = None,
|
||||
num_inference_steps: int | None = None,
|
||||
sigmas: list[float] | None = None,
|
||||
*args: Any,
|
||||
**kwargs: Any,
|
||||
) -> DiffusionOutput | list[DiffusionOutput]:
|
||||
"""Preserve the legacy I2V sigma slot, which was ignored by this pipeline."""
|
||||
del sigmas
|
||||
return super().forward(
|
||||
req,
|
||||
image,
|
||||
prompt,
|
||||
negative_prompt,
|
||||
height,
|
||||
width,
|
||||
num_frames,
|
||||
frame_rate,
|
||||
num_inference_steps,
|
||||
*args,
|
||||
**kwargs,
|
||||
)
|
||||
Reference in new issue
Block a user