From 733f4f6a3650585838a836729211d04ddb8bcb11 Mon Sep 17 00:00:00 2001 From: "Guanzhe (Leo) Huang" <116847811+leohuang257@users.noreply.github.com> Date: Tue, 23 Jun 2026 14:42:05 +0800 Subject: [PATCH] [Refactor] Migrate cosmos3 example to standard task example + model_extra (#4581) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: leohuang257 Signed-off-by: 汪志鹏 Co-authored-by: 汪志鹏 --- .../offline_inference/cosmos3/inputs/v2v.json | 14 -- .../image_to_video/README.md | 26 +++- .../image_to_video/image_to_video.py | 134 +++++++++++++----- .../text_to_image/text_to_image.py | 17 ++- .../text_to_video/text_to_video.md | 16 +++ .../text_to_video/text_to_video.py | 45 +++++- recipes/cosmos3/Cosmos3-Nano.md | 86 ++++++----- tests/model_extras/test_model_extras.py | 72 ++++++++++ vllm_omni/model_extras/cosmos3.py | 68 +++++++++ vllm_omni/model_extras/registry.py | 12 ++ 10 files changed, 383 insertions(+), 107 deletions(-) delete mode 100644 examples/offline_inference/cosmos3/inputs/v2v.json create mode 100644 vllm_omni/model_extras/cosmos3.py diff --git a/examples/offline_inference/cosmos3/inputs/v2v.json b/examples/offline_inference/cosmos3/inputs/v2v.json deleted file mode 100644 index c16c4bbb7..000000000 --- a/examples/offline_inference/cosmos3/inputs/v2v.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "prompt": "A robotic arm, primarily white with black joints and cables, is shown in a clean, modern indoor setting with a white tabletop. The arm, equipped with a gripper holding a small, light green pitcher, is positioned above a clear glass containing a reddish-brown liquid and a spoon. The robotic arm is in the process of pouring a transparent liquid into the glass. To the left of the pitcher, there is an opened jar with a similar reddish-brown substance visible through its transparent body. In the background, a vase with white flowers and a brown couch are partially visible, adding to the contemporary ambiance. The lighting is bright, casting soft shadows on the table. The robotic arm's movements are smooth and controlled, demonstrating precision in its task. As the video progresses, the robotic arm completes the pour, leaving the glass half-filled with the reddish-brown liquid. The jar remains untouched throughout the sequence, and the spoon inside the glass remains stationary. The other robotic arm on the right side also stays stationary throughout the video. The final frame captures the robotic arm with the pitcher finishing the pour, with the glass now filled to a higher level, while the pitcher is slightly tilted but still held securely by the gripper.", - "negative_prompt": "", - "vision_path": "https://github.com/nvidia-cosmos/cosmos-dependencies/raw/refs/heads/assets/cosmos3/inputs/vision/robot_pouring.mp4", - "height": 720, - "width": 1280, - "num_frames": 189, - "num_inference_steps": 35, - "guidance_scale": 6.0, - "flow_shift": 10.0, - "fps": 24, - "condition_frame_indexes_vision": [0, 1], - "condition_video_keep": "first" -} diff --git a/examples/offline_inference/image_to_video/README.md b/examples/offline_inference/image_to_video/README.md index a458850a0..257d6a42e 100644 --- a/examples/offline_inference/image_to_video/README.md +++ b/examples/offline_inference/image_to_video/README.md @@ -1,6 +1,8 @@ # Image-To-Video -This example demonstrates how to generate videos from images using Wan2.2 Image-to-Video models with vLLM-Omni's offline inference API. +This example demonstrates how to generate videos from images (image-to-video) +using Wan2.2, LTX2, HunyuanVideo-1.5, and Cosmos3 with vLLM-Omni's offline +inference API. ## Local CLI Usage @@ -48,19 +50,35 @@ python image_to_video.py \ --output i2v_output.mp4 ``` +### Cosmos3 + +```bash +# Cosmos3 bundles example frames under assets/ (any RGB image works too): +python image_to_video.py \ + --model nvidia/Cosmos3-Nano \ + --image /path/to/Cosmos3-Nano/assets/example_i2v_input.jpg \ + --prompt "The scene comes to life with smooth, natural motion." \ + --negative-prompt "blurry, distorted, low quality" \ + --height 720 --width 1280 --num-frames 189 --fps 24 \ + --num-inference-steps 35 --guidance-scale 6.0 \ + --extra-body '{"flow_shift": 10.0, "max_sequence_length": 4096, "guardrails": false}' \ + --output cosmos3_i2v.mp4 +``` + Key arguments: - `--model`: Model ID (I2V-A14B for MoE, TI2V-5B for unified T2V+I2V). - `--image`: Path to input image (required). +- `--extra-body`: JSON object of model-specific generation params, filtered against the model's declared `extra_body_params` (see [`vllm_omni/model_extras`](../../../vllm_omni/model_extras)). Used by Cosmos3. - `--prompt`: Text description of desired motion/animation. - `--height/--width`: Output resolution (auto-calculated from image if not set). Dimensions should be multiples of 16. -- `--num-frames`: Number of frames (default 81). +- `--num-frames`: Number of frames (default: model-specific — Wan 81, LTX2 121, Cosmos3 189). - `--guidance-scale` and `--guidance-scale-high`: CFG scale (applied to low/high-noise stages for MoE). - `--negative-prompt`: Optional list of artifacts to suppress. - `--boundary-ratio`: Boundary split ratio for two-stage MoE models. -- `--flow-shift`: Scheduler flow shift (5.0 for 720p, 12.0 for 480p). +- `--flow-shift`: Scheduler flow shift (default: model-specific — Wan/LTX2 5.0, Cosmos3 10.0). - `--sample-solver`: Wan2.2 sampling solver. Use `unipc` for the default multistep solver, or `euler` for Lightning/Distill checkpoints. -- `--num-inference-steps`: Number of denoising steps (default 50). +- `--num-inference-steps`: Number of denoising steps (default: model-specific — Wan 50, LTX2 40, Cosmos3 35). - `--fps`: Frames per second for the saved MP4 (requires `diffusers` export_to_video). - `--output`: Path to save the generated video. - `--vae-use-slicing`: Enable VAE slicing for memory optimization. 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 e5bbacdca..97a01617f 100644 --- a/examples/offline_inference/image_to_video/image_to_video.py +++ b/examples/offline_inference/image_to_video/image_to_video.py @@ -30,9 +30,16 @@ Usage: python image_to_video.py --model hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_i2v \ --image input.jpg --prompt "A cat playing with yarn" \ --flow-shift 5.0 --guidance-scale 6.0 + + # Cosmos3 I2V (image conditioning) + python image_to_video.py --model nvidia/Cosmos3-Nano \ + --image input.jpg --prompt "The scene comes to life with smooth, natural motion." \ + --num-frames 189 --num-inference-steps 35 --guidance-scale 6.0 --fps 24 \ + --extra-body '{"flow_shift": 10.0, "max_sequence_length": 4096, "guardrails": false}' """ import argparse +import functools import json import time from pathlib import Path @@ -43,22 +50,28 @@ import PIL.Image import torch from vllm_omni.diffusion.data import DiffusionParallelConfig +from vllm_omni.diffusion.utils.param_utils import apply_declared_extra_args from vllm_omni.entrypoints.omni import Omni from vllm_omni.inputs.data import OmniDiffusionSamplingParams +from vllm_omni.model_extras import get_extra_body_params, get_model_class_name from vllm_omni.outputs import OmniRequestOutput from vllm_omni.platforms import current_omni_platform -def parse_profiler_config(value: str) -> dict[str, Any]: +def parse_json_object(value: str, flag_name: str = "argument") -> dict[str, Any]: + """Parse a CLI value as a JSON object, attributing errors to ``flag_name``.""" try: config = json.loads(value) except json.JSONDecodeError as e: - raise argparse.ArgumentTypeError(f"--profiler-config must be valid JSON: {e}") from e + raise argparse.ArgumentTypeError(f"{flag_name} must be valid JSON: {e}") from e if not isinstance(config, dict): - raise argparse.ArgumentTypeError("--profiler-config must be a JSON object") + raise argparse.ArgumentTypeError(f"{flag_name} must be a JSON object") return config +parse_profiler_config = functools.partial(parse_json_object, flag_name="--profiler-config") + + def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Generate a video from an image (Wan2.2, LTX2, HunyuanVideo-1.5).") parser.add_argument( @@ -75,7 +88,7 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--prompt", default="", help="Text prompt describing the desired motion.") parser.add_argument("--negative-prompt", default="", help="Negative prompt.") parser.add_argument("--seed", type=int, default=42, help="Random seed.") - parser.add_argument("--guidance-scale", type=float, default=5.0, help="CFG scale.") + parser.add_argument("--guidance-scale", type=float, default=None, help="CFG scale. Default: model-specific.") parser.add_argument( "--guidance-scale-high", type=float, default=None, help="Optional separate CFG for high-noise (MoE only)." ) @@ -83,8 +96,10 @@ def parse_args() -> argparse.Namespace: "--height", type=int, default=None, help="Video height (auto-calculated from image if not set)." ) parser.add_argument("--width", type=int, default=None, help="Video width (auto-calculated from image if not set).") - 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("--num-frames", type=int, default=None, help="Number of frames. Default: model-specific.") + parser.add_argument( + "--num-inference-steps", type=int, default=None, help="Sampling steps. Default: model-specific." + ) parser.add_argument("--boundary-ratio", type=float, default=0.875, help="Boundary split ratio for MoE models.") parser.add_argument( "--frame-rate", @@ -93,7 +108,10 @@ def parse_args() -> argparse.Namespace: 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)." + "--flow-shift", + type=float, + default=None, + help="Scheduler flow_shift. Default: model-specific (Wan 5.0, Cosmos3 10.0).", ) parser.add_argument( "--sample-solver", @@ -244,6 +262,19 @@ def parse_args() -> argparse.Namespace: default=None, help='JSON profiler config for torch/cuda profiling, e.g. \'{"profiler":"torch","torch_profiler_dir":"./perf"}\'.', ) + parser.add_argument( + "--extra-body", + type=functools.partial(parse_json_object, flag_name="--extra-body"), + default=None, + help=( + "Model-specific generation params as a JSON object. Keys are filtered " + "against the model's declared extra_body_params (see vllm_omni/model_extras), " + "so unknown keys for the chosen model are silently dropped. " + 'Cosmos3 V2V example: \'{"condition_frame_indexes_vision": [0, 1], ' + '"condition_video_keep": "first", "flow_shift": 10.0, ' + '"max_sequence_length": 4096, "guardrails": false}\'.' + ), + ) return parser.parse_args() @@ -267,26 +298,42 @@ def main(): 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()) + is_cosmos = "cosmos" in model_name or (model_class_name is not None and "cosmos" 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) + # Per-model generation defaults, applied only when the matching flag is omitted. + # Cosmos3 would otherwise silently inherit the Wan2.2 defaults (wrong size/steps/shift). + if is_cosmos: + d_fps, d_guidance, d_num_frames, d_steps, d_flow_shift, d_max_area, d_mod = ( + 24, + 6.0, + 189, + 35, + 10.0, + 1280 * 720, + 16, + ) + elif is_ltx2: + d_fps, d_guidance, d_num_frames, d_steps, d_flow_shift, d_max_area, d_mod = 24, 4.0, 121, 40, 5.0, 512 * 768, 32 + else: # Wan2.2 / HunyuanVideo-1.5 + d_fps, d_guidance, d_num_frames, d_steps, d_flow_shift, d_max_area, d_mod = 16, 5.0, 81, 50, 5.0, 480 * 832, 16 - # Calculate dimensions if not provided + fps = args.fps if args.fps is not None else d_fps + 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 d_guidance + num_frames = args.num_frames if args.num_frames is not None else d_num_frames + num_inference_steps = args.num_inference_steps if args.num_inference_steps is not None else d_steps + flow_shift = args.flow_shift if args.flow_shift is not None else d_flow_shift + + # Calculate dimensions if not provided (model-aware max area). height = args.height width = args.width if height is None or width is None: - # 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) + calc_height, calc_width = calculate_dimensions(image, max_area=d_max_area, mod_value=d_mod) height = height or calc_height width = width or calc_width @@ -342,7 +389,7 @@ def main(): vae_use_slicing=args.vae_use_slicing, vae_use_tiling=args.vae_use_tiling, boundary_ratio=args.boundary_ratio, - flow_shift=args.flow_shift, + flow_shift=flow_shift, diffusion_kv_cache_dtype=args.diffusion_kv_cache_dtype, diffusion_kv_cache_skip_steps=args.diffusion_kv_cache_skip_steps, diffusion_kv_cache_skip_layers=args.diffusion_kv_cache_skip_layers, @@ -357,7 +404,13 @@ def main(): ) if args.quantization is not None: omni_kwargs["quantization"] = args.quantization + # Cosmos3 loads its (gated) guardrail models at build time, so the guardrails + # gate is an engine-level config (offline analog of the server's --no-guardrails). + if args.extra_body and "guardrails" in args.extra_body: + omni_kwargs["model_config"] = {"guardrails": bool(args.extra_body["guardrails"])} omni = Omni(**omni_kwargs) + resolved_model_class_name = get_model_class_name(omni) + declared_extra_body_params = get_extra_body_params(resolved_model_class_name) if profiler_enabled: print("[Profiler] Starting profiling...") @@ -367,8 +420,8 @@ def main(): print(f"\n{'=' * 60}") print("Generation Configuration:") print(f" Model: {args.model}") - print(f" Inference steps: {args.num_inference_steps}") - print(f" Frames: {args.num_frames}") + print(f" Inference steps: {num_inference_steps}") + print(f" Frames: {num_frames}") print(f" Solver: {args.sample_solver}") print(f" diffusion_kv_cache_dtype(config): {args.diffusion_kv_cache_dtype}") print(f" diffusion_kv_cache_skip_steps(config): {args.diffusion_kv_cache_skip_steps}") @@ -381,6 +434,31 @@ def main(): print(f" Video size: {args.width}x{args.height}") print(f"{'=' * 60}\n") + sampling_params = OmniDiffusionSamplingParams( + height=height, + width=width, + generator=generator, + guidance_scale=guidance_scale, + guidance_scale_2=args.guidance_scale_high, + boundary_ratio=args.boundary_ratio, + num_inference_steps=num_inference_steps, + num_frames=num_frames, + frame_rate=frame_rate, + extra_args={ + "sample_solver": args.sample_solver, + "flow_shift": flow_shift, + }, + ) + + # Route model-specific knobs through extra_body, filtered against the model's + # declared extra_body_params. Models without a declaration only forward explicit + # --extra-body JSON (e.g. Cosmos3 V2V's condition_frame_indexes_vision). + extra_body = dict(args.extra_body or {}) + if declared_extra_body_params: + apply_declared_extra_args(sampling_params, declared_extra_body_params, extra_body) + elif extra_body: + sampling_params.extra_args.update({k: v for k, v in extra_body.items() if v is not None}) + generation_start = time.perf_counter() # omni.generate() returns Generator[OmniRequestOutput, None, None] frames = omni.generate( @@ -389,21 +467,7 @@ def main(): "negative_prompt": args.negative_prompt, "multi_modal_data": {"image": image}, }, - OmniDiffusionSamplingParams( - height=height, - width=width, - generator=generator, - guidance_scale=guidance_scale, - guidance_scale_2=args.guidance_scale_high, - boundary_ratio=args.boundary_ratio, - num_inference_steps=num_inference_steps, - num_frames=num_frames, - frame_rate=frame_rate, - extra_args={ - "sample_solver": args.sample_solver, - "flow_shift": args.flow_shift, - }, - ), + sampling_params, ) generation_end = time.perf_counter() generation_time = generation_end - generation_start diff --git a/examples/offline_inference/text_to_image/text_to_image.py b/examples/offline_inference/text_to_image/text_to_image.py index 06e5dc181..ed51e85b6 100644 --- a/examples/offline_inference/text_to_image/text_to_image.py +++ b/examples/offline_inference/text_to_image/text_to_image.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import argparse +import functools import json import time from pathlib import Path @@ -38,16 +39,20 @@ def is_nextstep_model(model_name: str) -> bool: return False -def parse_profiler_config(value: str) -> dict[str, Any]: +def parse_json_object(value: str, flag_name: str = "argument") -> dict[str, Any]: + """Parse a CLI value as a JSON object, attributing errors to ``flag_name``.""" try: config = json.loads(value) except json.JSONDecodeError as e: - raise argparse.ArgumentTypeError(f"--profiler-config must be valid JSON: {e}") from e + raise argparse.ArgumentTypeError(f"{flag_name} must be valid JSON: {e}") from e if not isinstance(config, dict): - raise argparse.ArgumentTypeError("--profiler-config must be a JSON object") + raise argparse.ArgumentTypeError(f"{flag_name} must be a JSON object") return config +parse_profiler_config = functools.partial(parse_json_object, flag_name="--profiler-config") + + def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Generate an image with supported diffusion models.") parser.add_argument( @@ -269,7 +274,7 @@ def parse_args() -> argparse.Namespace: ) parser.add_argument( "--extra-body", - type=parse_profiler_config, + type=functools.partial(parse_json_object, flag_name="--extra-body"), default=None, help=( "Model-specific generation params as a JSON object, e.g. " @@ -425,6 +430,10 @@ def main(): if use_nextstep: # NextStep-1.1 requires explicit pipeline class omni_kwargs["model_class_name"] = "NextStep11Pipeline" + # Cosmos3 loads its (gated) guardrail models at build time, so the guardrails + # gate is an engine-level config (offline analog of the server's --no-guardrails). + if args.extra_body and "guardrails" in args.extra_body: + omni_kwargs["model_config"] = {"guardrails": bool(args.extra_body["guardrails"])} omni = Omni(**omni_kwargs) model_class_name = get_model_class_name(omni) declared_extra_body_params = get_extra_body_params(model_class_name) 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 3e8393ec2..903a514d0 100644 --- a/examples/offline_inference/text_to_video/text_to_video.md +++ b/examples/offline_inference/text_to_video/text_to_video.md @@ -9,6 +9,7 @@ A unified script for text-to-video generation. Supports multiple models with mod | `Wan-AI/Wan2.2-T2V-A14B-Diffusers` | 720x1280 | 81 | 40 | 4.0 | ~60 GiB | | `hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v` | 480x832 | 121 | 50 | 6.0 | 1×A100 80GB | | `hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-720p_t2v` | 720x1280 | 121 | 50 | 6.0 | FP8 + VAE tiling required | +| `nvidia/Cosmos3-Nano` | 720x1280 | 189 | 35 | 6.0 | ~46 GiB (peak, 720p) | | `BestWishYsh/Helios-Base` / `Helios-Mid` / `Helios-Distilled` | 384x640 | 99 | 50 | 5.0 / 5.0 / 1.0 | — | ## Local CLI Usage @@ -101,6 +102,20 @@ python text_to_video.py \ --output quick_test.mp4 ``` +### Cosmos3 + +```bash +python text_to_video.py \ + --model nvidia/Cosmos3-Nano \ + --prompt "A robot arm is cleaning a plate in the kitchen." \ + --negative-prompt "blurry, distorted, low quality, jittery, deformed" \ + --height 720 --width 1280 --num-frames 189 --fps 24 \ + --num-inference-steps 35 --guidance-scale 6.0 \ + --extra-body '{"flow_shift": 10.0, "max_sequence_length": 4096, "guardrails": false, + "use_resolution_template": false, "use_duration_template": false}' \ + --output cosmos3_t2v.mp4 +``` + ### Helios (T2V) Helios ships three variants. Model-specific knobs (declared in @@ -167,6 +182,7 @@ python text_to_video.py \ - `--audio-sample-rate`: audio sample rate for embedded audio (when the pipeline returns audio). - `--quantization`: quantization method (`fp8` for FP8, `gguf` for GGUF). - `--flow-shift`: scheduler flow_shift parameter. +- `--extra-body`: JSON object of model-specific generation params, filtered against the model's declared `extra_body_params` (see [`vllm_omni/model_extras`](../../../vllm_omni/model_extras)). Used by Cosmos3 (see above). ### Wan2.2-specific 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 9e9a8ac1d..e3a227bcd 100644 --- a/examples/offline_inference/text_to_video/text_to_video.py +++ b/examples/offline_inference/text_to_video/text_to_video.py @@ -11,8 +11,10 @@ import numpy as np import torch from vllm_omni.diffusion.data import DiffusionParallelConfig +from vllm_omni.diffusion.utils.param_utils import apply_declared_extra_args from vllm_omni.entrypoints.omni import Omni from vllm_omni.inputs.data import OmniDiffusionSamplingParams +from vllm_omni.model_extras import get_extra_body_params, get_model_class_name from vllm_omni.outputs import OmniRequestOutput from vllm_omni.platforms import current_omni_platform @@ -35,6 +37,16 @@ _MODEL_PRESETS = { "fps": 24, "output": "hunyuan_video_15_output.mp4", }, + "cosmos": { + "height": 720, + "width": 1280, + "num_frames": 189, + "num_inference_steps": 35, + "guidance_scale": 6.0, + "fps": 24, + "flow_shift": 10.0, + "output": "cosmos3_t2v_output.mp4", + }, "helios": { "height": 384, "width": 640, @@ -49,6 +61,8 @@ _MODEL_PRESETS = { def _detect_preset(model: str) -> dict: model_lower = model.lower() + if "cosmos" in model_lower: + return _MODEL_PRESETS["cosmos"] if "hunyuan" in model_lower: return _MODEL_PRESETS["hunyuan"] if "helios" in model_lower: @@ -106,8 +120,12 @@ def parse_args() -> argparse.Namespace: type=parse_extra_body, default=None, help="JSON dict of model-specific extra_body params (declared in vllm_omni/model_extras/), " - "merged into sampling extra_args. Example (Helios-Distilled): " - '\'{"is_enable_stage2": true, "pyramid_num_inference_steps_list": [2, 2, 2], "is_amplify_first_chunk": true}\'.', + "merged into sampling extra_args. Unknown keys for the chosen model are dropped. " + 'Cosmos3 example: \'{"flow_shift": 10.0, "max_sequence_length": 4096, "guardrails": false, ' + '"use_resolution_template": false, "use_duration_template": false}\' ' + '(add "generate_sound": true and optional "sound_duration" for synchronized audio). ' + 'Helios-Distilled example: \'{"is_enable_stage2": true, ' + '"pyramid_num_inference_steps_list": [2, 2, 2], "is_amplify_first_chunk": true}\'.', ) parser.add_argument("--seed", type=int, default=42, help="Random seed.") parser.add_argument("--guidance-scale", type=float, default=None, help="CFG scale. Default: model-specific.") @@ -357,7 +375,14 @@ def main(): omni_kwargs["cache_config"] = cache_config omni_kwargs["enable_cache_dit_summary"] = args.enable_cache_dit_summary + # Cosmos3 loads its (gated) guardrail models at build time, so the guardrails + # gate is an engine-level config (offline analog of the server's --no-guardrails). + if args.extra_body and "guardrails" in args.extra_body: + omni_kwargs["model_config"] = {"guardrails": bool(args.extra_body["guardrails"])} + omni = Omni(**omni_kwargs) + model_class_name = get_model_class_name(omni) + declared_extra_body_params = get_extra_body_params(model_class_name) if profiler_enabled: print("[Profiler] Starting profiling...") @@ -392,14 +417,22 @@ def main(): ) if args.guidance_scale_high is not None: sampling_kwargs["guidance_scale_2"] = args.guidance_scale_high - if args.extra_body: - # Model-specific knobs (declared in vllm_omni/model_extras/) routed via extra_args. - sampling_kwargs["extra_args"] = dict(args.extra_body) + + sampling_params = OmniDiffusionSamplingParams(**sampling_kwargs) + + # Route model-specific knobs through extra_body, filtered against the model's + # declared extra_body_params. Models without a declaration only forward explicit + # --extra-body JSON (preserving the generic flags' legacy behavior). + extra_body = dict(args.extra_body or {}) + if declared_extra_body_params: + apply_declared_extra_args(sampling_params, declared_extra_body_params, extra_body) + elif extra_body: + sampling_params.extra_args.update({k: v for k, v in extra_body.items() if v is not None}) generation_start = time.perf_counter() frames = omni.generate( prompt_dict, - OmniDiffusionSamplingParams(**sampling_kwargs), + sampling_params, ) generation_end = time.perf_counter() generation_time = generation_end - generation_start diff --git a/recipes/cosmos3/Cosmos3-Nano.md b/recipes/cosmos3/Cosmos3-Nano.md index e617f6127..e58a28623 100644 --- a/recipes/cosmos3/Cosmos3-Nano.md +++ b/recipes/cosmos3/Cosmos3-Nano.md @@ -367,60 +367,58 @@ vllm serve nvidia/Cosmos3-Nano-Policy-DROID \ #### Command -```python -# cosmos3_offline.py — run with: python cosmos3_offline.py -import torch -from vllm_omni.entrypoints.omni import Omni -from vllm_omni.inputs.data import OmniDiffusionSamplingParams +Cosmos3 runs through the standard task examples; pass model-specific knobs via +`--extra-body`. Guardrails are on by default — pass `"guardrails": false` for a +quick local run (install `cosmos-guardrail` + accept the gated repo to enable them). +```bash +# Text-to-image -> examples/offline_inference/text_to_image +python examples/offline_inference/text_to_image/text_to_image.py \ + --model nvidia/Cosmos3-Nano \ + --prompt "A photorealistic red sports car at golden hour, cinematic lighting." \ + --negative-prompt "blurry, distorted, low quality" \ + --height 1024 --width 1024 --num-inference-steps 50 --guidance-scale 7.0 \ + --extra-body '{"flow_shift": 3.0, "guardrails": false}' \ + --output cosmos3_t2i.png -def main(): - omni = Omni( - model="nvidia/Cosmos3-Nano", - model_class_name="Cosmos3OmniDiffusersPipeline", - trust_remote_code=True, - enforce_eager=True, - # Guardrails are disabled here for a quick local run; install - # cosmos-guardrail + gated-repo access and drop this to enable them. - model_config={"guardrails": False}, - ) - gen = torch.Generator(device="cpu").manual_seed(42) +# Text-to-video -> examples/offline_inference/text_to_video +python examples/offline_inference/text_to_video/text_to_video.py \ + --model nvidia/Cosmos3-Nano \ + --prompt "A robot arm is cleaning a plate in the kitchen." \ + --negative-prompt "blurry, distorted, low quality, jittery, deformed" \ + --height 720 --width 1280 --num-frames 189 --fps 24 \ + --num-inference-steps 35 --guidance-scale 6.0 \ + --extra-body '{"flow_shift": 10.0, "max_sequence_length": 4096, "guardrails": false, + "use_resolution_template": false, "use_duration_template": false}' \ + --output cosmos3_t2v.mp4 - # Text-to-image (modalities=["image"]). For T2V use modalities=["video"] - # plus num_frames/fps; for I2V add multi_modal_data={"image": }. - outputs = omni.generate( - { - "prompt": "A photorealistic red sports car at golden hour, cinematic lighting.", - "negative_prompt": "blurry, distorted, low quality", - "modalities": ["image"], - }, - OmniDiffusionSamplingParams( - height=1024, width=1024, generator=gen, - guidance_scale=7.0, num_inference_steps=50, num_outputs_per_prompt=1, - ), - ) - outputs[0].request_output.images[0].save("cosmos3_t2i.png") - omni.close() - - -if __name__ == "__main__": - main() +# Image-to-video -> examples/offline_inference/image_to_video +# (Cosmos3 bundles example frames under assets/; any RGB image works too.) +python examples/offline_inference/image_to_video/image_to_video.py \ + --model nvidia/Cosmos3-Nano \ + --image /path/to/Cosmos3-Nano/assets/example_i2v_input.jpg \ + --prompt "The scene comes to life with smooth, natural motion." \ + --height 720 --width 1280 --num-frames 189 --fps 24 \ + --num-inference-steps 35 --guidance-scale 6.0 \ + --extra-body '{"flow_shift": 10.0, "max_sequence_length": 4096, "guardrails": false}' \ + --output cosmos3_i2v.mp4 ``` #### Verification ```bash -python cosmos3_offline.py python -c "from PIL import Image; im=Image.open('cosmos3_t2i.png'); print('image', im.size, im.mode)" +ffprobe -v error -show_entries stream=codec_type,nb_frames,width,height cosmos3_t2v.mp4 ``` #### Notes -- Same `Cosmos3OmniDiffusersPipeline` as online; mode is chosen by - `prompt["modalities"]` (`["image"]` → T2I, `["video"]` → T2V) plus - `num_frames`/`fps`, `multi_modal_data={"image": ...}` for I2V, and - `multi_modal_data={"video": []}` or a video tensor/array for V2V. - For video, frames are returned in `outputs[0].request_output.images` as an - `(B, F, H, W, 3)` array. -- The offline entry must be guarded by `if __name__ == "__main__":` — the engine - spawns workers with the `spawn` start method. +- A single `Cosmos3OmniDiffusersPipeline` serves every mode; the standard examples + select it automatically from `model_index.json`. T2I is chosen by the + `text_to_image` prompt builder (which marks `modalities=["image"]`); `text_to_video` + defaults to T2V; `image_to_video` adds `multi_modal_data={"image": ...}` (I2V). + V2V is served online (`/v1/videos/sync`). +- Model-specific knobs (`flow_shift`, `max_sequence_length`, `condition_*`, + `generate_sound`/`sound_duration`, `guardrails`, `action_*`, ...) are declared + once in `vllm_omni/model_extras/cosmos3.py` and forwarded through `--extra-body`; + unknown keys for the model are dropped. diff --git a/tests/model_extras/test_model_extras.py b/tests/model_extras/test_model_extras.py index 22ce82bc2..ca34add96 100644 --- a/tests/model_extras/test_model_extras.py +++ b/tests/model_extras/test_model_extras.py @@ -57,6 +57,57 @@ def test_sensenova_extra_registry_declares_request_and_response_params() -> None assert should_init_extra_args_for_non_diffusion_stages("SenseNovaU1Pipeline") is False +@pytest.mark.core_model +@pytest.mark.cpu +def test_cosmos3_extra_registry_declares_request_and_response_params() -> None: + assert get_extra_body_params("Cosmos3OmniDiffusersPipeline") == frozenset( + { + "flow_shift", + "max_sequence_length", + "use_resolution_template", + "use_duration_template", + "use_system_prompt", + "system_prompt", + "negative_prompt", + "guardrails", + "condition_frame_indexes_vision", + "condition_video_keep", + "generate_sound", + "sound_gen", + "sound_duration", + "audio_duration", + "action_mode", + "action", + "domain_name", + "domain_id", + "raw_action_dim", + "action_chunk_size", + "action_space", + "action_fps", + "image_height", + "image_width", + "history_length", + "conditioning_fps", + "resolution", + "image_size", + "use_state", + "observation", + "robot_obs", + "deterministic_seed", + "session_id", + } + ) + assert get_extra_output_params("Cosmos3OmniDiffusersPipeline") == frozenset( + { + "action", + "raw_action_dim", + "domain_id", + "action_mode", + } + ) + assert should_init_extra_args_for_non_diffusion_stages("Cosmos3OmniDiffusersPipeline") is False + + @pytest.mark.core_model @pytest.mark.cpu def test_magi_human_extra_registry_declares_request_and_response_params() -> None: @@ -74,6 +125,27 @@ def test_magi_human_extra_registry_declares_request_and_response_params() -> Non assert should_init_extra_args_for_non_diffusion_stages("MagiHumanPipeline") is False +@pytest.mark.core_model +@pytest.mark.cpu +def test_cosmos3_text_to_image_prompt_builder_selects_image_modality() -> None: + assert build_text_to_image_prompt( + "Cosmos3OmniDiffusersPipeline", + prompt="a red sports car at golden hour", + negative_prompt="blurry, distorted", + height=1024, + width=1024, + ) == { + "prompt": "a red sports car at golden hour", + "modalities": ["image"], + "negative_prompt": "blurry, distorted", + } + assert build_text_to_image_prompt( + "Cosmos3OmniDiffusersPipeline", + prompt="a red sports car", + negative_prompt=None, + ) == {"prompt": "a red sports car", "modalities": ["image"]} + + @pytest.mark.core_model @pytest.mark.cpu def test_helios_extra_registry_declares_request_and_response_params() -> None: diff --git a/vllm_omni/model_extras/cosmos3.py b/vllm_omni/model_extras/cosmos3.py new file mode 100644 index 000000000..6303f0f11 --- /dev/null +++ b/vllm_omni/model_extras/cosmos3.py @@ -0,0 +1,68 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +from typing import Any + + +def build_text_to_image_prompt( + prompt: str, + negative_prompt: str | None, + height: int | None = None, + width: int | None = None, +) -> dict[str, Any]: + text_prompt: dict[str, Any] = { + "prompt": prompt, + "modalities": ["image"], + } + if negative_prompt is not None: + text_prompt["negative_prompt"] = negative_prompt + return text_prompt + + +COSMOS3_EXTRA_BODY_PARAMS = frozenset( + { + "flow_shift", + "max_sequence_length", + "use_resolution_template", + "use_duration_template", + "use_system_prompt", + "system_prompt", + "negative_prompt", + "guardrails", + "condition_frame_indexes_vision", + "condition_video_keep", + "generate_sound", + "sound_gen", + "sound_duration", + "audio_duration", + "action_mode", + "action", + "domain_name", + "domain_id", + "raw_action_dim", + "action_chunk_size", + "action_space", + "action_fps", + "image_height", + "image_width", + "history_length", + "conditioning_fps", + "resolution", + "image_size", + "use_state", + "observation", + "robot_obs", + "deterministic_seed", + "session_id", + } +) +COSMOS3_EXTRA_OUTPUT_PARAMS = frozenset( + { + "action", + "raw_action_dim", + "domain_id", + "action_mode", + } +) diff --git a/vllm_omni/model_extras/registry.py b/vllm_omni/model_extras/registry.py index 5c5f17b45..0b06ce10d 100644 --- a/vllm_omni/model_extras/registry.py +++ b/vllm_omni/model_extras/registry.py @@ -19,6 +19,13 @@ from vllm_omni.model_extras.bagel import ( from vllm_omni.model_extras.bagel import ( build_text_to_image_prompt as build_bagel_text_to_image_prompt, ) +from vllm_omni.model_extras.cosmos3 import ( + COSMOS3_EXTRA_BODY_PARAMS, + COSMOS3_EXTRA_OUTPUT_PARAMS, +) +from vllm_omni.model_extras.cosmos3 import ( + build_text_to_image_prompt as build_cosmos3_text_to_image_prompt, +) from vllm_omni.model_extras.helios import ( HELIOS_EXTRA_BODY_PARAMS, HELIOS_EXTRA_OUTPUT_PARAMS, @@ -84,6 +91,11 @@ _EXTRA_SPECS: dict[str, dict[str, Any]] = { "extra_body_params": SENSENOVA_U1_EXTRA_BODY_PARAMS, "extra_output_params": SENSENOVA_U1_EXTRA_OUTPUT_PARAMS, }, + "Cosmos3OmniDiffusersPipeline": { + "extra_body_params": COSMOS3_EXTRA_BODY_PARAMS, + "extra_output_params": COSMOS3_EXTRA_OUTPUT_PARAMS, + "text_to_image_prompt_builder": build_cosmos3_text_to_image_prompt, + }, "MagiHumanPipeline": { "extra_body_params": MAGI_HUMAN_EXTRA_BODY_PARAMS, "extra_output_params": MAGI_HUMAN_EXTRA_OUTPUT_PARAMS,