[diffusion][feature] Add LingBot-Video T2I and TI2V generation modes (#5311)

Signed-off-by: wtz2333 <2955110911@qq.com>
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
wtz2333andClaude authored and GitHub committed 2026-08-10 10:02:31 +08:00
1 parent 11f633aa83
commit 36135ef09a
28 files changed
+2410 -98

No files matched your search

@@ -1,16 +1,46 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm_omni.diffusion.models.lingbot_video.image_condition import (
LingBotImageCondition,
apply_clean_prefix,
geometry_align_image,
prepare_ti2v_image_condition,
)
from vllm_omni.diffusion.models.lingbot_video.lingbot_video_transformer import (
LingBotVideoTransformer3DModel,
)
from vllm_omni.diffusion.models.lingbot_video.pipeline_lingbot_video import (
LingBotVideoPipeline,
get_lingbot_video_post_process_func,
get_lingbot_video_pre_process_func,
)
from vllm_omni.diffusion.models.lingbot_video.request_utils import (
LingBotGenerationMode,
LingBotRequestConfig,
caption_from_lingbot_prompt,
normalize_lingbot_num_frames,
normalize_lingbot_request,
resolve_lingbot_num_frames,
resolve_lingbot_output_dimensions,
resolve_lingbot_size,
)
__all__ = [
"LingBotGenerationMode",
"LingBotImageCondition",
"LingBotRequestConfig",
"LingBotVideoPipeline",
"LingBotVideoTransformer3DModel",
"apply_clean_prefix",
"caption_from_lingbot_prompt",
"geometry_align_image",
"get_lingbot_video_pre_process_func",
"get_lingbot_video_post_process_func",
"normalize_lingbot_num_frames",
"normalize_lingbot_request",
"prepare_ti2v_image_condition",
"resolve_lingbot_num_frames",
"resolve_lingbot_output_dimensions",
"resolve_lingbot_size",
]
@@ -0,0 +1,209 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import math
from dataclasses import dataclass
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
IMAGE_MIN_TOKEN_NUM = 4
IMAGE_MAX_TOKEN_NUM = 16384
MAX_IMAGE_RATIO = 200
SPATIAL_MERGE_SIZE = 2
@dataclass(frozen=True)
class LingBotImageCondition:
vlm_image: Image.Image
clean_latent: torch.Tensor
def _round_by_factor(number: float, factor: int) -> int:
return round(number / factor) * factor
def _ceil_by_factor(number: float, factor: int) -> int:
return math.ceil(number / factor) * factor
def _floor_by_factor(number: float, factor: int) -> int:
return math.floor(number / factor) * factor
def smart_resize(
height: int,
width: int,
factor: int,
min_pixels: int | None = None,
max_pixels: int | None = None,
) -> tuple[int, int]:
max_pixels = max_pixels if max_pixels is not None else IMAGE_MAX_TOKEN_NUM * factor**2
min_pixels = min_pixels if min_pixels is not None else IMAGE_MIN_TOKEN_NUM * factor**2
if max_pixels < min_pixels:
raise ValueError("max_pixels must be greater than or equal to min_pixels.")
if min(height, width) <= 0:
raise ValueError(f"LingBot image height and width must be positive, got {height}x{width}.")
if max(height, width) / min(height, width) > MAX_IMAGE_RATIO:
raise ValueError(f"LingBot image absolute aspect ratio must be smaller than {MAX_IMAGE_RATIO}.")
resized_height = max(factor, _round_by_factor(height, factor))
resized_width = max(factor, _round_by_factor(width, factor))
if resized_height * resized_width > max_pixels:
beta = math.sqrt((height * width) / max_pixels)
resized_height = _floor_by_factor(height / beta, factor)
resized_width = _floor_by_factor(width / beta, factor)
elif resized_height * resized_width < min_pixels:
beta = math.sqrt(min_pixels / (height * width))
resized_height = _ceil_by_factor(height * beta, factor)
resized_width = _ceil_by_factor(width * beta, factor)
return resized_height, resized_width
def geometry_align_image(
image: Image.Image,
height: int,
width: int,
) -> torch.Tensor:
if not isinstance(image, Image.Image):
raise TypeError(f"LingBot input image must be a PIL image, got {type(image)!r}.")
if height <= 0 or width <= 0:
raise ValueError(f"LingBot target height and width must be positive, got {height}x{width}.")
raw = torch.from_numpy(np.array(image.convert("RGB"))).permute(2, 0, 1).unsqueeze(0).contiguous()
old_height, old_width = raw.shape[-2:]
scale = max(height / old_height, width / old_width)
new_height = max(math.ceil(old_height * scale), height)
new_width = max(math.ceil(old_width * scale), width)
resized = F.interpolate(
raw,
size=(new_height, new_width),
mode="bilinear",
align_corners=False,
)
top = int(round((new_height - height) / 2.0))
left = int(round((new_width - width) / 2.0))
cropped = resized[:, :, top : top + height, left : left + width]
return (cropped.float() / 255.0).unsqueeze(2)
def pixel_tensor_to_pil(pixel: torch.Tensor) -> Image.Image:
if pixel.ndim != 5 or pixel.shape[0] != 1 or pixel.shape[1] != 3:
raise ValueError(f"LingBot aligned image tensor must have shape [1,3,T,H,W], got {tuple(pixel.shape)}.")
frame = pixel[0, :, 0].detach().cpu().clamp(0, 1)
array = frame.permute(1, 2, 0).mul(255).byte().numpy()
return Image.fromarray(array, mode="RGB")
def vlm_image_from_aligned(
pixel: torch.Tensor,
*,
vision_patch_size: int,
) -> Image.Image:
image = pixel_tensor_to_pil(pixel)
patch_factor = int(vision_patch_size) * SPATIAL_MERGE_SIZE
if patch_factor <= 0:
raise ValueError(f"LingBot vision patch factor must be positive, got {patch_factor}.")
resized_height, resized_width = smart_resize(
image.height,
image.width,
factor=patch_factor,
)
return image.resize((resized_width, resized_height))
def _module_device(module: torch.nn.Module) -> torch.device:
try:
return next(module.parameters()).device
except StopIteration:
return torch.device("cpu")
@torch.no_grad()
def encode_clean_image_latent(
pixel: torch.Tensor,
*,
vae: torch.nn.Module,
generator: torch.Generator | None = None,
) -> torch.Tensor:
vae_device = _module_device(vae)
normalized = (pixel.to(device=vae_device, dtype=torch.float32) - 0.5) / 0.5
with torch.autocast(
"cuda",
dtype=torch.bfloat16,
enabled=vae_device.type == "cuda",
):
encoded = vae.encode(normalized)
# Match the official LingBot TI2V path exactly: sample the posterior
# with the request generator before initial noise latents are created.
# Using mode() would change both the clean prefix and the RNG stream.
clean_latent = encoded.latent_dist.sample(generator)
mean = torch.tensor(
vae.config.latents_mean,
device=clean_latent.device,
dtype=torch.float32,
).view(1, -1, 1, 1, 1)
std_inv = (
1.0
/ torch.tensor(
vae.config.latents_std,
device=clean_latent.device,
dtype=torch.float32,
)
).view(1, -1, 1, 1, 1)
return (clean_latent.float() - mean) * std_inv
def prepare_ti2v_image_condition(
image: Image.Image,
*,
height: int,
width: int,
vae: torch.nn.Module,
vision_patch_size: int,
device: torch.device,
generator: torch.Generator | None = None,
) -> LingBotImageCondition:
pixel = geometry_align_image(image, height, width)
vlm_image = vlm_image_from_aligned(
pixel,
vision_patch_size=vision_patch_size,
)
clean_latent = encode_clean_image_latent(
pixel,
vae=vae,
generator=generator,
).to(device=device, dtype=torch.float32)
return LingBotImageCondition(
vlm_image=vlm_image,
clean_latent=clean_latent,
)
def apply_clean_prefix(
latents: torch.Tensor,
clean_latent: torch.Tensor,
) -> torch.Tensor:
if latents.ndim != 5 or clean_latent.ndim != 5:
raise ValueError(
"LingBot latent and clean prefix must be 5D [B,C,T,H,W] tensors, "
f"got {tuple(latents.shape)} and {tuple(clean_latent.shape)}."
)
if latents.shape[:2] != clean_latent.shape[:2] or latents.shape[3:] != clean_latent.shape[3:]:
raise ValueError(
"LingBot clean prefix batch/channel/spatial shape must match latents, "
f"got {tuple(clean_latent.shape)} for {tuple(latents.shape)}."
)
prefix_length = int(clean_latent.shape[2])
if prefix_length > latents.shape[2]:
raise ValueError(f"LingBot clean prefix length {prefix_length} exceeds latent length {latents.shape[2]}.")
latents[:, :, :prefix_length] = clean_latent.to(
device=latents.device,
dtype=latents.dtype,
)
return latents
@@ -14,17 +14,31 @@ import torch
import torch.distributed as dist
from diffusers import AutoencoderKLWan
from diffusers.utils.torch_utils import randn_tensor
from PIL import Image
from torch import nn
from transformers import Qwen3VLForConditionalGeneration, Qwen3VLProcessor
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.models.interface import SupportsComponentDiscovery
from vllm_omni.diffusion.models.interface import (
SupportImageInput,
SupportsComponentDiscovery,
)
from vllm_omni.diffusion.models.lingbot_video.image_condition import (
LingBotImageCondition,
apply_clean_prefix,
prepare_ti2v_image_condition,
)
from vllm_omni.diffusion.models.lingbot_video.lingbot_video_transformer import LingBotVideoTransformer3DModel
from vllm_omni.diffusion.models.lingbot_video.request_utils import (
LingBotGenerationMode,
normalize_lingbot_request,
)
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
from vllm_omni.diffusion.models.schedulers import FlowUniPCMultistepScheduler
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
from vllm_omni.errors import OmniClientError
TOKEN_LENGTH = 37698
HIDDEN_STATE_SKIP_LAYER = 0
@@ -43,6 +57,7 @@ PROMPT_TEMPLATE = (
"commentary or evaluations:<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n"
"<|im_start|>assistant\n"
)
IMG_PROMPT_TEMPLATE = "<|vision_start|><|image_pad|><|vision_end|>"
DEFAULT_NEGATIVE_PROMPT = (
'{"universal_negative": {"visual_quality": ["low quality", "worst quality", "blurry", '
'"pixelated", "jpeg artifacts", "low resolution", "unstable color", "color flicker", '
@@ -57,6 +72,17 @@ DEFAULT_NEGATIVE_PROMPT = (
'"unrealistic texture", "deformed bottle", "liquid freezing improperly", '
'"distorted reflections"]}}'
)
DEFAULT_NEGATIVE_PROMPT_IMAGE = (
'{"universal_negative": {"visual_quality": ["low quality", "worst quality", '
'"blurry", "pixelated", "jpeg artifacts", "low resolution", "underexposed", '
'"overexposed", "invisible subject", "subject hidden in darkness"], '
'"artistic_style": ["painting", "illustration", "drawing", "cartoon", '
'"3d render", "cgi", "sketch", "digital art"], "composition_and_content": '
'["text", "watermark", "signature", "logo", "pillarboxed", "side bars", '
'"portrait image in landscape frame"], "material_and_structure": '
'["plastic-like glass", "unrealistic texture", "deformed bottle", '
'"distorted reflections"]}}'
)
def _dtype_from_name(value: Any, default: torch.dtype) -> torch.dtype:
@@ -74,17 +100,6 @@ def _dtype_from_name(value: Any, default: torch.dtype) -> torch.dtype:
raise ValueError(f"Unsupported LingBot dtype: {value!r}.")
def _extract_prompt(req: OmniDiffusionRequest) -> tuple[str, str | None]:
prompt_obj = req.prompt
if isinstance(prompt_obj, str):
return prompt_obj, None
if isinstance(prompt_obj, Mapping):
prompt = prompt_obj.get("prompt", "")
negative_prompt = prompt_obj.get("negative_prompt")
return str(prompt), None if negative_prompt is None else str(negative_prompt)
raise TypeError(f"Unsupported LingBot prompt type: {type(prompt_obj)!r}.")
def _module_dtype(module: torch.nn.Module) -> torch.dtype:
try:
return next(module.parameters()).dtype
@@ -213,19 +228,85 @@ def _batch_cfg_prompt_inputs(
)
def _load_lingbot_image(value: Any) -> Image.Image:
if isinstance(value, Image.Image):
return value.convert("RGB")
if isinstance(value, str):
try:
with Image.open(value) as image:
return image.convert("RGB")
except OSError as exc:
raise OmniClientError(f"Unable to load LingBot input image from {value!r}: {exc}.") from exc
raise OmniClientError(f"Unsupported LingBot image format {type(value)!r}; expected a PIL image or local path.")
def get_lingbot_video_pre_process_func(od_config: OmniDiffusionConfig):
del od_config
def pre_process_func(request: OmniDiffusionRequest) -> OmniDiffusionRequest:
prompt = request.prompt
if isinstance(prompt, str):
return request
if not isinstance(prompt, Mapping):
raise OmniClientError(f"LingBot prompt must be a string or mapping, got {type(prompt)!r}.")
multi_modal_data = prompt.get("multi_modal_data")
if multi_modal_data is None:
return request
if not isinstance(multi_modal_data, Mapping):
raise OmniClientError("LingBot `multi_modal_data` must be a mapping.")
raw_images = multi_modal_data.get("image")
if raw_images is None:
return request
multiple = isinstance(raw_images, (list, tuple))
image_values = list(raw_images) if multiple else [raw_images]
images = [_load_lingbot_image(image) for image in image_values]
normalized_prompt = dict(prompt)
normalized_multi_modal_data = dict(multi_modal_data)
normalized_multi_modal_data["image"] = images if multiple else images[0]
normalized_prompt["multi_modal_data"] = normalized_multi_modal_data
if request.is_dummy_run() and "modalities" not in normalized_prompt:
normalized_prompt["modalities"] = ["video"]
request.prompt = normalized_prompt
return request
return pre_process_func
def get_lingbot_video_post_process_func(od_config: OmniDiffusionConfig):
del od_config
def post_process_func(frames: torch.Tensor, sampling_params=None):
def post_process_func(frames: torch.Tensor | dict[str, torch.Tensor], sampling_params=None):
output_key = None
if isinstance(frames, dict):
output_keys = [key for key in ("image", "video") if key in frames]
if len(output_keys) != 1:
raise ValueError(
f"LingBot output must contain exactly one of 'image' or 'video', got {sorted(frames)!r}."
)
output_key = output_keys[0]
frames = frames[output_key]
output_type = getattr(sampling_params, "output_type", None) or "pt"
if output_type == "np" and isinstance(frames, torch.Tensor):
return frames.float().cpu().numpy()
return frames
# The image serving path currently accepts PIL images or NumPy arrays,
# while LingBot decodes T2I outputs to tensors. Keep that compatibility
# conversion without discarding the model's image/video payload key.
if (
isinstance(frames, torch.Tensor)
and output_type != "latent"
and (output_type == "np" or output_key == "image")
):
frames = frames.float().cpu().numpy()
return {output_key: frames} if output_key is not None else frames
return post_process_func
class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscovery):
class LingBotVideoPipeline(
nn.Module,
SupportImageInput,
ProgressBarMixin,
SupportsComponentDiscovery,
):
"""Native vLLM-Omni entry for LingBot-Video checkpoints.
The in-tree transformer supports both dense MLP blocks and routed MoE blocks.
@@ -235,6 +316,7 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
"""
supports_step_execution: ClassVar[bool] = False
max_outputs_per_prompt: ClassVar[int] = 1
_dit_modules: ClassVar[list[str]] = ["transformer"]
_encoder_modules: ClassVar[list[str]] = ["text_encoder"]
_vae_modules: ClassVar[list[str]] = ["vae"]
@@ -249,6 +331,7 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
self.token_length = TOKEN_LENGTH
self.hidden_state_skip_layer = HIDDEN_STATE_SKIP_LAYER
self.prompt_template = PROMPT_TEMPLATE
self.img_prompt_template = IMG_PROMPT_TEMPLATE
self._crop_start: int | None = None
model = od_config.model
@@ -298,6 +381,7 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
)
self.set_progress_bar_config(disable=bool(model_config.get("quiet_progress", True)))
self.default_negative_prompt = DEFAULT_NEGATIVE_PROMPT
self.default_image_negative_prompt = DEFAULT_NEGATIVE_PROMPT_IMAGE
def to(self, *args, **kwargs):
device, dtype, non_blocking, _ = torch._C._nn._parse_to(*args, **kwargs)
@@ -348,12 +432,18 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
self._crop_start = int(prefix["input_ids"].shape[1])
return self._crop_start
def _build_prompt_inputs(self, prompt: str | list[str]):
def _build_prompt_inputs(
self,
prompt: str | list[str],
*,
images: Any | None = None,
):
prompts = [prompt] if isinstance(prompt, str) else list(prompt)
texts = [self.apply_text_to_template(text, self.prompt_template) for text in prompts]
visual_template = self.img_prompt_template if images is not None else ""
texts = [self.apply_text_to_template(visual_template + text, self.prompt_template) for text in prompts]
return self.processor(
text=texts,
images=None,
images=images,
videos=None,
do_resize=False,
truncation=True,
@@ -367,10 +457,11 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
self,
prompt: str | list[str],
*,
images: Any | None = None,
device: str | torch.device | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
device = torch.device(device) if device is not None else self.device
inputs = self._build_prompt_inputs(prompt).to(device)
inputs = self._build_prompt_inputs(prompt, images=images).to(device)
outputs = self.text_encoder(
**inputs,
output_hidden_states=self.hidden_state_skip_layer is not None,
@@ -392,6 +483,35 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
prompt_mask = prompt_mask[:, :true_len]
return prompt_embeds, prompt_mask
def _vision_patch_size(self) -> int:
for obj in (
getattr(getattr(self.text_encoder, "config", None), "vision_config", None),
getattr(getattr(self.processor, "image_processor", None), "config", None),
getattr(self.processor, "image_processor", None),
):
patch_size = getattr(obj, "patch_size", None)
if patch_size is not None:
return int(patch_size)
return 16
def prepare_ti2v_image_condition(
self,
image: Image.Image,
*,
height: int,
width: int,
generator: torch.Generator | None = None,
) -> LingBotImageCondition:
return prepare_ti2v_image_condition(
image,
height=height,
width=width,
vae=self.vae,
vision_patch_size=self._vision_patch_size(),
device=self.device,
generator=generator,
)
def prepare_latents(
self,
num_frames: int,
@@ -441,6 +561,8 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
self,
*,
prompt: str,
mode: LingBotGenerationMode,
input_image: Image.Image | None = None,
negative_prompt: str = DEFAULT_NEGATIVE_PROMPT,
height: int = 480,
width: int = 480,
@@ -467,6 +589,22 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
self.check_inputs(height, width, num_frames)
device = self.device
do_cfg = guidance_scale > 1.0
image_condition = None
prompt_images = None
# Public image/mode combinations are validated by resolve_lingbot_mode.
# Keep these checks as defensive invariants for direct internal calls.
if mode is LingBotGenerationMode.TI2V:
if input_image is None:
raise ValueError("LingBot TI2V generation requires one input image.")
image_condition = self.prepare_ti2v_image_condition(
input_image,
height=height,
width=width,
generator=generator,
)
prompt_images = [image_condition.vlm_image]
elif input_image is not None:
raise ValueError(f"LingBot {mode.value} generation does not accept an input image.")
effective_batch_cfg = bool(batch_cfg)
cfg_parallel = cfg_parallel_group is not None
cfg_parallel_rank = 0
@@ -499,11 +637,19 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
if negative_prompt_embeds is not None:
negative_embeds, negative_mask = negative_prompt_embeds, negative_prompt_mask
else:
negative_embeds, negative_mask = self.encode_prompt(negative_prompt, device=device)
negative_embeds, negative_mask = self.encode_prompt(
negative_prompt,
images=prompt_images,
device=device,
)
prompt_embeds = prompt_mask = None
else:
if prompt_embeds is None:
prompt_embeds, prompt_mask = self.encode_prompt(prompt, device=device)
prompt_embeds, prompt_mask = self.encode_prompt(
prompt,
images=prompt_images,
device=device,
)
if do_cfg and not cfg_parallel:
if null_cond_clone_zero:
negative_embeds = torch.zeros_like(prompt_embeds)
@@ -511,9 +657,15 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
elif negative_prompt_embeds is not None:
negative_embeds, negative_mask = negative_prompt_embeds, negative_prompt_mask
else:
negative_embeds, negative_mask = self.encode_prompt(negative_prompt, device=device)
negative_embeds, negative_mask = self.encode_prompt(
negative_prompt,
images=prompt_images,
device=device,
)
latents = self.prepare_latents(num_frames, height, width, generator, latents, device)
if image_condition is not None:
latents = apply_clean_prefix(latents, image_condition.clean_latent)
sigmas = _compute_refiner_sigmas(
sigma_max=float(self.scheduler.sigma_max),
sigma_min=float(self.scheduler.sigma_min),
@@ -620,7 +772,15 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
)[0].float()
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)
latents = self.scheduler.step(noise_pred, timestep, latents, return_dict=False, generator=generator)[0]
latents = self.scheduler.step(
noise_pred,
timestep,
latents,
return_dict=False,
generator=generator,
)[0]
if image_condition is not None:
latents = apply_clean_prefix(latents, image_condition.clean_latent)
if cfg_parallel:
dist.barrier(group=cfg_parallel_group)
@@ -633,7 +793,14 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
if vae_offloaded and vae_restore_device is not None:
self.vae.to(device=vae_restore_device)
torch.accelerator.empty_cache()
return self._decode_latents(latents)
decoded = self._decode_latents(latents)
if mode is LingBotGenerationMode.T2I:
if decoded.shape[0] != 1:
raise RuntimeError(
f"LingBot T2I decode expected exactly one frame, got shape {tuple(decoded.shape)}."
)
return decoded[0]
return decoded
raise ValueError(f"Unsupported output_type: {output_type}")
@torch.inference_mode()
@@ -641,55 +808,67 @@ class LingBotVideoPipeline(nn.Module, ProgressBarMixin, SupportsComponentDiscove
if req.num_reqs != 1:
raise ValueError(f"LingBotVideoPipeline only supports one request per batch, got {req.num_reqs}.")
request = req.requests[0]
prompt, prompt_negative = _extract_prompt(request)
sampling = request.sampling_params
extra_args = dict(sampling.extra_args or {})
default_shift = getattr(self.od_config, "flow_shift", None) or 3.0
default_output_type = getattr(self.od_config, "output_type", None) or "pt"
if default_output_type not in {"pt", "np", "latent"}:
default_output_type = "pt"
try:
if sampling.num_outputs_per_prompt != 1:
raise ValueError(
f"LingBotVideoPipeline only supports one output per prompt, got {sampling.num_outputs_per_prompt}."
)
request_config = normalize_lingbot_request(
request,
default_negative_prompt=self.default_negative_prompt,
default_image_negative_prompt=self.default_image_negative_prompt,
default_shift=default_shift,
default_output_type=default_output_type,
)
except (TypeError, ValueError) as exc:
raise OmniClientError(str(exc)) from exc
generator = sampling.generator
if isinstance(generator, list):
generator = generator[0] if generator else None
if generator is None and sampling.seed is not None:
generator = torch.Generator(device=self.device).manual_seed(int(sampling.seed))
height = sampling.height if sampling.height is not None else extra_args.pop("height", 480)
width = sampling.width if sampling.width is not None else extra_args.pop("width", 480)
num_frames = sampling.num_frames or extra_args.pop("num_frames", 81)
num_inference_steps = (
sampling.num_inference_steps
if sampling.num_inference_steps is not None
else extra_args.pop("num_inference_steps", 40)
)
guidance_scale = (
sampling.guidance_scale if sampling.guidance_scale_provided else extra_args.pop("guidance_scale", 6.0)
)
shift = extra_args.pop(
"shift",
extra_args.pop("flow_shift", getattr(self.od_config, "flow_shift", None) or 3.0),
)
negative_prompt = extra_args.pop("negative_prompt", prompt_negative or self.default_negative_prompt)
output_type = (
sampling.output_type or getattr(self.od_config, "output_type", None) or extra_args.pop("output_type", "pt")
)
if output_type not in {"pt", "np", "latent"}:
output_type = "pt"
sampling.output_type = output_type
sampling.height = request_config.height
sampling.width = request_config.width
sampling.num_frames = request_config.num_frames
sampling.fps = request_config.fps
sampling.frame_rate = float(request_config.fps)
sampling.num_inference_steps = request_config.num_inference_steps
sampling.guidance_scale = request_config.guidance_scale
sampling.output_type = request_config.output_type
frames = self._generate(
prompt=prompt,
negative_prompt=negative_prompt,
height=height,
width=width,
num_frames=num_frames,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
shift=shift,
prompt=request_config.prompt,
mode=request_config.mode,
input_image=request_config.input_image,
negative_prompt=request_config.negative_prompt,
height=request_config.height,
width=request_config.width,
num_frames=request_config.num_frames,
num_inference_steps=request_config.num_inference_steps,
guidance_scale=request_config.guidance_scale,
shift=request_config.shift,
generator=generator,
latents=sampling.latents,
output_type=output_type,
batch_cfg=bool(extra_args.pop("batch_cfg", False)),
null_cond_clone_zero=bool(extra_args.pop("null_cond_clone_zero", False)),
offload_vae_during_denoise=bool(extra_args.pop("offload_vae_during_denoise", False)),
t_thresh=extra_args.pop("t_thresh", None),
refiner_sigma_tail_steps=int(extra_args.pop("refiner_sigma_tail_steps", LOW_NOISE_TAIL_V1_DEFAULT_STEPS)),
output_type=request_config.output_type,
batch_cfg=bool(extra_args.get("batch_cfg", False)),
null_cond_clone_zero=bool(extra_args.get("null_cond_clone_zero", False)),
offload_vae_during_denoise=bool(extra_args.get("offload_vae_during_denoise", False)),
t_thresh=extra_args.get("t_thresh"),
refiner_sigma_tail_steps=int(
extra_args.get(
"refiner_sigma_tail_steps",
LOW_NOISE_TAIL_V1_DEFAULT_STEPS,
)
),
)
return DiffusionOutput(output=frames)
output_key = "image" if request_config.mode is LingBotGenerationMode.T2I else "video"
return DiffusionOutput(output={output_key: frames})
@@ -0,0 +1,469 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import json
import math
from collections.abc import Mapping
from dataclasses import dataclass
from enum import Enum
from typing import Any
from PIL import Image
from vllm.logger import init_logger
logger = init_logger(__name__)
LINGBOT_RUNTIME_PROMPT_FIELDS = frozenset(
{
"duration",
"seconds",
"fps",
"height",
"width",
"size",
"num_frames",
"resolution",
"ratio",
}
)
# Values are stored as (height, width), matching the official LingBot runner.
LINGBOT_RESOLUTION_PRESETS: dict[str, dict[str, tuple[int, int]]] = {
"192p": {
"1:1": (192, 192),
"9:16": (192, 320),
"16:9": (320, 192),
"3:4": (192, 256),
"4:3": (256, 192),
},
"480p": {
"1:1": (480, 480),
"9:16": (480, 832),
"16:9": (832, 480),
"3:4": (480, 640),
"4:3": (640, 480),
},
"720p": {
"1:1": (736, 736),
"9:16": (736, 1280),
"16:9": (1280, 736),
"3:4": (736, 960),
"4:3": (960, 736),
},
"1080p": {
"1:1": (1088, 1088),
"9:16": (1088, 1920),
"16:9": (1920, 1088),
"3:4": (1088, 1440),
"4:3": (1440, 1088),
},
"2k": {
"1:1": (1440, 1440),
"9:16": (1440, 2560),
"16:9": (2560, 1440),
"3:4": (1440, 1920),
"4:3": (1920, 1440),
},
"4k": {
"1:1": (2176, 2176),
"9:16": (2176, 3840),
"16:9": (3840, 2176),
"3:4": (2176, 2880),
"4:3": (2880, 2176),
},
}
class LingBotGenerationMode(str, Enum):
T2I = "t2i"
T2V = "t2v"
TI2V = "ti2v"
@dataclass(frozen=True)
class LingBotRequestConfig:
mode: LingBotGenerationMode
prompt: str
negative_prompt: str
height: int
width: int
num_frames: int
fps: int
num_inference_steps: int
guidance_scale: float
shift: float
output_type: str
input_image: Image.Image | None
def _json_caption(value: Any) -> str:
try:
caption = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
except (TypeError, ValueError) as exc:
raise ValueError(f"LingBot structured prompt is not JSON serializable: {value!r}.") from exc
if caption in {"", '""', "{}"}:
raise ValueError("LingBot structured prompt must contain a non-empty caption.")
return caption
def caption_from_lingbot_prompt(value: Any) -> str:
if isinstance(value, str):
if not value:
raise ValueError("LingBot `prompt` must not be empty.")
return value
if not isinstance(value, Mapping):
raise TypeError(f"LingBot `prompt` must be a string or mapping, got {type(value)!r}.")
if "caption" in value:
caption = value["caption"]
if isinstance(caption, str):
if not caption:
raise ValueError("LingBot `caption` must not be empty.")
return caption
return _json_caption(caption)
caption_fields = {key: item for key, item in value.items() if key not in LINGBOT_RUNTIME_PROMPT_FIELDS}
if not caption_fields:
raise ValueError("LingBot structured prompt is empty after removing runtime fields.")
return _json_caption(caption_fields)
def _prompt_envelope(prompt_obj: Any) -> Mapping[str, Any]:
return prompt_obj if isinstance(prompt_obj, Mapping) else {}
def _prompt_value(prompt_obj: Any) -> Any:
envelope = _prompt_envelope(prompt_obj)
return envelope["prompt"] if "prompt" in envelope else prompt_obj
def _image_items(envelope: Mapping[str, Any]) -> list[Any]:
multi_modal_data = envelope.get("multi_modal_data") or {}
if not isinstance(multi_modal_data, Mapping):
raise TypeError("LingBot `multi_modal_data` must be a mapping.")
images = multi_modal_data.get("image")
if images is None:
return []
return list(images) if isinstance(images, (list, tuple)) else [images]
def resolve_lingbot_mode(prompt_obj: Any) -> LingBotGenerationMode:
envelope = _prompt_envelope(prompt_obj)
images = _image_items(envelope)
multi_modal_data = envelope.get("multi_modal_data") or {}
unsupported = [name for name in ("video", "audio") if multi_modal_data.get(name) is not None]
if unsupported:
raise ValueError(f"LingBot does not support reference modalities {unsupported!r}; only one image is allowed.")
modalities = envelope.get("modalities")
if modalities is None:
if images:
raise ValueError("LingBot requests with an input image must explicitly set `modalities=['video']`.")
logger.warning_once(
"LingBot request omitted `modalities`; falling back to legacy text-to-video behavior. "
"Set `modalities=['video']` explicitly."
)
return LingBotGenerationMode.T2V
if not isinstance(modalities, (list, tuple)) or len(modalities) != 1:
raise ValueError(f"LingBot `modalities` must contain exactly one output modality, got {modalities!r}.")
modality = modalities[0]
if modality == "image":
if images:
raise ValueError(f"LingBot text-to-image does not accept reference images, got {len(images)}.")
return LingBotGenerationMode.T2I
if modality == "video":
if len(images) == 0:
return LingBotGenerationMode.T2V
if len(images) == 1:
return LingBotGenerationMode.TI2V
raise ValueError(f"LingBot text-image-to-video accepts exactly one reference image, got {len(images)}.")
raise ValueError(f"LingBot output modality must be 'image' or 'video', got {modality!r}.")
def _positive_int(value: Any, name: str) -> int:
if isinstance(value, bool):
raise ValueError(f"LingBot `{name}` must be a positive integer, got {value!r}.")
try:
parsed = int(value)
numeric = float(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"LingBot `{name}` must be a positive integer, got {value!r}.") from exc
if not math.isfinite(numeric) or numeric != parsed or parsed <= 0:
raise ValueError(f"LingBot `{name}` must be a positive integer, got {value!r}.")
return parsed
def normalize_lingbot_num_frames(value: Any) -> int:
"""Round a video length up to LingBot's causal VAE ``4n+1`` grid."""
num_frames = _positive_int(value, "num_frames")
latent_frames = math.ceil((num_frames - 1) / 4)
return latent_frames * 4 + 1
def resolve_lingbot_num_frames(duration: Any, fps: Any) -> int:
try:
duration_seconds = float(duration)
except (TypeError, ValueError) as exc:
raise ValueError(f"LingBot `duration` must be a positive number, got {duration!r}.") from exc
if not math.isfinite(duration_seconds) or duration_seconds <= 0:
raise ValueError(f"LingBot `duration` must be a positive number, got {duration!r}.")
fps_value = _positive_int(fps, "fps")
raw_frames = int(duration_seconds * fps_value)
if raw_frames < 1:
raise ValueError(
f"LingBot `duration` and `fps` must produce at least one frame, got duration={duration!r}, fps={fps!r}."
)
return normalize_lingbot_num_frames(raw_frames)
def _parse_size(value: Any) -> tuple[int, int]:
if isinstance(value, str):
parts = value.lower().split("x")
if len(parts) != 2:
raise ValueError(f"LingBot `size` must use WIDTHxHEIGHT format, got {value!r}.")
width, height = parts
return _positive_int(height, "height"), _positive_int(width, "width")
if isinstance(value, (list, tuple)) and len(value) == 2:
width, height = value
return _positive_int(height, "height"), _positive_int(width, "width")
raise ValueError(f"LingBot `size` must use WIDTHxHEIGHT format, got {value!r}.")
def resolve_lingbot_size(
*,
width: Any = None,
height: Any = None,
size: Any = None,
resolution: Any = None,
ratio: Any = None,
) -> tuple[int, int]:
has_dimensions = width is not None or height is not None
has_size = size is not None
has_preset = resolution is not None or ratio is not None
if sum((has_dimensions, has_size, has_preset)) > 1:
raise ValueError("LingBot `size`, explicit `width`/`height`, and `resolution`/`ratio` are mutually exclusive.")
if has_preset:
if resolution is None or ratio is None:
raise ValueError("LingBot `resolution` and `ratio` must be provided together.")
resolution_value = str(resolution).lower()
ratio_value = str(ratio)
if resolution_value not in LINGBOT_RESOLUTION_PRESETS:
raise ValueError(
f"Unsupported LingBot `resolution` {resolution!r}; choices are {sorted(LINGBOT_RESOLUTION_PRESETS)!r}."
)
presets = LINGBOT_RESOLUTION_PRESETS[resolution_value]
if ratio_value not in presets:
raise ValueError(
f"Unsupported LingBot `ratio` {ratio!r} for resolution {resolution_value!r}; "
f"choices are {sorted(presets)!r}."
)
resolved_height, resolved_width = presets[ratio_value]
elif has_size:
resolved_height, resolved_width = _parse_size(size)
else:
if width is None or height is None:
raise ValueError(
f"LingBot `width` and `height` must be provided together, got width={width!r}, height={height!r}."
)
resolved_height = _positive_int(height, "height")
resolved_width = _positive_int(width, "width")
if resolved_height % 16 != 0 or resolved_width % 16 != 0:
raise ValueError(
"LingBot `height` and `width` must be multiples of 16, "
f"got height={resolved_height}, width={resolved_width}."
)
return resolved_height, resolved_width
def _runtime_prompt_fields(prompt_obj: Any) -> Mapping[str, Any]:
prompt_value = _prompt_value(prompt_obj)
return prompt_value if isinstance(prompt_value, Mapping) else {}
def _pick(mapping: Mapping[str, Any], key: str) -> Any:
value = mapping.get(key)
return value if value is not None else None
def _first_not_none(*values: Any) -> Any:
return next((value for value in values if value is not None), None)
def resolve_lingbot_output_dimensions(
*,
sampling_width: Any = None,
sampling_height: Any = None,
prompt_fields: Mapping[str, Any] | None = None,
default_width: int = 480,
default_height: int = 480,
) -> tuple[int, int]:
"""Resolve the ``(width, height)`` that LingBot will use for generation."""
prompt_fields = prompt_fields or {}
requested_width = _pick(prompt_fields, "width")
requested_height = _pick(prompt_fields, "height")
size = _pick(prompt_fields, "size")
resolution = _pick(prompt_fields, "resolution")
ratio = _pick(prompt_fields, "ratio")
if requested_width is not None or requested_height is not None:
width, height = requested_width, requested_height
elif size is not None or resolution is not None or ratio is not None:
width = height = None
else:
width, height = sampling_width, sampling_height
if width is None and height is None and size is None and resolution is None and ratio is None:
width, height = default_width, default_height
resolved_height, resolved_width = resolve_lingbot_size(
width=width,
height=height,
size=size,
resolution=resolution,
ratio=ratio,
)
return resolved_width, resolved_height
def normalize_lingbot_request(
request: Any,
*,
default_negative_prompt: str,
default_image_negative_prompt: str,
default_height: int = 480,
default_width: int = 480,
default_num_frames: int = 81,
default_fps: int = 24,
default_num_inference_steps: int = 40,
default_guidance_scale: float = 6.0,
default_shift: float = 3.0,
default_output_type: str = "pt",
) -> LingBotRequestConfig:
prompt_obj = request.prompt
envelope = _prompt_envelope(prompt_obj)
prompt_fields = _runtime_prompt_fields(prompt_obj)
sampling = request.sampling_params
extra_args = dict(sampling.extra_args or {})
mode = resolve_lingbot_mode(prompt_obj)
prompt = caption_from_lingbot_prompt(_prompt_value(prompt_obj))
images = _image_items(envelope)
input_image = images[0] if images else None
if input_image is not None and not isinstance(input_image, Image.Image):
raise TypeError(f"LingBot input image must be a PIL image after preprocessing, got {type(input_image)!r}.")
prompt_negative = envelope.get("negative_prompt")
if "negative_prompt" in extra_args:
negative_prompt = extra_args["negative_prompt"]
elif prompt_negative is not None:
negative_prompt = prompt_negative
else:
negative_prompt = (
default_image_negative_prompt if mode is LingBotGenerationMode.T2I else default_negative_prompt
)
if not isinstance(negative_prompt, str):
raise TypeError(f"LingBot `negative_prompt` must be a string, got {type(negative_prompt)!r}.")
fps_raw = _first_not_none(
_pick(extra_args, "fps"),
_pick(prompt_fields, "fps"),
sampling.resolved_frame_rate,
default_fps,
)
fps = _positive_int(fps_raw, "fps")
extra_seconds = _pick(extra_args, "seconds")
prompt_seconds = _pick(prompt_fields, "seconds")
duration_value = _pick(extra_args, "duration")
prompt_duration = _pick(prompt_fields, "duration")
if any(value is not None for value in (extra_seconds, prompt_seconds)) and any(
value is not None for value in (duration_value, prompt_duration)
):
raise ValueError("LingBot `seconds` and `duration` cannot be provided together.")
duration = next(
(value for value in (extra_seconds, prompt_seconds, duration_value, prompt_duration) if value is not None),
None,
)
model_num_frames = _first_not_none(
_pick(extra_args, "num_frames"),
_pick(prompt_fields, "num_frames"),
)
explicit_num_frames = model_num_frames
if explicit_num_frames is None and sampling.num_frames not in (None, 1):
# ``sampling.num_frames`` defaults to 1 (the image-model sentinel).
# Treat any other value as an explicit request; ``1`` means "omitted".
explicit_num_frames = sampling.num_frames
if mode is LingBotGenerationMode.T2I:
if duration is not None:
raise ValueError(f"LingBot text-to-image does not accept `seconds` or `duration`, got {duration!r}.")
if explicit_num_frames is not None and _positive_int(explicit_num_frames, "num_frames") != 1:
raise ValueError(f"LingBot text-to-image requires `num_frames=1`, got {explicit_num_frames!r}.")
num_frames = 1
elif explicit_num_frames is not None:
num_frames = normalize_lingbot_num_frames(explicit_num_frames)
elif duration is not None:
num_frames = resolve_lingbot_num_frames(duration, fps)
else:
num_frames = normalize_lingbot_num_frames(default_num_frames)
width, height = resolve_lingbot_output_dimensions(
sampling_width=sampling.width,
sampling_height=sampling.height,
prompt_fields=prompt_fields,
default_width=default_width,
default_height=default_height,
)
num_inference_steps = sampling.num_inference_steps
if num_inference_steps is None:
num_inference_steps = _first_not_none(_pick(extra_args, "num_inference_steps"), default_num_inference_steps)
num_inference_steps = _positive_int(num_inference_steps, "num_inference_steps")
guidance_scale = (
sampling.guidance_scale
if sampling.guidance_scale_provided
else _first_not_none(_pick(extra_args, "guidance_scale"), default_guidance_scale)
)
try:
guidance_scale = float(guidance_scale)
except (TypeError, ValueError) as exc:
raise ValueError(f"LingBot `guidance_scale` must be numeric, got {guidance_scale!r}.") from exc
if not math.isfinite(guidance_scale) or guidance_scale < 0:
raise ValueError(f"LingBot `guidance_scale` must be non-negative, got {guidance_scale!r}.")
shift_raw = (
extra_args["shift"]
if _pick(extra_args, "shift") is not None
else _first_not_none(_pick(extra_args, "flow_shift"), default_shift)
)
try:
shift = float(shift_raw)
except (TypeError, ValueError) as exc:
raise ValueError(f"LingBot `shift` must be numeric, got {shift_raw!r}.") from exc
if not math.isfinite(shift) or shift <= 0:
raise ValueError(f"LingBot `shift` must be positive, got {shift_raw!r}.")
output_type = _first_not_none(
sampling.output_type,
_pick(extra_args, "output_type"),
default_output_type,
)
if output_type not in {"pt", "np", "latent"}:
raise ValueError(f"LingBot `output_type` must be 'pt', 'np', or 'latent', got {output_type!r}.")
return LingBotRequestConfig(
mode=mode,
prompt=prompt,
negative_prompt=negative_prompt,
height=height,
width=width,
num_frames=num_frames,
fps=fps,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
shift=shift,
output_type=output_type,
input_image=input_image,
)