diff --git a/docs/contributing/README.md b/docs/contributing/README.md index 29a02dc41..77d96066a 100644 --- a/docs/contributing/README.md +++ b/docs/contributing/README.md @@ -71,14 +71,7 @@ For additional features and advanced configurations, refer to the: ### Testing vLLM-Omni uses `pytest` to test the codebase. - -```bash -# Run all tests -pytest tests/ - -# Run tests for a single test file with detailed output -pytest -s -v tests/test_omni_llm.py -``` +Please refer to the [test instructions](./ci/test_guide.md) for detailed testing information. !!! warning Currently, not all unit tests pass when run on CPU platforms. If you don't have access to a GPU platform to run unit tests locally, rely on the continuous integration system to run the tests for now. @@ -123,6 +116,9 @@ Only specific types of PRs will be reviewed. The PR title is prefixed appropriat !!! note If the PR spans more than one category, please include all relevant prefixes. +### Local Test +Please run the L1 and L2 test cases locally first and attach the results before contacting us to add the "ready" label. Please refer to the [test instructions](./ci/test_guide.md) for running the test cases. + ### Code Quality The PR needs to meet the following code quality standards: diff --git a/docs/contributing/ci/test_guide.md b/docs/contributing/ci/test_guide.md new file mode 100644 index 000000000..425f24332 --- /dev/null +++ b/docs/contributing/ci/test_guide.md @@ -0,0 +1,75 @@ +# Test Guide +## Setting Up the Test Environment +### Creating a Container +vLLM-Omni provides an official Docker image for deployment. These images are built upon vLLM Docker images and are available on [Docker Hub](https://hub.docker.com/r/vllm/vllm-omni/tags). The version of vLLM-Omni indicates which vLLM release it is based on. +For a local test environment, you can follow the steps below to create a container: +## Installing Dependencies +### vLLM & vLLM-Omni +vLLM-Omni is built based on vLLM. You can follow [install guide](../../getting_started/installation/README.md) to build your local environment. + +### Test Case Dependencies +When running test cases, you may need to install the following dependencies: + +```bash +uv pip install ".[dev]" +apt-get install -y ffmpeg +``` + +## Running Tests +Our test scripts use the pytest framework. First, please use `git clone https://github.com/vllm-project/vllm-omni.git` to download the vllm-omni source code. Then, in the root directory of vllm-omni, you can run the following commands in your local test environment to execute the corresponding test cases. + +=== "L1 level" + + ```bash + cd tests + pytest -s -v -m "core_model and cpu" + ``` + The latest test command is available in the "Simple Unit Test" step of this [pipeline](https://github.com/vllm-project/vllm-omni/blob/main/.buildkite/test-ready.yml). + +=== "L2 level" + + ```bash + cd tests + pytest -s -v -m "core_model and not cpu" --run-level=core_model + ``` + If you only want to run a specific test case, you can use: + ```bash + pytest -s -v test_xxxx.py --run-level=core_model + ``` + If you only want to run specific test cases on a particular platform, you can use: + ```bash + pytest -s -v -m "core_model and distributed_cuda and L4" --run-level=core_model + ``` + The latest test commands for various test suites can be found in the [pipeline](https://github.com/vllm-project/vllm-omni/blob/main/.buildkite/test-ready.yml). + +=== "L3 level & L4 level" + + ```bash + cd tests + pytest -s -v -m "advanced_model" --run-level=advanced_model + ``` + If you only want to run L3 test case, you can use: + ```bash + pytest -s -v e2e/ --ignore-glob='*expansion.py' -m "advanced_model" --run-level=advanced_model + ``` + If you only want to run a specific test case, you can use: + ```bash + pytest -s -v test_xxxx.py --run-level=advanced_model + ``` + If you only want to run specific test cases on a particular platform, you can use: + ```bash + pytest -s -v -m "core_model and distributed_cuda and L4" --run-level=core_model + ``` + Note: To run performance tests, use: + ```bash + pytest -s -v perf/scripts/run_benchmark.py + ``` + + The latest L3 test commands for various test suites can be found in the [pipeline](https://github.com/vllm-project/vllm-omni/blob/main/.buildkite/test-merge.yml). + + The latest L4 test commands for various test suites can be found in the [pipeline](https://github.com/vllm-project/vllm-omni/blob/main/.buildkite/test-nightly.yml). + +You can find more information about markers in the documentation: [marker doc](./tests_markers.md) + +## Adding New Test Cases +Please refer to the [L5 Layering Specification document](./CI_5levels.md). diff --git a/docs/contributing/model/adding_omni_model.md b/docs/contributing/model/adding_omni_model.md index 814991186..6216b4b78 100644 --- a/docs/contributing/model/adding_omni_model.md +++ b/docs/contributing/model/adding_omni_model.md @@ -460,7 +460,7 @@ def forward(self, ...): These keys are then accessible in your stage transition function: ```python # In stage_input_processors/qwen3_omni.py -thinker_embeddings = output.multimodal_output["0"] # Access by key +thinker_prefill_embeddings = output.multimodal_output["0"] # Access by key thinker_hidden_states = output.multimodal_output["24"] ``` @@ -513,11 +513,11 @@ def thinker2talker( for thinker_output in thinker_outputs: output = thinker_output.outputs[0] # Extract thinker embeddings and hidden states - thinker_embeddings = output.multimodal_output["0"].float().clone().detach().cuda() + thinker_prefill_embeddings = output.multimodal_output["0"].float().clone().detach().cuda() thinker_hidden_states = output.multimodal_output["24"].float().clone().detach().cuda() info = { - "thinker_embeddings": thinker_embeddings, + "thinker_prefill_embeddings": thinker_prefill_embeddings, "thinker_hidden_states": thinker_hidden_states, "thinker_sequences": thinker_output.prompt_token_ids + output.token_ids, "thinker_input_ids": thinker_output.prompt_token_ids, diff --git a/docs/design/feature/async_chunk_design.md b/docs/design/feature/async_chunk_design.md index b6a673a90..40b8f215a 100644 --- a/docs/design/feature/async_chunk_design.md +++ b/docs/design/feature/async_chunk_design.md @@ -19,7 +19,7 @@ The `async_chunk` feature enables asynchronous, chunked processing of data acros For qwen3-omni: - **Thinker → Talker**: Per decode step (typically chunk_size=1) -- **Talker → Code2Wav**: Accumulated to code2wav chunk_size(default=25, currently only support default, will support chunk_size soon) before sending +- **Talker → Code2Wav**: Accumulated to `codec_chunk_frames` (default=25) before sending. Set `initial_codec_chunk_frames` to emit smaller chunks during the initial phase for reduced TTFA - **Code2Wav**: Streaming decode with code2wav chunk_size With `async_chunk`: diff --git a/docs/design/feature/sequence_parallel.md b/docs/design/feature/sequence_parallel.md index ba09d6c04..18477e61a 100644 --- a/docs/design/feature/sequence_parallel.md +++ b/docs/design/feature/sequence_parallel.md @@ -240,7 +240,8 @@ class TransformerWithRoPE(nn.Module): ## Approach 2: Intrusive Modification (For Complex Cases) -For models with dynamic sharding logic that cannot be expressed via `_sp_plan`, manually insert shard/gather calls. +For models with dynamic sharding logic that cannot be expressed via `_sp_plan`, manually insert shard/gather calls. Importantly, when taking this approach, be careful to ensure that you correctly manage the `_sp_shard_depth`; if the sequence parallel shard depth is 0, Ulysses will not be used. + **When to use:** - Dynamic/conditional sharding logic @@ -252,15 +253,18 @@ from vllm_omni.diffusion.distributed.sp_sharding import sp_shard, sp_gather def forward(self, hidden_states, ...): if self.parallel_config.sequence_parallel_size > 1: + # hidden_states = sp_shard(hidden_states, dim=1) # ... computation ... if self.parallel_config.sequence_parallel_size > 1: output = sp_gather(output, dim=1) + # return output ``` +Note that currently, `sp_shard` / `sp_gather` do *not* automatically manage the `_sp_shard_depth`; you need to be careful to manage it yourself. --- diff --git a/docs/models/supported_models.md b/docs/models/supported_models.md index 98c746e09..56b5a0f6b 100644 --- a/docs/models/supported_models.md +++ b/docs/models/supported_models.md @@ -30,6 +30,8 @@ th { |`ZImagePipeline` | Z-Image | `Tongyi-MAI/Z-Image-Turbo` | | `WanPipeline` | Wan2.2-T2V, Wan2.2-TI2V | `Wan-AI/Wan2.2-T2V-A14B-Diffusers`, `Wan-AI/Wan2.2-TI2V-5B-Diffusers` | | `WanImageToVideoPipeline` | Wan2.2-I2V | `Wan-AI/Wan2.2-I2V-A14B-Diffusers` | +| `LTX2Pipeline` | LTX-2-T2V | `Lightricks/LTX-2` | +| `LTX2ImageToVideoPipeline` | LTX-2-I2V | `Lightricks/LTX-2` | | `HeliosPipeline`, `HeliosPyramidPipeline` | Helios | `BestWishYsh/Helios-Base`, `BestWishYsh/Helios-Mid`, `BestWishYsh/Helios-Distilled` | | `OvisImagePipeline` | Ovis-Image | `OvisAI/Ovis-Image` | |`LongcatImagePipeline` | LongCat-Image | `meituan-longcat/LongCat-Image` | diff --git a/docs/serving/speech_api.md b/docs/serving/speech_api.md index 86b7c73f8..b22aee84c 100644 --- a/docs/serving/speech_api.md +++ b/docs/serving/speech_api.md @@ -96,6 +96,7 @@ Content-Type: application/json | `language` | string | "Auto" | Language (see supported languages below) | | `instructions` | string | "" | Voice style/emotion instructions | | `max_new_tokens` | integer | 2048 | Maximum tokens to generate | +| `initial_codec_chunk_frames` | integer | null | Initial chunk size for reduced TTFA (overrides stage config) | **Supported languages:** Auto, Chinese, English, Japanese, Korean, German, French, Russian, Portuguese, Spanish, Italian diff --git a/docs/user_guide/diffusion/parallelism_acceleration.md b/docs/user_guide/diffusion/parallelism_acceleration.md index 4f4a209d0..04edc59b3 100644 --- a/docs/user_guide/diffusion/parallelism_acceleration.md +++ b/docs/user_guide/diffusion/parallelism_acceleration.md @@ -54,6 +54,7 @@ The following table shows which models are currently supported by parallelism me | Model | Model Identifier | Ulysses-SP | Ring-Attention | Tensor-Parallel | HSDP | VAE-Patch-Parallel | |-------|------------------|:----------:|:--------------:|:---------------:|:----:| :----:| | **Wan2.2** | `Wan-AI/Wan2.2-T2V-A14B-Diffusers` | ✅ | ✅ | ✅ | ✅ | ✅ | +| **LTX-2** | `Lightricks/LTX-2` | ✅ | ✅ | ✅ | ❌ | ❌ | ### Tensor Parallelism diff --git a/docs/user_guide/diffusion_acceleration.md b/docs/user_guide/diffusion_acceleration.md index 2c36c966c..5b86562b3 100644 --- a/docs/user_guide/diffusion_acceleration.md +++ b/docs/user_guide/diffusion_acceleration.md @@ -74,6 +74,7 @@ The following table shows which models are currently supported by each accelerat | Model | Model Identifier | TeaCache | Cache-DiT | Ulysses-SP | Ring-Attention | CFG-Parallel | HSDP | VAE-Patch-Parallel | |-------|------------------|:--------:|:---------:|:----------:|:--------------:|:------------:|:----:|:----:| | **Wan2.2** | `Wan-AI/Wan2.2-T2V-A14B-Diffusers` | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| **LTX-2** | `Lightricks/LTX-2` | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ### Quantization diff --git a/docs/user_guide/examples/offline_inference/qwen3_tts.md b/docs/user_guide/examples/offline_inference/qwen3_tts.md index a5acf32d6..5c3b044d7 100644 --- a/docs/user_guide/examples/offline_inference/qwen3_tts.md +++ b/docs/user_guide/examples/offline_inference/qwen3_tts.md @@ -98,7 +98,8 @@ Add `--streaming` to stream audio chunks progressively via `AsyncOmni` (requires python end2end.py --query-type CustomVoice --streaming --output-dir /tmp/out_stream ``` -Each 25-frame Code2Wav chunk is logged as it arrives. The final WAV file is written once generation +Each Code2Wav chunk is logged as it arrives (default 25 frames; configurable via `codec_chunk_frames` +and `initial_codec_chunk_frames` in the stage config). The final WAV file is written once generation completes. This demonstrates that audio data is available progressively rather than only at the end. > **Note:** Streaming uses `AsyncOmni` internally. The non-streaming path (`Omni`) is unchanged. diff --git a/docs/user_guide/examples/online_serving/qwen3_tts.md b/docs/user_guide/examples/online_serving/qwen3_tts.md index 82f187b25..77a3947b5 100644 --- a/docs/user_guide/examples/online_serving/qwen3_tts.md +++ b/docs/user_guide/examples/online_serving/qwen3_tts.md @@ -268,7 +268,7 @@ Returns binary audio data with appropriate `Content-Type` header (e.g., `audio/w ## Streaming Set `stream=true` with `response_format="pcm"` to receive raw PCM audio chunks as they are decoded -(one chunk per 25-frame Code2Wav window): +(one chunk per Code2Wav window, default 25 frames; configurable in the stage config): ```bash curl -X POST http://localhost:8091/v1/audio/speech \ diff --git a/examples/offline_inference/bagel/end2end.py b/examples/offline_inference/bagel/end2end.py index 04ae4c15d..584e463e1 100644 --- a/examples/offline_inference/bagel/end2end.py +++ b/examples/offline_inference/bagel/end2end.py @@ -51,6 +51,13 @@ def parse_args(): parser.add_argument( "--negative-prompt", type=str, default=None, help="Negative prompt for CFG (default: empty prompt)" ) + parser.add_argument( + "--cfg-parallel-size", + type=int, + default=1, + choices=[1, 2, 3], + help="CFG parallel size: 1=batched (single GPU), 2=parallel with 2 branches (text CFG only), 3=parallel (3 GPUs).", + ) args = parser.parse_args() return args @@ -82,12 +89,14 @@ def main(): from PIL import Image if args.modality == "img2img": - from PIL import Image - from vllm_omni.entrypoints.omni_diffusion import OmniDiffusion - print("[Info] Running in img2img mode (Stage 1 only)") - client = OmniDiffusion(model=model_name) + print(f"[Info] Running in {args.modality} mode (Stage 1 only, cfg_parallel_size={args.cfg_parallel_size})") + + client = OmniDiffusion( + model=model_name, + parallel_config={"cfg_parallel_size": args.cfg_parallel_size}, + ) if args.image_path: if os.path.exists(args.image_path): diff --git a/examples/offline_inference/image_to_video/README.md b/examples/offline_inference/image_to_video/README.md index 2643084f1..2692c76df 100644 --- a/examples/offline_inference/image_to_video/README.md +++ b/examples/offline_inference/image_to_video/README.md @@ -65,6 +65,7 @@ Key arguments: - `--vae-use-slicing`: Enable VAE slicing for memory optimization. - `--vae-use-tiling`: Enable VAE tiling for memory optimization. - `--cfg-parallel-size`: set it to 2 to enable CFG Parallel. See more examples in [`user_guide`](../../../docs/user_guide/diffusion/parallelism_acceleration.md#cfg-parallel). +- `--tensor-parallel-size`: tensor parallel size (effective for models that support TP, e.g. LTX2). - `--enable-cpu-offload`: enable CPU offloading for diffusion models. - `--use-hsdp`: Enable Hybrid Sharded Data Parallel to shard model weights across GPUs. - `--hsdp-shard-size`: Number of GPUs to shard model weights across within each replica group. -1 (default) auto-calculates as world_size / replicate_size. diff --git a/examples/offline_inference/image_to_video/image_to_video.py b/examples/offline_inference/image_to_video/image_to_video.py index 4e42b8b29..cdcabf48c 100644 --- a/examples/offline_inference/image_to_video/image_to_video.py +++ b/examples/offline_inference/image_to_video/image_to_video.py @@ -2,11 +2,12 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ -Image-to-Video generation example using Wan2.2 I2V/TI2V models. +Image-to-Video generation example using Wan2.2 I2V/TI2V models or LTX2. Supports: - Wan2.2-I2V-A14B-Diffusers: MoE model with CLIP image encoder - Wan2.2-TI2V-5B-Diffusers: Unified T2V+I2V model (dense 5B) +- LTX2 image-to-video pipeline Usage: # I2V-A14B (MoE) @@ -16,6 +17,13 @@ Usage: # TI2V-5B (unified) python image_to_video.py --model Wan-AI/Wan2.2-TI2V-5B-Diffusers \ --image input.jpg --prompt "A cat playing with yarn" + + # LTX2 image-to-video + python image_to_video.py --model /path/to/LTX-2 \ + --model-class-name LTX2ImageToVideoPipeline \ + --image input.jpg --prompt "A cinematic dolly shot of a boat" \ + --num-frames 121 --num_inference_steps 40 --guidance_scale 4.0 \ + --frame-rate 24 --fps 24 --output ltx2_i2v.mp4 """ import argparse @@ -35,12 +43,17 @@ from vllm_omni.platforms import current_omni_platform def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser(description="Generate a video from an image with Wan2.2 I2V/TI2V.") + parser = argparse.ArgumentParser(description="Generate a video from an image with Wan2.2 or LTX2.") parser.add_argument( "--model", default="Wan-AI/Wan2.2-I2V-A14B-Diffusers", help="Diffusers Wan2.2 I2V model ID or local path.", ) + parser.add_argument( + "--model-class-name", + default=None, + help="Override model class name (e.g., LTX2ImageToVideoPipeline).", + ) parser.add_argument("--image", required=True, help="Path to input image.") parser.add_argument("--prompt", default="", help="Text prompt describing the desired motion.") parser.add_argument("--negative-prompt", default="", help="Negative prompt.") @@ -56,11 +69,17 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--num-frames", type=int, default=81, help="Number of frames.") parser.add_argument("--num-inference-steps", type=int, default=50, help="Sampling steps.") parser.add_argument("--boundary-ratio", type=float, default=0.875, help="Boundary split ratio for MoE models.") + parser.add_argument( + "--frame-rate", + type=float, + default=None, + help="Optional generation frame rate (used by models like LTX2). Defaults to --fps.", + ) parser.add_argument( "--flow-shift", type=float, default=5.0, help="Scheduler flow_shift (5.0 for 720p, 12.0 for 480p)." ) parser.add_argument("--output", type=str, default="i2v_output.mp4", help="Path to save the video (mp4).") - parser.add_argument("--fps", type=int, default=16, help="Frames per second for the output video.") + parser.add_argument("--fps", type=int, default=None, help="Frames per second for the output video.") parser.add_argument( "--vae-use-slicing", action="store_true", @@ -117,6 +136,23 @@ def parse_args() -> argparse.Namespace: action="store_true", help="Disable torch.compile and force eager execution.", ) + parser.add_argument( + "--audio-sample-rate", + type=int, + default=24000, + help="Sample rate for audio output when saved (default: 24000 for LTX2).", + ) + parser.add_argument( + "--cache-backend", + type=str, + default=None, + choices=["cache_dit", "tea_cache"], + help=( + "Cache backend to use for acceleration. " + "Options: 'cache_dit' (DBCache + SCM + TaylorSeer), 'tea_cache' (Timestep Embedding Aware Cache). " + "Default: None (no cache acceleration)." + ), + ) parser.add_argument( "--use-hsdp", action="store_true", @@ -143,10 +179,13 @@ def parse_args() -> argparse.Namespace: return parser.parse_args() -def calculate_dimensions(image: PIL.Image.Image, max_area: int = 480 * 832) -> tuple[int, int]: +def calculate_dimensions( + image: PIL.Image.Image, + max_area: int = 480 * 832, + mod_value: int = 16, +) -> tuple[int, int]: """Calculate output dimensions maintaining aspect ratio.""" aspect_ratio = image.height / image.width - mod_value = 16 # Must be divisible by 16 height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value @@ -157,22 +196,66 @@ def calculate_dimensions(image: PIL.Image.Image, max_area: int = 480 * 832) -> t def main(): args = parse_args() generator = torch.Generator(device=current_omni_platform.device_type).manual_seed(args.seed) + model_name = str(args.model).lower() if args.model is not None else "" + model_class_name = args.model_class_name + is_ltx2 = "ltx2" in model_name or (model_class_name and "ltx2" in model_class_name.lower()) + if model_class_name is None and is_ltx2: + model_class_name = "LTX2ImageToVideoPipeline" # Load input image image = PIL.Image.open(args.image).convert("RGB") + fps = args.fps if args.fps is not None else (24 if is_ltx2 else 16) + frame_rate = args.frame_rate if args.frame_rate is not None else float(fps) + guidance_scale = args.guidance_scale if args.guidance_scale is not None else (4.0 if is_ltx2 else 5.0) + num_frames = args.num_frames if args.num_frames is not None else (121 if is_ltx2 else 81) + num_inference_steps = args.num_inference_steps if args.num_inference_steps is not None else (40 if is_ltx2 else 50) + # Calculate dimensions if not provided height = args.height width = args.width if height is None or width is None: - # Default to 480P area for I2V - calc_height, calc_width = calculate_dimensions(image, max_area=480 * 832) + # Default to 480P area for Wan2.2 I2V, 512x768 area for LTX2 + max_area = 512 * 768 if is_ltx2 else 480 * 832 + mod_value = 32 if is_ltx2 else 16 + calc_height, calc_width = calculate_dimensions(image, max_area=max_area, mod_value=mod_value) height = height or calc_height width = width or calc_width # Resize image to target dimensions image = image.resize((width, height), PIL.Image.Resampling.LANCZOS) + # Configure cache based on backend type + cache_config = None + if args.cache_backend == "cache_dit": + if is_ltx2: + cache_config = { + "Fn_compute_blocks": 2, + "Bn_compute_blocks": 0, + "max_warmup_steps": 8, + "residual_diff_threshold": 0.12, + "max_continuous_cached_steps": 1, + "max_cached_steps": 20, + "enable_taylorseer": False, + "scm_steps_mask_policy": None, + } + else: + cache_config = { + "Fn_compute_blocks": 1, + "Bn_compute_blocks": 0, + "max_warmup_steps": 4, + "residual_diff_threshold": 0.24, + "max_continuous_cached_steps": 3, + "enable_taylorseer": False, + "taylorseer_order": 1, + "scm_steps_mask_policy": None, + "scm_steps_policy": "dynamic", + } + elif args.cache_backend == "tea_cache": + cache_config = { + "rel_l1_thresh": 0.2, + } + # Check if profiling is requested via environment variable profiler_enabled = bool(os.getenv("VLLM_TORCH_PROFILER_DIR")) parallel_config = DiffusionParallelConfig( @@ -195,6 +278,9 @@ def main(): enable_cpu_offload=args.enable_cpu_offload, parallel_config=parallel_config, enforce_eager=args.enforce_eager, + model_class_name=model_class_name, + cache_backend=args.cache_backend, + cache_config=cache_config, ) if profiler_enabled: @@ -226,10 +312,11 @@ def main(): height=height, width=width, generator=generator, - guidance_scale=args.guidance_scale, + guidance_scale=guidance_scale, guidance_scale_2=args.guidance_scale_high, - num_inference_steps=args.num_inference_steps, - num_frames=args.num_frames, + num_inference_steps=num_inference_steps, + num_frames=num_frames, + frame_rate=frame_rate, ), ) generation_end = time.perf_counter() @@ -238,31 +325,56 @@ def main(): # Print profiling results print(f"Total generation time: {generation_time:.4f} seconds ({generation_time * 1000:.2f} ms)") - # Extract video frames from OmniRequestOutput - if isinstance(frames, list) and len(frames) > 0: - first_item = frames[0] + audio = None + if isinstance(frames, list): + frames = frames[0] if frames else None - # Check if it's an OmniRequestOutput - if hasattr(first_item, "final_output_type"): - if first_item.final_output_type != "image": - raise ValueError( - f"Unexpected output type '{first_item.final_output_type}', expected 'image' for video generation." - ) - - # Pipeline mode: extract from nested request_output - if hasattr(first_item, "is_pipeline_output") and first_item.is_pipeline_output: - if isinstance(first_item.request_output, list) and len(first_item.request_output) > 0: - inner_output = first_item.request_output[0] - if isinstance(inner_output, OmniRequestOutput) and hasattr(inner_output, "images"): - frames = inner_output.images[0] if inner_output.images else None - if frames is None: - raise ValueError("No video frames found in output.") - # Diffusion mode: use direct images field - elif hasattr(first_item, "images") and first_item.images: - frames = first_item.images + if isinstance(frames, OmniRequestOutput): + if frames.final_output_type != "image": + raise ValueError( + f"Unexpected output type '{frames.final_output_type}', expected 'image' for video generation." + ) + if frames.multimodal_output and "audio" in frames.multimodal_output: + audio = frames.multimodal_output["audio"] + if frames.is_pipeline_output and frames.request_output is not None: + inner_output = frames.request_output + if isinstance(inner_output, list): + inner_output = inner_output[0] if inner_output else None + if isinstance(inner_output, OmniRequestOutput): + if inner_output.multimodal_output and "audio" in inner_output.multimodal_output: + audio = inner_output.multimodal_output["audio"] + frames = inner_output + if isinstance(frames, OmniRequestOutput): + if frames.images: + if len(frames.images) == 1 and isinstance(frames.images[0], tuple) and len(frames.images[0]) == 2: + frames, audio = frames.images[0] + elif len(frames.images) == 1 and isinstance(frames.images[0], dict): + audio = frames.images[0].get("audio") + frames = frames.images[0].get("frames") or frames.images[0].get("video") + else: + frames = frames.images else: raise ValueError("No video frames found in OmniRequestOutput.") + if isinstance(frames, list) and frames: + first_item = frames[0] + if isinstance(first_item, tuple) and len(first_item) == 2: + frames, audio = first_item + elif isinstance(first_item, dict): + audio = first_item.get("audio") + frames = first_item.get("frames") or first_item.get("video") + elif isinstance(first_item, list): + frames = first_item + + if isinstance(frames, tuple) and len(frames) == 2: + frames, audio = frames + elif isinstance(frames, dict): + audio = frames.get("audio") + frames = frames.get("frames") or frames.get("video") + + if frames is None: + raise ValueError("No video frames found in output.") + output_path = Path(args.output) output_path.parent.mkdir(parents=True, exist_ok=True) @@ -271,32 +383,128 @@ def main(): except ImportError: raise ImportError("diffusers is required for export_to_video.") - # frames may be np.ndarray (preferred) or torch.Tensor + def _normalize_frame(frame): + if isinstance(frame, torch.Tensor): + frame_tensor = frame.detach().cpu() + if frame_tensor.dim() == 4 and frame_tensor.shape[0] == 1: + frame_tensor = frame_tensor[0] + if frame_tensor.dim() == 3 and frame_tensor.shape[0] in (3, 4): + frame_tensor = frame_tensor.permute(1, 2, 0) + if frame_tensor.is_floating_point(): + frame_tensor = frame_tensor.clamp(-1, 1) * 0.5 + 0.5 + return frame_tensor.float().numpy() + if isinstance(frame, np.ndarray): + frame_array = frame + if frame_array.ndim == 4 and frame_array.shape[0] == 1: + frame_array = frame_array[0] + if np.issubdtype(frame_array.dtype, np.integer): + frame_array = frame_array.astype(np.float32) / 255.0 + return frame_array + try: + from PIL import Image + except ImportError: + Image = None + if Image is not None and isinstance(frame, Image.Image): + return np.asarray(frame).astype(np.float32) / 255.0 + return frame + + def _ensure_frame_list(video_array): + if isinstance(video_array, list): + if len(video_array) == 0: + return video_array + first_item = video_array[0] + if isinstance(first_item, np.ndarray): + if first_item.ndim == 5: + return list(first_item[0]) + if first_item.ndim == 4: + if len(video_array) == 1: + return list(first_item) + return list(first_item) + if first_item.ndim == 3: + return video_array + return video_array + if isinstance(video_array, np.ndarray): + if video_array.ndim == 5: + return list(video_array[0]) + if video_array.ndim == 4: + return list(video_array) + if video_array.ndim == 3: + return [video_array] + return video_array + + # frames may be np.ndarray, torch.Tensor, or list of tensors/arrays/images # export_to_video expects a list of frames with values in [0, 1] if isinstance(frames, torch.Tensor): video_tensor = frames.detach().cpu() if video_tensor.dim() == 5: - # [B, C, F, H, W] or [B, F, H, W, C] if video_tensor.shape[1] in (3, 4): video_tensor = video_tensor[0].permute(1, 2, 3, 0) else: video_tensor = video_tensor[0] elif video_tensor.dim() == 4 and video_tensor.shape[0] in (3, 4): video_tensor = video_tensor.permute(1, 2, 3, 0) - # If float, assume [-1,1] and normalize to [0,1] if video_tensor.is_floating_point(): video_tensor = video_tensor.clamp(-1, 1) * 0.5 + 0.5 video_array = video_tensor.float().numpy() + elif isinstance(frames, np.ndarray): + video_array = frames + if video_array.ndim == 5: + video_array = video_array[0] + if np.issubdtype(video_array.dtype, np.integer): + video_array = video_array.astype(np.float32) / 255.0 + elif isinstance(frames, list): + if len(frames) == 0: + raise ValueError("No video frames found in output.") + video_array = [_normalize_frame(frame) for frame in frames] else: video_array = frames - if hasattr(video_array, "shape") and video_array.ndim == 5: - video_array = video_array[0] - # Convert 4D array (frames, H, W, C) to list of frames for export_to_video - if isinstance(video_array, np.ndarray) and video_array.ndim == 4: - video_array = list(video_array) + video_array = _ensure_frame_list(video_array) - export_to_video(video_array, str(output_path), fps=args.fps) + use_ltx2_export = is_ltx2 + encode_video = None + if use_ltx2_export: + try: + from diffusers.pipelines.ltx2.export_utils import encode_video + except ImportError: + encode_video = None + + if use_ltx2_export and encode_video is not None: + if isinstance(video_array, list): + frames_np = np.stack(video_array, axis=0) + elif isinstance(video_array, np.ndarray): + frames_np = video_array + else: + frames_np = np.asarray(video_array) + + if frames_np.ndim == 4 and frames_np.shape[-1] == 4: + frames_np = frames_np[..., :3] + + frames_np = np.clip(frames_np, 0.0, 1.0) + frames_u8 = (frames_np * 255).round().clip(0, 255).astype("uint8") + video_tensor = torch.from_numpy(frames_u8) + + audio_out = None + if audio is not None: + if isinstance(audio, list): + audio = audio[0] if audio else None + if isinstance(audio, np.ndarray): + audio = torch.from_numpy(audio) + if isinstance(audio, torch.Tensor): + audio_out = audio + if audio_out.dim() > 1: + audio_out = audio_out[0] + audio_out = audio_out.float().cpu() + + encode_video( + video_tensor, + fps=fps, + audio=audio_out, + audio_sample_rate=args.audio_sample_rate if audio_out is not None else None, + output_path=str(output_path), + ) + else: + export_to_video(video_array, str(output_path), fps=fps) print(f"Saved generated video to {output_path}") if profiler_enabled: diff --git a/examples/offline_inference/qwen3_tts/README.md b/examples/offline_inference/qwen3_tts/README.md index f4ce92f4d..c198f2c6e 100644 --- a/examples/offline_inference/qwen3_tts/README.md +++ b/examples/offline_inference/qwen3_tts/README.md @@ -95,7 +95,8 @@ Add `--streaming` to stream audio chunks progressively via `AsyncOmni` (requires python end2end.py --query-type CustomVoice --streaming --output-dir /tmp/out_stream ``` -Each 25-frame Code2Wav chunk is logged as it arrives. The final WAV file is written once generation +Each Code2Wav chunk is logged as it arrives (default 25 frames; configurable via `codec_chunk_frames` +and `initial_codec_chunk_frames` in the stage config). The final WAV file is written once generation completes. This demonstrates that audio data is available progressively rather than only at the end. > **Note:** Streaming uses `AsyncOmni` internally. The non-streaming path (`Omni`) is unchanged. diff --git a/examples/offline_inference/qwen3_tts/end2end.py b/examples/offline_inference/qwen3_tts/end2end.py index 2839a6958..98303533a 100644 --- a/examples/offline_inference/qwen3_tts/end2end.py +++ b/examples/offline_inference/qwen3_tts/end2end.py @@ -7,6 +7,7 @@ tasks, then runs Omni generation and saves output wav files. import asyncio import logging import os +import time from typing import Any, NamedTuple import soundfile as sf @@ -337,13 +338,27 @@ async def main_streaming(args): for i, prompt in enumerate(inputs): request_id = str(i) + t_start = time.perf_counter() + t_prev = t_start + chunk_idx = 0 async for stage_output in omni.generate(prompt, request_id=request_id): mm = stage_output.request_output.outputs[0].multimodal_output if not stage_output.finished: + t_now = time.perf_counter() audio = mm.get("audio") n = len(audio) if isinstance(audio, list) else (0 if audio is None else 1) - logger.info(f"Request {request_id}: received chunk {n}") + dt_ms = (t_now - t_prev) * 1000 + ttfa_ms = (t_now - t_start) * 1000 + if chunk_idx == 0: + logger.info(f"Request {request_id}: chunk {chunk_idx} samples={n} TTFA={ttfa_ms:.1f}ms") + else: + logger.info(f"Request {request_id}: chunk {chunk_idx} samples={n} inter_chunk={dt_ms:.1f}ms") + t_prev = t_now + chunk_idx += 1 else: + t_end = time.perf_counter() + total_ms = (t_end - t_start) * 1000 + logger.info(f"Request {request_id}: done total={total_ms:.1f}ms chunks={chunk_idx}") _save_wav(output_dir, request_id, mm) diff --git a/examples/offline_inference/text_to_video/text_to_video.md b/examples/offline_inference/text_to_video/text_to_video.md index 4e34ff8ba..cdac3d39a 100644 --- a/examples/offline_inference/text_to_video/text_to_video.md +++ b/examples/offline_inference/text_to_video/text_to_video.md @@ -1,6 +1,7 @@ # Text-To-Video -The `Wan-AI/Wan2.2-T2V-A14B-Diffusers` pipeline generates short videos from text prompts. +The `Wan-AI/Wan2.2-T2V-A14B-Diffusers` pipeline generates short videos from text prompts. This script can also be used +for `Lightricks/LTX-2` to generate video+audio. ## Local CLI Usage @@ -19,6 +20,22 @@ python text_to_video.py \ --output t2v_out.mp4 ``` +LTX2 example: + +```bash +python text_to_video.py \ + --model "Lightricks/LTX-2" \ + --prompt "A cinematic close-up of ocean waves at golden hour." \ + --negative-prompt "worst quality, inconsistent motion, blurry, jittery, distorted" \ + --height 512 \ + --width 768 \ + --num-frames 121 \ + --num-inference-steps 40 \ + --guidance-scale 4.0 \ + --frame-rate 24 \ + --output ltx2_out.mp4 +``` + Key arguments: - `--prompt`: text description (string). @@ -32,6 +49,9 @@ Key arguments: - `--vae-use-slicing`: enable VAE slicing for memory optimization. - `--vae-use-tiling`: enable VAE tiling for memory optimization. - `--cfg-parallel-size`: set it to 2 to enable CFG Parallel. See more examples in [`user_guide`](../../../docs/user_guide/diffusion/parallelism_acceleration.md#cfg-parallel). +- `--tensor-parallel-size`: tensor parallel size (effective for models that support TP, e.g. LTX2). - `--enable-cpu-offload`: enable CPU offloading for diffusion models. +- `--frame-rate`: generation FPS for pipelines that require it (e.g., LTX2). +- `--audio-sample-rate`: audio sample rate for embedded audio (when the pipeline returns audio). > ℹ️ If you encounter OOM errors, try using `--vae-use-slicing` and `--vae-use-tiling` to reduce memory usage. diff --git a/examples/offline_inference/text_to_video/text_to_video.py b/examples/offline_inference/text_to_video/text_to_video.py index 5db1b73dc..c1efd342e 100644 --- a/examples/offline_inference/text_to_video/text_to_video.py +++ b/examples/offline_inference/text_to_video/text_to_video.py @@ -31,6 +31,12 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--height", type=int, default=720, help="Video height.") parser.add_argument("--width", type=int, default=1280, help="Video width.") parser.add_argument("--num-frames", type=int, default=81, help="Number of frames (Wan default is 81).") + parser.add_argument( + "--frame-rate", + type=float, + default=None, + help="Optional generation frame rate (used by models like LTX2). Defaults to --fps.", + ) parser.add_argument("--num-inference-steps", type=int, default=40, help="Sampling steps.") parser.add_argument( "--boundary-ratio", @@ -109,6 +115,12 @@ def parse_args() -> argparse.Namespace: default=1, help="Number of GPUs used for tensor parallelism (TP) inside the DiT.", ) + parser.add_argument( + "--audio-sample-rate", + type=int, + default=24000, + help="Sample rate for audio output when saved (default: 24000 for LTX2).", + ) parser.add_argument( "--vae-patch-parallel-size", type=int, @@ -121,6 +133,7 @@ def parse_args() -> argparse.Namespace: def main(): args = parse_args() generator = torch.Generator(device=current_omni_platform.device_type).manual_seed(args.seed) + frame_rate = args.frame_rate if args.frame_rate is not None else float(args.fps) # Wan2.2 cache-dit tuning (from cache-dit examples and cache_alignment). cache_config = None @@ -140,8 +153,7 @@ def main(): "scm_steps_mask_policy": None, # SCM mask policy: None (disabled), "slow", "medium", "fast", "ultra" "scm_steps_policy": "dynamic", # SCM steps policy: "dynamic" or "static" } - # Configure parallel settings (only SP is supported for Wan) - # Note: cfg_parallel and tensor_parallel are not implemented for Wan models + # Configure parallel settings parallel_config = DiffusionParallelConfig( ulysses_degree=args.ulysses_degree, ring_degree=args.ring_degree, @@ -160,12 +172,12 @@ def main(): vae_use_tiling=args.vae_use_tiling, boundary_ratio=args.boundary_ratio, flow_shift=args.flow_shift, - cache_backend=args.cache_backend, - cache_config=cache_config, enable_cache_dit_summary=args.enable_cache_dit_summary, enable_cpu_offload=args.enable_cpu_offload, parallel_config=parallel_config, enforce_eager=args.enforce_eager, + cache_backend=args.cache_backend, + cache_config=cache_config, ) if profiler_enabled: @@ -200,6 +212,7 @@ def main(): guidance_scale_2=args.guidance_scale_high, num_inference_steps=args.num_inference_steps, num_frames=args.num_frames, + frame_rate=frame_rate, ), ) generation_end = time.perf_counter() @@ -208,31 +221,56 @@ def main(): # Print profiling results print(f"Total generation time: {generation_time:.4f} seconds ({generation_time * 1000:.2f} ms)") - # Extract video frames from OmniRequestOutput - if isinstance(frames, list) and len(frames) > 0: - first_item = frames[0] + audio = None + if isinstance(frames, list): + frames = frames[0] if frames else None - # Check if it's an OmniRequestOutput - if hasattr(first_item, "final_output_type"): - if first_item.final_output_type != "image": - raise ValueError( - f"Unexpected output type '{first_item.final_output_type}', expected 'image' for video generation." - ) - - # Pipeline mode: extract from nested request_output - if hasattr(first_item, "is_pipeline_output") and first_item.is_pipeline_output: - if isinstance(first_item.request_output, list) and len(first_item.request_output) > 0: - inner_output = first_item.request_output[0] - if isinstance(inner_output, OmniRequestOutput) and hasattr(inner_output, "images"): - frames = inner_output.images[0] if inner_output.images else None - if frames is None: - raise ValueError("No video frames found in output.") - # Diffusion mode: use direct images field - elif hasattr(first_item, "images") and first_item.images: - frames = first_item.images + if isinstance(frames, OmniRequestOutput): + if frames.final_output_type != "image": + raise ValueError( + f"Unexpected output type '{frames.final_output_type}', expected 'image' for video generation." + ) + if frames.multimodal_output and "audio" in frames.multimodal_output: + audio = frames.multimodal_output["audio"] + if frames.is_pipeline_output and frames.request_output is not None: + inner_output = frames.request_output + if isinstance(inner_output, list): + inner_output = inner_output[0] if inner_output else None + if isinstance(inner_output, OmniRequestOutput): + if inner_output.multimodal_output and "audio" in inner_output.multimodal_output: + audio = inner_output.multimodal_output["audio"] + frames = inner_output + if isinstance(frames, OmniRequestOutput): + if frames.images: + if len(frames.images) == 1 and isinstance(frames.images[0], tuple) and len(frames.images[0]) == 2: + frames, audio = frames.images[0] + elif len(frames.images) == 1 and isinstance(frames.images[0], dict): + audio = frames.images[0].get("audio") + frames = frames.images[0].get("frames") or frames.images[0].get("video") + else: + frames = frames.images else: raise ValueError("No video frames found in OmniRequestOutput.") + if isinstance(frames, list) and frames: + first_item = frames[0] + if isinstance(first_item, tuple) and len(first_item) == 2: + frames, audio = first_item + elif isinstance(first_item, dict): + audio = first_item.get("audio") + frames = first_item.get("frames") or first_item.get("video") + elif isinstance(first_item, list): + frames = first_item + + if isinstance(frames, tuple) and len(frames) == 2: + frames, audio = frames + elif isinstance(frames, dict): + audio = frames.get("audio") + frames = frames.get("frames") or frames.get("video") + + if frames is None: + raise ValueError("No video frames found in output.") + output_path = Path(args.output) output_path.parent.mkdir(parents=True, exist_ok=True) try: @@ -240,32 +278,127 @@ def main(): except ImportError: raise ImportError("diffusers is required for export_to_video.") - # frames may be np.ndarray (preferred) or torch.Tensor + def _normalize_frame(frame): + if isinstance(frame, torch.Tensor): + frame_tensor = frame.detach().cpu() + if frame_tensor.dim() == 4 and frame_tensor.shape[0] == 1: + frame_tensor = frame_tensor[0] + if frame_tensor.dim() == 3 and frame_tensor.shape[0] in (3, 4): + frame_tensor = frame_tensor.permute(1, 2, 0) + if frame_tensor.is_floating_point(): + frame_tensor = frame_tensor.clamp(-1, 1) * 0.5 + 0.5 + return frame_tensor.float().numpy() + if isinstance(frame, np.ndarray): + frame_array = frame + if frame_array.ndim == 4 and frame_array.shape[0] == 1: + frame_array = frame_array[0] + if np.issubdtype(frame_array.dtype, np.integer): + frame_array = frame_array.astype(np.float32) / 255.0 + return frame_array + try: + from PIL import Image + except ImportError: + Image = None + if Image is not None and isinstance(frame, Image.Image): + return np.asarray(frame).astype(np.float32) / 255.0 + return frame + + def _ensure_frame_list(video_array): + if isinstance(video_array, list): + if len(video_array) == 0: + return video_array + first_item = video_array[0] + if isinstance(first_item, np.ndarray): + if first_item.ndim == 5: + return list(first_item[0]) + if first_item.ndim == 4: + if len(video_array) == 1: + return list(first_item) + return list(first_item) + if first_item.ndim == 3: + return video_array + return video_array + if isinstance(video_array, np.ndarray): + if video_array.ndim == 5: + return list(video_array[0]) + if video_array.ndim == 4: + return list(video_array) + if video_array.ndim == 3: + return [video_array] + return video_array + + # frames may be np.ndarray, torch.Tensor, or list of tensors/arrays/images # export_to_video expects a list of frames with values in [0, 1] if isinstance(frames, torch.Tensor): video_tensor = frames.detach().cpu() if video_tensor.dim() == 5: - # [B, C, F, H, W] or [B, F, H, W, C] if video_tensor.shape[1] in (3, 4): video_tensor = video_tensor[0].permute(1, 2, 3, 0) else: video_tensor = video_tensor[0] elif video_tensor.dim() == 4 and video_tensor.shape[0] in (3, 4): video_tensor = video_tensor.permute(1, 2, 3, 0) - # If float, assume [-1,1] and normalize to [0,1] if video_tensor.is_floating_point(): video_tensor = video_tensor.clamp(-1, 1) * 0.5 + 0.5 video_array = video_tensor.float().numpy() + elif isinstance(frames, np.ndarray): + video_array = frames + if video_array.ndim == 5: + video_array = video_array[0] + if np.issubdtype(video_array.dtype, np.integer): + video_array = video_array.astype(np.float32) / 255.0 + elif isinstance(frames, list): + if len(frames) == 0: + raise ValueError("No video frames found in output.") + video_array = [_normalize_frame(frame) for frame in frames] else: video_array = frames - if hasattr(video_array, "shape") and video_array.ndim == 5: - video_array = video_array[0] - # Convert 4D array (frames, H, W, C) to list of frames for export_to_video - if isinstance(video_array, np.ndarray) and video_array.ndim == 4: - video_array = list(video_array) + video_array = _ensure_frame_list(video_array) - export_to_video(video_array, str(output_path), fps=args.fps) + use_ltx2_export = False + if args.model and "ltx" in str(args.model).lower(): + use_ltx2_export = True + if audio is not None: + use_ltx2_export = True + + if use_ltx2_export: + try: + from diffusers.pipelines.ltx2.export_utils import encode_video + except ImportError: + raise ImportError("diffusers is required for LTX2 encode_video.") + + if isinstance(video_array, list): + frames_np = np.stack(video_array, axis=0) + elif isinstance(video_array, np.ndarray): + frames_np = video_array + else: + frames_np = np.asarray(video_array) + + frames_u8 = (frames_np * 255).round().clip(0, 255).astype("uint8") + video_tensor = torch.from_numpy(frames_u8) + + audio_out = None + if audio is not None: + if isinstance(audio, list): + audio = audio[0] if audio else None + if isinstance(audio, np.ndarray): + audio = torch.from_numpy(audio) + if isinstance(audio, torch.Tensor): + audio_out = audio + if audio_out.dim() > 1: + audio_out = audio_out[0] + audio_out = audio_out.float().cpu() + + encode_video( + video_tensor, + fps=args.fps, + audio=audio_out, + audio_sample_rate=args.audio_sample_rate if audio_out is not None else None, + output_path=str(output_path), + ) + else: + export_to_video(video_array, str(output_path), fps=args.fps) print(f"Saved generated video to {output_path}") if profiler_enabled: diff --git a/examples/online_serving/qwen3_tts/README.md b/examples/online_serving/qwen3_tts/README.md index d50baa289..2046c6508 100644 --- a/examples/online_serving/qwen3_tts/README.md +++ b/examples/online_serving/qwen3_tts/README.md @@ -250,6 +250,7 @@ Returns binary audio data with appropriate `Content-Type` header (e.g., `audio/w | `language` | string | "Auto" | Language (see supported languages below) | | `instructions` | string | "" | Voice style/emotion instructions | | `max_new_tokens` | int | 2048 | Maximum tokens to generate | +| `initial_codec_chunk_frames` | int | null | Initial chunk size for reduced TTFA (overrides stage config) | | `stream` | bool | false | Stream raw PCM chunks as they are decoded (requires `response_format="pcm"`) | **Supported languages:** Auto, Chinese, English, Japanese, Korean, German, French, Russian, Portuguese, Spanish, Italian @@ -265,7 +266,7 @@ Returns binary audio data with appropriate `Content-Type` header (e.g., `audio/w ## Streaming Set `stream=true` with `response_format="pcm"` to receive raw PCM audio chunks as they are decoded -(one chunk per 25-frame Code2Wav window): +(one chunk per Code2Wav window, default 25 frames; configurable in the stage config): ```bash curl -X POST http://localhost:8091/v1/audio/speech \ diff --git a/tests/diffusion/models/bagel/__init__.py b/tests/diffusion/models/bagel/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/diffusion/models/bagel/test_combine_cfg.py b/tests/diffusion/models/bagel/test_combine_cfg.py new file mode 100644 index 000000000..88611fdc4 --- /dev/null +++ b/tests/diffusion/models/bagel/test_combine_cfg.py @@ -0,0 +1,316 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Unit tests for Bagel._combine_cfg logic.""" + +import pytest +import torch + +from vllm_omni.diffusion.models.bagel.bagel_transformer import Bagel + +pytestmark = [pytest.mark.core_model, pytest.mark.cpu] + + +class TestCombineCfg: + """Tests for the _combine_cfg static method.""" + + def _make_tensors(self, shape=(10, 64), seed=42): + """Create deterministic test tensors.""" + gen = torch.Generator().manual_seed(seed) + v_t = torch.randn(shape, generator=gen) + cfg_text_v_t = torch.randn(shape, generator=gen) + cfg_img_v_t = torch.randn(shape, generator=gen) + return v_t, cfg_text_v_t, cfg_img_v_t + + def test_text_channel_renorm_preserves_direction(self): + """text_channel renorm should change direction but constrain magnitude.""" + v_t, cfg_text_v_t, _ = self._make_tensors() + + result = Bagel._combine_cfg( + v_t, + cfg_text_v_t, + None, + cfg_text_scale=4.0, + cfg_img_scale=1.0, + cfg_renorm_type="text_channel", + cfg_renorm_min=0.0, + ) + + # Result norm per token should be <= original v_t norm (clamp max=1.0) + result_norm = torch.norm(result, dim=-1) + v_t_norm = torch.norm(v_t, dim=-1) + assert torch.all(result_norm <= v_t_norm + 1e-6), "text_channel renorm should not increase per-token norm" + + def test_scale_1_returns_v_t(self): + """cfg_text_scale=1.0 means no CFG: result should equal v_t.""" + v_t, cfg_text_v_t, _ = self._make_tensors() + + result = Bagel._combine_cfg( + v_t, + cfg_text_v_t, + None, + cfg_text_scale=1.0, + cfg_img_scale=1.0, + cfg_renorm_type="text_channel", + cfg_renorm_min=0.0, + ) + + # scale=1 → v_t_text_ = cfg_text + 1*(v_t - cfg_text) = v_t + # renorm scale = norm(v_t)/norm(v_t) = 1.0, so result = v_t + assert torch.allclose(result, v_t, atol=1e-6) + + def test_img_cfg_applied_when_scale_gt_1(self): + """When cfg_img_scale > 1.0, result should differ from text-only CFG.""" + v_t, cfg_text_v_t, cfg_img_v_t = self._make_tensors() + + text_only = Bagel._combine_cfg( + v_t, + cfg_text_v_t, + None, + cfg_text_scale=4.0, + cfg_img_scale=1.0, + cfg_renorm_type="text_channel", + cfg_renorm_min=0.0, + ) + + with_img = Bagel._combine_cfg( + v_t, + cfg_text_v_t, + cfg_img_v_t, + cfg_text_scale=4.0, + cfg_img_scale=1.5, + cfg_renorm_type="text_channel", + cfg_renorm_min=0.0, + ) + + assert not torch.allclose(text_only, with_img, atol=1e-6), ( + "Image CFG should produce different result from text-only CFG" + ) + + def test_img_cfg_none_ignored(self): + """cfg_img_v_t=None should be equivalent to cfg_img_scale <= 1.0.""" + v_t, cfg_text_v_t, cfg_img_v_t = self._make_tensors() + + result_none = Bagel._combine_cfg( + v_t, + cfg_text_v_t, + None, + cfg_text_scale=4.0, + cfg_img_scale=1.5, + cfg_renorm_type="text_channel", + cfg_renorm_min=0.0, + ) + + result_low_scale = Bagel._combine_cfg( + v_t, + cfg_text_v_t, + cfg_img_v_t, + cfg_text_scale=4.0, + cfg_img_scale=0.5, + cfg_renorm_type="text_channel", + cfg_renorm_min=0.0, + ) + + assert torch.allclose(result_none, result_low_scale, atol=1e-6), ( + "cfg_img_v_t=None and cfg_img_scale<=1.0 should give same result" + ) + + def test_global_renorm(self): + """global renorm should produce valid output without error.""" + v_t, cfg_text_v_t, cfg_img_v_t = self._make_tensors() + + result = Bagel._combine_cfg( + v_t, + cfg_text_v_t, + cfg_img_v_t, + cfg_text_scale=4.0, + cfg_img_scale=1.5, + cfg_renorm_type="global", + cfg_renorm_min=0.0, + ) + + assert result.shape == v_t.shape + assert not torch.any(torch.isnan(result)) + + def test_channel_renorm(self): + """channel renorm should produce valid output without error.""" + v_t, cfg_text_v_t, cfg_img_v_t = self._make_tensors() + + result = Bagel._combine_cfg( + v_t, + cfg_text_v_t, + cfg_img_v_t, + cfg_text_scale=4.0, + cfg_img_scale=1.5, + cfg_renorm_type="channel", + cfg_renorm_min=0.0, + ) + + assert result.shape == v_t.shape + assert not torch.any(torch.isnan(result)) + + def test_invalid_renorm_type_raises(self): + """Unknown renorm type should raise NotImplementedError.""" + v_t, cfg_text_v_t, _ = self._make_tensors() + + with pytest.raises(NotImplementedError): + Bagel._combine_cfg( + v_t, + cfg_text_v_t, + None, + cfg_text_scale=4.0, + cfg_img_scale=1.0, + cfg_renorm_type="unknown", + cfg_renorm_min=0.0, + ) + + def test_renorm_min_clamps_scale(self): + """cfg_renorm_min should prevent scale from going too low.""" + v_t = torch.ones(10, 64) + # Make cfg_text_v_t very different so CFG amplifies heavily + cfg_text_v_t = torch.zeros(10, 64) + + result_no_min = Bagel._combine_cfg( + v_t, + cfg_text_v_t, + None, + cfg_text_scale=100.0, + cfg_img_scale=1.0, + cfg_renorm_type="text_channel", + cfg_renorm_min=0.0, + ) + + result_with_min = Bagel._combine_cfg( + v_t, + cfg_text_v_t, + None, + cfg_text_scale=100.0, + cfg_img_scale=1.0, + cfg_renorm_type="text_channel", + cfg_renorm_min=0.5, + ) + + # With higher renorm_min, result magnitude should be larger + # (scale is clamped to at least 0.5 instead of going near 0) + norm_no_min = torch.norm(result_no_min) + norm_with_min = torch.norm(result_with_min) + assert norm_with_min >= norm_no_min - 1e-6, "Higher cfg_renorm_min should preserve more magnitude" + + def test_global_renorm_with_img_cfg(self): + """global renorm + img CFG should produce valid, different output.""" + v_t, cfg_text_v_t, cfg_img_v_t = self._make_tensors() + + text_only = Bagel._combine_cfg( + v_t.clone(), + cfg_text_v_t.clone(), + None, + cfg_text_scale=4.0, + cfg_img_scale=1.0, + cfg_renorm_type="global", + cfg_renorm_min=0.0, + ) + + with_img = Bagel._combine_cfg( + v_t.clone(), + cfg_text_v_t.clone(), + cfg_img_v_t.clone(), + cfg_text_scale=4.0, + cfg_img_scale=1.5, + cfg_renorm_type="global", + cfg_renorm_min=0.0, + ) + + assert not torch.allclose(text_only, with_img, atol=1e-6), ( + "global renorm + img CFG should differ from text-only" + ) + assert not torch.any(torch.isnan(with_img)) + + def test_channel_renorm_with_img_cfg(self): + """channel renorm + img CFG should produce valid, different output.""" + v_t, cfg_text_v_t, cfg_img_v_t = self._make_tensors() + + text_only = Bagel._combine_cfg( + v_t.clone(), + cfg_text_v_t.clone(), + None, + cfg_text_scale=4.0, + cfg_img_scale=1.0, + cfg_renorm_type="channel", + cfg_renorm_min=0.0, + ) + + with_img = Bagel._combine_cfg( + v_t.clone(), + cfg_text_v_t.clone(), + cfg_img_v_t.clone(), + cfg_text_scale=4.0, + cfg_img_scale=1.5, + cfg_renorm_type="channel", + cfg_renorm_min=0.0, + ) + + assert not torch.allclose(text_only, with_img, atol=1e-6), ( + "channel renorm + img CFG should differ from text-only" + ) + assert not torch.any(torch.isnan(with_img)) + + def test_global_channel_renorm_constrains_norm(self): + """global and channel renorm should not increase overall norm.""" + v_t, cfg_text_v_t, cfg_img_v_t = self._make_tensors() + + for renorm_type in ["global", "channel"]: + result = Bagel._combine_cfg( + v_t.clone(), + cfg_text_v_t.clone(), + cfg_img_v_t.clone(), + cfg_text_scale=4.0, + cfg_img_scale=1.5, + cfg_renorm_type=renorm_type, + cfg_renorm_min=0.0, + ) + # Global norm of result should be <= global norm of v_t (clamp max=1.0) + assert torch.norm(result) <= torch.norm(v_t) + 1e-5, f"{renorm_type} renorm should not increase global norm" + + def test_text_channel_img_cfg_no_second_renorm(self): + """text_channel mode: img CFG is applied AFTER renorm, without a second renorm. + So the result norm can exceed v_t norm when img_scale > 1.""" + v_t, cfg_text_v_t, cfg_img_v_t = self._make_tensors() + + result = Bagel._combine_cfg( + v_t, + cfg_text_v_t, + cfg_img_v_t, + cfg_text_scale=4.0, + cfg_img_scale=2.0, + cfg_renorm_type="text_channel", + cfg_renorm_min=0.0, + ) + + # text_channel renorms after text CFG, then applies img CFG without renorm + # So result norm CAN exceed v_t norm — this is expected behavior + assert result.shape == v_t.shape + assert not torch.any(torch.isnan(result)) + + def test_all_renorm_types_consistent_direction(self): + """All renorm types should guide in the same general direction.""" + v_t, cfg_text_v_t, _ = self._make_tensors() + + results = {} + for renorm_type in ["text_channel", "global", "channel"]: + results[renorm_type] = Bagel._combine_cfg( + v_t.clone(), + cfg_text_v_t.clone(), + None, + cfg_text_scale=4.0, + cfg_img_scale=1.0, + cfg_renorm_type=renorm_type, + cfg_renorm_min=0.0, + ) + + # All results should have positive cosine similarity with each other + for a_name, a in results.items(): + for b_name, b in results.items(): + cos_sim = torch.nn.functional.cosine_similarity(a.flatten().unsqueeze(0), b.flatten().unsqueeze(0)) + assert cos_sim > 0.5, ( + f"{a_name} and {b_name} should point in similar direction, " + f"but cosine similarity = {cos_sim.item():.4f}" + ) diff --git a/tests/e2e/online_serving/test_qwen3_tts_base.py b/tests/e2e/online_serving/test_qwen3_tts_base.py new file mode 100644 index 000000000..9dd662f08 --- /dev/null +++ b/tests/e2e/online_serving/test_qwen3_tts_base.py @@ -0,0 +1,167 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +""" +E2E tests for Qwen3-TTS Base voice-clone model. + +Regression test for #1663: speech tokenizer loaded in bfloat16 produced +all-silence PCM due to NaN overflow in SnakeBeta activation. +""" + +import os + +os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" +os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0" + +import struct +import tempfile +from pathlib import Path + +import httpx +import pytest + +from tests.conftest import ( + OmniServer, + convert_audio_file_to_text, + cosine_similarity_text, +) +from tests.utils import hardware_test + +MODEL = "Qwen/Qwen3-TTS-12Hz-1.7B-Base" + +# Official Qwen3-TTS reference audio/text from examples/offline_inference/qwen3_tts/end2end.py +REF_AUDIO_URL = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen3-TTS-Repo/clone_2.wav" +REF_TEXT = "Okay. Yeah. I resent you. I love you. I respect you. But you know what? You blew it! And thanks to you." +SYN_TEXT = "Good one. Okay, fine, I'm just gonna leave this sock monkey here. Goodbye." + + +def get_stage_config(): + return str( + Path(__file__).parent.parent.parent.parent / "vllm_omni" / "model_executor" / "stage_configs" / "qwen3_tts.yaml" + ) + + +@pytest.fixture(scope="module") +def omni_server(): + """Start vLLM-Omni server with Base voice-clone model.""" + stage_config_path = get_stage_config() + + with OmniServer( + MODEL, + [ + "--stage-configs-path", + stage_config_path, + "--stage-init-timeout", + "120", + "--trust-remote-code", + "--enforce-eager", + "--disable-log-stats", + ], + ) as server: + yield server + + +def make_base_speech_request( + host: str, + port: int, + text: str = SYN_TEXT, + ref_text: str = REF_TEXT, + ref_audio: str = REF_AUDIO_URL, + response_format: str = "wav", + timeout: float = 120.0, +) -> httpx.Response: + url = f"http://{host}:{port}/v1/audio/speech" + payload = { + "model": MODEL, + "input": text, + "task_type": "Base", + "ref_text": ref_text, + "ref_audio": ref_audio, + "response_format": response_format, + } + with httpx.Client(timeout=timeout) as client: + return client.post(url, json=payload) + + +def verify_wav_audio(content: bytes) -> bool: + if len(content) < 44: + return False + return content[:4] == b"RIFF" and content[8:12] == b"WAVE" + + +def assert_not_silence(pcm_bytes: bytes): + """Assert PCM16 samples are not all identical (e.g. all-silence).""" + samples = struct.unpack(f"<{len(pcm_bytes) // 2}h", pcm_bytes) + unique = set(samples) + assert len(unique) > 1, ( + f"All-silence detected: {len(samples)} samples, unique values: {unique}. " + "See https://github.com/vllm-project/vllm-omni/issues/1663" + ) + + +MIN_AUDIO_BYTES = 10000 + + +class TestQwen3TTSBaseVoiceClone: + """Regression tests for Base voice-clone (fix #1663).""" + + @pytest.mark.core_model + @pytest.mark.omni + @hardware_test(res={"cuda": "L4"}, num_cards=4) + def test_base_voice_clone_not_silence(self, omni_server) -> None: + """PCM output must contain real audio, not all-silence.""" + response = make_base_speech_request( + host=omni_server.host, + port=omni_server.port, + response_format="pcm", + ) + + assert response.status_code == 200, f"Request failed: {response.text}" + assert len(response.content) > MIN_AUDIO_BYTES, f"Audio too small: {len(response.content)} bytes" + assert_not_silence(response.content) + + @pytest.mark.core_model + @pytest.mark.omni + @hardware_test(res={"cuda": "L4"}, num_cards=4) + def test_base_voice_clone_whisper_transcription(self, omni_server) -> None: + """Whisper must transcribe the output as intelligible speech.""" + response = make_base_speech_request( + host=omni_server.host, + port=omni_server.port, + response_format="wav", + ) + + assert response.status_code == 200, f"Request failed: {response.text}" + assert verify_wav_audio(response.content), "Response is not valid WAV" + assert len(response.content) > MIN_AUDIO_BYTES + + with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f: + f.write(response.content) + wav_path = f.name + + try: + transcript = convert_audio_file_to_text(wav_path) + print(f"Whisper transcript: {transcript}") + assert len(transcript.strip()) > 0, "Whisper returned empty transcript — audio is likely silence" + similarity = cosine_similarity_text(transcript.lower(), SYN_TEXT.lower()) + print(f"Cosine similarity: {similarity:.3f}") + assert similarity > 0.9, ( + f"Transcript doesn't match input: similarity={similarity:.2f}, transcript='{transcript}'" + ) + finally: + os.unlink(wav_path) + + @pytest.mark.core_model + @pytest.mark.omni + @hardware_test(res={"cuda": "L4"}, num_cards=4) + def test_base_voice_clone_wav_format(self, omni_server) -> None: + """WAV response must have valid headers and sufficient size.""" + response = make_base_speech_request( + host=omni_server.host, + port=omni_server.port, + response_format="wav", + ) + + assert response.status_code == 200, f"Request failed: {response.text}" + assert response.headers.get("content-type") == "audio/wav" + assert verify_wav_audio(response.content), "Response is not valid WAV" + assert len(response.content) > MIN_AUDIO_BYTES diff --git a/tests/entrypoints/openai_api/test_video_server.py b/tests/entrypoints/openai_api/test_video_server.py index dc9414a67..307780309 100644 --- a/tests/entrypoints/openai_api/test_video_server.py +++ b/tests/entrypoints/openai_api/test_video_server.py @@ -5,6 +5,7 @@ Unit tests for OpenAI-compatible video generation endpoints. """ import io +from types import SimpleNamespace import pytest from fastapi import FastAPI @@ -21,8 +22,12 @@ pytestmark = [pytest.mark.core_model, pytest.mark.cpu] class MockVideoResult: - def __init__(self, videos): + def __init__(self, videos, audios=None, sample_rate=None): self.multimodal_output = {"video": videos} + if audios is not None: + self.multimodal_output["audio"] = audios + if sample_rate is not None: + self.multimodal_output["audio_sample_rate"] = sample_rate class FakeAsyncOmni: @@ -91,6 +96,7 @@ def test_t2v_video_generation_form(test_client, mocker: MockerFixture): assert captured.height == 360 assert captured.num_frames == 24 assert captured.fps == 12 + assert captured.frame_rate == 12.0 assert fps_values == [12, 12] @@ -121,6 +127,32 @@ def test_i2v_video_generation_form(test_client, mocker: MockerFixture): assert input_image.size == (48, 32) +def test_i2v_video_generation_resizes_input_to_requested_dimensions(test_client, mocker: MockerFixture): + image_bytes = _make_test_image_bytes((48, 32)) + + mocker.patch( + "vllm_omni.entrypoints.openai.serving_video.encode_video_base64", + return_value="Zg==", + ) + response = test_client.post( + "/v1/videos", + data={ + "prompt": "A bear playing with yarn.", + "width": "96", + "height": "64", + }, + files={"input_reference": ("input.png", image_bytes, "image/png")}, + ) + + assert response.status_code == 200 + + engine = test_client.app.state.openai_serving_video._engine_client + prompt = engine.captured_prompt + input_image = prompt["multi_modal_data"]["image"] + assert isinstance(input_image, Image.Image) + assert input_image.size == (96, 64) + + def test_seconds_defaults_fps_and_frames(test_client, mocker: MockerFixture): fps_values = [] @@ -168,6 +200,42 @@ def test_size_param_sets_width_height(test_client, mocker: MockerFixture): assert captured.height == 240 +def test_audio_sample_rate_comes_from_model_config(test_client, mocker: MockerFixture): + audio_sample_rates = [] + + def _fake_encode(video, fps, audio=None, audio_sample_rate=None): + audio_sample_rates.append(audio_sample_rate) + return "Zg==" + + engine = test_client.app.state.openai_serving_video._engine_client + engine.model_config = SimpleNamespace( + hf_config=SimpleNamespace( + vocoder=SimpleNamespace( + config=SimpleNamespace(output_sampling_rate=16000), + ), + ), + ) + + async def _generate(prompt, request_id, sampling_params_list): + engine.captured_prompt = prompt + engine.captured_sampling_params_list = sampling_params_list + yield MockVideoResult([object()], audios=[object()]) + + engine.generate = _generate + + mocker.patch( + "vllm_omni.entrypoints.openai.serving_video.encode_video_base64", + side_effect=_fake_encode, + ) + response = test_client.post( + "/v1/videos", + data={"prompt": "video with audio"}, + ) + + assert response.status_code == 200 + assert audio_sample_rates == [16000] + + def test_sampling_params_pass_through(test_client, mocker: MockerFixture): mocker.patch( "vllm_omni.entrypoints.openai.serving_video.encode_video_base64", diff --git a/tests/model_executor/test_cosyvoice3_components.py b/tests/model_executor/models/cosyvoice3/test_cosyvoice3_components.py similarity index 100% rename from tests/model_executor/test_cosyvoice3_components.py rename to tests/model_executor/models/cosyvoice3/test_cosyvoice3_components.py diff --git a/tests/model_executor/test_cosyvoice3_utils.py b/tests/model_executor/models/cosyvoice3/test_cosyvoice3_utils.py similarity index 100% rename from tests/model_executor/test_cosyvoice3_utils.py rename to tests/model_executor/models/cosyvoice3/test_cosyvoice3_utils.py diff --git a/tests/model_executor/stage_input_processors/test_qwen3_tts_async_chunk.py b/tests/model_executor/stage_input_processors/test_qwen3_tts_async_chunk.py index e29b6af82..15464032b 100644 --- a/tests/model_executor/stage_input_processors/test_qwen3_tts_async_chunk.py +++ b/tests/model_executor/stage_input_processors/test_qwen3_tts_async_chunk.py @@ -4,27 +4,60 @@ from collections import defaultdict from types import SimpleNamespace +import pytest import torch from vllm_omni.model_executor.stage_input_processors.qwen3_tts import talker2code2wav_async_chunk +_FRAME = [1, 2, 3, 4] # 4-codebook frame +_Q = len(_FRAME) # num quantizers -def _req(external_req_id: str, *, finished: bool): + +def _req(rid: str, *, finished: bool, initial_codec_chunk_frames: int | None = None): + ai = None + if initial_codec_chunk_frames is not None: + entry = SimpleNamespace(list_data=[initial_codec_chunk_frames]) + ai = SimpleNamespace(entries={"initial_codec_chunk_frames": entry}) return SimpleNamespace( - external_req_id=external_req_id, + external_req_id=rid, is_finished=lambda: finished, + additional_information=ai, ) -def test_talker2code2wav_async_chunk_does_not_emit_empty_chunk_when_not_finished(): - transfer_manager = SimpleNamespace( +def _tm(*, chunk_frames=25, left_context=25, initial_chunk=0): + return SimpleNamespace( code_prompt_token_ids=defaultdict(list), - connector=SimpleNamespace(config={"extra": {"codec_chunk_frames": 25, "codec_left_context_frames": 25}}), + put_req_chunk=defaultdict(int), + connector=SimpleNamespace( + config={ + "extra": { + "codec_chunk_frames": chunk_frames, + "codec_left_context_frames": left_context, + "initial_codec_chunk_frames": initial_chunk, + } + } + ), ) + + +def _call(tm, rid, *, n_frames, put_req=0, finished=False, req_ic=None): + tm.code_prompt_token_ids[rid] = [_FRAME[:] for _ in range(n_frames)] + tm.put_req_chunk[rid] = put_req + return talker2code2wav_async_chunk( + transfer_manager=tm, + pooling_output={"audio_codes": torch.zeros((0,))}, + request=_req(rid, finished=finished, initial_codec_chunk_frames=req_ic), + is_finished=finished, + ) + + +def test_does_not_emit_empty_chunk_when_not_finished(): + tm = _tm() request = _req("rid-empty", finished=False) payload = talker2code2wav_async_chunk( - transfer_manager=transfer_manager, + transfer_manager=tm, pooling_output={"audio_codes": torch.zeros((0,))}, request=request, ) @@ -32,36 +65,29 @@ def test_talker2code2wav_async_chunk_does_not_emit_empty_chunk_when_not_finished assert payload is None -def test_talker2code2wav_async_chunk_flushes_tail_when_finished_without_pooler_output(): - transfer_manager = SimpleNamespace( - code_prompt_token_ids=defaultdict(list), - connector=SimpleNamespace(config={"extra": {"codec_chunk_frames": 25, "codec_left_context_frames": 25}}), - ) - request_id = "rid-tail" - transfer_manager.code_prompt_token_ids[request_id] = [[1, 2, 3, 4] for _ in range(24)] - request = _req(request_id, finished=True) +def test_flushes_tail_when_finished_without_pooler_output(): + tm = _tm() + rid = "rid-tail" + tm.code_prompt_token_ids[rid] = [_FRAME[:] for _ in range(24)] + request = _req(rid, finished=True) payload = talker2code2wav_async_chunk( - transfer_manager=transfer_manager, - pooling_output=None, # e.g. EOS step with no audio_codes + transfer_manager=tm, + pooling_output=None, request=request, ) assert payload is not None assert payload["finished"].item() is True - # ctx_frames header + flat codes - assert len(payload["code_predictor_codes"]) == 1 + 4 * 24 + assert len(payload["code_predictor_codes"]) == _Q * 24 -def test_talker2code2wav_async_chunk_emits_eof_marker_when_finished_with_no_frames(): - transfer_manager = SimpleNamespace( - code_prompt_token_ids=defaultdict(list), - connector=SimpleNamespace(config={"extra": {"codec_chunk_frames": 25, "codec_left_context_frames": 25}}), - ) +def test_emits_eof_marker_when_finished_with_no_frames(): + tm = _tm() request = _req("rid-eof", finished=True) payload = talker2code2wav_async_chunk( - transfer_manager=transfer_manager, + transfer_manager=tm, pooling_output=None, request=request, ) @@ -70,3 +96,59 @@ def test_talker2code2wav_async_chunk_emits_eof_marker_when_finished_with_no_fram "code_predictor_codes": [], "finished": torch.tensor(True, dtype=torch.bool), } + + +_CASES = [ + # Normal path (initial=0): emit at chunk_size boundaries + ((25, 25, 0), (24, 0, False), None), + ((25, 25, 0), (25, 0, False), (0, 25)), + # Initial-chunk phase: hold, first emit, second emit + ((25, 25, 10), (9, 0, False), None), + ((25, 25, 10), (10, 0, False), (0, 10)), + ((25, 25, 10), (20, 1, False), (10, 20)), + # Non-divisible: holds at chunk boundary + ((25, 25, 12), (25, 2, False), None), + # Normal phase: offset by initial_coverage (chunk//initial * initial) + ((25, 25, 10), (45, 2, False), (20, 45)), + # Second normal emit (offset must stay stable) + ((25, 25, 10), (70, 3, False), (25, 50)), + # initial >= chunk clamps to chunk_size (behaves as normal) + ((25, 25, 30), (25, 0, False), (0, 25)), + # finished=True flushes IC tail + ((25, 25, 10), (5, 0, True), (0, 5)), + # finished=True flushes non-divisible IC residual + ((25, 25, 12), (25, 2, True), (24, 25)), + # finished=True flushes normal phase tail + ((25, 25, 10), (30, 2, True), (20, 30)), +] + + +@pytest.mark.parametrize("config, state, expected", _CASES) +def test_streaming_decoding_with_variable_initial(config, state, expected): + chunk_frames, left_context, initial_chunk = config + n_frames, put_req, finished = state + + tm = _tm(chunk_frames=chunk_frames, left_context=left_context, initial_chunk=initial_chunk) + payload = _call(tm, "r", n_frames=n_frames, put_req=put_req, finished=finished) + + if expected is None: + assert payload is None + else: + exp_ctx, exp_window = expected + assert payload is not None + assert payload["left_context_size"] == exp_ctx + assert len(payload["code_predictor_codes"]) == _Q * exp_window + + +def test_per_request_override_activates_initial_phase(): + tm = _tm(initial_chunk=0) + payload = _call(tm, "r-override", n_frames=10, req_ic=10) + assert payload is not None + assert payload["left_context_size"] == 0 + assert len(payload["code_predictor_codes"]) == _Q * 10 + + +def test_per_request_override_wins_over_stage_config(): + tm = _tm(initial_chunk=5) + payload = _call(tm, "r-override2", n_frames=10, put_req=0, req_ic=15) + assert payload is None diff --git a/tests/perf/tests/test.json b/tests/perf/tests/test.json index c2cc801b2..88041c119 100644 --- a/tests/perf/tests/test.json +++ b/tests/perf/tests/test.json @@ -10,13 +10,11 @@ "dataset_name": "random", "num_prompts": [ 10, - 40, - 100 + 40 ], "max_concurrency": [ 1, - 4, - 10 + 4 ], "random_input_len": 100, "random_output_len": 100, @@ -32,13 +30,11 @@ "dataset_name": "random-mm", "num_prompts": [ 10, - 40, - 100 + 40 ], "max_concurrency": [ 1, - 4, - 10 + 4 ], "random_input_len": 100, "random_output_len": 100, @@ -94,13 +90,11 @@ "dataset_name": "random", "num_prompts": [ 10, - 40, - 100 + 40 ], "max_concurrency": [ 1, - 4, - 10 + 4 ], "random_input_len": 100, "random_output_len": 100, @@ -116,13 +110,11 @@ "dataset_name": "random-mm", "num_prompts": [ 10, - 40, - 100 + 40 ], "max_concurrency": [ 1, - 4, - 10 + 4 ], "random_input_len": 100, "random_output_len": 100, diff --git a/vllm_omni/config/model.py b/vllm_omni/config/model.py index 9f3a0fe17..fa5483b31 100644 --- a/vllm_omni/config/model.py +++ b/vllm_omni/config/model.py @@ -34,6 +34,8 @@ class OmniModelConfig(ModelConfig): "audio", "latents"). If None, output type is inferred. stage_connector_config: Stage connector configuration dictionary. Contains "name" (connector name), "extra" (extra connector config). + task_type: Default task type for TTS models (CustomVoice, VoiceDesign, or Base). + If not specified, will be inferred from model path. Example: >>> config = OmniModelConfig( @@ -59,6 +61,7 @@ class OmniModelConfig(ModelConfig): ) omni_kv_config: dict | None = None codec_frame_rate_hz: float | None = None + task_type: str | None = None @property def registry(self): diff --git a/vllm_omni/diffusion/cache/cache_dit_backend.py b/vllm_omni/diffusion/cache/cache_dit_backend.py index f014d073e..5008a8fa3 100644 --- a/vllm_omni/diffusion/cache/cache_dit_backend.py +++ b/vllm_omni/diffusion/cache/cache_dit_backend.py @@ -414,6 +414,60 @@ def enable_cache_for_sd3(pipeline: Any, cache_config: Any) -> Callable[[int], No return refresh_cache_context +def enable_cache_for_ltx2(pipeline: Any, cache_config: Any) -> Callable[[int], None]: + """Enable cache-dit for LTX2 pipelines (audio-video transformer blocks).""" + transformer = pipeline.transformer + + db_cache_config = _build_db_cache_config(cache_config) + + calibrator_config = None + if cache_config.enable_taylorseer: + taylorseer_order = cache_config.taylorseer_order + calibrator_config = TaylorSeerCalibratorConfig(taylorseer_order=taylorseer_order) + logger.info(f"TaylorSeer enabled with order={taylorseer_order}") + + blocks = transformer.transformer_blocks + + logger.info( + f"Enabling cache-dit on LTX2 transformer: " + f"Fn={db_cache_config.Fn_compute_blocks}, " + f"Bn={db_cache_config.Bn_compute_blocks}, " + f"W={db_cache_config.max_warmup_steps}, " + ) + + cache_dit.enable_cache( + BlockAdapter( + transformer=transformer, + blocks=blocks, + # LTX2 blocks return (hidden_states, audio_hidden_states) + forward_pattern=ForwardPattern.Pattern_0, + # Treat audio_hidden_states as encoder_hidden_states in Pattern_0 + check_forward_pattern=False, + ), + cache_config=db_cache_config, + calibrator_config=calibrator_config, + ) + + def refresh_cache_context(pipeline: Any, num_inference_steps: int, verbose: bool = True) -> None: + if cache_config.scm_steps_mask_policy is None: + cache_dit.refresh_context(pipeline.transformer, num_inference_steps=num_inference_steps, verbose=verbose) + else: + cache_dit.refresh_context( + pipeline.transformer, + cache_config=DBCacheConfig().reset( + num_inference_steps=num_inference_steps, + steps_computation_mask=cache_dit.steps_mask( + mask_policy=cache_config.scm_steps_mask_policy, + total_steps=num_inference_steps, + ), + steps_computation_policy=cache_config.scm_steps_policy, + ), + verbose=verbose, + ) + + return refresh_cache_context + + def enable_cache_for_dit(pipeline: Any, cache_config: Any) -> Callable[[int], None]: """Enable cache-dit for regular single-transformer DiT models. @@ -862,6 +916,8 @@ CUSTOM_DIT_ENABLERS.update( "LongCatImagePipeline": enable_cache_for_longcat_image, "LongCatImageEditPipeline": enable_cache_for_longcat_image, "StableDiffusion3Pipeline": enable_cache_for_sd3, + "LTX2Pipeline": enable_cache_for_ltx2, + "LTX2ImageToVideoPipeline": enable_cache_for_ltx2, "BagelPipeline": enable_cache_for_bagel, } ) diff --git a/vllm_omni/diffusion/data.py b/vllm_omni/diffusion/data.py index bd5af2263..da68adbdb 100644 --- a/vllm_omni/diffusion/data.py +++ b/vllm_omni/diffusion/data.py @@ -77,7 +77,9 @@ class DiffusionParallelConfig: assert self.ulysses_degree > 0, "Ulysses degree must be > 0" assert self.ring_degree > 0, "Ring degree must be > 0" assert self.cfg_parallel_size > 0, "CFG parallel size must be > 0" - assert self.cfg_parallel_size in [1, 2], f"CFG parallel size must be 1 or 2, but got {self.cfg_parallel_size}" + assert self.cfg_parallel_size in [1, 2, 3], ( + f"CFG parallel size must be 1, 2, or 3, but got {self.cfg_parallel_size}" + ) assert self.vae_patch_parallel_size > 0, "VAE patch parallel size must be > 0" assert self.sequence_parallel_size == self.ulysses_degree * self.ring_degree, ( "Sequence parallel size must be equal to the product of ulysses degree and ring degree," diff --git a/vllm_omni/diffusion/diffusion_engine.py b/vllm_omni/diffusion/diffusion_engine.py index 8e4a9f7a2..066ba2bb8 100644 --- a/vllm_omni/diffusion/diffusion_engine.py +++ b/vllm_omni/diffusion/diffusion_engine.py @@ -94,6 +94,10 @@ class DiffusionEngine: postprocess_start_time = time.time() outputs = self.post_process_func(output.output) if self.post_process_func is not None else output.output + audio_payload = None + if isinstance(outputs, dict): + audio_payload = outputs.get("audio") + outputs = outputs.get("video", outputs) postprocess_time = time.time() - postprocess_start_time logger.info(f"Post-processing completed in {postprocess_time:.4f} seconds") @@ -117,7 +121,7 @@ class DiffusionEngine: request_id = request.request_ids[0] if request.request_ids else "" if supports_audio_output(self.od_config.model_class_name): - audio_payload = outputs[0] if len(outputs) == 1 else outputs + request_audio_payload = outputs[0] if len(outputs) == 1 else outputs return [ OmniRequestOutput.from_diffusion( request_id=request_id, @@ -125,11 +129,14 @@ class DiffusionEngine: prompt=prompt, metrics=metrics, latents=output.trajectory_latents, - multimodal_output={"audio": audio_payload}, + multimodal_output={"audio": request_audio_payload}, final_output_type="audio", ), ] else: + mm_output = {} + if audio_payload is not None: + mm_output["audio"] = audio_payload return [ OmniRequestOutput.from_diffusion( request_id=request_id, @@ -137,6 +144,7 @@ class DiffusionEngine: prompt=prompt, metrics=metrics, latents=output.trajectory_latents, + multimodal_output=mm_output, ), ] else: @@ -150,11 +158,13 @@ class DiffusionEngine: # Get images for this request num_outputs = request.sampling_params.num_outputs_per_prompt - request_outputs = outputs[output_idx : output_idx + num_outputs] if output_idx < len(outputs) else [] - output_idx += num_outputs + start_idx = output_idx + end_idx = start_idx + num_outputs + request_outputs = outputs[start_idx:end_idx] if output_idx < len(outputs) else [] + output_idx = end_idx if supports_audio_output(self.od_config.model_class_name): - audio_payload = request_outputs[0] if len(request_outputs) == 1 else request_outputs + request_audio_payload = request_outputs[0] if len(request_outputs) == 1 else request_outputs results.append( OmniRequestOutput.from_diffusion( request_id=request_id, @@ -162,11 +172,24 @@ class DiffusionEngine: prompt=prompt, metrics=metrics, latents=output.trajectory_latents, - multimodal_output={"audio": audio_payload}, + multimodal_output={"audio": request_audio_payload}, final_output_type="audio", - ) + ), ) else: + mm_output = {} + if audio_payload is not None: + sliced_audio = audio_payload + if isinstance(audio_payload, (list, tuple)): + sliced_audio = audio_payload[start_idx:end_idx] + if len(sliced_audio) == 1: + sliced_audio = sliced_audio[0] + elif hasattr(audio_payload, "shape") and getattr(audio_payload, "shape", None) is not None: + if len(audio_payload.shape) > 0 and audio_payload.shape[0] >= end_idx: + sliced_audio = audio_payload[start_idx:end_idx] + if num_outputs == 1: + sliced_audio = sliced_audio[0] + mm_output["audio"] = sliced_audio results.append( OmniRequestOutput.from_diffusion( request_id=request_id, @@ -174,7 +197,8 @@ class DiffusionEngine: prompt=prompt, metrics=metrics, latents=output.trajectory_latents, - ) + multimodal_output=mm_output, + ), ) return results @@ -336,6 +360,9 @@ class DiffusionEngine: # classifier-free guidance with an empty negative prompt. guidance_scale=0.0, num_outputs_per_prompt=1, + # Disable CFG for warmup to avoid triggering CFG parallel + # validation when cfg_parallel_size > 1. + extra_args={"cfg_text_scale": 1.0, "cfg_img_scale": 1.0}, ), ) logger.info("dummy run to warm up the model") diff --git a/vllm_omni/diffusion/models/bagel/bagel_transformer.py b/vllm_omni/diffusion/models/bagel/bagel_transformer.py index 541a03716..e715bdaec 100644 --- a/vllm_omni/diffusion/models/bagel/bagel_transformer.py +++ b/vllm_omni/diffusion/models/bagel/bagel_transformer.py @@ -32,6 +32,11 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader from vllm.transformers_utils.configs.bagel import BagelConfig from vllm_omni.diffusion.attention.backends.utils.fa import flash_attn_varlen_func +from vllm_omni.diffusion.distributed.parallel_state import ( + get_cfg_group, + get_classifier_free_guidance_rank, + get_classifier_free_guidance_world_size, +) from vllm_omni.diffusion.layers.rope import RotaryEmbedding @@ -1330,7 +1335,6 @@ class Bagel(nn.Module): cfg_img_past_key_values: NaiveCache | None = None, cfg_img_key_values_lens: torch.IntTensor | None = None, cfg_img_packed_key_value_indexes: torch.LongTensor | None = None, - cfg_type: str = "parallel", ): x_t = packed_init_noises @@ -1339,9 +1343,45 @@ class Bagel(nn.Module): dts = timesteps[:-1] - timesteps[1:] timesteps = timesteps[:-1] - # ── Pre-compute batched CFG state (merged caches + indices) ── use_cfg_text = cfg_text_scale > 1.0 use_cfg_img = cfg_img_scale > 1.0 + + # ── Detect CFG parallel mode ── + cfg_parallel_ready = use_cfg_text and get_classifier_free_guidance_world_size() > 1 + + if cfg_parallel_ready: + return self._generate_image_parallel( + x_t=x_t, + timesteps=timesteps, + dts=dts, + packed_text_ids=packed_text_ids, + packed_text_indexes=packed_text_indexes, + packed_vae_position_ids=packed_vae_position_ids, + packed_vae_token_indexes=packed_vae_token_indexes, + packed_seqlens=packed_seqlens, + packed_position_ids=packed_position_ids, + packed_indexes=packed_indexes, + past_key_values=past_key_values, + key_values_lens=key_values_lens, + packed_key_value_indexes=packed_key_value_indexes, + cfg_renorm_min=cfg_renorm_min, + cfg_renorm_type=cfg_renorm_type, + cfg_interval=cfg_interval, + cfg_text_scale=cfg_text_scale, + cfg_text_packed_query_indexes=cfg_text_packed_query_indexes, + cfg_text_packed_position_ids=cfg_text_packed_position_ids, + cfg_text_past_key_values=cfg_text_past_key_values, + cfg_text_key_values_lens=cfg_text_key_values_lens, + cfg_text_packed_key_value_indexes=cfg_text_packed_key_value_indexes, + cfg_img_scale=cfg_img_scale, + cfg_img_packed_query_indexes=cfg_img_packed_query_indexes, + cfg_img_packed_position_ids=cfg_img_packed_position_ids, + cfg_img_past_key_values=cfg_img_past_key_values, + cfg_img_key_values_lens=cfg_img_key_values_lens, + cfg_img_packed_key_value_indexes=cfg_img_packed_key_value_indexes, + ) + + # ── Batched CFG mode (cfg_parallel_size=1) ── cfg_batched = None if use_cfg_text: @@ -1430,6 +1470,266 @@ class Bagel(nn.Module): unpacked_latent = x_t.split((packed_seqlens - 2).tolist()) return unpacked_latent + def _generate_image_parallel( + self, + x_t: torch.Tensor, + timesteps: torch.Tensor, + dts: torch.Tensor, + packed_text_ids: torch.LongTensor, + packed_text_indexes: torch.LongTensor, + packed_vae_position_ids: torch.LongTensor, + packed_vae_token_indexes: torch.LongTensor, + packed_seqlens: torch.IntTensor, + packed_position_ids: torch.LongTensor, + packed_indexes: torch.LongTensor, + past_key_values: NaiveCache, + key_values_lens: torch.IntTensor, + packed_key_value_indexes: torch.LongTensor, + cfg_renorm_min: float, + cfg_renorm_type: str, + cfg_interval: tuple[float, float], + cfg_text_scale: float, + cfg_text_packed_query_indexes: torch.LongTensor | None, + cfg_text_packed_position_ids: torch.LongTensor | None, + cfg_text_past_key_values: NaiveCache | None, + cfg_text_key_values_lens: torch.IntTensor | None, + cfg_text_packed_key_value_indexes: torch.LongTensor | None, + cfg_img_scale: float, + cfg_img_packed_query_indexes: torch.LongTensor | None, + cfg_img_packed_position_ids: torch.LongTensor | None, + cfg_img_past_key_values: NaiveCache | None, + cfg_img_key_values_lens: torch.IntTensor | None, + cfg_img_packed_key_value_indexes: torch.LongTensor | None, + ): + """CFG parallel denoising loop: each rank computes one CFG branch. + + Rank 0: gen branch (full conditioning) + Rank 1: text_cfg branch (unconditional text) + Rank 2: img_cfg branch (no image condition), only when cfg_img_scale > 1.0 + """ + cfg_group = get_cfg_group() + cfg_rank = get_classifier_free_guidance_rank() + cfg_world_size = get_classifier_free_guidance_world_size() + use_cfg_img = cfg_img_scale > 1.0 + + # Validate cfg_parallel_size vs cfg_img_scale consistency + if cfg_world_size == 3 and not use_cfg_img: + raise ValueError( + f"cfg_parallel_size=3 requires cfg_img_scale > 1.0, " + f"but got cfg_img_scale={cfg_img_scale}. " + f"Use cfg_parallel_size=2 for text-only CFG parallel(text2img), or set cfg_img_scale > 1.0." + ) + if cfg_world_size == 2 and use_cfg_img: + raise ValueError( + f"Image CFG (cfg_img_scale={cfg_img_scale}) requires cfg_parallel_size=3, " + f"but got cfg_parallel_size=2. " + f"Use cfg_parallel_size=3 to enable image CFG in parallel mode." + ) + + # Select this rank's branch inputs + if cfg_rank == 0: + # Gen branch: use main inputs directly + branch_position_ids = packed_position_ids + branch_indexes = packed_indexes + branch_past_key_values = past_key_values + branch_key_values_lens = key_values_lens + branch_key_value_indexes = packed_key_value_indexes + elif cfg_rank == 1: + # Text CFG branch + branch_position_ids = cfg_text_packed_position_ids + branch_indexes = cfg_text_packed_query_indexes + branch_past_key_values = cfg_text_past_key_values + branch_key_values_lens = cfg_text_key_values_lens + branch_key_value_indexes = cfg_text_packed_key_value_indexes + elif cfg_rank == 2: + # Image CFG branch + branch_position_ids = cfg_img_packed_position_ids + branch_indexes = cfg_img_packed_query_indexes + branch_past_key_values = cfg_img_past_key_values + branch_key_values_lens = cfg_img_key_values_lens + branch_key_value_indexes = cfg_img_packed_key_value_indexes + else: + raise RuntimeError(f"Unexpected cfg_rank={cfg_rank} for Bagel 3-branch CFG parallel") + + for i, t in enumerate(timesteps): + timestep = torch.tensor([t] * x_t.shape[0], device=x_t.device) + if t > cfg_interval[0] and t <= cfg_interval[1]: + cfg_text_scale_ = cfg_text_scale + cfg_img_scale_ = cfg_img_scale + else: + cfg_text_scale_ = 1.0 + cfg_img_scale_ = 1.0 + + use_cfg_this_step = cfg_text_scale_ > 1.0 + + if use_cfg_this_step: + # Each rank computes its branch's velocity + local_v_t = self._forward_flow_single_branch( + x_t=x_t, + timestep=timestep, + packed_vae_token_indexes=packed_vae_token_indexes, + packed_vae_position_ids=packed_vae_position_ids, + packed_text_ids=packed_text_ids, + packed_text_indexes=packed_text_indexes, + packed_indexes=branch_indexes, + packed_position_ids=branch_position_ids, + packed_seqlens=packed_seqlens, + key_values_lens=branch_key_values_lens, + past_key_values=branch_past_key_values, + packed_key_value_indexes=branch_key_value_indexes, + ) + + # All-gather velocities from all CFG ranks + gathered = cfg_group.all_gather(local_v_t, separate_tensors=True) + + # Rank 0 combines with CFG formula + if cfg_rank == 0: + v_t = gathered[0] # gen branch + cfg_text_v_t = gathered[1] # text_cfg branch + cfg_img_v_t = gathered[2] if (use_cfg_img and len(gathered) > 2) else None + v_t = self._combine_cfg( + v_t, + cfg_text_v_t, + cfg_img_v_t, + cfg_text_scale_, + cfg_img_scale_, + cfg_renorm_type, + cfg_renorm_min, + ) + x_t = x_t - v_t.to(x_t.device) * dts[i] + else: + # Outside cfg_interval: only rank 0 computes (no CFG needed) + if cfg_rank == 0: + v_t = self._forward_flow_single_branch( + x_t=x_t, + timestep=timestep, + packed_vae_token_indexes=packed_vae_token_indexes, + packed_vae_position_ids=packed_vae_position_ids, + packed_text_ids=packed_text_ids, + packed_text_indexes=packed_text_indexes, + packed_indexes=packed_indexes, + packed_position_ids=packed_position_ids, + packed_seqlens=packed_seqlens, + key_values_lens=key_values_lens, + past_key_values=past_key_values, + packed_key_value_indexes=packed_key_value_indexes, + ) + x_t = x_t - v_t.to(x_t.device) * dts[i] + + # Broadcast updated x_t from rank 0 to all ranks + x_t = x_t.contiguous() + cfg_group.broadcast(x_t, src=0) + + unpacked_latent = x_t.split((packed_seqlens - 2).tolist()) + return unpacked_latent + + @staticmethod + def _combine_cfg( + v_t: torch.Tensor, + cfg_text_v_t: torch.Tensor, + cfg_img_v_t: torch.Tensor | None, + cfg_text_scale: float, + cfg_img_scale: float, + cfg_renorm_type: str, + cfg_renorm_min: float, + ) -> torch.Tensor: + """Combine 3-branch CFG predictions with renormalization. + + Args: + v_t: velocity from gen branch (full conditioning) + cfg_text_v_t: velocity from text_cfg branch (unconditional text) + cfg_img_v_t: velocity from img_cfg branch (no image), or None + cfg_text_scale: text guidance scale + cfg_img_scale: image guidance scale + cfg_renorm_type: "text_channel", "global", or "channel" + cfg_renorm_min: minimum renormalization scale + """ + if cfg_renorm_type == "text_channel": + v_t_text_ = cfg_text_v_t + cfg_text_scale * (v_t - cfg_text_v_t) + norm_v_t = torch.norm(v_t, dim=-1, keepdim=True) + norm_v_t_text_ = torch.norm(v_t_text_, dim=-1, keepdim=True) + scale = (norm_v_t / (norm_v_t_text_ + 1e-8)).clamp(min=cfg_renorm_min, max=1.0) + v_t_text = v_t_text_ * scale + if cfg_img_scale > 1.0 and cfg_img_v_t is not None: + v_t = cfg_img_v_t + cfg_img_scale * (v_t_text - cfg_img_v_t) + else: + v_t = v_t_text + else: + v_t_text_ = cfg_text_v_t + cfg_text_scale * (v_t - cfg_text_v_t) + + if cfg_img_scale > 1.0 and cfg_img_v_t is not None: + v_t_ = cfg_img_v_t + cfg_img_scale * (v_t_text_ - cfg_img_v_t) + else: + v_t_ = v_t_text_ + + # NOTE norm is computed over all dimensions, thus currently only supports batch_size = 1 with navit + if cfg_renorm_type == "global": + norm_v_t = torch.norm(v_t) + norm_v_t_ = torch.norm(v_t_) + elif cfg_renorm_type == "channel": + norm_v_t = torch.norm(v_t, dim=-1, keepdim=True) + norm_v_t_ = torch.norm(v_t_, dim=-1, keepdim=True) + else: + raise NotImplementedError(f"{cfg_renorm_type} is not supported") + scale = (norm_v_t / (norm_v_t_ + 1e-8)).clamp(min=cfg_renorm_min, max=1.0) + v_t = v_t_ * scale + + return v_t + + def _forward_flow_single_branch( + self, + x_t: torch.Tensor, + timestep: torch.LongTensor, + packed_vae_token_indexes: torch.LongTensor, + packed_vae_position_ids: torch.LongTensor, + packed_text_ids: torch.LongTensor, + packed_text_indexes: torch.LongTensor, + packed_indexes: torch.LongTensor, + packed_position_ids: torch.LongTensor, + packed_seqlens: torch.IntTensor, + key_values_lens: torch.IntTensor, + past_key_values: NaiveCache, + packed_key_value_indexes: torch.LongTensor, + ) -> torch.Tensor: + """Run a single-branch forward pass (no CFG batching). + + Used by CFG parallel mode where each rank computes one branch. + Returns the velocity v_t for the given branch. + """ + packed_text_embedding = self.language_model.model.embed_tokens(packed_text_ids) + packed_sequence = packed_text_embedding.new_zeros((sum(packed_seqlens), self.hidden_size)) + packed_sequence[packed_text_indexes] = packed_text_embedding + + assert timestep.unique().shape[0] == 1 + packed_pos_embed = self.latent_pos_embed(packed_vae_position_ids) + packed_timestep_embeds = self.time_embedder(timestep) + x_t_emb = self.vae2llm(x_t) + packed_timestep_embeds + packed_pos_embed + if x_t_emb.dtype != packed_sequence.dtype: + x_t_emb = x_t_emb.to(packed_sequence.dtype) + packed_sequence[packed_vae_token_indexes] = x_t_emb + + extra_inputs = {} + if self.use_moe: + extra_inputs["mode"] = "gen" + extra_inputs["packed_vae_token_indexes"] = packed_vae_token_indexes + extra_inputs["packed_text_indexes"] = packed_text_indexes + + output = self.language_model.forward( + packed_query_sequence=packed_sequence, + query_lens=packed_seqlens, + packed_query_position_ids=packed_position_ids, + packed_query_indexes=packed_indexes, + past_key_values=past_key_values, + key_values_lens=key_values_lens, + packed_key_value_indexes=packed_key_value_indexes, + update_past_key_values=False, + is_causal=False, + **extra_inputs, + ) + v_t = self.llm2vae(output.packed_query_sequence) + v_t = v_t[packed_vae_token_indexes] + return v_t + def _forward_flow( self, x_t: torch.Tensor, @@ -1535,34 +1835,14 @@ class Bagel(nn.Module): # ── CFG combination ── if use_cfg: - if cfg_renorm_type == "text_channel": - v_t_text_ = cfg_text_v_t + cfg_text_scale * (v_t - cfg_text_v_t) - norm_v_t = torch.norm(v_t, dim=-1, keepdim=True) - norm_v_t_text_ = torch.norm(v_t_text_, dim=-1, keepdim=True) - scale = (norm_v_t / (norm_v_t_text_ + 1e-8)).clamp(min=cfg_renorm_min, max=1.0) - v_t_text = v_t_text_ * scale - if cfg_img_scale > 1.0: - v_t = cfg_img_v_t + cfg_img_scale * (v_t_text - cfg_img_v_t) - else: - v_t = v_t_text - else: - v_t_text_ = cfg_text_v_t + cfg_text_scale * (v_t - cfg_text_v_t) - - if cfg_img_scale > 1.0: - v_t_ = cfg_img_v_t + cfg_img_scale * (v_t_text_ - cfg_img_v_t) - else: - v_t_ = v_t_text_ - - # NOTE norm is computed over all dimensions, thus currently only supports batch_size = 1 with navit - if cfg_renorm_type == "global": - norm_v_t = torch.norm(v_t) - norm_v_t_ = torch.norm(v_t_) - elif cfg_renorm_type == "channel": - norm_v_t = torch.norm(v_t, dim=-1, keepdim=True) - norm_v_t_ = torch.norm(v_t_, dim=-1, keepdim=True) - else: - raise NotImplementedError(f"{cfg_renorm_type} is not supported") - scale = (norm_v_t / (norm_v_t_ + 1e-8)).clamp(min=cfg_renorm_min, max=1.0) - v_t = v_t_ * scale + v_t = self._combine_cfg( + v_t, + cfg_text_v_t, + cfg_img_v_t, + cfg_text_scale, + cfg_img_scale, + cfg_renorm_type, + cfg_renorm_min, + ) return v_t diff --git a/vllm_omni/diffusion/models/helios/pipeline_helios.py b/vllm_omni/diffusion/models/helios/pipeline_helios.py index 0a89d2d02..1a33a5eea 100644 --- a/vllm_omni/diffusion/models/helios/pipeline_helios.py +++ b/vllm_omni/diffusion/models/helios/pipeline_helios.py @@ -26,6 +26,7 @@ from vllm_omni.diffusion.distributed.utils import get_local_device from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader from vllm_omni.diffusion.models.helios.helios_transformer import HeliosTransformer3DModel from vllm_omni.diffusion.models.helios.scheduling_helios import HeliosScheduler +from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin from vllm_omni.diffusion.request import OmniDiffusionRequest from vllm_omni.platforms import current_omni_platform @@ -140,7 +141,7 @@ def get_helios_pre_process_func( return pre_process_func -class HeliosPipeline(nn.Module, CFGParallelMixin): +class HeliosPipeline(nn.Module, CFGParallelMixin, ProgressBarMixin): """Helios text-to-video / image-to-video / video-to-video pipeline for vllm-omni. Supports T2V, I2V (with image input), and V2V (with video input). @@ -662,67 +663,70 @@ class HeliosPipeline(nn.Module, CFGParallelMixin): batch_size = latents.shape[0] do_true_cfg = guidance_scale > 1.0 and negative_prompt_embeds is not None - for i, t in enumerate(timesteps): - self._current_timestep = t - timestep = t.expand(batch_size) + with self.progress_bar(total=len(timesteps)) as pbar: + for i, t in enumerate(timesteps): + self._current_timestep = t + timestep = t.expand(batch_size) - transformer_kwargs = { - "hidden_states": latents.to(transformer_dtype), - "timestep": timestep, - "indices_hidden_states": indices_hidden_states, - "indices_latents_history_short": indices_latents_history_short, - "indices_latents_history_mid": indices_latents_history_mid, - "indices_latents_history_long": indices_latents_history_long, - "latents_history_short": latents_history_short.to(transformer_dtype), - "latents_history_mid": latents_history_mid.to(transformer_dtype), - "latents_history_long": latents_history_long.to(transformer_dtype), - "attention_kwargs": attention_kwargs, - "return_dict": False, - } - - if use_cfg_zero_star and do_true_cfg: - noise_pred = self.transformer( - encoder_hidden_states=prompt_embeds, - **transformer_kwargs, - )[0] - - noise_uncond = self.transformer( - encoder_hidden_states=negative_prompt_embeds, - **transformer_kwargs, - )[0] - - positive_flat = noise_pred.view(batch_size, -1) - negative_flat = noise_uncond.view(batch_size, -1) - alpha_cfg = optimized_scale(positive_flat, negative_flat) - alpha_cfg = alpha_cfg.view(batch_size, *([1] * (len(noise_pred.shape) - 1))) - alpha_cfg = alpha_cfg.to(noise_pred.dtype) - - if (i <= zero_steps) and use_zero_init: - noise_pred = noise_pred * 0.0 - else: - noise_pred = noise_uncond * alpha_cfg + guidance_scale * (noise_pred - noise_uncond * alpha_cfg) - else: - positive_kwargs = { - "encoder_hidden_states": prompt_embeds, - **transformer_kwargs, + transformer_kwargs = { + "hidden_states": latents.to(transformer_dtype), + "timestep": timestep, + "indices_hidden_states": indices_hidden_states, + "indices_latents_history_short": indices_latents_history_short, + "indices_latents_history_mid": indices_latents_history_mid, + "indices_latents_history_long": indices_latents_history_long, + "latents_history_short": latents_history_short.to(transformer_dtype), + "latents_history_mid": latents_history_mid.to(transformer_dtype), + "latents_history_long": latents_history_long.to(transformer_dtype), + "attention_kwargs": attention_kwargs, + "return_dict": False, } - if do_true_cfg: - negative_kwargs = { - "encoder_hidden_states": negative_prompt_embeds, + + if use_cfg_zero_star and do_true_cfg: + noise_pred = self.transformer( + encoder_hidden_states=prompt_embeds, + **transformer_kwargs, + )[0] + + noise_uncond = self.transformer( + encoder_hidden_states=negative_prompt_embeds, + **transformer_kwargs, + )[0] + + positive_flat = noise_pred.view(batch_size, -1) + negative_flat = noise_uncond.view(batch_size, -1) + alpha_cfg = optimized_scale(positive_flat, negative_flat) + alpha_cfg = alpha_cfg.view(batch_size, *([1] * (len(noise_pred.shape) - 1))) + alpha_cfg = alpha_cfg.to(noise_pred.dtype) + + if (i <= zero_steps) and use_zero_init: + noise_pred = noise_pred * 0.0 + else: + noise_pred = noise_uncond * alpha_cfg + guidance_scale * (noise_pred - noise_uncond * alpha_cfg) + else: + positive_kwargs = { + "encoder_hidden_states": prompt_embeds, **transformer_kwargs, } - else: - negative_kwargs = None + if do_true_cfg: + negative_kwargs = { + "encoder_hidden_states": negative_prompt_embeds, + **transformer_kwargs, + } + else: + negative_kwargs = None - noise_pred = self.predict_noise_maybe_with_cfg( - do_true_cfg=do_true_cfg, - true_cfg_scale=guidance_scale, - positive_kwargs=positive_kwargs, - negative_kwargs=negative_kwargs, - cfg_normalize=False, - ) + noise_pred = self.predict_noise_maybe_with_cfg( + do_true_cfg=do_true_cfg, + true_cfg_scale=guidance_scale, + positive_kwargs=positive_kwargs, + negative_kwargs=negative_kwargs, + cfg_normalize=False, + ) - latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg) + latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg) + + pbar.update() return latents @@ -807,62 +811,65 @@ class HeliosPipeline(nn.Module, CFGParallelMixin): if self.is_distilled and start_point_list is not None: start_point_list.append(latents) - for idx, t in enumerate(timesteps): - self._current_timestep = t - timestep = t.expand(latents.shape[0]).to(torch.int64) + with self.progress_bar(total=len(timesteps)) as pbar: + for idx, t in enumerate(timesteps): + self._current_timestep = t + timestep = t.expand(latents.shape[0]).to(torch.int64) - transformer_kwargs = { - "hidden_states": latents.to(transformer_dtype), - "timestep": timestep, - "indices_hidden_states": indices_hidden_states, - "indices_latents_history_short": indices_latents_history_short, - "indices_latents_history_mid": indices_latents_history_mid, - "indices_latents_history_long": indices_latents_history_long, - "latents_history_short": latents_history_short.to(transformer_dtype), - "latents_history_mid": latents_history_mid.to(transformer_dtype), - "latents_history_long": latents_history_long.to(transformer_dtype), - "attention_kwargs": attention_kwargs, - "return_dict": False, - } + transformer_kwargs = { + "hidden_states": latents.to(transformer_dtype), + "timestep": timestep, + "indices_hidden_states": indices_hidden_states, + "indices_latents_history_short": indices_latents_history_short, + "indices_latents_history_mid": indices_latents_history_mid, + "indices_latents_history_long": indices_latents_history_long, + "latents_history_short": latents_history_short.to(transformer_dtype), + "latents_history_mid": latents_history_mid.to(transformer_dtype), + "latents_history_long": latents_history_long.to(transformer_dtype), + "attention_kwargs": attention_kwargs, + "return_dict": False, + } - noise_pred = self.transformer( - encoder_hidden_states=prompt_embeds, - **transformer_kwargs, - )[0] - - if do_true_cfg: - noise_uncond = self.transformer( - encoder_hidden_states=negative_prompt_embeds, + noise_pred = self.transformer( + encoder_hidden_states=prompt_embeds, **transformer_kwargs, )[0] - if use_cfg_zero_star: - positive_flat = noise_pred.view(batch_size, -1) - negative_flat = noise_uncond.view(batch_size, -1) - alpha_cfg = optimized_scale(positive_flat, negative_flat) - alpha_cfg = alpha_cfg.view(batch_size, *([1] * (len(noise_pred.shape) - 1))) - alpha_cfg = alpha_cfg.to(noise_pred.dtype) + if do_true_cfg: + noise_uncond = self.transformer( + encoder_hidden_states=negative_prompt_embeds, + **transformer_kwargs, + )[0] - if (i_s == 0 and idx <= zero_steps) and use_zero_init: - noise_pred = noise_pred * 0.0 + if use_cfg_zero_star: + positive_flat = noise_pred.view(batch_size, -1) + negative_flat = noise_uncond.view(batch_size, -1) + alpha_cfg = optimized_scale(positive_flat, negative_flat) + alpha_cfg = alpha_cfg.view(batch_size, *([1] * (len(noise_pred.shape) - 1))) + alpha_cfg = alpha_cfg.to(noise_pred.dtype) + + if (i_s == 0 and idx <= zero_steps) and use_zero_init: + noise_pred = noise_pred * 0.0 + else: + noise_pred = noise_uncond * alpha_cfg + guidance_scale * ( + noise_pred - noise_uncond * alpha_cfg + ) else: - noise_pred = noise_uncond * alpha_cfg + guidance_scale * ( - noise_pred - noise_uncond * alpha_cfg - ) - else: - noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond) + noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond) - latents = self.scheduler.step( - noise_pred, - t, - latents, - return_dict=False, - cur_sampling_step=idx, - dmd_noisy_tensor=start_point_list[i_s] if start_point_list is not None else None, - dmd_sigmas=self.scheduler.sigmas, - dmd_timesteps=self.scheduler.timesteps, - all_timesteps=timesteps, - )[0] + latents = self.scheduler.step( + noise_pred, + t, + latents, + return_dict=False, + cur_sampling_step=idx, + dmd_noisy_tensor=start_point_list[i_s] if start_point_list is not None else None, + dmd_sigmas=self.scheduler.sigmas, + dmd_timesteps=self.scheduler.timesteps, + all_timesteps=timesteps, + )[0] + + pbar.update() return latents diff --git a/vllm_omni/diffusion/models/longcat_image/longcat_image_transformer.py b/vllm_omni/diffusion/models/longcat_image/longcat_image_transformer.py index 4334ef62e..ccf35ea4e 100644 --- a/vllm_omni/diffusion/models/longcat_image/longcat_image_transformer.py +++ b/vllm_omni/diffusion/models/longcat_image/longcat_image_transformer.py @@ -580,19 +580,28 @@ class LongCatImageTransformer2DModel(nn.Module): guidance: torch.Tensor = None, return_dict: bool = True, ) -> torch.FloatTensor | Transformer2DModelOutput: + fwd_context = get_forward_context() # Before: hidden_states shape = (B, img_seq_len, in_channels) # After: hidden_states shape = (B, img_seq_len // SP, in_channels) sp_size = self.parallel_config.sequence_parallel_size # Store SP size in forward context for sub-modules to access - get_forward_context().sequence_parallel_size = sp_size - if sp_size > 1: + if sp_size is not None and sp_size > 1: sp_world_size = get_sequence_parallel_world_size() sp_rank = get_sequence_parallel_rank() original_shape = hidden_states.shape hidden_states = torch.chunk(hidden_states, sp_world_size, dim=1)[sp_rank] # LongCat uses dual-stream (text + image) with joint attention # Text embeddings should be replicated across SP ranks for correctness - get_forward_context().split_text_embed_in_sp = False + fwd_context.sequence_parallel_size = sp_size + fwd_context.split_text_embed_in_sp = False + + # Mark SP as active so attention layers; we need this to ensure we use + # Ulysses instead of NoParallelAttention since we don't set an sp plan + # for this model. + # TODO: would be nice to refactor this to use sp_plan if possible to + # tracking this directly, even though we only have one level. + fwd_context._sp_shard_depth = 1 + # Debug log (only first forward) if not hasattr(self, "_sp_forward_logged"): self._sp_forward_logged = True @@ -601,6 +610,7 @@ class LongCatImageTransformer2DModel(nn.Module): f"rank={sp_rank}, original_shape={original_shape}, chunked_shape={hidden_states.shape}" ) else: + fwd_context._sp_shard_depth = 0 if not hasattr(self, "_sp_forward_logged"): self._sp_forward_logged = True logger.info(f"[LongCat Transformer] SP disabled: sp_size={sp_size}") @@ -621,7 +631,7 @@ class LongCatImageTransformer2DModel(nn.Module): image_rotary_emb = self.pos_embed(ids) # SP: Chunk RoPE embeddings along sequence dimension - if self.parallel_config.sequence_parallel_size > 1: + if sp_size is not None and sp_size > 1: sp_world_size = get_sequence_parallel_world_size() sp_rank = get_sequence_parallel_rank() freqs_cos, freqs_sin = image_rotary_emb @@ -653,46 +663,30 @@ class LongCatImageTransformer2DModel(nn.Module): torch.cat([txt_freqs_sin, img_freqs_sin], dim=0), ) - for index_block, block in enumerate(self.transformer_blocks): - if torch.is_grad_enabled() and self.gradient_checkpointing and self.use_checkpoint[index_block]: - encoder_hidden_states, hidden_states = self._gradient_checkpointing_func( - block, - hidden_states, - encoder_hidden_states, - temb, - image_rotary_emb, - ) - else: - encoder_hidden_states, hidden_states = block( - hidden_states=hidden_states, - encoder_hidden_states=encoder_hidden_states, - temb=temb, - image_rotary_emb=image_rotary_emb, - ) + for block in self.transformer_blocks: + encoder_hidden_states, hidden_states = block( + hidden_states=hidden_states, + encoder_hidden_states=encoder_hidden_states, + temb=temb, + image_rotary_emb=image_rotary_emb, + ) - for index_block, block in enumerate(self.single_transformer_blocks): - if torch.is_grad_enabled() and self.gradient_checkpointing and self.use_single_checkpoint[index_block]: - encoder_hidden_states, hidden_states = self._gradient_checkpointing_func( - block, - hidden_states, - encoder_hidden_states, - temb, - image_rotary_emb, - ) - else: - encoder_hidden_states, hidden_states = block( - hidden_states=hidden_states, - encoder_hidden_states=encoder_hidden_states, - temb=temb, - image_rotary_emb=image_rotary_emb, - ) + for block in self.single_transformer_blocks: + encoder_hidden_states, hidden_states = block( + hidden_states=hidden_states, + encoder_hidden_states=encoder_hidden_states, + temb=temb, + image_rotary_emb=image_rotary_emb, + ) hidden_states = self.norm_out(hidden_states, temb) output = self.proj_out(hidden_states) # SP: All-gather output to reconstruct full sequence - if self.parallel_config.sequence_parallel_size > 1: + if sp_size is not None and sp_size > 1: output = get_sp_group().all_gather(output, dim=1) + # Mark SP as inactive after gathering + get_forward_context()._sp_shard_depth = 0 if not return_dict: return (output,) diff --git a/vllm_omni/diffusion/models/ltx2/__init__.py b/vllm_omni/diffusion/models/ltx2/__init__.py new file mode 100644 index 000000000..0a92d4f24 --- /dev/null +++ b/vllm_omni/diffusion/models/ltx2/__init__.py @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from vllm_omni.diffusion.models.ltx2.ltx2_transformer import LTX2VideoTransformer3DModel +from vllm_omni.diffusion.models.ltx2.pipeline_ltx2 import ( + LTX2Pipeline, + create_transformer_from_config, + get_ltx2_post_process_func, + load_transformer_config, +) +from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_image2video import LTX2ImageToVideoPipeline + +__all__ = [ + "LTX2Pipeline", + "LTX2ImageToVideoPipeline", + "get_ltx2_post_process_func", + "load_transformer_config", + "create_transformer_from_config", + "LTX2VideoTransformer3DModel", +] diff --git a/vllm_omni/diffusion/models/ltx2/ltx2_transformer.py b/vllm_omni/diffusion/models/ltx2/ltx2_transformer.py new file mode 100644 index 000000000..a1bf7f780 --- /dev/null +++ b/vllm_omni/diffusion/models/ltx2/ltx2_transformer.py @@ -0,0 +1,1835 @@ +# Copyright 2025 The Lightricks team and The HuggingFace Team. +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +from collections.abc import Iterable +from dataclasses import dataclass +from types import SimpleNamespace +from typing import Any + +import torch +import torch.distributed +import torch.nn as nn +import torch.nn.functional as F +from diffusers.models.embeddings import PixArtAlphaCombinedTimestepSizeEmbeddings, PixArtAlphaTextProjection +from diffusers.utils import ( + BaseOutput, + is_torch_version, +) +from torch.utils.checkpoint import checkpoint +from vllm.distributed import get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size +from vllm.logger import init_logger +from vllm.model_executor.layers.layernorm import RMSNorm +from vllm.model_executor.layers.linear import ( + ColumnParallelLinear, + QKVParallelLinear, + RowParallelLinear, +) +from vllm.model_executor.model_loader.weight_utils import default_weight_loader + +from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata +from vllm_omni.diffusion.attention.layer import Attention +from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelInput, SequenceParallelOutput +from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available + +logger = init_logger(__name__) + +_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.""" + kwargs: dict[str, Any] = {"eps": eps} + if "elementwise_affine" in _RMSNORM_INIT_PARAMS: + kwargs["elementwise_affine"] = elementwise_affine + elif "has_weight" in _RMSNORM_INIT_PARAMS: + kwargs["has_weight"] = elementwise_affine + elif not elementwise_affine: + raise TypeError("RMSNorm backend does not support disabling affine weights.") + return RMSNorm(hidden_size, **kwargs) + + +def apply_interleaved_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor: + cos, sin = freqs + x_real, x_imag = x.unflatten(2, (-1, 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) + return out + + +def apply_split_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor: + cos, sin = freqs + + x_dtype = x.dtype + needs_reshape = False + if x.ndim != 4 and cos.ndim == 4: + # cos is (#b, h, t, r) -> reshape x to (b, h, t, dim_per_head) + # The cos/sin batch dim may only be broadcastable, so take batch size from x + b = x.shape[0] + _, h, t, _ = cos.shape + x = x.reshape(b, t, h, -1).swapaxes(1, 2) + needs_reshape = True + + # Split last dim (2*r) into (d=2, r) + last = x.shape[-1] + if last % 2 != 0: + raise ValueError(f"Expected x.shape[-1] to be even for split rotary, got {last}.") + r = last // 2 + + # (..., 2, r) + split_x = x.reshape(*x.shape[:-1], 2, r).float() # Explicitly upcast to float + first_x = split_x[..., :1, :] # (..., 1, r) + second_x = split_x[..., 1:, :] # (..., 1, r) + + cos_u = cos.unsqueeze(-2) # broadcast to (..., 1, r) against (..., 2, r) + sin_u = sin.unsqueeze(-2) + + out = split_x * cos_u + first_out = out[..., :1, :] + second_out = out[..., 1:, :] + + first_out.addcmul_(-sin_u, second_x) + second_out.addcmul_(sin_u, first_x) + + out = out.reshape(*out.shape[:-2], last) + + if needs_reshape: + out = out.swapaxes(1, 2).reshape(b, t, -1) + + out = out.to(dtype=x_dtype) + return out + + +@dataclass +class AudioVisualModelOutput(BaseOutput): + r""" + Holds the output of an audiovisual model which produces both visual (e.g. video) and audio outputs. + + Args: + sample (`torch.Tensor` of shape `(batch_size, num_video_tokens, out_channels)`): + The patchified visual output conditioned on the `encoder_hidden_states` input. This is the transformer + output before the pipeline unpacks it back into video latent dimensions. + audio_sample (`torch.Tensor` of shape `(batch_size, num_audio_tokens, audio_out_channels)`): + The patchified audio output of the audiovisual model before the pipeline unpacks it back into audio latent + dimensions. + """ + + sample: "torch.Tensor" # noqa: F821 + audio_sample: "torch.Tensor" # noqa: F821 + + +class LTX2AdaLayerNormSingle(nn.Module): + r""" + Norm layer adaptive layer norm single (adaLN-single). + + As proposed in PixArt-Alpha (see: https://huggingface.co/papers/2310.00426; Section 2.3) and adapted by the LTX-2.0 + model. In particular, the number of modulation parameters to be calculated is now configurable. + + Parameters: + embedding_dim (`int`): The size of each embedding vector. + num_mod_params (`int`, *optional*, defaults to `6`): + The number of modulation parameters which will be calculated in the first return argument. The default of 6 + is standard, but sometimes we may want to have a different (usually smaller) number of modulation + parameters. + use_additional_conditions (`bool`, *optional*, defaults to `False`): + Whether to use additional conditions for normalization or not. + """ + + def __init__(self, embedding_dim: int, num_mod_params: int = 6, use_additional_conditions: bool = False): + super().__init__() + self.num_mod_params = num_mod_params + + self.emb = PixArtAlphaCombinedTimestepSizeEmbeddings( + embedding_dim, size_emb_dim=embedding_dim // 3, use_additional_conditions=use_additional_conditions + ) + + self.silu = nn.SiLU() + self.linear = nn.Linear(embedding_dim, self.num_mod_params * embedding_dim, bias=True) + + def forward( + self, + timestep: torch.Tensor, + added_cond_kwargs: dict[str, torch.Tensor] | None = None, + batch_size: int | None = None, + hidden_dtype: torch.dtype | None = None, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + # No modulation happening here. + added_cond_kwargs = added_cond_kwargs or {"resolution": None, "aspect_ratio": None} + embedded_timestep = self.emb(timestep, **added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_dtype) + return self.linear(self.silu(embedded_timestep)), embedded_timestep + + +class ColumnParallelApproxGELU(nn.Module): + def __init__(self, dim_in: int, dim_out: int, *, approximate: str, bias: bool = True): + super().__init__() + self.proj = ColumnParallelLinear( + dim_in, + dim_out, + bias=bias, + gather_output=False, + return_bias=False, + ) + self.approximate = approximate + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + return F.gelu(x, approximate=self.approximate) + + +class LTX2FeedForward(nn.Module): + def __init__( + self, + dim: int, + dim_out: int | None = None, + mult: int = 4, + activation_fn: str = "gelu-approximate", + inner_dim: int | None = None, + bias: bool = True, + dropout: float = 0.0, + final_dropout: bool = False, + ) -> None: + super().__init__() + + assert activation_fn == "gelu-approximate", "Only gelu-approximate is supported." + + inner_dim = inner_dim or int(dim * mult) + dim_out = dim_out or dim + + dropout_layer: nn.Module = nn.Dropout(dropout) if dropout > 0 else nn.Identity() + + layers: list[nn.Module] = [ + ColumnParallelApproxGELU(dim, inner_dim, approximate="tanh", bias=bias), + dropout_layer, + RowParallelLinear( + inner_dim, + dim_out, + input_is_parallel=True, + return_bias=False, + ), + ] + if final_dropout: + layers.append(nn.Dropout(dropout) if dropout > 0 else nn.Identity()) + + self.net = nn.ModuleList(layers) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + for module in self.net: + hidden_states = module(hidden_states) + return hidden_states + + +class TensorParallelRMSNorm(nn.Module): + """RMSNorm that computes stats across TP shards for q/k norm. + + LTX2 uses qk_norm="rms_norm_across_heads" while Q/K are tensor-parallel + sharded. A local RMSNorm would compute statistics on only the local shard, + which changes the normalization when TP > 1. We all-reduce the squared + sum to match the global RMS across all heads. + """ + + def __init__(self, hidden_size: int, eps: float = 1e-6, elementwise_affine: bool = True, tp_size: int = 1): + super().__init__() + self.hidden_size = hidden_size + self.global_hidden_size = hidden_size * max(tp_size, 1) + self.eps = eps + self.tp_size = tp_size + if elementwise_affine: + self.weight = nn.Parameter(torch.ones(hidden_size)) + else: + self.register_parameter("weight", None) + + def _all_reduce(self, tensor: torch.Tensor) -> None: + if not torch.distributed.is_initialized(): + return + try: + import vllm.distributed.parallel_state as vllm_parallel_state + + tp_group = getattr(vllm_parallel_state, "_TP", None) + except Exception: + tp_group = None + + if tp_group is not None and hasattr(tp_group, "all_reduce"): + tp_group.all_reduce(tensor) + return + + if tp_group is not None: + torch.distributed.all_reduce(tensor, group=tp_group) + else: + torch.distributed.all_reduce(tensor) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x_dtype = x.dtype + x_float = x.float() + local_sum = x_float.pow(2).sum(dim=-1, keepdim=True) + if self.tp_size > 1: + self._all_reduce(local_sum) + inv_rms = torch.rsqrt(local_sum / self.global_hidden_size + self.eps) + out = x_float * inv_rms + if self.weight is not None: + out = out * self.weight.float() + return out.to(dtype=x_dtype) + + +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. + Compared to the LTX-1.0 model, we allow the RoPE embeddings for the queries and keys to be separate so that we can + support audio-to-video (a2v) and video-to-audio (v2a) cross attention. + """ + + _attention_backend = None + _parallel_config = None + + def __init__(self): + if is_torch_version("<", "2.0"): + raise ValueError( + "LTX attention processors require a minimum PyTorch version of 2.0. " + "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(): + return False + try: + od_config = get_forward_context().omni_diffusion_config + parallel_config = getattr(od_config, "parallel_config", None) if od_config is not None else None + return getattr(parallel_config, "sequence_parallel_size", 1) > 1 + except Exception: + return False + + def _prepare_attention_mask( + self, + attn: "LTX2Attention", + hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor | None, + attention_mask: torch.Tensor | None, + batch_size: int, + sequence_length: int, + ) -> torch.Tensor | None: + if attention_mask is None: + return None + + if self._is_sp_enabled(): + # In SP, Ulysses expects a 2D padding mask that matches query length. + # 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) + + 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) + return attention_mask + + @staticmethod + def _project_qkv( + attn: "LTX2Attention", + hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor | None, + is_self_attention: bool, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if is_self_attention and attn.to_qkv is not None: + qkv, _ = attn.to_qkv(hidden_states) + q_heads = getattr(attn, "query_num_heads", attn.heads) + kv_heads = getattr(attn, "kv_num_heads", attn.heads) + q_size = q_heads * attn.head_dim + kv_size = kv_heads * attn.head_dim + query, key, value = qkv.split([q_size, kv_size, kv_size], dim=-1) + return query, key, value + + query = attn.to_q(hidden_states) + if isinstance(query, tuple): + query = query[0] + if encoder_hidden_states is None: + raise ValueError("encoder_hidden_states is required for cross-attention projection.") + key = attn.to_k(encoder_hidden_states) + if isinstance(key, tuple): + key = key[0] + value = attn.to_v(encoder_hidden_states) + if isinstance(value, tuple): + value = value[0] + return query, key, value + + @staticmethod + def _slice_rope_for_tp( + rope: tuple[torch.Tensor, torch.Tensor] | None, + attn_module: "LTX2Attention", + ) -> tuple[torch.Tensor, torch.Tensor] | None: + if rope is None: + return None + cos, sin = rope + tp_size = get_tensor_model_parallel_world_size() + if tp_size <= 1: + return rope + tp_rank = get_tensor_model_parallel_rank() + + if cos.ndim == 4: + if cos.shape[1] != attn_module.heads: + local_heads = cos.shape[1] // tp_size + if local_heads == attn_module.heads: + start = tp_rank * local_heads + end = start + local_heads + cos = cos[:, start:end, :, :] + sin = sin[:, start:end, :, :] + elif cos.ndim == 3: + local_dim = attn_module.heads * attn_module.head_dim + if cos.shape[-1] != local_dim: + if cos.shape[-1] == local_dim * tp_size: + start = tp_rank * local_dim + end = start + local_dim + cos = cos[..., start:end] + sin = sin[..., start:end] + + return cos, sin + + def __call__( + self, + attn: "LTX2Attention", + 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: + is_self_attention = encoder_hidden_states is None + batch_size, sequence_length, _ = hidden_states.shape if is_self_attention else encoder_hidden_states.shape + + attention_mask = self._prepare_attention_mask( + attn=attn, + hidden_states=hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=attention_mask, + batch_size=batch_size, + sequence_length=sequence_length, + ) + + if is_self_attention: + encoder_hidden_states = hidden_states + + query, key, value = self._project_qkv( + attn=attn, + hidden_states=hidden_states, + encoder_hidden_states=encoder_hidden_states, + is_self_attention=is_self_attention, + ) + + query = attn.norm_q(query) + key = attn.norm_k(key) + + if query_rotary_emb is not None: + query_rotary_emb = self._slice_rope_for_tp(query_rotary_emb, attn) + if key_rotary_emb is not None: + key_rotary_emb = self._slice_rope_for_tp(key_rotary_emb, attn) + if attn.rope_type == "interleaved": + query = apply_interleaved_rotary_emb(query, query_rotary_emb) + key = apply_interleaved_rotary_emb( + key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb + ) + elif attn.rope_type == "split": + query = apply_split_rotary_emb(query, query_rotary_emb) + key = apply_split_rotary_emb(key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb) + + query = query.unflatten(2, (attn.heads, -1)) + key = key.unflatten(2, (attn.heads, -1)) + value = value.unflatten(2, (attn.heads, -1)) + + 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 = hidden_states.flatten(2, 3) + hidden_states = hidden_states.to(query.dtype) + + hidden_states = attn.to_out[0](hidden_states) + if isinstance(hidden_states, tuple): + hidden_states = hidden_states[0] + hidden_states = attn.to_out[1](hidden_states) + return hidden_states + + +class LTX2Attention(torch.nn.Module): + r""" + Attention class for all LTX-2.0 attention layers. Compared to LTX-1.0, this supports specifying the query and key + RoPE embeddings separately for audio-to-video (a2v) and video-to-audio (v2a) cross-attention. + """ + + _default_processor_cls = LTX2AudioVideoAttnProcessor + _available_processors = [LTX2AudioVideoAttnProcessor] + + def __init__( + self, + query_dim: int, + heads: int = 8, + kv_heads: int = 8, + dim_head: int = 64, + dropout: float = 0.0, + bias: bool = True, + cross_attention_dim: int | None = None, + out_bias: bool = True, + qk_norm: str = "rms_norm_across_heads", + norm_eps: float = 1e-6, + norm_elementwise_affine: bool = True, + rope_type: str = "interleaved", + processor=None, + ): + super().__init__() + if qk_norm != "rms_norm_across_heads": + raise NotImplementedError("Only 'rms_norm_across_heads' is supported as a valid value for `qk_norm`.") + + kv_heads = heads if kv_heads is None else kv_heads + + self.head_dim = dim_head + self.inner_dim = dim_head * heads + self.inner_kv_dim = dim_head * kv_heads + self.query_dim = query_dim + self.cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim + self.use_bias = bias + self.dropout = dropout + self.out_dim = query_dim + self.total_num_heads = heads + self.total_num_kv_heads = kv_heads + self.rope_type = rope_type + + self.to_qkv = None + self.to_q = None + self.to_k = None + self.to_v = None + if cross_attention_dim is None: + self.to_qkv = QKVParallelLinear( + hidden_size=query_dim, + head_size=self.head_dim, + total_num_heads=heads, + bias=bias, + ) + self.query_num_heads = self.to_qkv.num_heads + self.kv_num_heads = self.to_qkv.num_kv_heads + else: + tp_size = get_tensor_model_parallel_world_size() + self.query_num_heads = heads // tp_size + self.kv_num_heads = kv_heads // tp_size + + self.to_q = ColumnParallelLinear( + query_dim, + self.inner_dim, + bias=bias, + gather_output=False, + return_bias=False, + ) + self.to_k = ColumnParallelLinear( + self.cross_attention_dim, + self.inner_kv_dim, + bias=bias, + gather_output=False, + return_bias=False, + ) + self.to_v = ColumnParallelLinear( + self.cross_attention_dim, + self.inner_kv_dim, + bias=bias, + gather_output=False, + return_bias=False, + ) + + self.heads = self.query_num_heads + tp_size = get_tensor_model_parallel_world_size() + self.norm_q = TensorParallelRMSNorm( + dim_head * self.query_num_heads, + eps=norm_eps, + elementwise_affine=norm_elementwise_affine, + tp_size=tp_size, + ) + self.norm_k = TensorParallelRMSNorm( + dim_head * self.kv_num_heads, + eps=norm_eps, + elementwise_affine=norm_elementwise_affine, + tp_size=tp_size, + ) + + self.to_out = torch.nn.ModuleList( + [ + RowParallelLinear( + self.inner_dim, + self.out_dim, + bias=out_bias, + input_is_parallel=True, + return_bias=False, + ), + torch.nn.Dropout(dropout) if dropout > 0 else torch.nn.Identity(), + ] + ) + self.attn = Attention( + num_heads=self.query_num_heads, + head_size=dim_head, + num_kv_heads=self.kv_num_heads, + softmax_scale=1.0 / (dim_head**0.5), + causal=False, + ) + + if processor is None: + processor = self._default_processor_cls() + self.set_processor(processor) + + def set_processor(self, processor: Any) -> None: + if processor is None: + raise ValueError("processor must not be None.") + self.processor = processor + + def get_processor(self) -> Any: + return self.processor + + def prepare_attention_mask( + self, + attention_mask: torch.Tensor | None, + target_length: int, + batch_size: int, + out_dim: int = 3, + ) -> torch.Tensor | None: + if attention_mask is None: + return None + + current_length = attention_mask.shape[-1] + if current_length != target_length: + pad_length = target_length - current_length + if pad_length > 0: + attention_mask = F.pad(attention_mask, (0, pad_length), value=0.0) + else: + attention_mask = attention_mask[..., :target_length] + + if out_dim == 3: + expected_batch = batch_size * self.heads + if attention_mask.shape[0] != expected_batch: + repeat_factor = expected_batch // attention_mask.shape[0] + if repeat_factor * attention_mask.shape[0] != expected_batch: + raise ValueError( + "attention_mask batch dimension is incompatible with the requested batch/head expansion: " + f"got {attention_mask.shape[0]}, expected a divisor of {expected_batch}." + ) + attention_mask = attention_mask.repeat_interleave(repeat_factor, dim=0) + elif out_dim == 4: + attention_mask = attention_mask.unsqueeze(1) + attention_mask = attention_mask.repeat_interleave(self.heads, dim=1) + else: + raise ValueError(f"Unsupported out_dim={out_dim}; expected 3 or 4.") + + return attention_mask + + def forward( + self, + 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, + **kwargs, + ) -> torch.Tensor: + attn_parameters = set(inspect.signature(self.processor.__call__).parameters.keys()) + unused_kwargs = [k for k, _ in kwargs.items() if k not in attn_parameters] + if len(unused_kwargs) > 0: + logger.warning( + "attention_kwargs %s are not expected by %s and will be ignored.", + unused_kwargs, + self.processor.__class__.__name__, + ) + kwargs = {k: w for k, w in kwargs.items() if k in attn_parameters} + hidden_states = self.processor( + self, hidden_states, encoder_hidden_states, attention_mask, query_rotary_emb, key_rotary_emb, **kwargs + ) + return hidden_states + + +class LTX2VideoTransformerBlock(nn.Module): + r""" + Transformer block used in [LTX-2.0](https://huggingface.co/Lightricks/LTX-Video). + + Args: + dim (`int`): + The number of channels in the input and output. + num_attention_heads (`int`): + The number of heads to use for multi-head attention. + attention_head_dim (`int`): + The number of channels in each head. + qk_norm (`str`, defaults to `"rms_norm"`): + The normalization layer to use. + activation_fn (`str`, defaults to `"gelu-approximate"`): + Activation function to use in feed-forward. + eps (`float`, defaults to `1e-6`): + Epsilon value for normalization layers. + """ + + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + cross_attention_dim: int, + audio_dim: int, + audio_num_attention_heads: int, + audio_attention_head_dim, + audio_cross_attention_dim: int, + qk_norm: str = "rms_norm_across_heads", + activation_fn: str = "gelu-approximate", + attention_bias: bool = True, + attention_out_bias: bool = True, + eps: float = 1e-6, + elementwise_affine: bool = False, + rope_type: str = "interleaved", + ): + super().__init__() + + # 1. Self-Attention (video and audio) + self.norm1 = _make_rms_norm(dim, eps=eps, elementwise_affine=elementwise_affine) + self.attn1 = LTX2Attention( + query_dim=dim, + heads=num_attention_heads, + kv_heads=num_attention_heads, + dim_head=attention_head_dim, + bias=attention_bias, + cross_attention_dim=None, + out_bias=attention_out_bias, + qk_norm=qk_norm, + rope_type=rope_type, + ) + + self.audio_norm1 = _make_rms_norm(audio_dim, eps=eps, elementwise_affine=elementwise_affine) + self.audio_attn1 = LTX2Attention( + query_dim=audio_dim, + heads=audio_num_attention_heads, + kv_heads=audio_num_attention_heads, + dim_head=audio_attention_head_dim, + bias=attention_bias, + cross_attention_dim=None, + out_bias=attention_out_bias, + qk_norm=qk_norm, + rope_type=rope_type, + ) + + # 2. Prompt Cross-Attention + self.norm2 = _make_rms_norm(dim, eps=eps, elementwise_affine=elementwise_affine) + self.attn2 = LTX2Attention( + query_dim=dim, + cross_attention_dim=cross_attention_dim, + heads=num_attention_heads, + kv_heads=num_attention_heads, + dim_head=attention_head_dim, + bias=attention_bias, + out_bias=attention_out_bias, + qk_norm=qk_norm, + rope_type=rope_type, + ) + + self.audio_norm2 = _make_rms_norm(audio_dim, eps=eps, elementwise_affine=elementwise_affine) + self.audio_attn2 = LTX2Attention( + query_dim=audio_dim, + cross_attention_dim=audio_cross_attention_dim, + heads=audio_num_attention_heads, + kv_heads=audio_num_attention_heads, + dim_head=audio_attention_head_dim, + bias=attention_bias, + out_bias=attention_out_bias, + qk_norm=qk_norm, + rope_type=rope_type, + ) + + # 3. Audio-to-Video (a2v) and Video-to-Audio (v2a) Cross-Attention + # Audio-to-Video (a2v) Attention --> Q: Video; K,V: Audio + self.audio_to_video_norm = _make_rms_norm(dim, eps=eps, elementwise_affine=elementwise_affine) + self.audio_to_video_attn = LTX2Attention( + query_dim=dim, + cross_attention_dim=audio_dim, + heads=audio_num_attention_heads, + kv_heads=audio_num_attention_heads, + dim_head=audio_attention_head_dim, + bias=attention_bias, + out_bias=attention_out_bias, + qk_norm=qk_norm, + rope_type=rope_type, + ) + + # Video-to-Audio (v2a) Attention --> Q: Audio; K,V: Video + self.video_to_audio_norm = _make_rms_norm(audio_dim, eps=eps, elementwise_affine=elementwise_affine) + self.video_to_audio_attn = LTX2Attention( + query_dim=audio_dim, + cross_attention_dim=dim, + heads=audio_num_attention_heads, + kv_heads=audio_num_attention_heads, + dim_head=audio_attention_head_dim, + bias=attention_bias, + out_bias=attention_out_bias, + qk_norm=qk_norm, + rope_type=rope_type, + ) + + # 4. Feedforward layers + self.norm3 = _make_rms_norm(dim, eps=eps, elementwise_affine=elementwise_affine) + self.ff = LTX2FeedForward(dim, activation_fn=activation_fn) + + self.audio_norm3 = _make_rms_norm(audio_dim, eps=eps, elementwise_affine=elementwise_affine) + self.audio_ff = LTX2FeedForward(audio_dim, activation_fn=activation_fn) + + # 5. Per-Layer Modulation Parameters + # Self-Attention / Feedforward AdaLayerNorm-Zero mod params + self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5) + self.audio_scale_shift_table = nn.Parameter(torch.randn(6, audio_dim) / audio_dim**0.5) + + # Per-layer a2v, v2a Cross-Attention mod params + self.video_a2v_cross_attn_scale_shift_table = nn.Parameter(torch.randn(5, dim)) + self.audio_a2v_cross_attn_scale_shift_table = nn.Parameter(torch.randn(5, audio_dim)) + + def forward( + self, + hidden_states: torch.Tensor, + audio_hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor, + audio_encoder_hidden_states: torch.Tensor, + temb: torch.Tensor, + temb_audio: torch.Tensor, + temb_ca_scale_shift: torch.Tensor, + temb_ca_audio_scale_shift: torch.Tensor, + temb_ca_gate: torch.Tensor, + temb_ca_audio_gate: torch.Tensor, + video_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None, + audio_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None, + ca_video_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None, + ca_audio_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None, + encoder_attention_mask: torch.Tensor | None = None, + audio_encoder_attention_mask: torch.Tensor | None = None, + a2v_cross_attention_mask: torch.Tensor | None = None, + v2a_cross_attention_mask: torch.Tensor | None = None, + ) -> torch.Tensor: + batch_size = hidden_states.size(0) + + # 1. Video and Audio Self-Attention + norm_hidden_states = self.norm1(hidden_states) + + num_ada_params = self.scale_shift_table.shape[0] + ada_values = self.scale_shift_table[None, None].to(temb.device) + temb.reshape( + batch_size, temb.size(1), num_ada_params, -1 + ) + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ada_values.unbind(dim=2) + norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa + + attn_hidden_states = self.attn1( + hidden_states=norm_hidden_states, + encoder_hidden_states=None, + query_rotary_emb=video_rotary_emb, + ) + hidden_states = hidden_states + attn_hidden_states * gate_msa + + norm_audio_hidden_states = self.audio_norm1(audio_hidden_states) + + num_audio_ada_params = self.audio_scale_shift_table.shape[0] + audio_ada_values = self.audio_scale_shift_table[None, None].to(temb_audio.device) + temb_audio.reshape( + batch_size, temb_audio.size(1), num_audio_ada_params, -1 + ) + audio_shift_msa, audio_scale_msa, audio_gate_msa, audio_shift_mlp, audio_scale_mlp, audio_gate_mlp = ( + audio_ada_values.unbind(dim=2) + ) + norm_audio_hidden_states = norm_audio_hidden_states * (1 + audio_scale_msa) + audio_shift_msa + + attn_audio_hidden_states = self.audio_attn1( + hidden_states=norm_audio_hidden_states, + encoder_hidden_states=None, + query_rotary_emb=audio_rotary_emb, + ) + audio_hidden_states = audio_hidden_states + attn_audio_hidden_states * audio_gate_msa + + # 2. Video and Audio Cross-Attention with the text embeddings + norm_hidden_states = self.norm2(hidden_states) + attn_hidden_states = self.attn2( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + query_rotary_emb=None, + attention_mask=encoder_attention_mask, + ) + hidden_states = hidden_states + attn_hidden_states + + norm_audio_hidden_states = self.audio_norm2(audio_hidden_states) + attn_audio_hidden_states = self.audio_attn2( + norm_audio_hidden_states, + encoder_hidden_states=audio_encoder_hidden_states, + query_rotary_emb=None, + attention_mask=audio_encoder_attention_mask, + ) + audio_hidden_states = audio_hidden_states + attn_audio_hidden_states + + # 3. Audio-to-Video (a2v) and Video-to-Audio (v2a) Cross-Attention + norm_hidden_states = self.audio_to_video_norm(hidden_states) + norm_audio_hidden_states = self.video_to_audio_norm(audio_hidden_states) + + # Combine global and per-layer cross attention modulation parameters + # Video + video_per_layer_ca_scale_shift = self.video_a2v_cross_attn_scale_shift_table[:4, :] + video_per_layer_ca_gate = self.video_a2v_cross_attn_scale_shift_table[4:, :] + + video_ca_scale_shift_table = ( + video_per_layer_ca_scale_shift[:, :, ...].to(temb_ca_scale_shift.dtype) + + temb_ca_scale_shift.reshape(batch_size, temb_ca_scale_shift.shape[1], 4, -1) + ).unbind(dim=2) + video_ca_gate = ( + video_per_layer_ca_gate[:, :, ...].to(temb_ca_gate.dtype) + + temb_ca_gate.reshape(batch_size, temb_ca_gate.shape[1], 1, -1) + ).unbind(dim=2) + + video_a2v_ca_scale, video_a2v_ca_shift, video_v2a_ca_scale, video_v2a_ca_shift = video_ca_scale_shift_table + a2v_gate = video_ca_gate[0].squeeze(2) + + # Audio + audio_per_layer_ca_scale_shift = self.audio_a2v_cross_attn_scale_shift_table[:4, :] + audio_per_layer_ca_gate = self.audio_a2v_cross_attn_scale_shift_table[4:, :] + + audio_ca_scale_shift_table = ( + audio_per_layer_ca_scale_shift[:, :, ...].to(temb_ca_audio_scale_shift.dtype) + + temb_ca_audio_scale_shift.reshape(batch_size, temb_ca_audio_scale_shift.shape[1], 4, -1) + ).unbind(dim=2) + audio_ca_gate = ( + audio_per_layer_ca_gate[:, :, ...].to(temb_ca_audio_gate.dtype) + + temb_ca_audio_gate.reshape(batch_size, temb_ca_audio_gate.shape[1], 1, -1) + ).unbind(dim=2) + + audio_a2v_ca_scale, audio_a2v_ca_shift, audio_v2a_ca_scale, audio_v2a_ca_shift = audio_ca_scale_shift_table + v2a_gate = audio_ca_gate[0].squeeze(2) + + # Audio-to-Video Cross Attention: Q: Video; K,V: Audio + mod_norm_hidden_states = norm_hidden_states * (1 + video_a2v_ca_scale.squeeze(2)) + video_a2v_ca_shift.squeeze( + 2 + ) + mod_norm_audio_hidden_states = norm_audio_hidden_states * ( + 1 + audio_a2v_ca_scale.squeeze(2) + ) + audio_a2v_ca_shift.squeeze(2) + + a2v_attn_hidden_states = self.audio_to_video_attn( + mod_norm_hidden_states, + encoder_hidden_states=mod_norm_audio_hidden_states, + query_rotary_emb=ca_video_rotary_emb, + key_rotary_emb=ca_audio_rotary_emb, + attention_mask=a2v_cross_attention_mask, + ) + + hidden_states = hidden_states + a2v_gate * a2v_attn_hidden_states + + # Video-to-Audio Cross Attention: Q: Audio; K,V: Video + mod_norm_hidden_states = norm_hidden_states * (1 + video_v2a_ca_scale.squeeze(2)) + video_v2a_ca_shift.squeeze( + 2 + ) + mod_norm_audio_hidden_states = norm_audio_hidden_states * ( + 1 + audio_v2a_ca_scale.squeeze(2) + ) + audio_v2a_ca_shift.squeeze(2) + + v2a_attn_hidden_states = self.video_to_audio_attn( + mod_norm_audio_hidden_states, + encoder_hidden_states=mod_norm_hidden_states, + query_rotary_emb=ca_audio_rotary_emb, + key_rotary_emb=ca_video_rotary_emb, + attention_mask=v2a_cross_attention_mask, + ) + + audio_hidden_states = audio_hidden_states + v2a_gate * v2a_attn_hidden_states + + # 4. Feedforward + norm_hidden_states = self.norm3(hidden_states) * (1 + scale_mlp) + shift_mlp + ff_output = self.ff(norm_hidden_states) + hidden_states = hidden_states + ff_output * gate_mlp + + norm_audio_hidden_states = self.audio_norm3(audio_hidden_states) * (1 + audio_scale_mlp) + audio_shift_mlp + audio_ff_output = self.audio_ff(norm_audio_hidden_states) + audio_hidden_states = audio_hidden_states + audio_ff_output * audio_gate_mlp + + return hidden_states, audio_hidden_states + + +class LTX2AudioVideoRotaryPosEmbed(nn.Module): + """ + Video and audio rotary positional embeddings (RoPE) for the LTX-2.0 model. + + Args: + causal_offset (`int`, *optional*, defaults to `1`): + Offset in the temporal axis for causal VAE modeling. This is typically 1 (for causal modeling where the VAE + treats the very first frame differently), but could also be 0 (for non-causal modeling). + """ + + def __init__( + self, + dim: int, + patch_size: int = 1, + patch_size_t: int = 1, + base_num_frames: int = 20, + base_height: int = 2048, + base_width: int = 2048, + sampling_rate: int = 16000, + hop_length: int = 160, + scale_factors: tuple[int, ...] = (8, 32, 32), + theta: float = 10000.0, + causal_offset: int = 1, + modality: str = "video", + double_precision: bool = True, + rope_type: str = "interleaved", + num_attention_heads: int = 32, + ) -> None: + super().__init__() + + self.dim = dim + self.patch_size = patch_size + self.patch_size_t = patch_size_t + + if rope_type not in ["interleaved", "split"]: + raise ValueError(f"{rope_type=} not supported. Choose between 'interleaved' and 'split'.") + self.rope_type = rope_type + + self.base_num_frames = base_num_frames + self.num_attention_heads = num_attention_heads + + # Video-specific + self.base_height = base_height + self.base_width = base_width + + # Audio-specific + self.sampling_rate = sampling_rate + self.hop_length = hop_length + self.audio_latents_per_second = float(sampling_rate) / float(hop_length) / float(scale_factors[0]) + + self.scale_factors = scale_factors + self.theta = theta + self.causal_offset = causal_offset + + self.modality = modality + if self.modality not in ["video", "audio"]: + raise ValueError(f"Modality {modality} is not supported. Supported modalities are `video` and `audio`.") + self.double_precision = double_precision + + def prepare_video_coords( + self, + batch_size: int, + num_frames: int, + height: int, + width: int, + device: torch.device, + fps: float = 24.0, + ) -> torch.Tensor: + """ + Create per-dimension bounds [inclusive start, exclusive end) for each patch with respect to the original pixel + space video grid (num_frames, height, width). This will ultimately have shape (batch_size, 3, num_patches, 2) + where + - axis 1 (size 3) enumerates (frame, height, width) dimensions (e.g. idx 0 corresponds to frames) + - axis 3 (size 2) stores `[start, end)` indices within each dimension + + Args: + batch_size (`int`): + Batch size of the video latents. + num_frames (`int`): + Number of latent frames in the video latents. + height (`int`): + Latent height of the video latents. + width (`int`): + Latent width of the video latents. + device (`torch.device`): + Device on which to create the video grid. + + Returns: + `torch.Tensor`: + Per-dimension patch boundaries tensor of shape [batch_size, 3, num_patches, 2]. + """ + + # 1. Generate grid coordinates for each spatiotemporal dimension (frames, height, width) + # Always compute rope in fp32 + grid_f = torch.arange(start=0, end=num_frames, step=self.patch_size_t, dtype=torch.float32, device=device) + grid_h = torch.arange(start=0, end=height, step=self.patch_size, dtype=torch.float32, device=device) + grid_w = torch.arange(start=0, end=width, step=self.patch_size, dtype=torch.float32, device=device) + # indexing='ij' ensures that the dimensions are kept in order as (frames, height, width) + grid = torch.meshgrid(grid_f, grid_h, grid_w, indexing="ij") + grid = torch.stack(grid, dim=0) # [3, N_F, N_H, N_W], where e.g. N_F is the number of temporal patches + + # 2. Get the patch boundaries with respect to the latent video grid + patch_size = (self.patch_size_t, self.patch_size, self.patch_size) + patch_size_delta = torch.tensor(patch_size, dtype=grid.dtype, device=grid.device) + patch_ends = grid + patch_size_delta.view(3, 1, 1, 1) + + # Combine the start (grid) and end (patch_ends) coordinates along new trailing dimension + latent_coords = torch.stack([grid, patch_ends], dim=-1) # [3, N_F, N_H, N_W, 2] + # Reshape to (batch_size, 3, num_patches, 2) + latent_coords = latent_coords.flatten(1, 3) + latent_coords = latent_coords.unsqueeze(0).repeat(batch_size, 1, 1, 1) + + # 3. Calculate the pixel space patch boundaries from the latent boundaries. + scale_tensor = torch.tensor(self.scale_factors, device=latent_coords.device) + # Broadcast the VAE scale factors such that they are compatible with latent_coords's shape + broadcast_shape = [1] * latent_coords.ndim + broadcast_shape[1] = -1 # This is the (frame, height, width) dim + # Apply per-axis scaling to convert latent coordinates to pixel space coordinates + pixel_coords = latent_coords * scale_tensor.view(*broadcast_shape) + + # As the VAE temporal stride for the first frame is 1 instead of self.vae_scale_factors[0], we need to shift + # and clamp to keep the first-frame timestamps causal and non-negative. + pixel_coords[:, 0, ...] = (pixel_coords[:, 0, ...] + self.causal_offset - self.scale_factors[0]).clamp(min=0) + + # Scale the temporal coordinates by the video FPS + pixel_coords[:, 0, ...] = pixel_coords[:, 0, ...] / fps + + return pixel_coords + + def prepare_audio_coords( + self, + batch_size: int, + num_frames: int, + device: torch.device, + shift: int = 0, + ) -> torch.Tensor: + """ + Create per-dimension bounds [inclusive start, exclusive end) of start and end timestamps for each latent frame. + This will ultimately have shape (batch_size, 3, num_patches, 2) where + - axis 1 (size 1) represents the temporal dimension + - axis 3 (size 2) stores `[start, end)` indices within each dimension + + Args: + batch_size (`int`): + Batch size of the audio latents. + num_frames (`int`): + Number of latent frames in the audio latents. + device (`torch.device`): + Device on which to create the audio grid. + shift (`int`, *optional*, defaults to `0`): + Offset on the latent indices. Different shift values correspond to different overlapping windows with + respect to the same underlying latent grid. + + Returns: + `torch.Tensor`: + Per-dimension patch boundaries tensor of shape [batch_size, 1, num_patches, 2]. + """ + + # 1. Generate coordinates in the frame (time) dimension. + # Always compute rope in fp32 + grid_f = torch.arange( + start=shift, end=num_frames + shift, step=self.patch_size_t, dtype=torch.float32, device=device + ) + + # 2. Calculate start timestamps in seconds with respect to the original spectrogram grid + audio_scale_factor = self.scale_factors[0] + # Scale back to mel spectrogram space + grid_start_mel = grid_f * audio_scale_factor + # Handle first frame causal offset, ensuring non-negative timestamps + grid_start_mel = (grid_start_mel + self.causal_offset - audio_scale_factor).clip(min=0) + # Convert mel bins back into seconds + grid_start_s = grid_start_mel * self.hop_length / self.sampling_rate + + # 3. Calculate start timestamps in seconds with respect to the original spectrogram grid + grid_end_mel = (grid_f + self.patch_size_t) * audio_scale_factor + grid_end_mel = (grid_end_mel + self.causal_offset - audio_scale_factor).clip(min=0) + grid_end_s = grid_end_mel * self.hop_length / self.sampling_rate + + audio_coords = torch.stack([grid_start_s, grid_end_s], dim=-1) # [num_patches, 2] + audio_coords = audio_coords.unsqueeze(0).expand(batch_size, -1, -1) # [batch_size, num_patches, 2] + audio_coords = audio_coords.unsqueeze(1) # [batch_size, 1, num_patches, 2] + return audio_coords + + def prepare_coords(self, *args, **kwargs): + if self.modality == "video": + return self.prepare_video_coords(*args, **kwargs) + elif self.modality == "audio": + return self.prepare_audio_coords(*args, **kwargs) + + def forward( + self, coords: torch.Tensor, device: str | torch.device | None = None + ) -> tuple[torch.Tensor, torch.Tensor]: + device = device or coords.device + + # Number of spatiotemporal dimensions (3 for video, 1 (temporal) for audio and cross attn) + num_pos_dims = coords.shape[1] + + # 1. If the coords are patch boundaries [start, end), use the midpoint of these boundaries as the patch + # position index + if coords.ndim == 4: + coords_start, coords_end = coords.chunk(2, dim=-1) + coords = (coords_start + coords_end) / 2.0 + coords = coords.squeeze(-1) # [B, num_pos_dims, num_patches] + + # 2. Get coordinates as a fraction of the base data shape + if self.modality == "video": + max_positions = (self.base_num_frames, self.base_height, self.base_width) + elif self.modality == "audio": + max_positions = (self.base_num_frames,) + # [B, num_pos_dims, num_patches] --> [B, num_patches, num_pos_dims] + grid = torch.stack([coords[:, i] / max_positions[i] for i in range(num_pos_dims)], dim=-1).to(device) + # Number of spatiotemporal dimensions (3 for video, 1 for audio and cross attn) times 2 for cos, sin + num_rope_elems = num_pos_dims * 2 + + # 3. Create a 1D grid of frequencies for RoPE + freqs_dtype = torch.float64 if self.double_precision else torch.float32 + pow_indices = torch.pow( + self.theta, + torch.linspace(start=0.0, end=1.0, steps=self.dim // num_rope_elems, dtype=freqs_dtype, device=device), + ) + freqs = (pow_indices * torch.pi / 2.0).to(dtype=torch.float32) + + # 4. Tensor-vector outer product between pos ids tensor of shape (B, 3, num_patches) and freqs vector of shape + # (self.dim // num_elems,) + freqs = (grid.unsqueeze(-1) * 2 - 1) * freqs # [B, num_patches, num_pos_dims, self.dim // num_elems] + freqs = freqs.transpose(-1, -2).flatten(2) # [B, num_patches, self.dim // 2] + + # 5. Get real, interleaved (cos, sin) frequencies, padded to self.dim. + # Kept inline here to stay aligned with the upstream diffusers connector logic. + # src/diffusers/pipelines/ltx2/connectors.py + if self.rope_type == "interleaved": + cos_freqs = freqs.cos().repeat_interleave(2, dim=-1) + sin_freqs = freqs.sin().repeat_interleave(2, dim=-1) + + if self.dim % num_rope_elems != 0: + cos_padding = torch.ones_like(cos_freqs[:, :, : self.dim % num_rope_elems]) + sin_padding = torch.zeros_like(cos_freqs[:, :, : self.dim % num_rope_elems]) + cos_freqs = torch.cat([cos_padding, cos_freqs], dim=-1) + sin_freqs = torch.cat([sin_padding, sin_freqs], dim=-1) + + elif self.rope_type == "split": + expected_freqs = self.dim // 2 + current_freqs = freqs.shape[-1] + pad_size = expected_freqs - current_freqs + cos_freq = freqs.cos() + sin_freq = freqs.sin() + + if pad_size != 0: + cos_padding = torch.ones_like(cos_freq[:, :, :pad_size]) + sin_padding = torch.zeros_like(sin_freq[:, :, :pad_size]) + + cos_freq = torch.concatenate([cos_padding, cos_freq], axis=-1) + sin_freq = torch.concatenate([sin_padding, sin_freq], axis=-1) + + # Reshape freqs to be compatible with multi-head attention + b = cos_freq.shape[0] + t = cos_freq.shape[1] + + cos_freq = cos_freq.reshape(b, t, self.num_attention_heads, -1) + sin_freq = sin_freq.reshape(b, t, self.num_attention_heads, -1) + + 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) + + return cos_freqs, sin_freqs + + +class LTX2VideoTransformer3DModel(nn.Module): + r""" + A Transformer model for video-like data used in [LTX](https://huggingface.co/Lightricks/LTX-Video). + + Args: + in_channels (`int`, defaults to `128`): + The number of channels in the input. + out_channels (`int`, defaults to `128`): + The number of channels in the output. + patch_size (`int`, defaults to `1`): + The size of the spatial patches to use in the patch embedding layer. + patch_size_t (`int`, defaults to `1`): + The size of the tmeporal patches to use in the patch embedding layer. + num_attention_heads (`int`, defaults to `32`): + The number of heads to use for multi-head attention. + attention_head_dim (`int`, defaults to `64`): + The number of channels in each head. + cross_attention_dim (`int`, defaults to `2048 `): + The number of channels for cross attention heads. + num_layers (`int`, defaults to `28`): + The number of layers of Transformer blocks to use. + activation_fn (`str`, defaults to `"gelu-approximate"`): + Activation function to use in feed-forward. + qk_norm (`str`, defaults to `"rms_norm_across_heads"`): + The normalization layer to use. + """ + + _supports_gradient_checkpointing = True + _skip_layerwise_casting_patterns = ["norm"] + _repeated_blocks = ["LTX2VideoTransformerBlock"] + _sp_plan: dict[str, Any] | None = None + + @staticmethod + def _build_sp_plan(rope_type: str) -> dict[str, Any]: + if rope_type == "split": + # split RoPE returns (B, H, T, D/2) -> shard along T dim + rope_expected_dims = 4 + rope_split_dim = 2 + else: + # interleaved RoPE returns (B, T, D) -> shard along T dim + rope_expected_dims = 3 + rope_split_dim = 1 + + return { + "": { + # Shard video/audio latents across sequence + "hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False), + "audio_hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False), + # 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) + "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), + 1: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True), + }, + "audio_rope": { + 0: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True), + 1: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True), + }, + "cross_attn_rope": { + 0: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True), + 1: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True), + }, + "cross_attn_audio_rope": { + 0: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True), + 1: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True), + }, + # Gather outputs before returning + "proj_out": SequenceParallelOutput(gather_dim=1, expected_dims=3), + "audio_proj_out": SequenceParallelOutput(gather_dim=1, expected_dims=3), + } + + def __init__( + self, + in_channels: int = 128, # Video Arguments + out_channels: int | None = 128, + patch_size: int = 1, + patch_size_t: int = 1, + num_attention_heads: int = 32, + attention_head_dim: int = 128, + cross_attention_dim: int = 4096, + vae_scale_factors: tuple[int, int, int] = (8, 32, 32), + pos_embed_max_pos: int = 20, + base_height: int = 2048, + base_width: int = 2048, + audio_in_channels: int = 128, # Audio Arguments + audio_out_channels: int | None = 128, + audio_patch_size: int = 1, + audio_patch_size_t: int = 1, + audio_num_attention_heads: int = 32, + audio_attention_head_dim: int = 64, + audio_cross_attention_dim: int = 2048, + audio_scale_factor: int = 4, + audio_pos_embed_max_pos: int = 20, + audio_sampling_rate: int = 16000, + audio_hop_length: int = 160, + num_layers: int = 48, # Shared arguments + activation_fn: str = "gelu-approximate", + qk_norm: str = "rms_norm_across_heads", + norm_elementwise_affine: bool = False, + norm_eps: float = 1e-6, + caption_channels: int = 3840, + attention_bias: bool = True, + attention_out_bias: bool = True, + rope_theta: float = 10000.0, + rope_double_precision: bool = True, + causal_offset: int = 1, + timestep_scale_multiplier: int = 1000, + cross_attn_timestep_scale_multiplier: int = 1000, + rope_type: str = "interleaved", + ) -> None: + super().__init__() + + out_channels = out_channels or in_channels + audio_out_channels = audio_out_channels or audio_in_channels + inner_dim = num_attention_heads * attention_head_dim + audio_inner_dim = audio_num_attention_heads * audio_attention_head_dim + self.config = SimpleNamespace( + in_channels=in_channels, + out_channels=out_channels, + patch_size=patch_size, + patch_size_t=patch_size_t, + num_attention_heads=num_attention_heads, + attention_head_dim=attention_head_dim, + cross_attention_dim=cross_attention_dim, + vae_scale_factors=vae_scale_factors, + pos_embed_max_pos=pos_embed_max_pos, + base_height=base_height, + base_width=base_width, + audio_in_channels=audio_in_channels, + audio_out_channels=audio_out_channels, + audio_patch_size=audio_patch_size, + audio_patch_size_t=audio_patch_size_t, + audio_num_attention_heads=audio_num_attention_heads, + audio_attention_head_dim=audio_attention_head_dim, + audio_cross_attention_dim=audio_cross_attention_dim, + audio_scale_factor=audio_scale_factor, + audio_pos_embed_max_pos=audio_pos_embed_max_pos, + audio_sampling_rate=audio_sampling_rate, + audio_hop_length=audio_hop_length, + num_layers=num_layers, + activation_fn=activation_fn, + qk_norm=qk_norm, + norm_elementwise_affine=norm_elementwise_affine, + norm_eps=norm_eps, + caption_channels=caption_channels, + attention_bias=attention_bias, + attention_out_bias=attention_out_bias, + rope_theta=rope_theta, + rope_double_precision=rope_double_precision, + causal_offset=causal_offset, + timestep_scale_multiplier=timestep_scale_multiplier, + cross_attn_timestep_scale_multiplier=cross_attn_timestep_scale_multiplier, + rope_type=rope_type, + ) + + # 1. Patchification input projections + self.proj_in = nn.Linear(in_channels, inner_dim) + self.audio_proj_in = nn.Linear(audio_in_channels, audio_inner_dim) + + # 2. Prompt embeddings + self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim) + self.audio_caption_projection = PixArtAlphaTextProjection( + in_features=caption_channels, hidden_size=audio_inner_dim + ) + + # 3. Timestep Modulation Params and Embedding + # 3.1. Global Timestep Modulation Parameters (except for cross-attention) and timestep + size embedding + # time_embed and audio_time_embed calculate both the timestep embedding and (global) modulation parameters + self.time_embed = LTX2AdaLayerNormSingle(inner_dim, num_mod_params=6, use_additional_conditions=False) + self.audio_time_embed = LTX2AdaLayerNormSingle( + audio_inner_dim, num_mod_params=6, use_additional_conditions=False + ) + + # 3.2. Global Cross Attention Modulation Parameters + # Used in the audio-to-video and video-to-audio cross attention layers as a global set of modulation params, + # which are then further modified by per-block modulaton params in each transformer block. + # There are 2 sets of scale/shift parameters for each modality, 1 each for audio-to-video (a2v) and + # video-to-audio (v2a) cross attention + self.av_cross_attn_video_scale_shift = LTX2AdaLayerNormSingle( + inner_dim, num_mod_params=4, use_additional_conditions=False + ) + self.av_cross_attn_audio_scale_shift = LTX2AdaLayerNormSingle( + audio_inner_dim, num_mod_params=4, use_additional_conditions=False + ) + # Gate param for audio-to-video (a2v) cross attn (where the video is the queries (Q) and the audio is the keys + # and values (KV)) + self.av_cross_attn_video_a2v_gate = LTX2AdaLayerNormSingle( + inner_dim, num_mod_params=1, use_additional_conditions=False + ) + # Gate param for video-to-audio (v2a) cross attn (where the audio is the queries (Q) and the video is the keys + # and values (KV)) + self.av_cross_attn_audio_v2a_gate = LTX2AdaLayerNormSingle( + audio_inner_dim, num_mod_params=1, use_additional_conditions=False + ) + + # 3.3. Output Layer Scale/Shift Modulation parameters + self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5) + self.audio_scale_shift_table = nn.Parameter(torch.randn(2, audio_inner_dim) / audio_inner_dim**0.5) + + # 4. Rotary Positional Embeddings (RoPE) + # Self-Attention + self.rope = LTX2AudioVideoRotaryPosEmbed( + dim=inner_dim, + patch_size=patch_size, + patch_size_t=patch_size_t, + base_num_frames=pos_embed_max_pos, + base_height=base_height, + base_width=base_width, + scale_factors=vae_scale_factors, + theta=rope_theta, + causal_offset=causal_offset, + modality="video", + double_precision=rope_double_precision, + rope_type=rope_type, + num_attention_heads=num_attention_heads, + ) + self.audio_rope = LTX2AudioVideoRotaryPosEmbed( + dim=audio_inner_dim, + patch_size=audio_patch_size, + patch_size_t=audio_patch_size_t, + base_num_frames=audio_pos_embed_max_pos, + sampling_rate=audio_sampling_rate, + hop_length=audio_hop_length, + scale_factors=[audio_scale_factor], + theta=rope_theta, + causal_offset=causal_offset, + modality="audio", + double_precision=rope_double_precision, + rope_type=rope_type, + num_attention_heads=audio_num_attention_heads, + ) + + # Audio-to-Video, Video-to-Audio Cross-Attention + cross_attn_pos_embed_max_pos = max(pos_embed_max_pos, audio_pos_embed_max_pos) + self.cross_attn_rope = LTX2AudioVideoRotaryPosEmbed( + dim=audio_cross_attention_dim, + patch_size=patch_size, + patch_size_t=patch_size_t, + base_num_frames=cross_attn_pos_embed_max_pos, + base_height=base_height, + base_width=base_width, + theta=rope_theta, + causal_offset=causal_offset, + modality="video", + double_precision=rope_double_precision, + rope_type=rope_type, + num_attention_heads=num_attention_heads, + ) + self.cross_attn_audio_rope = LTX2AudioVideoRotaryPosEmbed( + dim=audio_cross_attention_dim, + patch_size=audio_patch_size, + patch_size_t=audio_patch_size_t, + base_num_frames=cross_attn_pos_embed_max_pos, + sampling_rate=audio_sampling_rate, + hop_length=audio_hop_length, + theta=rope_theta, + causal_offset=causal_offset, + modality="audio", + double_precision=rope_double_precision, + rope_type=rope_type, + num_attention_heads=audio_num_attention_heads, + ) + + # 5. Transformer Blocks + self.transformer_blocks = nn.ModuleList( + [ + LTX2VideoTransformerBlock( + dim=inner_dim, + num_attention_heads=num_attention_heads, + attention_head_dim=attention_head_dim, + cross_attention_dim=cross_attention_dim, + audio_dim=audio_inner_dim, + audio_num_attention_heads=audio_num_attention_heads, + audio_attention_head_dim=audio_attention_head_dim, + audio_cross_attention_dim=audio_cross_attention_dim, + qk_norm=qk_norm, + activation_fn=activation_fn, + attention_bias=attention_bias, + attention_out_bias=attention_out_bias, + eps=norm_eps, + elementwise_affine=norm_elementwise_affine, + rope_type=rope_type, + ) + for _ in range(num_layers) + ] + ) + + # 6. Output layers + self.norm_out = nn.LayerNorm(inner_dim, eps=1e-6, elementwise_affine=False) + self.proj_out = nn.Linear(inner_dim, out_channels) + + self.audio_norm_out = nn.LayerNorm(audio_inner_dim, eps=1e-6, elementwise_affine=False) + self.audio_proj_out = nn.Linear(audio_inner_dim, audio_out_channels) + + self.gradient_checkpointing = False + self._sp_plan = self._build_sp_plan(rope_type) + + def _gradient_checkpointing_func(self, module: nn.Module, *inputs: Any): + def custom_forward(*checkpoint_inputs: Any): + return module(*checkpoint_inputs) + + return checkpoint(custom_forward, *inputs, use_reentrant=False) + + def enable_gradient_checkpointing(self) -> None: + self.gradient_checkpointing = True + + def disable_gradient_checkpointing(self) -> None: + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.Tensor, + audio_hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor, + audio_encoder_hidden_states: torch.Tensor, + timestep: torch.LongTensor, + audio_timestep: torch.LongTensor | None = None, + encoder_attention_mask: torch.Tensor | None = None, + audio_encoder_attention_mask: torch.Tensor | None = None, + num_frames: int | None = None, + height: int | None = None, + width: int | None = None, + fps: float = 24.0, + audio_num_frames: int | None = None, + video_coords: torch.Tensor | None = None, + audio_coords: torch.Tensor | None = None, + attention_kwargs: dict[str, Any] | None = None, + return_dict: bool = True, + ) -> torch.Tensor: + """ + Forward pass for LTX-2.0 audiovisual video transformer. + + Args: + hidden_states (`torch.Tensor`): + Input patchified video latents of shape `(batch_size, num_video_tokens, in_channels)`. + audio_hidden_states (`torch.Tensor`): + Input patchified audio latents of shape `(batch_size, num_audio_tokens, audio_in_channels)`. + encoder_hidden_states (`torch.Tensor`): + Input video text embeddings of shape `(batch_size, text_seq_len, self.config.caption_channels)`. + audio_encoder_hidden_states (`torch.Tensor`): + Input audio text embeddings of shape `(batch_size, text_seq_len, self.config.caption_channels)`. + timestep (`torch.Tensor`): + Input timestep of shape `(batch_size, num_video_tokens)`. These should already be scaled by + `self.config.timestep_scale_multiplier`. + audio_timestep (`torch.Tensor`, *optional*): + Input timestep of shape `(batch_size,)` or `(batch_size, num_audio_tokens)` for audio modulation + params. This is only used by certain pipelines such as the I2V pipeline. + encoder_attention_mask (`torch.Tensor`, *optional*): + Optional multiplicative text attention mask of shape `(batch_size, text_seq_len)`. + audio_encoder_attention_mask (`torch.Tensor`, *optional*): + Optional multiplicative text attention mask of shape `(batch_size, text_seq_len)` for audio modeling. + num_frames (`int`, *optional*): + The number of latent video frames. Used if calculating the video coordinates for RoPE. + height (`int`, *optional*): + The latent video height. Used if calculating the video coordinates for RoPE. + width (`int`, *optional*): + The latent video width. Used if calculating the video coordinates for RoPE. + fps: (`float`, *optional*, defaults to `24.0`): + The desired frames per second of the generated video. Used if calculating the video coordinates for + RoPE. + audio_num_frames: (`int`, *optional*): + The number of latent audio frames. Used if calculating the audio coordinates for RoPE. + video_coords (`torch.Tensor`, *optional*): + The video coordinates to be used when calculating the rotary positional embeddings (RoPE) of shape + `(batch_size, 3, num_video_tokens, 2)`. If not supplied, this will be calculated inside `forward`. + audio_coords (`torch.Tensor`, *optional*): + The audio coordinates to be used when calculating the rotary positional embeddings (RoPE) of shape + `(batch_size, 1, num_audio_tokens, 2)`. If not supplied, this will be calculated inside `forward`. + attention_kwargs (`Dict[str, Any]`, *optional*): + Optional dict of keyword args to be passed to the attention processor. + return_dict (`bool`, *optional*, defaults to `True`): + Whether to return a dict-like structured output of type `AudioVisualModelOutput` or a tuple. + + Returns: + `AudioVisualModelOutput` or `tuple`: + If `return_dict` is `True`, returns a structured output of type `AudioVisualModelOutput`, otherwise a + `tuple` is returned where the first element is the denoised video latent patch sequence and the second + element is the denoised audio latent patch sequence. + """ + # Determine timestep for audio. + audio_timestep = audio_timestep if audio_timestep is not None else 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 + encoder_attention_mask = encoder_attention_mask.unsqueeze(1) + + if audio_encoder_attention_mask is not None and audio_encoder_attention_mask.ndim == 2: + audio_encoder_attention_mask = (1 - audio_encoder_attention_mask.to(audio_hidden_states.dtype)) * -10000.0 + audio_encoder_attention_mask = audio_encoder_attention_mask.unsqueeze(1) + + batch_size = hidden_states.size(0) + + # 1. Prepare RoPE positional embeddings + if video_coords is None: + video_coords = self.rope.prepare_video_coords( + batch_size, num_frames, height, width, hidden_states.device, fps=fps + ) + if audio_coords is None: + audio_coords = self.audio_rope.prepare_audio_coords( + 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_cross_attn_rotary_emb = self.cross_attn_rope(video_coords[:, 0:1, :], device=hidden_states.device) + audio_cross_attn_rotary_emb = self.cross_attn_audio_rope( + audio_coords[:, 0:1, :], device=audio_hidden_states.device + ) + + # 2. Patchify input projections + hidden_states = self.proj_in(hidden_states) + audio_hidden_states = self.audio_proj_in(audio_hidden_states) + + # 3. Prepare timestep embeddings and modulation parameters + timestep_cross_attn_gate_scale_factor = ( + self.config.cross_attn_timestep_scale_multiplier / self.config.timestep_scale_multiplier + ) + + # 3.1. Prepare global modality (video and audio) timestep embedding and modulation parameters + # temb is used in the transformer blocks (as expected), while embedded_timestep is used for the output layer + # modulation with scale_shift_table (and similarly for audio) + temb, embedded_timestep = self.time_embed( + timestep.flatten(), + batch_size=batch_size, + hidden_dtype=hidden_states.dtype, + ) + temb = temb.view(batch_size, -1, temb.size(-1)) + embedded_timestep = embedded_timestep.view(batch_size, -1, embedded_timestep.size(-1)) + + temb_audio, audio_embedded_timestep = self.audio_time_embed( + audio_timestep.flatten(), + batch_size=batch_size, + hidden_dtype=audio_hidden_states.dtype, + ) + temb_audio = temb_audio.view(batch_size, -1, temb_audio.size(-1)) + audio_embedded_timestep = audio_embedded_timestep.view(batch_size, -1, audio_embedded_timestep.size(-1)) + + # 3.2. Prepare global modality cross attention modulation parameters + video_cross_attn_scale_shift, _ = self.av_cross_attn_video_scale_shift( + timestep.flatten(), + batch_size=batch_size, + 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, + batch_size=batch_size, + hidden_dtype=hidden_states.dtype, + ) + video_cross_attn_scale_shift = video_cross_attn_scale_shift.view( + batch_size, -1, video_cross_attn_scale_shift.shape[-1] + ) + video_cross_attn_a2v_gate = video_cross_attn_a2v_gate.view(batch_size, -1, video_cross_attn_a2v_gate.shape[-1]) + + audio_cross_attn_scale_shift, _ = self.av_cross_attn_audio_scale_shift( + audio_timestep.flatten(), + batch_size=batch_size, + 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, + batch_size=batch_size, + hidden_dtype=audio_hidden_states.dtype, + ) + audio_cross_attn_scale_shift = audio_cross_attn_scale_shift.view( + batch_size, -1, audio_cross_attn_scale_shift.shape[-1] + ) + audio_cross_attn_v2a_gate = audio_cross_attn_v2a_gate.view(batch_size, -1, audio_cross_attn_v2a_gate.shape[-1]) + + # 4. Prepare prompt embeddings + encoder_hidden_states = self.caption_projection(encoder_hidden_states) + encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.size(-1)) + + 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)) + + # 5. Run transformer blocks + for block in self.transformer_blocks: + if torch.is_grad_enabled() and self.gradient_checkpointing: + hidden_states, audio_hidden_states = self._gradient_checkpointing_func( + block, + hidden_states, + audio_hidden_states, + encoder_hidden_states, + audio_encoder_hidden_states, + temb, + temb_audio, + video_cross_attn_scale_shift, + audio_cross_attn_scale_shift, + video_cross_attn_a2v_gate, + audio_cross_attn_v2a_gate, + video_rotary_emb, + audio_rotary_emb, + video_cross_attn_rotary_emb, + audio_cross_attn_rotary_emb, + encoder_attention_mask, + audio_encoder_attention_mask, + ) + else: + hidden_states, audio_hidden_states = block( + hidden_states, + audio_hidden_states, + encoder_hidden_states, + audio_encoder_hidden_states, + temb, + temb_audio, + video_cross_attn_scale_shift, + audio_cross_attn_scale_shift, + video_cross_attn_a2v_gate, + audio_cross_attn_v2a_gate, + video_rotary_emb, + audio_rotary_emb, + video_cross_attn_rotary_emb, + audio_cross_attn_rotary_emb, + encoder_attention_mask, + audio_encoder_attention_mask, + ) + + # 6. Output layers (including unpatchification) + scale_shift_values = self.scale_shift_table[None, None] + embedded_timestep[:, :, None] + shift, scale = scale_shift_values[:, :, 0], scale_shift_values[:, :, 1] + + hidden_states = self.norm_out(hidden_states) + hidden_states = hidden_states * (1 + scale) + shift + output = self.proj_out(hidden_states) + + audio_scale_shift_values = self.audio_scale_shift_table[None, None] + audio_embedded_timestep[:, :, None] + audio_shift, audio_scale = audio_scale_shift_values[:, :, 0], audio_scale_shift_values[:, :, 1] + + audio_hidden_states = self.audio_norm_out(audio_hidden_states) + audio_hidden_states = audio_hidden_states * (1 + audio_scale) + audio_shift + audio_output = self.audio_proj_out(audio_hidden_states) + + if not return_dict: + return (output, audio_output) + return AudioVisualModelOutput(sample=output, audio_sample=audio_output) + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + """ + Load weights from a pretrained model, mapping separate Q/K/V projections + into fused QKV projections for self-attention blocks. + + Returns: + Set of parameter names that were successfully loaded. + """ + stacked_params_mapping = [ + (".attn1.to_qkv", ".attn1.to_q", "q"), + (".attn1.to_qkv", ".attn1.to_k", "k"), + (".attn1.to_qkv", ".attn1.to_v", "v"), + (".audio_attn1.to_qkv", ".audio_attn1.to_q", "q"), + (".audio_attn1.to_qkv", ".audio_attn1.to_k", "k"), + (".audio_attn1.to_qkv", ".audio_attn1.to_v", "v"), + ] + + params_dict = dict(self.named_parameters()) + tp_size = get_tensor_model_parallel_world_size() + tp_rank = get_tensor_model_parallel_rank() if tp_size > 1 else 0 + loaded_params: set[str] = set() + + def _maybe_shard_weight(weight: torch.Tensor, param: torch.Tensor) -> torch.Tensor: + if tp_size <= 1 or weight.shape == param.shape: + return weight + + if weight.ndim == 1 and weight.numel() == param.numel() * tp_size: + return weight.chunk(tp_size, dim=0)[tp_rank] + + if weight.ndim == 2: + if weight.shape[0] == param.shape[0] * tp_size: + return weight.chunk(tp_size, dim=0)[tp_rank] + if weight.shape[1] == param.shape[1] * tp_size: + return weight.chunk(tp_size, dim=1)[tp_rank] + + return weight + + for name, loaded_weight in weights: + 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) + param = params_dict[name] + weight_loader = param.weight_loader + weight_loader(param, loaded_weight, shard_id) + break + else: + param = params_dict[name] + weight_loader = getattr(param, "weight_loader", None) + if weight_loader is not None: + weight_loader(param, loaded_weight) + else: + loaded_weight = _maybe_shard_weight(loaded_weight, param) + default_weight_loader(param, loaded_weight) + loaded_params.add(name) + + return loaded_params diff --git a/vllm_omni/diffusion/models/ltx2/pipeline_ltx2.py b/vllm_omni/diffusion/models/ltx2/pipeline_ltx2.py new file mode 100644 index 000000000..34263e217 --- /dev/null +++ b/vllm_omni/diffusion/models/ltx2/pipeline_ltx2.py @@ -0,0 +1,1176 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +import copy +import inspect +import json +import os +from collections.abc import Iterable +from contextlib import nullcontext +from typing import Any + +import numpy as np +import torch +from diffusers import AutoencoderKLLTX2Audio, AutoencoderKLLTX2Video, FlowMatchEulerDiscreteScheduler +from diffusers.pipelines.ltx2 import LTX2TextConnectors +from diffusers.pipelines.ltx2.vocoder import LTX2Vocoder +from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import rescale_noise_cfg, retrieve_timesteps +from diffusers.utils.torch_utils import randn_tensor +from diffusers.video_processor import VideoProcessor +from torch import nn +from transformers import AutoTokenizer, Gemma3ForConditionalGeneration +from vllm.model_executor.models.utils import AutoWeightsLoader + +from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig +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, + get_classifier_free_guidance_world_size, +) +from vllm_omni.diffusion.distributed.utils import get_local_device +from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader +from vllm_omni.diffusion.request import OmniDiffusionRequest + +from .ltx2_transformer import LTX2VideoTransformer3DModel + + +def load_transformer_config(model_path: str, subfolder: str = "transformer", local_files_only: bool = True) -> dict: + """Load transformer config from model directory or 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 f: + return json.load(f) + 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 f: + return json.load(f) + except Exception: + pass + return {} + + +def create_transformer_from_config(config: dict) -> LTX2VideoTransformer3DModel: + """Create LTX2VideoTransformer3DModel from config dict.""" + if not config: + return LTX2VideoTransformer3DModel() + + signature = inspect.signature(LTX2VideoTransformer3DModel.__init__) + allowed_keys = set(signature.parameters.keys()) + kwargs = {k: v for k, v in config.items() if k in allowed_keys} + return LTX2VideoTransformer3DModel(**kwargs) + + +def get_ltx2_post_process_func( + od_config: OmniDiffusionConfig, +): + def post_process_func(output: tuple[torch.Tensor, torch.Tensor] | torch.Tensor): + if isinstance(output, tuple) and len(output) == 2: + video, audio = output + if isinstance(audio, torch.Tensor): + audio = audio.detach().cpu() + return {"video": video, "audio": audio} + return output + + return post_process_func + + +def _unwrap_request_tensor(value: Any) -> Any: + if isinstance(value, list): + return value[0] if value else None + return value + + +def _get_prompt_field(prompt: Any, key: str) -> Any: + if isinstance(prompt, str): + return None + value = prompt.get(key) + if value is None: + additional = prompt.get("additional_information") + if isinstance(additional, dict): + value = additional.get(key) + return _unwrap_request_tensor(value) + + +def calculate_shift( + image_seq_len, + base_seq_len: int = 256, + max_seq_len: int = 4096, + base_shift: float = 0.5, + max_shift: float = 1.15, +): + m = (max_shift - base_shift) / (max_seq_len - base_seq_len) + b = base_shift - m * base_seq_len + mu = image_seq_len * m + b + return mu + + +class LTX2Pipeline(nn.Module, CFGParallelMixin): + def __init__( + self, + *, + od_config: OmniDiffusionConfig, + prefix: str = "", + ): + super().__init__() + self.od_config = od_config + + self.device = get_local_device() + dtype = getattr(od_config, "dtype", torch.bfloat16) + + model = od_config.model + local_files_only = os.path.exists(model) + + self.weights_sources = [ + DiffusersPipelineLoader.ComponentSource( + model_or_path=od_config.model, + subfolder="transformer", + revision=None, + prefix="transformer.", + fall_back_to_pt=True, + ), + ] + + self.tokenizer = AutoTokenizer.from_pretrained( + model, + subfolder="tokenizer", + local_files_only=local_files_only, + ) + self.text_encoder = Gemma3ForConditionalGeneration.from_pretrained( + model, + subfolder="text_encoder", + torch_dtype=dtype, + local_files_only=local_files_only, + ).to(self.device) + self.connectors = LTX2TextConnectors.from_pretrained( + model, + subfolder="connectors", + torch_dtype=dtype, + local_files_only=local_files_only, + ).to(self.device) + + self.vae = AutoencoderKLLTX2Video.from_pretrained( + model, + subfolder="vae", + torch_dtype=dtype, + local_files_only=local_files_only, + ).to(self.device) + self.audio_vae = AutoencoderKLLTX2Audio.from_pretrained( + model, + subfolder="audio_vae", + torch_dtype=dtype, + local_files_only=local_files_only, + ).to(self.device) + self.vocoder = LTX2Vocoder.from_pretrained( + model, + subfolder="vocoder", + torch_dtype=dtype, + local_files_only=local_files_only, + ).to(self.device) + + transformer_config = load_transformer_config(model, "transformer", local_files_only) + self.transformer = create_transformer_from_config(transformer_config) + + self.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained( + model, subfolder="scheduler", local_files_only=local_files_only + ) + + 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.audio_vae_mel_compression_ratio = ( + self.audio_vae.mel_compression_ratio if getattr(self, "audio_vae", None) is not None else 4 + ) + self.audio_vae_temporal_compression_ratio = ( + self.audio_vae.temporal_compression_ratio if getattr(self, "audio_vae", None) is not None else 4 + ) + self.transformer_spatial_patch_size = ( + self.transformer.config.patch_size if getattr(self, "transformer", None) is not None else 1 + ) + self.transformer_temporal_patch_size = ( + self.transformer.config.patch_size_t if getattr(self, "transformer", None) is not None else 1 + ) + + self.audio_sampling_rate = ( + self.audio_vae.config.sample_rate if getattr(self, "audio_vae", None) is not None else 16000 + ) + self.audio_hop_length = ( + self.audio_vae.config.mel_hop_length if getattr(self, "audio_vae", None) is not None else 160 + ) + + self.video_processor = VideoProcessor(vae_scale_factor=self.vae_spatial_compression_ratio) + tokenizer_max_length = 1024 + if getattr(self, "tokenizer", None) is not None: + tokenizer_max_length = self.tokenizer.model_max_length + if tokenizer_max_length is None or tokenizer_max_length > 100000: + encoder_config = getattr(self.text_encoder, "config", None) + config_max_len = getattr(encoder_config, "max_position_embeddings", None) + if config_max_len is None: + config_max_len = getattr(encoder_config, "max_seq_len", None) + tokenizer_max_length = config_max_len or 1024 + self.tokenizer_max_length = int(tokenizer_max_length) + + self._guidance_scale = None + self._guidance_rescale = None + self._attention_kwargs = None + self._interrupt = False + self._num_timesteps = None + self._current_timestep = None + + @staticmethod + def _pack_text_embeds( + text_hidden_states: torch.Tensor, + sequence_lengths: torch.Tensor, + device: str | torch.device, + padding_side: str = "left", + scale_factor: int = 8, + eps: float = 1e-6, + ) -> torch.Tensor: + batch_size, seq_len, hidden_dim, num_layers = text_hidden_states.shape + original_dtype = text_hidden_states.dtype + + token_indices = torch.arange(seq_len, device=device).unsqueeze(0) + if padding_side == "right": + mask = token_indices < sequence_lengths[:, None] + elif padding_side == "left": + start_indices = seq_len - sequence_lengths[:, None] + mask = token_indices >= start_indices + else: + raise ValueError(f"padding_side must be 'left' or 'right', got {padding_side}") + mask = mask[:, :, None, None] + + masked_text_hidden_states = text_hidden_states.masked_fill(~mask, 0.0) + num_valid_positions = (sequence_lengths * hidden_dim).view(batch_size, 1, 1, 1) + masked_mean = masked_text_hidden_states.sum(dim=(1, 2), keepdim=True) / (num_valid_positions + eps) + + x_min = text_hidden_states.masked_fill(~mask, float("inf")).amin(dim=(1, 2), keepdim=True) + x_max = text_hidden_states.masked_fill(~mask, float("-inf")).amax(dim=(1, 2), keepdim=True) + + normalized_hidden_states = (text_hidden_states - masked_mean) / (x_max - x_min + eps) + normalized_hidden_states = normalized_hidden_states * scale_factor + + normalized_hidden_states = normalized_hidden_states.flatten(2) + mask_flat = mask.squeeze(-1).expand(-1, -1, hidden_dim * num_layers) + normalized_hidden_states = normalized_hidden_states.masked_fill(~mask_flat, 0.0) + normalized_hidden_states = normalized_hidden_states.to(dtype=original_dtype) + return normalized_hidden_states + + def _get_gemma_prompt_embeds( + self, + prompt: str | list[str], + num_videos_per_prompt: int = 1, + max_sequence_length: int = 1024, + scale_factor: int = 8, + device: torch.device | None = None, + dtype: torch.dtype | None = None, + ): + device = device or self.device + dtype = dtype or self.text_encoder.dtype + + prompt = [prompt] if isinstance(prompt, str) else prompt + batch_size = len(prompt) + + if getattr(self, "tokenizer", None) is not None: + self.tokenizer.padding_side = "left" + if self.tokenizer.pad_token is None: + self.tokenizer.pad_token = self.tokenizer.eos_token + + prompt = [p.strip() for p in prompt] + text_inputs = self.tokenizer( + prompt, + padding="max_length", + max_length=max_sequence_length, + truncation=True, + add_special_tokens=True, + return_tensors="pt", + ) + text_input_ids = text_inputs.input_ids + prompt_attention_mask = text_inputs.attention_mask + text_input_ids = text_input_ids.to(device) + prompt_attention_mask = prompt_attention_mask.to(device) + + text_encoder_outputs = self.text_encoder( + input_ids=text_input_ids, attention_mask=prompt_attention_mask, output_hidden_states=True + ) + text_encoder_hidden_states = text_encoder_outputs.hidden_states + text_encoder_hidden_states = torch.stack(text_encoder_hidden_states, dim=-1) + sequence_lengths = prompt_attention_mask.sum(dim=-1) + + prompt_embeds = self._pack_text_embeds( + text_encoder_hidden_states, + sequence_lengths, + device=device, + padding_side=self.tokenizer.padding_side, + scale_factor=scale_factor, + ) + prompt_embeds = prompt_embeds.to(dtype=dtype) + + _, seq_len, _ = prompt_embeds.shape + prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1) + prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1) + + prompt_attention_mask = prompt_attention_mask.view(batch_size, -1) + prompt_attention_mask = prompt_attention_mask.repeat(num_videos_per_prompt, 1) + + return prompt_embeds, prompt_attention_mask + + def encode_prompt( + self, + prompt: str | list[str], + negative_prompt: str | list[str] | None = None, + do_classifier_free_guidance: bool = True, + num_videos_per_prompt: int = 1, + 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, + max_sequence_length: int = 1024, + scale_factor: int = 8, + device: torch.device | None = None, + dtype: torch.dtype | None = None, + ): + device = device or self.device + + prompt = [prompt] if isinstance(prompt, str) else prompt + if prompt is not None: + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + 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, + ) + + if do_classifier_free_guidance 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 to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + + negative_prompt_embeds, negative_prompt_attention_mask = self._get_gemma_prompt_embeds( + prompt=negative_prompt, + num_videos_per_prompt=num_videos_per_prompt, + max_sequence_length=max_sequence_length, + scale_factor=scale_factor, + device=device, + dtype=dtype, + ) + + return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask + + def check_inputs( + self, + prompt, + height, + width, + prompt_embeds=None, + negative_prompt_embeds=None, + prompt_attention_mask=None, + negative_prompt_attention_mask=None, + ): + if height % 32 != 0 or width % 32 != 0: + raise ValueError(f"`height` and `width` have to be divisible by 32 but are {height} and {width}.") + + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + + if prompt_embeds is not None and prompt_attention_mask is None: + raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.") + + if negative_prompt_embeds is not None and negative_prompt_attention_mask is None: + raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.") + + if prompt_embeds is not None and negative_prompt_embeds is not None: + if prompt_embeds.shape != negative_prompt_embeds.shape: + raise ValueError( + "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" + f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" + f" {negative_prompt_embeds.shape}." + ) + if prompt_attention_mask.shape != negative_prompt_attention_mask.shape: + raise ValueError( + "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when " + "passed directly, but got: `prompt_attention_mask` " + f"{prompt_attention_mask.shape} != `negative_prompt_attention_mask` " + f"{negative_prompt_attention_mask.shape}." + ) + + @staticmethod + def _pack_latents(latents: torch.Tensor, patch_size: int = 1, patch_size_t: int = 1) -> torch.Tensor: + batch_size, num_channels, num_frames, height, width = latents.shape + post_patch_num_frames = num_frames // patch_size_t + post_patch_height = height // patch_size + post_patch_width = width // patch_size + latents = latents.reshape( + batch_size, + -1, + post_patch_num_frames, + patch_size_t, + post_patch_height, + patch_size, + post_patch_width, + patch_size, + ) + latents = latents.permute(0, 2, 4, 6, 1, 3, 5, 7).flatten(4, 7).flatten(1, 3) + return latents + + @staticmethod + def _unpack_latents( + latents: torch.Tensor, num_frames: int, height: int, width: int, patch_size: int = 1, patch_size_t: int = 1 + ) -> torch.Tensor: + 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 + + @staticmethod + def _denormalize_latents( + latents: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor, scaling_factor: float = 1.0 + ) -> torch.Tensor: + 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 + def _denormalize_audio_latents(latents: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor): + latents_mean = latents_mean.to(latents.device, latents.dtype) + latents_std = latents_std.to(latents.device, latents.dtype) + return (latents * latents_std) + latents_mean + + @staticmethod + 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, num_channels, 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 + ) + latents = latents.permute(0, 2, 4, 1, 3, 5).flatten(3, 5).flatten(1, 2) + else: + latents = latents.transpose(1, 2).flatten(2, 3) + return latents + + @staticmethod + 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) + latents = latents.permute(0, 3, 1, 4, 2, 5).flatten(4, 5).flatten(2, 3) + else: + latents = latents.unflatten(2, (-1, num_mel_bins)).transpose(1, 2) + return latents + + def prepare_latents( + self, + batch_size: int = 1, + num_channels_latents: int = 128, + height: int = 512, + width: int = 768, + num_frames: int = 121, + 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: + return latents.to(device=device, dtype=dtype) + + height = height // self.vae_spatial_compression_ratio + width = width // self.vae_spatial_compression_ratio + num_frames = (num_frames - 1) // self.vae_temporal_compression_ratio + 1 + + shape = (batch_size, num_channels_latents, num_frames, height, width) + + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + latents = self._pack_latents(latents, self.transformer_spatial_patch_size, self.transformer_temporal_patch_size) + + return latents + + def prepare_audio_latents( + self, + batch_size: int = 1, + num_channels_latents: int = 8, + num_mel_bins: int = 64, + num_frames: int = 121, + frame_rate: float = 25.0, + sampling_rate: int = 16000, + hop_length: int = 160, + dtype: torch.dtype | None = None, + device: torch.device | None = None, + generator: torch.Generator | None = None, + latents: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, int]: + duration_s = num_frames / frame_rate + latents_per_second = float(sampling_rate) / float(hop_length) / float(self.audio_vae_temporal_compression_ratio) + latent_length = round(duration_s * latents_per_second) + + latent_mel_bins = num_mel_bins // self.audio_vae_mel_compression_ratio + + sp_size = getattr(self.od_config.parallel_config, "sequence_parallel_size", 1) + if sp_size > 1: + pad_len = (sp_size - (latent_length % sp_size)) % sp_size + if pad_len > 0: + if latents is not None: + pad_shape = list(latents.shape) + pad_shape[2] = pad_len + padding = torch.zeros(pad_shape, dtype=latents.dtype, device=latents.device) + latents = torch.cat([latents, padding], dim=2) + latent_length += pad_len + + if latents is not None: + return latents.to(device=device, dtype=dtype), latent_length + + shape = (batch_size, num_channels_latents, latent_length, 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) + latents = self._pack_audio_latents(latents) + return latents, latent_length + + @property + def guidance_scale(self): + return self._guidance_scale + + @property + def guidance_rescale(self): + return self._guidance_rescale + + @property + def do_classifier_free_guidance(self): + return self._guidance_scale > 1.0 + + @property + def num_timesteps(self): + return self._num_timesteps + + @property + def current_timestep(self): + return self._current_timestep + + @property + def attention_kwargs(self): + return self._attention_kwargs + + @property + def interrupt(self): + return self._interrupt + + def _is_cfg_parallel_enabled(self, do_true_cfg: bool) -> bool: + return do_true_cfg and get_classifier_free_guidance_world_size() > 1 + + def _transformer_cache_context(self, context_name: str): + cache_context = getattr(self.transformer, "cache_context", None) + if callable(cache_context): + return cache_context(context_name) + return nullcontext() + + def _predict_noise_av(self, **kwargs) -> tuple[torch.Tensor, torch.Tensor]: + with self._transformer_cache_context("cond_uncond"): + noise_pred_video, noise_pred_audio = self.transformer(**kwargs) + return noise_pred_video, noise_pred_audio + + def predict_noise_av_maybe_with_cfg( + self, + do_true_cfg: bool, + true_cfg_scale: float, + positive_kwargs: dict[str, Any], + negative_kwargs: dict[str, Any] | None, + guidance_rescale: float = 0.0, + cfg_normalize: bool = False, + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + if do_true_cfg: + cfg_parallel_ready = get_classifier_free_guidance_world_size() > 1 + + if cfg_parallel_ready: + cfg_group = get_cfg_group() + cfg_rank = get_classifier_free_guidance_rank() + + if cfg_rank == 0: + noise_pred_video, noise_pred_audio = self._predict_noise_av(**positive_kwargs) + else: + noise_pred_video, noise_pred_audio = self._predict_noise_av(**negative_kwargs) + + noise_pred_video = noise_pred_video.float() + noise_pred_audio = noise_pred_audio.float() + + gathered_video = cfg_group.all_gather(noise_pred_video, separate_tensors=True) + gathered_audio = cfg_group.all_gather(noise_pred_audio, separate_tensors=True) + + if cfg_rank == 0: + noise_pred_video_text = gathered_video[0] + noise_pred_video_uncond = gathered_video[1] + noise_pred_audio_text = gathered_audio[0] + noise_pred_audio_uncond = gathered_audio[1] + + noise_pred_video = self.combine_cfg_noise( + noise_pred_video_text, + noise_pred_video_uncond, + true_cfg_scale, + cfg_normalize, + ) + noise_pred_audio = self.combine_cfg_noise( + noise_pred_audio_text, + noise_pred_audio_uncond, + true_cfg_scale, + cfg_normalize, + ) + + if guidance_rescale > 0: + noise_pred_video = rescale_noise_cfg( + noise_pred_video, + noise_pred_video_text, + guidance_rescale=guidance_rescale, + ) + noise_pred_audio = rescale_noise_cfg( + noise_pred_audio, + noise_pred_audio_text, + guidance_rescale=guidance_rescale, + ) + return noise_pred_video, noise_pred_audio + return None, None + + noise_pred_video_text, noise_pred_audio_text = self._predict_noise_av(**positive_kwargs) + noise_pred_video_uncond, noise_pred_audio_uncond = self._predict_noise_av(**negative_kwargs) + + noise_pred_video_text = noise_pred_video_text.float() + noise_pred_audio_text = noise_pred_audio_text.float() + noise_pred_video_uncond = noise_pred_video_uncond.float() + noise_pred_audio_uncond = noise_pred_audio_uncond.float() + + noise_pred_video = self.combine_cfg_noise( + noise_pred_video_text, + noise_pred_video_uncond, + true_cfg_scale, + cfg_normalize, + ) + noise_pred_audio = self.combine_cfg_noise( + noise_pred_audio_text, + noise_pred_audio_uncond, + true_cfg_scale, + cfg_normalize, + ) + + if guidance_rescale > 0: + noise_pred_video = rescale_noise_cfg( + noise_pred_video, + noise_pred_video_text, + guidance_rescale=guidance_rescale, + ) + noise_pred_audio = rescale_noise_cfg( + noise_pred_audio, + noise_pred_audio_text, + guidance_rescale=guidance_rescale, + ) + + return noise_pred_video, noise_pred_audio + + noise_pred_video, noise_pred_audio = self._predict_noise_av(**positive_kwargs) + return noise_pred_video.float(), noise_pred_audio.float() + + def _scheduler_step_video_audio_maybe_with_cfg( + self, + noise_pred_video: torch.Tensor | None, + noise_pred_audio: torch.Tensor | None, + t: torch.Tensor, + latents: torch.Tensor, + audio_latents: torch.Tensor, + audio_scheduler: FlowMatchEulerDiscreteScheduler, + do_true_cfg: bool, + ) -> tuple[torch.Tensor, torch.Tensor]: + cfg_parallel_ready = self._is_cfg_parallel_enabled(do_true_cfg) + + if cfg_parallel_ready: + cfg_group = get_cfg_group() + cfg_rank = get_classifier_free_guidance_rank() + + if cfg_rank == 0: + latents = self.scheduler.step(noise_pred_video, t, latents, return_dict=False)[0] + audio_latents = audio_scheduler.step(noise_pred_audio, t, audio_latents, return_dict=False)[0] + + latents = latents.contiguous() + audio_latents = audio_latents.contiguous() + cfg_group.broadcast(latents, src=0) + cfg_group.broadcast(audio_latents, src=0) + return latents, audio_latents + + latents = self.scheduler.step(noise_pred_video, t, latents, return_dict=False)[0] + audio_latents = audio_scheduler.step(noise_pred_audio, t, audio_latents, return_dict=False)[0] + return latents, audio_latents + + @torch.no_grad() + def forward( + self, + req: OmniDiffusionRequest, + 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, + 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: + prompt = [p if isinstance(p, str) else (p.get("prompt") or "") for p in req.prompts] or prompt + if all(isinstance(p, str) or p.get("negative_prompt") is None for p in req.prompts): + negative_prompt = None + elif req.prompts: + negative_prompt = ["" if isinstance(p, str) else (p.get("negative_prompt") or "") for p in req.prompts] + + height = req.sampling_params.height or height or 512 + width = req.sampling_params.width or width or 768 + num_frames = req.sampling_params.num_frames or num_frames or 121 + frame_rate = req.sampling_params.resolved_frame_rate or frame_rate or 24.0 + num_inference_steps = req.sampling_params.num_inference_steps or num_inference_steps or 40 + 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.") + num_videos_per_prompt = ( + req.sampling_params.num_outputs_per_prompt + if req.sampling_params.num_outputs_per_prompt > 0 + else num_videos_per_prompt or 1 + ) + max_sequence_length = ( + req.sampling_params.max_sequence_length or max_sequence_length or self.tokenizer_max_length + ) + + if req.sampling_params.guidance_scale_provided: + guidance_scale = req.sampling_params.guidance_scale + if req.sampling_params.guidance_rescale is not None: + guidance_rescale = req.sampling_params.guidance_rescale + + if generator is None: + generator = req.sampling_params.generator + if generator is None and req.sampling_params.seed is not None: + generator = torch.Generator(device=self.device).manual_seed(req.sampling_params.seed) + + latents = req.sampling_params.latents if req.sampling_params.latents is not None else latents + audio_latents = ( + req.sampling_params.audio_latents + if req.sampling_params.audio_latents is not None + else req.sampling_params.extra_args.get("audio_latents", audio_latents) + ) + + req_prompt_embeds = [_get_prompt_field(p, "prompt_embeds") for p in req.prompts] + if any(p is not None for p in req_prompt_embeds): + prompt_embeds = torch.stack(req_prompt_embeds) # type: ignore[arg-type] + + req_negative_prompt_embeds = [_get_prompt_field(p, "negative_prompt_embeds") for p in req.prompts] + if any(p is not None for p in req_negative_prompt_embeds): + negative_prompt_embeds = torch.stack(req_negative_prompt_embeds) # type: ignore[arg-type] + + req_prompt_attention_masks = [ + _get_prompt_field(p, "prompt_attention_mask") or _get_prompt_field(p, "attention_mask") for p in req.prompts + ] + if any(m is not None for m in req_prompt_attention_masks): + prompt_attention_mask = torch.stack(req_prompt_attention_masks) # type: ignore[arg-type] + + req_negative_attention_masks = [ + _get_prompt_field(p, "negative_prompt_attention_mask") or _get_prompt_field(p, "negative_attention_mask") + for p in req.prompts + ] + if any(m is not None for m in req_negative_attention_masks): + negative_prompt_attention_mask = torch.stack(req_negative_attention_masks) # type: ignore[arg-type] + + if req.sampling_params.decode_timestep is not None: + decode_timestep = req.sampling_params.decode_timestep + if req.sampling_params.decode_noise_scale is not None: + decode_noise_scale = req.sampling_params.decode_noise_scale + if req.sampling_params.output_type is not None: + output_type = req.sampling_params.output_type + + self.check_inputs( + prompt=prompt, + height=height, + width=width, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + prompt_attention_mask=prompt_attention_mask, + negative_prompt_attention_mask=negative_prompt_attention_mask, + ) + + self._guidance_scale = guidance_scale + self._guidance_rescale = guidance_rescale + self._attention_kwargs = attention_kwargs + self._interrupt = False + self._current_timestep = None + + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self.device + + ( + prompt_embeds, + prompt_attention_mask, + negative_prompt_embeds, + negative_prompt_attention_mask, + ) = self.encode_prompt( + prompt=prompt, + negative_prompt=negative_prompt, + do_classifier_free_guidance=self.do_classifier_free_guidance, + num_videos_per_prompt=num_videos_per_prompt, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + prompt_attention_mask=prompt_attention_mask, + negative_prompt_attention_mask=negative_prompt_attention_mask, + max_sequence_length=max_sequence_length, + device=device, + ) + cfg_parallel_ready = self._is_cfg_parallel_enabled(self.do_classifier_free_guidance) + if self.do_classifier_free_guidance and not cfg_parallel_ready: + prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0) + prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0) + + additive_attention_mask = (1 - prompt_attention_mask.to(prompt_embeds.dtype)) * -1000000.0 + connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = self.connectors( + prompt_embeds, additive_attention_mask, additive_mask=True + ) + + negative_connector_prompt_embeds = None + negative_connector_audio_prompt_embeds = None + negative_connector_attention_mask = None + if cfg_parallel_ready: + negative_additive_attention_mask = ( + 1 - negative_prompt_attention_mask.to(negative_prompt_embeds.dtype) + ) * -1000000.0 + ( + negative_connector_prompt_embeds, + negative_connector_audio_prompt_embeds, + negative_connector_attention_mask, + ) = self.connectors( + negative_prompt_embeds, + negative_additive_attention_mask, + additive_mask=True, + ) + + 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 + video_sequence_length = latent_num_frames * latent_height * latent_width + + num_channels_latents = self.transformer.config.in_channels + latents = self.prepare_latents( + batch_size * num_videos_per_prompt, + num_channels_latents, + height, + width, + num_frames, + torch.float32, + device, + generator, + latents, + ) + + num_mel_bins = self.audio_vae.config.mel_bins if getattr(self, "audio_vae", None) is not None else 64 + latent_mel_bins = num_mel_bins // self.audio_vae_mel_compression_ratio + + num_channels_latents_audio = ( + self.audio_vae.config.latent_channels if getattr(self, "audio_vae", None) is not None else 8 + ) + audio_latents, audio_num_frames = self.prepare_audio_latents( + batch_size * num_videos_per_prompt, + num_channels_latents=num_channels_latents_audio, + num_mel_bins=num_mel_bins, + num_frames=num_frames, + frame_rate=frame_rate, + sampling_rate=self.audio_sampling_rate, + hop_length=self.audio_hop_length, + dtype=torch.float32, + device=device, + generator=generator, + latents=audio_latents, + ) + + sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) + mu = calculate_shift( + video_sequence_length, + self.scheduler.config.get("base_image_seq_len", 1024), + self.scheduler.config.get("max_image_seq_len", 4096), + self.scheduler.config.get("base_shift", 0.95), + self.scheduler.config.get("max_shift", 2.05), + ) + audio_scheduler = copy.deepcopy(self.scheduler) + _ = retrieve_timesteps( + audio_scheduler, + num_inference_steps, + device, + timesteps, + sigmas=sigmas, + mu=mu, + ) + timesteps, num_inference_steps = retrieve_timesteps( + self.scheduler, + num_inference_steps, + device, + timesteps, + sigmas=sigmas, + mu=mu, + ) + num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0) + self._num_timesteps = len(timesteps) + + video_coords = self.transformer.rope.prepare_video_coords( + latents.shape[0], latent_num_frames, latent_height, latent_width, latents.device, fps=frame_rate + ) + audio_coords = self.transformer.audio_rope.prepare_audio_coords( + audio_latents.shape[0], audio_num_frames, audio_latents.device + ) + + for i, t in enumerate(timesteps): + if self.interrupt: + continue + + self._current_timestep = t + + if cfg_parallel_ready: + latent_model_input = latents.to(prompt_embeds.dtype) + audio_latent_model_input = audio_latents.to(prompt_embeds.dtype) + timestep = t.expand(latent_model_input.shape[0]) + + positive_kwargs = { + "hidden_states": latent_model_input, + "audio_hidden_states": audio_latent_model_input, + "encoder_hidden_states": connector_prompt_embeds, + "audio_encoder_hidden_states": connector_audio_prompt_embeds, + "timestep": timestep, + "encoder_attention_mask": connector_attention_mask, + "audio_encoder_attention_mask": connector_attention_mask, + "num_frames": latent_num_frames, + "height": latent_height, + "width": latent_width, + "fps": frame_rate, + "audio_num_frames": audio_num_frames, + "video_coords": video_coords, + "audio_coords": audio_coords, + "attention_kwargs": attention_kwargs, + "return_dict": False, + } + negative_kwargs = { + "hidden_states": latent_model_input, + "audio_hidden_states": audio_latent_model_input, + "encoder_hidden_states": negative_connector_prompt_embeds, + "audio_encoder_hidden_states": negative_connector_audio_prompt_embeds, + "timestep": timestep, + "encoder_attention_mask": negative_connector_attention_mask, + "audio_encoder_attention_mask": negative_connector_attention_mask, + "num_frames": latent_num_frames, + "height": latent_height, + "width": latent_width, + "fps": frame_rate, + "audio_num_frames": audio_num_frames, + "video_coords": video_coords, + "audio_coords": audio_coords, + "attention_kwargs": attention_kwargs, + "return_dict": False, + } + + noise_pred_video, noise_pred_audio = self.predict_noise_av_maybe_with_cfg( + do_true_cfg=True, + true_cfg_scale=guidance_scale, + positive_kwargs=positive_kwargs, + negative_kwargs=negative_kwargs, + guidance_rescale=guidance_rescale, + cfg_normalize=False, + ) + + latents, audio_latents = self._scheduler_step_video_audio_maybe_with_cfg( + noise_pred_video, + noise_pred_audio, + t, + latents, + audio_latents, + audio_scheduler, + do_true_cfg=True, + ) + else: + latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents + latent_model_input = latent_model_input.to(prompt_embeds.dtype) + audio_latent_model_input = ( + torch.cat([audio_latents] * 2) if self.do_classifier_free_guidance else audio_latents + ) + audio_latent_model_input = audio_latent_model_input.to(prompt_embeds.dtype) + + timestep = t.expand(latent_model_input.shape[0]) + + with self._transformer_cache_context("cond_uncond"): + noise_pred_video, noise_pred_audio = self.transformer( + hidden_states=latent_model_input, + audio_hidden_states=audio_latent_model_input, + encoder_hidden_states=connector_prompt_embeds, + audio_encoder_hidden_states=connector_audio_prompt_embeds, + timestep=timestep, + encoder_attention_mask=connector_attention_mask, + audio_encoder_attention_mask=connector_attention_mask, + num_frames=latent_num_frames, + height=latent_height, + width=latent_width, + fps=frame_rate, + audio_num_frames=audio_num_frames, + video_coords=video_coords, + audio_coords=audio_coords, + attention_kwargs=attention_kwargs, + return_dict=False, + ) + noise_pred_video = noise_pred_video.float() + noise_pred_audio = noise_pred_audio.float() + + if self.do_classifier_free_guidance: + noise_pred_video_uncond, noise_pred_video_text = noise_pred_video.chunk(2) + noise_pred_video = noise_pred_video_uncond + guidance_scale * ( + noise_pred_video_text - noise_pred_video_uncond + ) + + noise_pred_audio_uncond, noise_pred_audio_text = noise_pred_audio.chunk(2) + noise_pred_audio = noise_pred_audio_uncond + guidance_scale * ( + noise_pred_audio_text - noise_pred_audio_uncond + ) + + if guidance_rescale > 0: + noise_pred_video = rescale_noise_cfg( + noise_pred_video, noise_pred_video_text, guidance_rescale=guidance_rescale + ) + noise_pred_audio = rescale_noise_cfg( + noise_pred_audio, noise_pred_audio_text, guidance_rescale=guidance_rescale + ) + + latents = self.scheduler.step(noise_pred_video, t, latents, return_dict=False)[0] + audio_latents = audio_scheduler.step(noise_pred_audio, t, audio_latents, return_dict=False)[0] + + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + pass + + latents = self._unpack_latents( + latents, + latent_num_frames, + latent_height, + latent_width, + self.transformer_spatial_patch_size, + self.transformer_temporal_patch_size, + ) + latents = self._denormalize_latents( + latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor + ) + + audio_latents = self._denormalize_audio_latents( + audio_latents, self.audio_vae.latents_mean, self.audio_vae.latents_std + ) + audio_latents = self._unpack_audio_latents(audio_latents, audio_num_frames, num_mel_bins=latent_mel_bins) + + if output_type == "latent": + video = latents + audio = audio_latents + else: + latents = latents.to(prompt_embeds.dtype) + + 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 + + latents = latents.to(self.vae.dtype) + video = self.vae.decode(latents, timestep, return_dict=False)[0] + video = self.video_processor.postprocess_video(video, output_type=output_type) + + audio_latents = audio_latents.to(self.audio_vae.dtype) + generated_mel_spectrograms = self.audio_vae.decode(audio_latents, return_dict=False)[0] + audio = self.vocoder(generated_mel_spectrograms) + + if not return_dict: + return DiffusionOutput(output=(video, audio)) + + return DiffusionOutput(output=(video, audio)) + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + loader = AutoWeightsLoader(self) + return loader.load_weights(weights) diff --git a/vllm_omni/diffusion/models/ltx2/pipeline_ltx2_image2video.py b/vllm_omni/diffusion/models/ltx2/pipeline_ltx2_image2video.py new file mode 100644 index 000000000..5fa9cc797 --- /dev/null +++ b/vllm_omni/diffusion/models/ltx2/pipeline_ltx2_image2video.py @@ -0,0 +1,705 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +import copy +from typing import Any + +import numpy as np +import PIL.Image +import torch +from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import rescale_noise_cfg, retrieve_timesteps +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_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig +from vllm_omni.diffusion.distributed.parallel_state import get_cfg_group, get_classifier_free_guidance_rank +from vllm_omni.diffusion.request import OmniDiffusionRequest + +from .pipeline_ltx2 import ( + LTX2Pipeline, + _get_prompt_field, + calculate_shift, +) +from .pipeline_ltx2 import ( + get_ltx2_post_process_func as _get_ltx2_post_process_func, +) + + +def get_ltx2_post_process_func(od_config: OmniDiffusionConfig): + return _get_ltx2_post_process_func(od_config) + + +class LTX2ImageToVideoPipeline(LTX2Pipeline): + support_image_input = True + + def __init__( + self, + *, + od_config: OmniDiffusionConfig, + prefix: str = "", + ): + super().__init__(od_config=od_config, prefix=prefix) + self.video_processor = VideoProcessor(vae_scale_factor=self.vae_spatial_compression_ratio, resample="bilinear") + + @staticmethod + def _normalize_latents( + latents: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor, scaling_factor: float = 1.0 + ) -> torch.Tensor: + 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_mean) * scaling_factor / latents_std + 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, + 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]: + height = height // self.vae_spatial_compression_ratio + width = width // self.vae_spatial_compression_ratio + num_frames = (num_frames - 1) // self.vae_temporal_compression_ratio + 1 + + shape = (batch_size, num_channels_latents, num_frames, height, width) + mask_shape = (batch_size, 1, num_frames, height, width) + + if latents is not None: + conditioning_mask = latents.new_zeros(mask_shape) + conditioning_mask[:, :, 0] = 1.0 + conditioning_mask = self._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_batch_size = image.shape[0] + if image_batch_size == 0: + raise ValueError("`image` batch is empty.") + if batch_size % image_batch_size != 0: + raise ValueError( + f"`batch_size` ({batch_size}) must be divisible by image batch size ({image_batch_size}) " + "for image-to-video outputs." + ) + num_videos_per_prompt = batch_size // image_batch_size + + 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" + f" batch size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + image_generators = [generator[i * num_videos_per_prompt] for i in range(image_batch_size)] + init_latents = [ + retrieve_latents(self.vae.encode(image[i].unsqueeze(0).unsqueeze(2)), image_generators[i], "argmax") + for i in range(image_batch_size) + ] + else: + init_latents = [ + retrieve_latents(self.vae.encode(img.unsqueeze(0).unsqueeze(2)), generator, "argmax") for img in image + ] + + init_latents = torch.cat(init_latents, dim=0).to(dtype) + if num_videos_per_prompt > 1: + init_latents = init_latents.repeat_interleave(num_videos_per_prompt, dim=0) + init_latents = self._normalize_latents(init_latents, self.vae.latents_mean, self.vae.latents_std) + 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) + + conditioning_mask = self._pack_latents( + conditioning_mask, self.transformer_spatial_patch_size, self.transformer_temporal_patch_size + ).squeeze(-1) + latents = self._pack_latents(latents, self.transformer_spatial_patch_size, self.transformer_temporal_patch_size) + + return latents, conditioning_mask + + def check_inputs( + self, + image, + height, + width, + prompt, + latents=None, + prompt_embeds=None, + negative_prompt_embeds=None, + prompt_attention_mask=None, + negative_prompt_attention_mask=None, + ): + if height % 32 != 0 or width % 32 != 0: + raise ValueError(f"`height` and `width` have to be divisible by 32 but are {height} and {width}.") + + if image is None and latents is None: + raise ValueError("Provide either `image` or `latents`. Cannot leave both undefined.") + + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + if prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + if prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + + if prompt_embeds is not None and prompt_attention_mask is None: + raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.") + + if negative_prompt_embeds is not None and negative_prompt_attention_mask is None: + raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.") + + if prompt_embeds is not None and negative_prompt_embeds is not None: + if prompt_embeds.shape != negative_prompt_embeds.shape: + raise ValueError( + "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" + f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" + f" {negative_prompt_embeds.shape}." + ) + if prompt_attention_mask.shape != negative_prompt_attention_mask.shape: + raise ValueError( + "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when" + " passed directly, but" + f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`" + f" {negative_prompt_attention_mask.shape}." + ) + + def _step_video_latents_i2v( + self, + noise_pred_video: torch.Tensor, + latents: torch.Tensor, + t: torch.Tensor, + latent_num_frames: int, + latent_height: int, + latent_width: int, + ) -> torch.Tensor: + noise_pred_video = self._unpack_latents( + noise_pred_video, + latent_num_frames, + latent_height, + latent_width, + self.transformer_spatial_patch_size, + self.transformer_temporal_patch_size, + ) + latents_unpacked = self._unpack_latents( + latents, + latent_num_frames, + latent_height, + latent_width, + self.transformer_spatial_patch_size, + self.transformer_temporal_patch_size, + ) + + noise_pred_video = noise_pred_video[:, :, 1:] + noise_latents = latents_unpacked[:, :, 1:] + pred_latents = self.scheduler.step(noise_pred_video, t, noise_latents, return_dict=False)[0] + + latents_unpacked = torch.cat([latents_unpacked[:, :, :1], pred_latents], dim=2) + latents = self._pack_latents( + latents_unpacked, self.transformer_spatial_patch_size, self.transformer_temporal_patch_size + ) + return latents + + @torch.no_grad() + def forward( + self, + req: OmniDiffusionRequest, + image: PIL.Image.Image | torch.Tensor | 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, + timesteps: list[int] | None = None, + guidance_scale: float = 4.0, + guidance_rescale: 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: + prompt = [p if isinstance(p, str) else (p.get("prompt") or "") for p in req.prompts] or prompt + if all(isinstance(p, str) or p.get("negative_prompt") is None for p in req.prompts): + negative_prompt = None + elif req.prompts: + negative_prompt = ["" if isinstance(p, str) else (p.get("negative_prompt") or "") for p in req.prompts] + + height = req.sampling_params.height or height or 512 + width = req.sampling_params.width or width or 768 + num_frames = req.sampling_params.num_frames or num_frames or 121 + frame_rate = req.sampling_params.resolved_frame_rate or frame_rate or 24.0 + num_inference_steps = req.sampling_params.num_inference_steps or num_inference_steps or 40 + 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.") + num_videos_per_prompt = ( + req.sampling_params.num_outputs_per_prompt + if req.sampling_params.num_outputs_per_prompt > 0 + else num_videos_per_prompt or 1 + ) + max_sequence_length = ( + req.sampling_params.max_sequence_length or max_sequence_length or self.tokenizer_max_length + ) + + if req.sampling_params.guidance_scale_provided: + guidance_scale = req.sampling_params.guidance_scale + if req.sampling_params.guidance_rescale is not None: + guidance_rescale = req.sampling_params.guidance_rescale + + if generator is None: + generator = req.sampling_params.generator + if generator is None and req.sampling_params.seed is not None: + generator = torch.Generator(device=self.device).manual_seed(req.sampling_params.seed) + + latents = req.sampling_params.latents if req.sampling_params.latents is not None else latents + audio_latents = ( + req.sampling_params.audio_latents + if req.sampling_params.audio_latents is not None + else req.sampling_params.extra_args.get("audio_latents", audio_latents) + ) + + req_prompt_embeds = [_get_prompt_field(p, "prompt_embeds") for p in req.prompts] + if any(p is not None for p in req_prompt_embeds): + prompt_embeds = torch.stack(req_prompt_embeds) # type: ignore[arg-type] + + req_negative_prompt_embeds = [_get_prompt_field(p, "negative_prompt_embeds") for p in req.prompts] + if any(p is not None for p in req_negative_prompt_embeds): + negative_prompt_embeds = torch.stack(req_negative_prompt_embeds) # type: ignore[arg-type] + + req_prompt_attention_masks = [ + _get_prompt_field(p, "prompt_attention_mask") or _get_prompt_field(p, "attention_mask") for p in req.prompts + ] + if any(m is not None for m in req_prompt_attention_masks): + prompt_attention_mask = torch.stack(req_prompt_attention_masks) # type: ignore[arg-type] + + req_negative_attention_masks = [ + _get_prompt_field(p, "negative_prompt_attention_mask") or _get_prompt_field(p, "negative_attention_mask") + for p in req.prompts + ] + if any(m is not None for m in req_negative_attention_masks): + negative_prompt_attention_mask = torch.stack(req_negative_attention_masks) # type: ignore[arg-type] + + if req.sampling_params.decode_timestep is not None: + decode_timestep = req.sampling_params.decode_timestep + if req.sampling_params.decode_noise_scale is not None: + decode_noise_scale = req.sampling_params.decode_noise_scale + if req.sampling_params.output_type is not None: + output_type = req.sampling_params.output_type + + if image is None and req.prompts: + raw_images = [] + for prompt_item in req.prompts: + if isinstance(prompt_item, str): + raw_image = None + else: + multi_modal_data = prompt_item.get("multi_modal_data") or {} + raw_image = multi_modal_data.get("image") + if raw_image is None: + additional = prompt_item.get("additional_information") or {} + raw_image = ( + additional.get("preprocessed_image") + or additional.get("pixel_values") + or additional.get("image") + ) + if isinstance(raw_image, list): + raw_image = raw_image[0] if raw_image else None + if isinstance(raw_image, str): + raw_image = PIL.Image.open(raw_image).convert("RGB") + raw_images.append(raw_image) + + if any(img is None for img in raw_images): + if latents is None: + raise ValueError("Image is required for LTX2 I2V generation.") + if len(raw_images) == 1: + image = raw_images[0] + elif raw_images: + image = raw_images + + self.check_inputs( + image=image, + height=height, + width=width, + prompt=prompt, + latents=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, + ) + + self._guidance_scale = guidance_scale + self._guidance_rescale = guidance_rescale + self._attention_kwargs = attention_kwargs + self._interrupt = False + self._current_timestep = None + + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self.device + + ( + prompt_embeds, + prompt_attention_mask, + negative_prompt_embeds, + negative_prompt_attention_mask, + ) = self.encode_prompt( + prompt=prompt, + negative_prompt=negative_prompt, + do_classifier_free_guidance=self.do_classifier_free_guidance, + num_videos_per_prompt=num_videos_per_prompt, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + prompt_attention_mask=prompt_attention_mask, + negative_prompt_attention_mask=negative_prompt_attention_mask, + max_sequence_length=max_sequence_length, + device=device, + ) + cfg_parallel_ready = self._is_cfg_parallel_enabled(self.do_classifier_free_guidance) + if self.do_classifier_free_guidance and not cfg_parallel_ready: + prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0) + prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0) + + additive_attention_mask = (1 - prompt_attention_mask.to(prompt_embeds.dtype)) * -1000000.0 + connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = self.connectors( + prompt_embeds, additive_attention_mask, additive_mask=True + ) + + negative_connector_prompt_embeds = None + negative_connector_audio_prompt_embeds = None + negative_connector_attention_mask = None + if cfg_parallel_ready: + negative_additive_attention_mask = ( + 1 - negative_prompt_attention_mask.to(negative_prompt_embeds.dtype) + ) * -1000000.0 + ( + negative_connector_prompt_embeds, + negative_connector_audio_prompt_embeds, + negative_connector_attention_mask, + ) = self.connectors( + negative_prompt_embeds, + negative_additive_attention_mask, + additive_mask=True, + ) + + if latents is 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) + else: + image = self.video_processor.preprocess(image, height=height, width=width) + image = image.to(device=device, dtype=prompt_embeds.dtype) + + num_channels_latents = self.transformer.config.in_channels + latents, conditioning_mask = self.prepare_latents( + image, + batch_size * num_videos_per_prompt, + num_channels_latents, + height, + width, + num_frames, + torch.float32, + device, + generator, + latents, + ) + if self.do_classifier_free_guidance and not cfg_parallel_ready: + conditioning_mask = torch.cat([conditioning_mask, conditioning_mask]) + + num_mel_bins = self.audio_vae.config.mel_bins if getattr(self, "audio_vae", None) is not None else 64 + latent_mel_bins = num_mel_bins // self.audio_vae_mel_compression_ratio + + num_channels_latents_audio = ( + self.audio_vae.config.latent_channels if getattr(self, "audio_vae", None) is not None else 8 + ) + audio_latents, audio_num_frames = self.prepare_audio_latents( + batch_size * num_videos_per_prompt, + num_channels_latents=num_channels_latents_audio, + num_mel_bins=num_mel_bins, + num_frames=num_frames, + frame_rate=frame_rate, + sampling_rate=self.audio_sampling_rate, + hop_length=self.audio_hop_length, + dtype=torch.float32, + device=device, + generator=generator, + latents=audio_latents, + ) + + 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 + video_sequence_length = latent_num_frames * latent_height * latent_width + + sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) + mu = calculate_shift( + video_sequence_length, + self.scheduler.config.get("base_image_seq_len", 1024), + self.scheduler.config.get("max_image_seq_len", 4096), + self.scheduler.config.get("base_shift", 0.95), + self.scheduler.config.get("max_shift", 2.05), + ) + audio_scheduler = copy.deepcopy(self.scheduler) + _ = retrieve_timesteps( + audio_scheduler, + num_inference_steps, + device, + timesteps, + sigmas=sigmas, + mu=mu, + ) + timesteps, num_inference_steps = retrieve_timesteps( + self.scheduler, + num_inference_steps, + device, + timesteps, + sigmas=sigmas, + mu=mu, + ) + num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0) + self._num_timesteps = len(timesteps) + + video_coords = self.transformer.rope.prepare_video_coords( + latents.shape[0], latent_num_frames, latent_height, latent_width, latents.device, fps=frame_rate + ) + audio_coords = self.transformer.audio_rope.prepare_audio_coords( + audio_latents.shape[0], audio_num_frames, audio_latents.device + ) + + for i, t in enumerate(timesteps): + if self.interrupt: + continue + + self._current_timestep = t + + if cfg_parallel_ready: + latent_model_input = latents.to(prompt_embeds.dtype) + audio_latent_model_input = audio_latents.to(prompt_embeds.dtype) + + timestep = t.expand(latent_model_input.shape[0]) + video_timestep = timestep.unsqueeze(-1) * (1 - conditioning_mask) + + positive_kwargs = { + "hidden_states": latent_model_input, + "audio_hidden_states": audio_latent_model_input, + "encoder_hidden_states": connector_prompt_embeds, + "audio_encoder_hidden_states": connector_audio_prompt_embeds, + "timestep": video_timestep, + "audio_timestep": timestep, + "encoder_attention_mask": connector_attention_mask, + "audio_encoder_attention_mask": connector_attention_mask, + "num_frames": latent_num_frames, + "height": latent_height, + "width": latent_width, + "fps": frame_rate, + "audio_num_frames": audio_num_frames, + "video_coords": video_coords, + "audio_coords": audio_coords, + "attention_kwargs": attention_kwargs, + "return_dict": False, + } + negative_kwargs = { + "hidden_states": latent_model_input, + "audio_hidden_states": audio_latent_model_input, + "encoder_hidden_states": negative_connector_prompt_embeds, + "audio_encoder_hidden_states": negative_connector_audio_prompt_embeds, + "timestep": video_timestep, + "audio_timestep": timestep, + "encoder_attention_mask": negative_connector_attention_mask, + "audio_encoder_attention_mask": negative_connector_attention_mask, + "num_frames": latent_num_frames, + "height": latent_height, + "width": latent_width, + "fps": frame_rate, + "audio_num_frames": audio_num_frames, + "video_coords": video_coords, + "audio_coords": audio_coords, + "attention_kwargs": attention_kwargs, + "return_dict": False, + } + + noise_pred_video, noise_pred_audio = self.predict_noise_av_maybe_with_cfg( + do_true_cfg=True, + true_cfg_scale=guidance_scale, + positive_kwargs=positive_kwargs, + negative_kwargs=negative_kwargs, + guidance_rescale=guidance_rescale, + cfg_normalize=False, + ) + + if get_classifier_free_guidance_rank() == 0: + latents = self._step_video_latents_i2v( + noise_pred_video, + latents, + t, + latent_num_frames, + latent_height, + latent_width, + ) + audio_latents = audio_scheduler.step(noise_pred_audio, t, audio_latents, return_dict=False)[0] + + cfg_group = get_cfg_group() + latents = latents.contiguous() + audio_latents = audio_latents.contiguous() + cfg_group.broadcast(latents, src=0) + cfg_group.broadcast(audio_latents, src=0) + else: + latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents + latent_model_input = latent_model_input.to(prompt_embeds.dtype) + audio_latent_model_input = ( + torch.cat([audio_latents] * 2) if self.do_classifier_free_guidance else audio_latents + ) + audio_latent_model_input = audio_latent_model_input.to(prompt_embeds.dtype) + + timestep = t.expand(latent_model_input.shape[0]) + video_timestep = timestep.unsqueeze(-1) * (1 - conditioning_mask) + + with self._transformer_cache_context("cond_uncond"): + noise_pred_video, noise_pred_audio = self.transformer( + hidden_states=latent_model_input, + audio_hidden_states=audio_latent_model_input, + encoder_hidden_states=connector_prompt_embeds, + audio_encoder_hidden_states=connector_audio_prompt_embeds, + timestep=video_timestep, + audio_timestep=timestep, + encoder_attention_mask=connector_attention_mask, + audio_encoder_attention_mask=connector_attention_mask, + num_frames=latent_num_frames, + height=latent_height, + width=latent_width, + fps=frame_rate, + audio_num_frames=audio_num_frames, + video_coords=video_coords, + audio_coords=audio_coords, + attention_kwargs=attention_kwargs, + return_dict=False, + ) + noise_pred_video = noise_pred_video.float() + noise_pred_audio = noise_pred_audio.float() + + if self.do_classifier_free_guidance: + noise_pred_video_uncond, noise_pred_video_text = noise_pred_video.chunk(2) + noise_pred_video = noise_pred_video_uncond + guidance_scale * ( + noise_pred_video_text - noise_pred_video_uncond + ) + + noise_pred_audio_uncond, noise_pred_audio_text = noise_pred_audio.chunk(2) + noise_pred_audio = noise_pred_audio_uncond + guidance_scale * ( + noise_pred_audio_text - noise_pred_audio_uncond + ) + + if guidance_rescale > 0: + noise_pred_video = rescale_noise_cfg( + noise_pred_video, noise_pred_video_text, guidance_rescale=guidance_rescale + ) + noise_pred_audio = rescale_noise_cfg( + noise_pred_audio, noise_pred_audio_text, guidance_rescale=guidance_rescale + ) + + latents = self._step_video_latents_i2v( + noise_pred_video, + latents, + t, + latent_num_frames, + latent_height, + latent_width, + ) + + audio_latents = audio_scheduler.step(noise_pred_audio, t, audio_latents, return_dict=False)[0] + + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + pass + + latents = self._unpack_latents( + latents, + latent_num_frames, + latent_height, + latent_width, + self.transformer_spatial_patch_size, + self.transformer_temporal_patch_size, + ) + latents = self._denormalize_latents( + latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor + ) + + audio_latents = self._denormalize_audio_latents( + audio_latents, self.audio_vae.latents_mean, self.audio_vae.latents_std + ) + audio_latents = self._unpack_audio_latents(audio_latents, audio_num_frames, num_mel_bins=latent_mel_bins) + + if output_type == "latent": + video = latents + audio = audio_latents + else: + latents = latents.to(prompt_embeds.dtype) + + 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 + + latents = latents.to(self.vae.dtype) + video = self.vae.decode(latents, timestep, return_dict=False)[0] + video = self.video_processor.postprocess_video(video, output_type=output_type) + + audio_latents = audio_latents.to(self.audio_vae.dtype) + generated_mel_spectrograms = self.audio_vae.decode(audio_latents, return_dict=False)[0] + audio = self.vocoder(generated_mel_spectrograms) + + if not return_dict: + return DiffusionOutput(output=(video, audio)) + + return DiffusionOutput(output=(video, audio)) diff --git a/vllm_omni/diffusion/models/progress_bar.py b/vllm_omni/diffusion/models/progress_bar.py new file mode 100644 index 000000000..a414a787e --- /dev/null +++ b/vllm_omni/diffusion/models/progress_bar.py @@ -0,0 +1,53 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +""" +Progress bar mixin for diffusion pipelines. + +Provides a diffusers-compatible progress_bar() method that wraps tqdm, +automatically disabling output on non-zero ranks in distributed settings. +""" + +import torch +from tqdm.auto import tqdm + + +class ProgressBarMixin: + """Mixin that provides a progress bar for denoising loops. + + Usage in pipeline: + class MyPipeline(nn.Module, CFGParallelMixin, ProgressBarMixin): + def diffuse(self, ...): + with self.progress_bar(total=num_steps) as pbar: + for i, t in enumerate(timesteps): + ... + pbar.update() + """ + + def progress_bar(self, iterable=None, total=None): + if not hasattr(self, "_progress_bar_config"): + self._progress_bar_config = {} + elif not isinstance(self._progress_bar_config, dict): + raise ValueError( + f"`self._progress_bar_config` should be of type `dict`, but is {type(self._progress_bar_config)}." + ) + + config = dict(self._progress_bar_config) + # Only show progress bar on rank 0 in distributed settings + if "disable" not in config: + config["disable"] = not _is_rank_zero() + + if iterable is not None: + return tqdm(iterable, **config) + elif total is not None: + return tqdm(total=total, **config) + else: + raise ValueError("Either `total` or `iterable` has to be defined.") + + def set_progress_bar_config(self, **kwargs): + self._progress_bar_config = kwargs + + +def _is_rank_zero() -> bool: + if not torch.distributed.is_initialized(): + return True + return torch.distributed.get_rank() == 0 diff --git a/vllm_omni/diffusion/models/qwen_image/cfg_parallel.py b/vllm_omni/diffusion/models/qwen_image/cfg_parallel.py index 9a882f7bf..bd815aa9e 100644 --- a/vllm_omni/diffusion/models/qwen_image/cfg_parallel.py +++ b/vllm_omni/diffusion/models/qwen_image/cfg_parallel.py @@ -15,11 +15,12 @@ import torch from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin from vllm_omni.diffusion.distributed.parallel_state import get_classifier_free_guidance_world_size +from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin logger = logging.getLogger(__name__) -class QwenImageCFGParallelMixin(CFGParallelMixin): +class QwenImageCFGParallelMixin(CFGParallelMixin, ProgressBarMixin): """ Base Mixin class for Qwen Image pipelines providing shared CFG methods. """ @@ -69,58 +70,61 @@ class QwenImageCFGParallelMixin(CFGParallelMixin): self.transformer.do_true_cfg = do_true_cfg additional_transformer_kwargs = additional_transformer_kwargs or {} - for i, t in enumerate(timesteps): - if self.interrupt: - continue - self._current_timestep = t + with self.progress_bar(total=len(timesteps)) as pbar: + for i, t in enumerate(timesteps): + if self.interrupt: + continue + self._current_timestep = t - # Broadcast timestep to match batch size - timestep = t.expand(latents.shape[0]).to(device=latents.device, dtype=latents.dtype) + # Broadcast timestep to match batch size + timestep = t.expand(latents.shape[0]).to(device=latents.device, dtype=latents.dtype) - # Concatenate image latents with noise latents if available (for editing pipelines) - latent_model_input = latents - if image_latents is not None: - latent_model_input = torch.cat([latents, image_latents], dim=1) + # Concatenate image latents with noise latents if available (for editing pipelines) + latent_model_input = latents + if image_latents is not None: + latent_model_input = torch.cat([latents, image_latents], dim=1) - positive_kwargs = { - "hidden_states": latent_model_input, - "timestep": timestep / 1000, - "guidance": guidance, - "encoder_hidden_states_mask": prompt_embeds_mask, - "encoder_hidden_states": prompt_embeds, - "img_shapes": img_shapes, - "txt_seq_lens": txt_seq_lens, - **additional_transformer_kwargs, - } - if do_true_cfg: - negative_kwargs = { + positive_kwargs = { "hidden_states": latent_model_input, "timestep": timestep / 1000, "guidance": guidance, - "encoder_hidden_states_mask": negative_prompt_embeds_mask, - "encoder_hidden_states": negative_prompt_embeds, + "encoder_hidden_states_mask": prompt_embeds_mask, + "encoder_hidden_states": prompt_embeds, "img_shapes": img_shapes, - "txt_seq_lens": negative_txt_seq_lens, + "txt_seq_lens": txt_seq_lens, **additional_transformer_kwargs, } - else: - negative_kwargs = None + if do_true_cfg: + negative_kwargs = { + "hidden_states": latent_model_input, + "timestep": timestep / 1000, + "guidance": guidance, + "encoder_hidden_states_mask": negative_prompt_embeds_mask, + "encoder_hidden_states": negative_prompt_embeds, + "img_shapes": img_shapes, + "txt_seq_lens": negative_txt_seq_lens, + **additional_transformer_kwargs, + } + else: + negative_kwargs = None - # For editing pipelines, we need to slice the output to remove condition latents - output_slice = latents.size(1) if image_latents is not None else None + # For editing pipelines, we need to slice the output to remove condition latents + output_slice = latents.size(1) if image_latents is not None else None - # Predict noise with automatic CFG parallel handling - noise_pred = self.predict_noise_maybe_with_cfg( - do_true_cfg, - true_cfg_scale, - positive_kwargs, - negative_kwargs, - cfg_normalize, - output_slice, - ) + # Predict noise with automatic CFG parallel handling + noise_pred = self.predict_noise_maybe_with_cfg( + do_true_cfg, + true_cfg_scale, + positive_kwargs, + negative_kwargs, + cfg_normalize, + output_slice, + ) - # Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync - latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg) + # Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync + latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg) + + pbar.update() return latents diff --git a/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2.py b/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2.py index 63de7395f..1de801c10 100644 --- a/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2.py +++ b/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2.py @@ -21,6 +21,7 @@ from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import Dist from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin from vllm_omni.diffusion.distributed.utils import get_local_device from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader +from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin from vllm_omni.diffusion.models.schedulers import FlowUniPCMultistepScheduler from vllm_omni.diffusion.models.wan2_2.wan2_2_transformer import WanTransformer3DModel from vllm_omni.diffusion.request import OmniDiffusionRequest @@ -186,7 +187,7 @@ def get_wan22_pre_process_func( return pre_process_func -class Wan22Pipeline(nn.Module, CFGParallelMixin): +class Wan22Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin): def __init__( self, *, @@ -547,87 +548,90 @@ class Wan22Pipeline(nn.Module, CFGParallelMixin): attention_kwargs = {} # Denoising - for t in timesteps: - self._current_timestep = t + with self.progress_bar(total=len(timesteps)) as pbar: + for t in timesteps: + self._current_timestep = t - # Select model based on timestep and boundary_ratio - # High noise stage (t >= boundary_timestep): use transformer - # Low noise stage (t < boundary_timestep): use transformer_2 - if boundary_timestep is not None and t < boundary_timestep: - # Low noise stage - always use guidance_high for this stage - current_guidance_scale = guidance_high - if self.transformer_2 is not None: - current_model = self.transformer_2 - elif self.transformer is not None: - # Fallback to transformer if transformer_2 not loaded - current_model = self.transformer + # Select model based on timestep and boundary_ratio + # High noise stage (t >= boundary_timestep): use transformer + # Low noise stage (t < boundary_timestep): use transformer_2 + if boundary_timestep is not None and t < boundary_timestep: + # Low noise stage - always use guidance_high for this stage + current_guidance_scale = guidance_high + if self.transformer_2 is not None: + current_model = self.transformer_2 + elif self.transformer is not None: + # Fallback to transformer if transformer_2 not loaded + current_model = self.transformer + else: + raise RuntimeError("No transformer available for low-noise stage") else: - raise RuntimeError("No transformer available for low-noise stage") - else: - # High noise stage - always use guidance_low for this stage - current_guidance_scale = guidance_low - if self.transformer is not None: - current_model = self.transformer - elif self.transformer_2 is not None: - # Fallback to transformer_2 if transformer not loaded - current_model = self.transformer_2 + # High noise stage - always use guidance_low for this stage + current_guidance_scale = guidance_low + if self.transformer is not None: + current_model = self.transformer + elif self.transformer_2 is not None: + # Fallback to transformer_2 if transformer not loaded + current_model = self.transformer_2 + else: + raise RuntimeError("No transformer available for high-noise stage") + + if self.expand_timesteps and latent_condition is not None: + # I2V mode: blend condition with latents using mask + latent_model_input = (1 - first_frame_mask) * latent_condition + first_frame_mask * latents + latent_model_input = latent_model_input.to(dtype) + + # Expand timesteps per patch - use floor division to match patch embedding + patch_size = self.transformer_config.patch_size + num_latent_frames = latents.shape[2] + patch_height = latents.shape[3] // patch_size[1] + patch_width = latents.shape[4] // patch_size[2] + + # Create mask at patch resolution (same as hidden states sequence length) + patch_mask = first_frame_mask[:, :, :, :: patch_size[1], :: patch_size[2]] + patch_mask = patch_mask[:, :, :, :patch_height, :patch_width] # Ensure correct dimensions + temp_ts = (patch_mask[0][0] * t).flatten() + timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1) else: - raise RuntimeError("No transformer available for high-noise stage") + # T2V mode: standard forward + latent_model_input = latents.to(dtype) + timestep = t.expand(latents.shape[0]) - if self.expand_timesteps and latent_condition is not None: - # I2V mode: blend condition with latents using mask - latent_model_input = (1 - first_frame_mask) * latent_condition + first_frame_mask * latents - latent_model_input = latent_model_input.to(dtype) - - # Expand timesteps per patch - use floor division to match patch embedding - patch_size = self.transformer_config.patch_size - num_latent_frames = latents.shape[2] - patch_height = latents.shape[3] // patch_size[1] - patch_width = latents.shape[4] // patch_size[2] - - # Create mask at patch resolution (same as hidden states sequence length) - patch_mask = first_frame_mask[:, :, :, :: patch_size[1], :: patch_size[2]] - patch_mask = patch_mask[:, :, :, :patch_height, :patch_width] # Ensure correct dimensions - temp_ts = (patch_mask[0][0] * t).flatten() - timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1) - else: - # T2V mode: standard forward - latent_model_input = latents.to(dtype) - timestep = t.expand(latents.shape[0]) - - do_true_cfg = current_guidance_scale > 1.0 and negative_prompt_embeds is not None - # Prepare kwargs for positive and negative predictions - positive_kwargs = { - "hidden_states": latent_model_input, - "timestep": timestep, - "encoder_hidden_states": prompt_embeds, - "attention_kwargs": attention_kwargs, - "return_dict": False, - "current_model": current_model, - } - if do_true_cfg: - negative_kwargs = { + do_true_cfg = current_guidance_scale > 1.0 and negative_prompt_embeds is not None + # Prepare kwargs for positive and negative predictions + positive_kwargs = { "hidden_states": latent_model_input, "timestep": timestep, - "encoder_hidden_states": negative_prompt_embeds, + "encoder_hidden_states": prompt_embeds, "attention_kwargs": attention_kwargs, "return_dict": False, "current_model": current_model, } - else: - negative_kwargs = None + if do_true_cfg: + negative_kwargs = { + "hidden_states": latent_model_input, + "timestep": timestep, + "encoder_hidden_states": negative_prompt_embeds, + "attention_kwargs": attention_kwargs, + "return_dict": False, + "current_model": current_model, + } + else: + negative_kwargs = None - # Predict noise with automatic CFG parallel handling - noise_pred = self.predict_noise_maybe_with_cfg( - do_true_cfg=do_true_cfg, - true_cfg_scale=current_guidance_scale, - positive_kwargs=positive_kwargs, - negative_kwargs=negative_kwargs, - cfg_normalize=False, - ) + # Predict noise with automatic CFG parallel handling + noise_pred = self.predict_noise_maybe_with_cfg( + do_true_cfg=do_true_cfg, + true_cfg_scale=current_guidance_scale, + positive_kwargs=positive_kwargs, + negative_kwargs=negative_kwargs, + cfg_normalize=False, + ) - # Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync - latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg) + # Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync + latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg) + + pbar.update() # Wan2.2 is prone to out of memory errors when predicting large videos # so we empty the cache here to avoid OOM before vae decoding. diff --git a/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2_i2v.py b/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2_i2v.py index 2d750c762..b673cd0fa 100644 --- a/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2_i2v.py +++ b/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2_i2v.py @@ -22,6 +22,7 @@ from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin from vllm_omni.diffusion.distributed.utils import get_local_device from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader from vllm_omni.diffusion.models.interface import SupportImageInput +from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin from vllm_omni.diffusion.models.schedulers import FlowUniPCMultistepScheduler from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import ( create_transformer_from_config, @@ -138,7 +139,7 @@ def get_wan22_i2v_pre_process_func( return pre_process_func -class Wan22I2VPipeline(nn.Module, SupportImageInput, CFGParallelMixin): +class Wan22I2VPipeline(nn.Module, SupportImageInput, CFGParallelMixin, ProgressBarMixin): """ Wan2.2 Image-to-Video Pipeline. @@ -468,65 +469,68 @@ class Wan22I2VPipeline(nn.Module, SupportImageInput, CFGParallelMixin): attention_kwargs = {} # Denoising loop - for t in timesteps: - self._current_timestep = t + with self.progress_bar(total=len(timesteps)) as pbar: + for t in timesteps: + self._current_timestep = t - # Select model and guidance scale based on timestep - current_model = self.transformer - current_guidance_scale = guidance_low - if boundary_timestep is not None and t < boundary_timestep and self.transformer_2 is not None: - current_model = self.transformer_2 - current_guidance_scale = guidance_high + # Select model and guidance scale based on timestep + current_model = self.transformer + current_guidance_scale = guidance_low + if boundary_timestep is not None and t < boundary_timestep and self.transformer_2 is not None: + current_model = self.transformer_2 + current_guidance_scale = guidance_high - # Prepare latent input - if self.expand_timesteps: - # TI2V-5B style: blend condition with latents using mask - latent_model_input = (1 - first_frame_mask) * condition + first_frame_mask * latents - latent_model_input = latent_model_input.to(dtype) + # Prepare latent input + if self.expand_timesteps: + # TI2V-5B style: blend condition with latents using mask + latent_model_input = (1 - first_frame_mask) * condition + first_frame_mask * latents + latent_model_input = latent_model_input.to(dtype) - # Expand timesteps for each patch - temp_ts = (first_frame_mask[0][0][:, ::2, ::2] * t).flatten() - timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1) - else: - # Wan2.1 style: concatenate condition with latents - latent_model_input = torch.cat([latents, condition], dim=1).to(dtype) - timestep = t.expand(latents.shape[0]) + # Expand timesteps for each patch + temp_ts = (first_frame_mask[0][0][:, ::2, ::2] * t).flatten() + timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1) + else: + # Wan2.1 style: concatenate condition with latents + latent_model_input = torch.cat([latents, condition], dim=1).to(dtype) + timestep = t.expand(latents.shape[0]) - do_true_cfg = current_guidance_scale > 1.0 and negative_prompt_embeds is not None - # Prepare kwargs for positive and negative predictions - positive_kwargs = { - "hidden_states": latent_model_input, - "timestep": timestep, - "encoder_hidden_states": prompt_embeds, - "encoder_hidden_states_image": image_embeds, - "attention_kwargs": attention_kwargs, - "return_dict": False, - "current_model": current_model, - } - if do_true_cfg: - negative_kwargs = { + do_true_cfg = current_guidance_scale > 1.0 and negative_prompt_embeds is not None + # Prepare kwargs for positive and negative predictions + positive_kwargs = { "hidden_states": latent_model_input, "timestep": timestep, - "encoder_hidden_states": negative_prompt_embeds, + "encoder_hidden_states": prompt_embeds, "encoder_hidden_states_image": image_embeds, "attention_kwargs": attention_kwargs, "return_dict": False, "current_model": current_model, } - else: - negative_kwargs = None + if do_true_cfg: + negative_kwargs = { + "hidden_states": latent_model_input, + "timestep": timestep, + "encoder_hidden_states": negative_prompt_embeds, + "encoder_hidden_states_image": image_embeds, + "attention_kwargs": attention_kwargs, + "return_dict": False, + "current_model": current_model, + } + else: + negative_kwargs = None - # Predict noise with automatic CFG parallel handling - noise_pred = self.predict_noise_maybe_with_cfg( - do_true_cfg=do_true_cfg, - true_cfg_scale=current_guidance_scale, - positive_kwargs=positive_kwargs, - negative_kwargs=negative_kwargs, - cfg_normalize=False, - ) + # Predict noise with automatic CFG parallel handling + noise_pred = self.predict_noise_maybe_with_cfg( + do_true_cfg=do_true_cfg, + true_cfg_scale=current_guidance_scale, + positive_kwargs=positive_kwargs, + negative_kwargs=negative_kwargs, + cfg_normalize=False, + ) - # Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync - latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg) + # Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync + latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg) + + pbar.update() # Wan2.2 is prone to out of memory errors when predicting large videos # so we empty the cache here to avoid OOM before vae decoding. diff --git a/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2_ti2v.py b/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2_ti2v.py index d32b7d697..f116834cf 100644 --- a/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2_ti2v.py +++ b/vllm_omni/diffusion/models/wan2_2/pipeline_wan2_2_ti2v.py @@ -35,6 +35,7 @@ from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin from vllm_omni.diffusion.distributed.utils import get_local_device from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader from vllm_omni.diffusion.models.interface import SupportImageInput +from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin from vllm_omni.diffusion.models.schedulers import FlowUniPCMultistepScheduler from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import ( create_transformer_from_config, @@ -128,7 +129,7 @@ def get_wan22_ti2v_pre_process_func( return pre_process_func -class Wan22TI2VPipeline(nn.Module, SupportImageInput, CFGParallelMixin): +class Wan22TI2VPipeline(nn.Module, SupportImageInput, CFGParallelMixin, ProgressBarMixin): """ Wan2.2 Text-Image-to-Video (TI2V) Pipeline. @@ -380,60 +381,63 @@ class Wan22TI2VPipeline(nn.Module, SupportImageInput, CFGParallelMixin): attention_kwargs = {} # Denoising loop - for t in timesteps: - self._current_timestep = t + with self.progress_bar(total=len(timesteps)) as pbar: + for t in timesteps: + self._current_timestep = t - # Prepare latent input - if latent_condition is not None: - # I2V mode: blend condition with latents using mask - latent_model_input = (1 - first_frame_mask) * latent_condition + first_frame_mask * latents - latent_model_input = latent_model_input.to(dtype) + # Prepare latent input + if latent_condition is not None: + # I2V mode: blend condition with latents using mask + latent_model_input = (1 - first_frame_mask) * latent_condition + first_frame_mask * latents + latent_model_input = latent_model_input.to(dtype) - # Expand timesteps for each patch (TI2V style) - temp_ts = (first_frame_mask[0][0][:, ::2, ::2] * t).flatten() - timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1) - else: - # T2V mode: use latents directly - latent_model_input = latents.to(dtype) + # Expand timesteps for each patch (TI2V style) + temp_ts = (first_frame_mask[0][0][:, ::2, ::2] * t).flatten() + timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1) + else: + # T2V mode: use latents directly + latent_model_input = latents.to(dtype) - # Expand timesteps for TI2V model architecture - mask = torch.ones(1, 1, num_latent_frames, latent_height, latent_width, device=device) - temp_ts = (mask[0][0][:, ::2, ::2] * t).flatten() - timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1) + # Expand timesteps for TI2V model architecture + mask = torch.ones(1, 1, num_latent_frames, latent_height, latent_width, device=device) + temp_ts = (mask[0][0][:, ::2, ::2] * t).flatten() + timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1) - do_true_cfg = guidance_scale > 1.0 and negative_prompt_embeds is not None - # Prepare kwargs for positive and negative predictions - positive_kwargs = { - "hidden_states": latent_model_input, - "timestep": timestep, - "encoder_hidden_states": prompt_embeds, - "attention_kwargs": attention_kwargs, - "return_dict": False, - "current_model": self.transformer, - } - if do_true_cfg: - negative_kwargs = { + do_true_cfg = guidance_scale > 1.0 and negative_prompt_embeds is not None + # Prepare kwargs for positive and negative predictions + positive_kwargs = { "hidden_states": latent_model_input, "timestep": timestep, - "encoder_hidden_states": negative_prompt_embeds, + "encoder_hidden_states": prompt_embeds, "attention_kwargs": attention_kwargs, "return_dict": False, "current_model": self.transformer, } - else: - negative_kwargs = None + if do_true_cfg: + negative_kwargs = { + "hidden_states": latent_model_input, + "timestep": timestep, + "encoder_hidden_states": negative_prompt_embeds, + "attention_kwargs": attention_kwargs, + "return_dict": False, + "current_model": self.transformer, + } + else: + negative_kwargs = None - # Predict noise with automatic CFG parallel handling - noise_pred = self.predict_noise_maybe_with_cfg( - do_true_cfg=do_true_cfg, - true_cfg_scale=guidance_scale, - positive_kwargs=positive_kwargs, - negative_kwargs=negative_kwargs, - cfg_normalize=False, - ) + # Predict noise with automatic CFG parallel handling + noise_pred = self.predict_noise_maybe_with_cfg( + do_true_cfg=do_true_cfg, + true_cfg_scale=guidance_scale, + positive_kwargs=positive_kwargs, + negative_kwargs=negative_kwargs, + cfg_normalize=False, + ) - # Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync - latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg) + # Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync + latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg) + + pbar.update() # Wan2.2 is prone to out of memory errors when predicting large videos # so we empty the cache here to avoid OOM before vae decoding. diff --git a/vllm_omni/diffusion/registry.py b/vllm_omni/diffusion/registry.py index 37bc316cc..fe874c9e2 100644 --- a/vllm_omni/diffusion/registry.py +++ b/vllm_omni/diffusion/registry.py @@ -56,6 +56,16 @@ _DIFFUSION_MODELS = { "pipeline_wan2_2", "Wan22Pipeline", ), + "LTX2Pipeline": ( + "ltx2", + "pipeline_ltx2", + "LTX2Pipeline", + ), + "LTX2ImageToVideoPipeline": ( + "ltx2", + "pipeline_ltx2_image2video", + "LTX2ImageToVideoPipeline", + ), "StableAudioPipeline": ( "stable_audio", "pipeline_stable_audio", @@ -275,6 +285,8 @@ _DIFFUSION_POST_PROCESS_FUNCS = { "ZImagePipeline": "get_post_process_func", "OvisImagePipeline": "get_ovis_image_post_process_func", "WanPipeline": "get_wan22_post_process_func", + "LTX2Pipeline": "get_ltx2_post_process_func", + "LTX2ImageToVideoPipeline": "get_ltx2_post_process_func", "StableAudioPipeline": "get_stable_audio_post_process_func", "WanImageToVideoPipeline": "get_wan22_i2v_post_process_func", "LongCatImagePipeline": "get_longcat_image_post_process_func", diff --git a/vllm_omni/distributed/omni_connectors/transfer_adapter/chunk_transfer_adapter.py b/vllm_omni/distributed/omni_connectors/transfer_adapter/chunk_transfer_adapter.py index d80323bbd..c7289d8b8 100644 --- a/vllm_omni/distributed/omni_connectors/transfer_adapter/chunk_transfer_adapter.py +++ b/vllm_omni/distributed/omni_connectors/transfer_adapter/chunk_transfer_adapter.py @@ -185,9 +185,12 @@ class OmniChunkTransferAdapter(OmniTransferAdapterBase): self.request_payload[req_id] = payload_data return payload_data origin_payload = self.request_payload[req_id] + override_keys = payload_data.pop("override_keys", []) for key, value in payload_data.items(): if key == "finished": continue + elif key in override_keys: + payload_data[key] = value elif isinstance(value, torch.Tensor) and key in origin_payload: payload_data[key] = torch.cat([origin_payload[key], value], dim=0) elif isinstance(value, list) and key in origin_payload: diff --git a/vllm_omni/engine/arg_utils.py b/vllm_omni/engine/arg_utils.py index 7a75d3563..c4f719703 100644 --- a/vllm_omni/engine/arg_utils.py +++ b/vllm_omni/engine/arg_utils.py @@ -65,6 +65,8 @@ class OmniEngineArgs(EngineArgs): stage_connector_spec: Extra configuration for stage connector async_chunk: If set to True, perform async chunk worker_type: Model Type, e.g., "ar" or "generation" + task_type: Default task type for TTS models (CustomVoice, VoiceDesign, or Base). + If not specified, will be inferred from model path. """ stage_id: int = 0 @@ -78,6 +80,7 @@ class OmniEngineArgs(EngineArgs): omni_kv_config: dict | None = None quantization_config: Any | None = None worker_type: str | None = None + task_type: str | None = None def __post_init__(self) -> None: load_omni_general_plugins() @@ -201,6 +204,7 @@ class OmniEngineArgs(EngineArgs): custom_process_next_stage_input_func=self.custom_process_next_stage_input_func, stage_connector_config=stage_connector_config, omni_kv_config=self.omni_kv_config, + task_type=self.task_type, ) omni_config.hf_config.architectures = omni_config.architectures @@ -223,6 +227,8 @@ class AsyncOmniEngineArgs(AsyncEngineArgs): "audio", "latents"). If None, output type is inferred. stage_connector_spec: Extra configuration for stage connector worker_type: Model Type, e.g., "ar" or "generation" + task_type: Default task type for TTS models (CustomVoice, VoiceDesign, or Base). + If not specified, will be inferred from model path. """ stage_id: int = 0 @@ -236,6 +242,7 @@ class AsyncOmniEngineArgs(AsyncEngineArgs): omni_kv_config: dict | None = None quantization_config: Any | None = None worker_type: str | None = None + task_type: str | None = None def __post_init__(self) -> None: load_omni_general_plugins() @@ -359,6 +366,7 @@ class AsyncOmniEngineArgs(AsyncEngineArgs): custom_process_next_stage_input_func=self.custom_process_next_stage_input_func, stage_connector_config=stage_connector_config, omni_kv_config=self.omni_kv_config, + task_type=self.task_type, ) omni_config.hf_config.architectures = omni_config.architectures diff --git a/vllm_omni/entrypoints/async_omni.py b/vllm_omni/entrypoints/async_omni.py index 1d193ad88..b93038146 100644 --- a/vllm_omni/entrypoints/async_omni.py +++ b/vllm_omni/entrypoints/async_omni.py @@ -180,6 +180,7 @@ class AsyncOmni(OmniBase): }, "engine_args": { "parallel_config": parallel_config, + "model_class_name": kwargs.get("model_class_name", None), "vae_use_slicing": kwargs.get("vae_use_slicing", False), "vae_use_tiling": kwargs.get("vae_use_tiling", False), "cache_backend": cache_backend, diff --git a/vllm_omni/entrypoints/async_omni_diffusion.py b/vllm_omni/entrypoints/async_omni_diffusion.py index b3c02892c..5da6e81ed 100644 --- a/vllm_omni/entrypoints/async_omni_diffusion.py +++ b/vllm_omni/entrypoints/async_omni_diffusion.py @@ -87,7 +87,8 @@ class AsyncOmniDiffusion: try: config_dict = get_hf_file_to_dict("model_index.json", od_config.model) if config_dict is not None: - od_config.model_class_name = config_dict.get("_class_name", None) + if od_config.model_class_name is None: + od_config.model_class_name = config_dict.get("_class_name", None) od_config.update_multimodal_support() tf_config_dict = get_hf_file_to_dict("transformer/config.json", od_config.model) diff --git a/vllm_omni/entrypoints/cli/serve.py b/vllm_omni/entrypoints/cli/serve.py index f99e6c77a..a580f9536 100644 --- a/vllm_omni/entrypoints/cli/serve.py +++ b/vllm_omni/entrypoints/cli/serve.py @@ -113,6 +113,14 @@ class OmniServeCommand(CLISubcommand): action="store_true", help="Enable vLLM-Omni mode for multi-modal and diffusion models", ) + omni_config_group.add_argument( + "--task-type", + type=str, + default=None, + choices=["CustomVoice", "VoiceDesign", "Base"], + help="Default task type for TTS models (CustomVoice, VoiceDesign, or Base). " + "If not specified, will be inferred from model path.", + ) omni_config_group.add_argument( "--stage-configs-path", type=str, @@ -193,6 +201,13 @@ class OmniServeCommand(CLISubcommand): default=None, help="Number of GPUs to use for diffusion model inference.", ) + omni_config_group.add_argument( + "--model-class-name", + dest="model_class_name", + type=str, + default=None, + help="Override the diffusion pipeline class name (e.g. LTX2ImageToVideoPipeline).", + ) omni_config_group.add_argument( "--usp", "--ulysses-degree", diff --git a/vllm_omni/entrypoints/omni_diffusion.py b/vllm_omni/entrypoints/omni_diffusion.py index 12db495c5..9937726e5 100644 --- a/vllm_omni/entrypoints/omni_diffusion.py +++ b/vllm_omni/entrypoints/omni_diffusion.py @@ -58,7 +58,8 @@ class OmniDiffusion: od_config.model, ) if config_dict is not None: - od_config.model_class_name = config_dict.get("_class_name", None) + if od_config.model_class_name is None: + od_config.model_class_name = config_dict.get("_class_name", None) od_config.update_multimodal_support() tf_config_dict = get_hf_file_to_dict( @@ -91,7 +92,8 @@ class OmniDiffusion: if pipeline_class is None: raise ValueError(f"Unknown model type: {model_type}, architectures: {architectures}") - od_config.model_class_name = pipeline_class + if od_config.model_class_name is None: + od_config.model_class_name = pipeline_class od_config.tf_model_config = TransformerConfig() od_config.update_multimodal_support() diff --git a/vllm_omni/entrypoints/openai/api_server.py b/vllm_omni/entrypoints/openai/api_server.py index 5fa155690..969531b08 100644 --- a/vllm_omni/entrypoints/openai/api_server.py +++ b/vllm_omni/entrypoints/openai/api_server.py @@ -856,7 +856,13 @@ async def create_speech(request: OpenAICreateSpeechRequest, raw_request: Request ) return base_server.create_error_response(message="The model does not support Speech API") try: - return await handler.create_speech(request, raw_request) + result = await handler.create_speech(request, raw_request) + if isinstance(result, ErrorResponse): + return JSONResponse( + content=result.model_dump(), + status_code=result.error.code if result.error else 400, + ) + return result except Exception as e: raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=str(e)) from e diff --git a/vllm_omni/entrypoints/openai/protocol/audio.py b/vllm_omni/entrypoints/openai/protocol/audio.py index 8915e544b..1efab8ebe 100644 --- a/vllm_omni/entrypoints/openai/protocol/audio.py +++ b/vllm_omni/entrypoints/openai/protocol/audio.py @@ -55,6 +55,11 @@ class OpenAICreateSpeechRequest(BaseModel): default=None, description="Maximum tokens to generate", ) + initial_codec_chunk_frames: int | None = Field( + default=None, + ge=0, + description="Initial chunk size for reduced TTFA. Overrides stage config for this request.", + ) @field_validator("stream_format") @classmethod diff --git a/vllm_omni/entrypoints/openai/serving_speech.py b/vllm_omni/entrypoints/openai/serving_speech.py index 986e06ace..9ff7bc767 100644 --- a/vllm_omni/entrypoints/openai/serving_speech.py +++ b/vllm_omni/entrypoints/openai/serving_speech.py @@ -468,6 +468,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin): else: params["max_new_tokens"] = [2048] + if request.initial_codec_chunk_frames is not None: + params["initial_codec_chunk_frames"] = [request.initial_codec_chunk_frames] + # VoiceDesign requires non_streaming_mode (match offline script behaviour). # CustomVoice and Base rely on the model default (True and False respectively). if params["task_type"][0] == "VoiceDesign": diff --git a/vllm_omni/entrypoints/openai/serving_video.py b/vllm_omni/entrypoints/openai/serving_video.py index c5140f24a..f73df5ea4 100644 --- a/vllm_omni/entrypoints/openai/serving_video.py +++ b/vllm_omni/entrypoints/openai/serving_video.py @@ -89,12 +89,17 @@ class OmniOpenAIServingVideo: status_code=HTTPStatus.BAD_REQUEST.value, detail=str(exc), ) from exc - if input_image is not None: - prompt["multi_modal_data"] = {"image": input_image} gen_params = OmniDiffusionSamplingParams(num_outputs_per_prompt=request.n) width, height, num_frames, fps = self._resolve_video_params(request) + if input_image is not None and width is not None and height is not None: + target_size = (width, height) + if input_image.size != target_size: + input_image = input_image.resize(target_size, Image.Resampling.LANCZOS) + if input_image is not None: + prompt["multi_modal_data"] = {"image": input_image} + if width is not None and height is not None: gen_params.width = width gen_params.height = height @@ -102,6 +107,7 @@ class OmniOpenAIServingVideo: gen_params.num_frames = num_frames if fps is not None: gen_params.fps = fps + gen_params.frame_rate = float(fps) if request.num_inference_steps is not None: gen_params.num_inference_steps = request.num_inference_steps @@ -136,9 +142,25 @@ class OmniOpenAIServingVideo: result = await self._run_generation(prompt, gen_params, request_id, raw_request) videos = self._extract_video_outputs(result) + audios = self._extract_audio_outputs(result, expected_count=len(videos)) output_fps = fps or 24 + audio_sample_rate = self._resolve_audio_sample_rate(result) - video_data = [VideoData(b64_json=encode_video_base64(video, fps=output_fps)) for video in videos] + video_data = [ + VideoData( + b64_json=( + encode_video_base64(video, fps=output_fps) + if audios[idx] is None + else encode_video_base64( + video, + fps=output_fps, + audio=audios[idx], + audio_sample_rate=audio_sample_rate, + ) + ) + ) + for idx, video in enumerate(videos) + ] return VideoGenerationResponse(created=int(time.time()), data=video_data) def _resolve_model_name(self, raw_request: Request | None) -> str | None: @@ -323,3 +345,127 @@ class OmniOpenAIServingVideo: detail="No video outputs found in generation result.", ) return normalized + + @staticmethod + def _extract_audio_outputs(result: Any, expected_count: int) -> list[Any | None]: + audio = None + if hasattr(result, "multimodal_output") and result.multimodal_output: + audio = result.multimodal_output.get("audio") + elif hasattr(result, "request_output"): + request_output = result.request_output + if isinstance(request_output, dict) and request_output.get("multimodal_output"): + mm_output = request_output.get("multimodal_output") or {} + audio = mm_output.get("audio") + elif hasattr(request_output, "multimodal_output") and request_output.multimodal_output: + audio = request_output.multimodal_output.get("audio") + + if audio is None: + return [None] * expected_count + + if isinstance(audio, (list, tuple)): + if len(audio) == expected_count and any(hasattr(item, "shape") or hasattr(item, "ndim") for item in audio): + return list(audio) + if expected_count == 1: + return [audio] + + if hasattr(audio, "ndim") and getattr(audio, "ndim", None) is not None and audio.ndim > 1: + first_dim = getattr(audio, "shape", [0])[0] + if first_dim == expected_count: + return [audio[i] for i in range(expected_count)] + + if expected_count == 1: + return [audio] + + return [audio] + [None] * max(expected_count - 1, 0) + + def _resolve_audio_sample_rate(self, result: Any) -> int: + result_sample_rate = self._extract_audio_sample_rate_from_result(result) + if result_sample_rate is not None: + return result_sample_rate + + model_config = getattr(self._engine_client, "model_config", None) + hf_config = getattr(model_config, "hf_config", None) + config_sample_rate = self._extract_audio_sample_rate_from_config(hf_config) + if config_sample_rate is not None: + return config_sample_rate + + return 24000 + + @classmethod + def _extract_audio_sample_rate_from_result(cls, result: Any) -> int | None: + multimodal_output = getattr(result, "multimodal_output", None) + if isinstance(multimodal_output, dict): + sample_rate = cls._coerce_audio_sample_rate( + multimodal_output.get("audio_sample_rate") + or multimodal_output.get("sample_rate") + or multimodal_output.get("sampling_rate") + or multimodal_output.get("sr") + ) + if sample_rate is not None: + return sample_rate + + request_output = getattr(result, "request_output", None) + if isinstance(request_output, dict): + multimodal_output = request_output.get("multimodal_output") or {} + if isinstance(multimodal_output, dict): + return cls._coerce_audio_sample_rate( + multimodal_output.get("audio_sample_rate") + or multimodal_output.get("sample_rate") + or multimodal_output.get("sampling_rate") + or multimodal_output.get("sr") + ) + elif hasattr(request_output, "multimodal_output"): + multimodal_output = getattr(request_output, "multimodal_output", None) + if isinstance(multimodal_output, dict): + return cls._coerce_audio_sample_rate( + multimodal_output.get("audio_sample_rate") + or multimodal_output.get("sample_rate") + or multimodal_output.get("sampling_rate") + or multimodal_output.get("sr") + ) + + return None + + @classmethod + def _extract_audio_sample_rate_from_config(cls, config: Any) -> int | None: + if config is None: + return None + + for attr_name in ("output_sampling_rate", "audio_sample_rate", "sample_rate", "sampling_rate"): + raw_value = config.get(attr_name) if isinstance(config, dict) else getattr(config, attr_name, None) + sample_rate = cls._coerce_audio_sample_rate(raw_value) + if sample_rate is not None: + return sample_rate + + for component_name in ("vocoder", "audio_vae"): + component = ( + config.get(component_name) if isinstance(config, dict) else getattr(config, component_name, None) + ) + if component is None: + continue + + sample_rate = cls._extract_audio_sample_rate_from_config(component) + if sample_rate is not None: + return sample_rate + + component_config = ( + component.get("config") if isinstance(component, dict) else getattr(component, "config", None) + ) + sample_rate = cls._extract_audio_sample_rate_from_config(component_config) + if sample_rate is not None: + return sample_rate + + return None + + @staticmethod + def _coerce_audio_sample_rate(value: Any) -> int | None: + if value is None: + return None + + try: + sample_rate = value.item() if hasattr(value, "item") else value + sample_rate = int(sample_rate) + except (TypeError, ValueError): + return None + + return sample_rate if sample_rate > 0 else None diff --git a/vllm_omni/entrypoints/openai/video_api_utils.py b/vllm_omni/entrypoints/openai/video_api_utils.py index 865b1a528..64672ef6f 100644 --- a/vllm_omni/entrypoints/openai/video_api_utils.py +++ b/vllm_omni/entrypoints/openai/video_api_utils.py @@ -136,8 +136,44 @@ def _coerce_video_to_frames(video: Any) -> list[np.ndarray]: raise ValueError(f"Unsupported video payload type: {type(video)}") -def encode_video_base64(video: Any, fps: int) -> str: - """Encode a video (frames/array/tensor) to base64 MP4.""" +def _coerce_audio_to_waveform(audio: Any) -> torch.Tensor: + """Convert an audio payload into a 2-channel CPU float tensor for LTX2 export.""" + if isinstance(audio, torch.Tensor): + waveform = audio.detach().cpu() + elif isinstance(audio, np.ndarray): + waveform = torch.from_numpy(audio) + elif isinstance(audio, list): + waveform = torch.tensor(audio) + else: + raise ValueError(f"Unsupported audio payload type: {type(audio)}") + + waveform = waveform.squeeze() + + if waveform.ndim == 0: + raise ValueError("Audio payload must contain at least one sample.") + + if waveform.ndim == 1: + waveform = waveform.unsqueeze(0) + elif waveform.ndim == 2: + if waveform.shape[0] in (1, 2): + pass + elif waveform.shape[1] in (1, 2): + waveform = waveform.transpose(0, 1) + else: + raise ValueError(f"Unsupported audio payload shape: {tuple(waveform.shape)}") + else: + raise ValueError(f"Unsupported audio payload rank: {waveform.ndim}") + + if waveform.shape[0] == 1: + waveform = waveform.repeat(2, 1) + elif waveform.shape[0] != 2: + raise ValueError(f"Expected mono or stereo audio, got shape {tuple(waveform.shape)}") + + return waveform.float().contiguous() + + +def _encode_video_bytes(video: Any, fps: int, audio: Any | None = None, audio_sample_rate: int | None = None) -> bytes: + """Encode a video payload into MP4 bytes, optionally muxing audio.""" try: from diffusers.utils import export_to_video except ImportError as exc: # pragma: no cover - optional dependency @@ -150,12 +186,34 @@ def encode_video_base64(video: Any, fps: int) -> str: tmp_file = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) tmp_file.close() try: - export_to_video(frames, tmp_file.name, fps=fps) + if audio is not None: + from diffusers.pipelines.ltx2.export_utils import encode_video as encode_ltx2_video + + frames_np = np.stack(frames, axis=0) + if frames_np.ndim == 4 and frames_np.shape[-1] == 4: + frames_np = frames_np[..., :3] + frames_np = np.clip(frames_np, 0.0, 1.0) + frames_u8 = (frames_np * 255).round().clip(0, 255).astype("uint8") + video_tensor = torch.from_numpy(frames_u8) + encode_ltx2_video( + video_tensor, + fps=fps, + audio=_coerce_audio_to_waveform(audio), + audio_sample_rate=audio_sample_rate, + output_path=tmp_file.name, + ) + else: + export_to_video(frames, tmp_file.name, fps=fps) with open(tmp_file.name, "rb") as f: - video_bytes = f.read() - return base64.b64encode(video_bytes).decode("utf-8") + return f.read() finally: try: os.remove(tmp_file.name) except OSError: pass + + +def encode_video_base64(video: Any, fps: int, audio: Any | None = None, audio_sample_rate: int | None = None) -> str: + """Encode a video (frames/array/tensor) to base64 MP4.""" + video_bytes = _encode_video_bytes(video, fps=fps, audio=audio, audio_sample_rate=audio_sample_rate) + return base64.b64encode(video_bytes).decode("utf-8") diff --git a/vllm_omni/inputs/data.py b/vllm_omni/inputs/data.py index 438abb971..16d690bf3 100644 --- a/vllm_omni/inputs/data.py +++ b/vllm_omni/inputs/data.py @@ -163,6 +163,7 @@ class OmniDiffusionSamplingParams: max_sequence_length: int | None = None prompt_template: dict[str, Any] | None = None do_classifier_free_guidance: bool = False + output_type: str | None = None # Batch info num_outputs_per_prompt: int = 1 @@ -187,6 +188,7 @@ class OmniDiffusionSamplingParams: # Latent tensors latents: torch.Tensor | None = None + audio_latents: torch.Tensor | None = None raw_latent_shape: torch.Tensor | None = None noise_pred: torch.Tensor | None = None image_latent: torch.Tensor | None = None @@ -200,7 +202,8 @@ class OmniDiffusionSamplingParams: # Original dimensions (before VAE scaling) height: int | None = None width: int | None = None - fps: int | None = None + fps: int | None = None # Integer FPS kept for request compatibility and output encoding. + frame_rate: float | None = None # Floating-point rate used by the diffusion model when it differs from `fps`. height_not_provided: bool = False width_not_provided: bool = False @@ -216,6 +219,8 @@ class OmniDiffusionSamplingParams: guidance_scale_provided: bool = False guidance_scale_2: float | None = None guidance_rescale: float = 0.0 + decode_timestep: float | list[float] | None = None + decode_noise_scale: float | list[float] | None = None eta: float = 0.0 sigmas: list[float] | None = None @@ -284,6 +289,20 @@ class OmniDiffusionSamplingParams: # Only adjust batch size for number of videos per prompt return self.num_outputs_per_prompt + @property + def resolved_frame_rate(self) -> float | None: + if self.frame_rate is not None: + return float(self.frame_rate) + + fps = self.fps + if isinstance(fps, list): + fps = fps[0] if fps else None + + if fps is None: + return None + + return float(fps) + def __str__(self): return pprint.pformat(asdict(self), indent=2, width=120) diff --git a/vllm_omni/model_executor/models/qwen3_omni/qwen3_omni.py b/vllm_omni/model_executor/models/qwen3_omni/qwen3_omni.py index 7506c117d..ec928195a 100644 --- a/vllm_omni/model_executor/models/qwen3_omni/qwen3_omni.py +++ b/vllm_omni/model_executor/models/qwen3_omni/qwen3_omni.py @@ -603,7 +603,7 @@ class Qwen3OmniMoeForConditionalGeneration( else: # decode if not info_dict.get("decode_flag", False): - info_dict["num_processed_tokens"] = len(info_dict.get("thinker_input_ids", [])) + 1 + info_dict["num_processed_tokens"] = 0 update_dict["decode_flag"] = True last_talker_hidden, text_step, update_dict = self.talker_preprocess_decode( @@ -673,7 +673,7 @@ class Qwen3OmniMoeForConditionalGeneration( start_index = info_dict.get("num_processed_tokens", 0) end_index = start_index + input_embeds.shape[0] # Read thinker outputs for prefill - thinker_sequence_embeds = info_dict.get("thinker_embeddings").to( + thinker_sequence_embeds = info_dict.get("thinker_prefill_embeddings").to( device=self._module_device(self.talker), dtype=torch.bfloat16 ) # Tensor [P,H] thinker_hidden_states = info_dict.get("thinker_hidden_states").to( @@ -703,7 +703,7 @@ class Qwen3OmniMoeForConditionalGeneration( if thinker_sequence_embeds is None or thinker_hidden_states is None: raise ValueError( "additional_information_by_req_id must include " - "'thinker_embeddings' and 'thinker_hidden_states' for talker prefill." + "'thinker_prefill_embeddings' and 'thinker_hidden_states' for talker prefill." ) # Normalize to tensors @@ -770,9 +770,35 @@ class Qwen3OmniMoeForConditionalGeneration( update_dict["tts_pad_embed_projected"] = pad_proj.detach().to("cpu").contiguous() except Exception: pass + self._talker_cache_thinker_decode_embeds(info_dict, update_dict) return req_input_ids[start_index:end_index], req_embeds[start_index:end_index], update_dict + def _talker_cache_thinker_decode_embeds( + self, + info_dict: dict[str, Any], + update_dict: dict[str, Any], + ) -> None: + """ + Cache thinker embeds for decode stage. + """ + thinker_decode_embeds = info_dict.get("thinker_decode_embeddings", None) + if thinker_decode_embeds is not None: + cached_thinker_decode_embeds = info_dict.get("cached_thinker_decode_embeddings", None) + if cached_thinker_decode_embeds is None: + update_dict["cached_thinker_decode_embeddings"] = thinker_decode_embeds + else: + cached_thinker_decode_embeds = cached_thinker_decode_embeds.to( + device=self._module_device(self.talker), dtype=torch.bfloat16 + ) + thinker_decode_embeds = thinker_decode_embeds.to( + device=self._module_device(self.talker), dtype=torch.bfloat16 + ) + update_dict["cached_thinker_decode_embeddings"] = torch.cat( + [cached_thinker_decode_embeds, thinker_decode_embeds], dim=0 + ) + update_dict["thinker_decode_embeddings"] = None + def _thinker_to_talker_prefill( self, thinker_embed: torch.Tensor, @@ -866,15 +892,25 @@ class Qwen3OmniMoeForConditionalGeneration( Returns: (input_ids, input_embeds) for talker """ - thinker_embed = info_dict.get("thinker_embeddings", None) + cached_thinker_decode_embeds = info_dict.get("cached_thinker_decode_embeddings", None) + thinker_decode_embed = info_dict.get("thinker_decode_embeddings", None) start_index = info_dict.get("num_processed_tokens", 0) - if start_index >= thinker_embed.shape[0]: + thinker_output_token_ids = info_dict.get("thinker_output_token_ids", []) + if start_index >= len(thinker_output_token_ids) - 1: if info_dict.get("finished_flag"): return self.tts_pad_embed.to(device) update_dict["finished_flag"] = True return self.tts_eos_embed.to(device) - - thinker_embed = thinker_embed[start_index : start_index + 1].to(device) + if cached_thinker_decode_embeds is not None and start_index < cached_thinker_decode_embeds.shape[0]: + cached_thinker_decode_embeds = cached_thinker_decode_embeds.to(device) + thinker_embed = cached_thinker_decode_embeds[start_index] + if thinker_decode_embed is not None: + thinker_decode_embed = thinker_decode_embed.to(device) + cached_thinker_decode_embeds = torch.cat([cached_thinker_decode_embeds, thinker_decode_embed], dim=0) + update_dict["cached_thinker_decode_embeddings"] = cached_thinker_decode_embeds + else: + thinker_embed = thinker_decode_embed.to(device) + update_dict["thinker_decode_embeddings"] = None return self.talker.text_projection(thinker_embed).to(device) def talker_preprocess_decode( diff --git a/vllm_omni/model_executor/models/qwen3_tts/qwen3_tts.py b/vllm_omni/model_executor/models/qwen3_tts/qwen3_tts.py index 028d4a53d..b70f2f3b3 100644 --- a/vllm_omni/model_executor/models/qwen3_tts/qwen3_tts.py +++ b/vllm_omni/model_executor/models/qwen3_tts/qwen3_tts.py @@ -94,7 +94,9 @@ class Qwen3TTSModelForGeneration(nn.Module): torch_dtype=torch.bfloat16, **attn_kwargs, ) - self.task_type = _normalize_task_type(model_path.split("-")[-1].split("/")[0]) + self.task_type = getattr(vllm_config.model_config, "task_type", None) or _normalize_task_type( + model_path.split("-")[-1].split("/")[0] + ) # Mark that this model produces multimodal outputs self.have_multimodal_outputs = True diff --git a/vllm_omni/model_executor/models/qwen3_tts/qwen3_tts_code2wav.py b/vllm_omni/model_executor/models/qwen3_tts/qwen3_tts_code2wav.py index 851455bda..c93d027d7 100644 --- a/vllm_omni/model_executor/models/qwen3_tts/qwen3_tts_code2wav.py +++ b/vllm_omni/model_executor/models/qwen3_tts/qwen3_tts_code2wav.py @@ -73,7 +73,7 @@ class Qwen3TTSCode2Wav(nn.Module): tok = Qwen3TTSTokenizer.from_pretrained( speech_tokenizer_dir, - torch_dtype=torch.bfloat16, + torch_dtype=torch.float32, load_feature_extractor=False, ) diff --git a/vllm_omni/model_executor/stage_configs/qwen3_tts.yaml b/vllm_omni/model_executor/stage_configs/qwen3_tts.yaml index 90053852a..564f1160c 100644 --- a/vllm_omni/model_executor/stage_configs/qwen3_tts.yaml +++ b/vllm_omni/model_executor/stage_configs/qwen3_tts.yaml @@ -96,6 +96,10 @@ runtime: # Align with Omni: small chunks with sufficient context overlap. codec_chunk_frames: 25 codec_left_context_frames: 25 + # First chunk size for reduced TTFA (0 = disabled). + # When > 0, emits small chunks every N frames during the initial phase, + # then switches to codec_chunk_frames cadence. + initial_codec_chunk_frames: 0 edges: - from: 0 diff --git a/vllm_omni/model_executor/stage_configs/qwen3_tts_batch.yaml b/vllm_omni/model_executor/stage_configs/qwen3_tts_batch.yaml index d73739109..43df70fc2 100644 --- a/vllm_omni/model_executor/stage_configs/qwen3_tts_batch.yaml +++ b/vllm_omni/model_executor/stage_configs/qwen3_tts_batch.yaml @@ -98,6 +98,10 @@ runtime: # Align with Omni: small chunks with sufficient context overlap. codec_chunk_frames: 25 codec_left_context_frames: 25 + # First chunk size for reduced TTFA (0 = disabled). + # When > 0, emits small chunks every N frames during the initial phase, + # then switches to codec_chunk_frames cadence. + initial_codec_chunk_frames: 0 edges: - from: 0 diff --git a/vllm_omni/model_executor/stage_input_processors/qwen3_omni.py b/vllm_omni/model_executor/stage_input_processors/qwen3_omni.py index 31a5ddd47..7cfc59f79 100644 --- a/vllm_omni/model_executor/stage_input_processors/qwen3_omni.py +++ b/vllm_omni/model_executor/stage_input_processors/qwen3_omni.py @@ -105,7 +105,7 @@ def thinker2talker_async_chunk( all_token_ids = _ensure_list(all_token_ids) prompt_token_ids = _ensure_list(prompt_token_ids) talker_additional_info = { - "thinker_embeddings": pooling_output.get("0").detach().cpu(), + "thinker_prefill_embeddings": pooling_output.get("0").detach().cpu(), "thinker_hidden_states": pooling_output.get("24").detach().cpu(), "thinker_sequences": all_token_ids, "thinker_input_ids": prompt_token_ids, @@ -121,8 +121,12 @@ def thinker2talker_async_chunk( return None else: save_payload = transfer_manager.request_payload.pop(request_id) - talker_additional_info["thinker_embeddings"] = torch.cat( - (save_payload.get("thinker_embeddings"), talker_additional_info.get("thinker_embeddings")), dim=0 + talker_additional_info["thinker_prefill_embeddings"] = torch.cat( + ( + save_payload.get("thinker_prefill_embeddings"), + talker_additional_info.get("thinker_prefill_embeddings"), + ), + dim=0, ) talker_additional_info["thinker_hidden_states"] = torch.cat( (save_payload.get("thinker_hidden_states"), talker_additional_info.get("thinker_hidden_states")), @@ -134,12 +138,15 @@ def thinker2talker_async_chunk( output_token_ids = _ensure_list(output_token_ids) talker_additional_info = { - "thinker_embeddings": pooling_output.get("0").detach().cpu(), "finished": torch.tensor(is_finished, dtype=torch.bool), } - - if not output_token_ids: + if output_token_ids: + talker_additional_info["override_keys"] = ["thinker_decode_embeddings", "thinker_output_token_ids"] + talker_additional_info["thinker_decode_embeddings"] = pooling_output.get("0").detach().cpu() + talker_additional_info["thinker_output_token_ids"] = output_token_ids + else: # When prefilling a chunked thinker, thinker_hidden_states needs to be updated. + talker_additional_info["thinker_prefill_embeddings"] = pooling_output.get("0").detach().cpu() talker_additional_info["thinker_hidden_states"] = pooling_output.get("24").detach().cpu() return talker_additional_info @@ -177,7 +184,7 @@ def thinker2talker( output = thinker_output.outputs[0] info = { - "thinker_embeddings": output.multimodal_output["0"].detach().to(device=device, dtype=torch.float), + "thinker_prefill_embeddings": output.multimodal_output["0"].detach().to(device=device, dtype=torch.float), "thinker_hidden_states": output.multimodal_output["24"].detach().to(device=device, dtype=torch.float), "thinker_sequences": ( thinker_output.prompt_token_ids + output.token_ids diff --git a/vllm_omni/model_executor/stage_input_processors/qwen3_tts.py b/vllm_omni/model_executor/stage_input_processors/qwen3_tts.py index 8c21052e9..c0bcfa612 100644 --- a/vllm_omni/model_executor/stage_input_processors/qwen3_tts.py +++ b/vllm_omni/model_executor/stage_input_processors/qwen3_tts.py @@ -3,6 +3,9 @@ from typing import Any import torch +from vllm.logger import init_logger + +logger = init_logger(__name__) def _extract_last_frame(pooling_output: dict[str, Any]) -> torch.Tensor | None: @@ -40,13 +43,32 @@ def talker2code2wav_async_chunk( connector = getattr(transfer_manager, "connector", None) raw_cfg = getattr(connector, "config", {}) or {} cfg = raw_cfg.get("extra", raw_cfg) if isinstance(raw_cfg, dict) else {} - chunk_size_config = int(cfg.get("codec_chunk_frames", 25)) + chunk_size = int(cfg.get("codec_chunk_frames", 25)) left_context_size_config = int(cfg.get("codec_left_context_frames", 25)) - if chunk_size_config <= 0 or left_context_size_config < 0: + initial_chunk_size = int(cfg.get("initial_codec_chunk_frames", 0)) + # Per-request override (takes priority over stage config) + additional_information = getattr(request, "additional_information", None) + if ( + additional_information is not None + and hasattr(additional_information, "entries") + and "initial_codec_chunk_frames" in additional_information.entries + ): + entry = additional_information.entries["initial_codec_chunk_frames"] + if entry.list_data is not None and len(entry.list_data) == 1: + initial_chunk_size = int(entry.list_data[0]) + if chunk_size <= 0 or left_context_size_config < 0 or initial_chunk_size < 0: raise ValueError( - f"Invalid codec chunk config: codec_chunk_frames={chunk_size_config}, " - f"codec_left_context_frames={left_context_size_config}" + f"Invalid codec chunk config: codec_chunk_frames={chunk_size}, " + f"codec_left_context_frames={left_context_size_config}, " + f"initial_codec_chunk_frames={initial_chunk_size}" ) + if initial_chunk_size > chunk_size: + logger.warning( + "initial_codec_chunk_frames=%d > codec_chunk_frames=%d, clamping to codec_chunk_frames.", + initial_chunk_size, + chunk_size, + ) + initial_chunk_size = chunk_size length = len(transfer_manager.code_prompt_token_ids[request_id]) # Avoid emitting empty chunks during normal streaming. If the request is @@ -59,21 +81,36 @@ def talker2code2wav_async_chunk( } return None - chunk_length = length % chunk_size_config + in_initial_phase = initial_chunk_size > 0 and length <= chunk_size - if chunk_length != 0 and not finished: - return None - - context_length = chunk_length if chunk_length != 0 else chunk_size_config - end_index = min(length, left_context_size_config + context_length) - left_context_size = max(0, int(end_index - context_length)) - window_frames = transfer_manager.code_prompt_token_ids[request_id][-end_index:] + if in_initial_phase: + # Initial-chunk phase: emit every initial_chunk_size frames with full accumulated context. + already_sent = transfer_manager.put_req_chunk[request_id] * initial_chunk_size + pending = length - already_sent + if pending <= 0: + return None + if pending < initial_chunk_size and not finished: + return None + context_length = min(pending, initial_chunk_size) + end_index = length + left_context_size = max(0, length - context_length) + window_frames = transfer_manager.code_prompt_token_ids[request_id][:length] + else: + # Normal phase: standard chunk_size cadence with left_context sliding window. + # Offset by initial_coverage so normal starts from where the initial-chunk phase left off. + initial_coverage = (chunk_size // initial_chunk_size) * initial_chunk_size if initial_chunk_size > 0 else 0 + adjusted = length - initial_coverage + chunk_length = adjusted % chunk_size + if chunk_length != 0 and not finished: + return None + context_length = chunk_length if chunk_length != 0 else chunk_size + end_index = min(length, left_context_size_config + context_length) + left_context_size = max(0, int(end_index - context_length)) + window_frames = transfer_manager.code_prompt_token_ids[request_id][-end_index:] # Pack context + chunk into codebook-major flat codes for adapter. code_predictor_codes = torch.tensor(window_frames).transpose(0, 1).reshape(-1).tolist() - # Build final prompt_token_ids and left_context_size header for Qwen3-TTS Code2Wav. - # The model expects input_ids layout: [*flat_codes]. return { "code_predictor_codes": code_predictor_codes, "left_context_size": left_context_size, diff --git a/vllm_omni/platforms/npu/stage_configs/qwen3_tts.yaml b/vllm_omni/platforms/npu/stage_configs/qwen3_tts.yaml index 60659a976..5ad0cc90e 100644 --- a/vllm_omni/platforms/npu/stage_configs/qwen3_tts.yaml +++ b/vllm_omni/platforms/npu/stage_configs/qwen3_tts.yaml @@ -96,6 +96,10 @@ runtime: # Align with Omni: small chunks with sufficient context overlap. codec_chunk_frames: 25 codec_left_context_frames: 25 + # First chunk size for reduced TTFA (0 = disabled). + # When > 0, emits small chunks every N frames during the initial phase, + # then switches to codec_chunk_frames cadence. + initial_codec_chunk_frames: 0 edges: - from: 0