[Refactor][CI] Reorganize test tree, and move slow e2e to weekly (#4951)

Signed-off-by: wangyu <410167048@qq.com>
This commit is contained in:
wangyu authored and GitHub committed 2026-07-29 23:53:03 +08:00
1 parent 925347332f
commit 7c17111ff5
158 files changed
+3479 -4130

No files matched your search

@@ -1,14 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from tests.e2e.offline_inference.custom_pipeline.qwen_image_pipeline_with_logprob import (
QwenImagePipelineWithLogProbForTest,
)
from tests.e2e.offline_inference.custom_pipeline.worker_extension import (
vLLMOmniColocateWorkerExtensionForTest,
)
__all__ = [
"QwenImagePipelineWithLogProbForTest",
"vLLMOmniColocateWorkerExtensionForTest",
]
@@ -1,220 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Literal
import torch
from diffusers import FlowMatchEulerDiscreteScheduler
from diffusers.utils import BaseOutput
from diffusers.utils.torch_utils import randn_tensor
@dataclass
class FlowMatchSDEDiscreteSchedulerOutputForTest(BaseOutput):
"""
Output class for the scheduler's `step` function output.
Args:
prev_sample (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_channels)` for images):
Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
denoising loop.
log_prob (`torch.FloatTensor` of shape `(batch_size,)`, *optional*):
The log probability of the previous sample.
prev_sample_mean (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_channels)` for images):
The mean of the computed sample of previous timestep.
std_dev_t (`torch.FloatTensor` of shape `(batch_size, 1, 1)`):
The standard deviation used to compute `prev_sample`.
"""
prev_sample: torch.FloatTensor
log_prob: torch.FloatTensor | None
prev_sample_mean: torch.FloatTensor
std_dev_t: torch.FloatTensor
class FlowMatchSDEDiscreteSchedulerForTest(FlowMatchEulerDiscreteScheduler):
"""SDE version of the FlowMatchEulerDiscreteScheduler.
The implementation is based on FlowGRPO paper (https://arxiv.org/abs/2505.05470)
and diffusers v0.37 branch.
"""
def step(
self,
model_output: torch.FloatTensor,
timestep: float | torch.FloatTensor,
sample: torch.FloatTensor,
s_churn: float = 0.0,
s_tmin: float = 0.0,
s_tmax: float = float("inf"),
s_noise: float = 1.0,
generator: torch.Generator | None = None,
per_token_timesteps: torch.Tensor | None = None,
return_dict: bool = True,
noise_level: float = 0.7,
prev_sample: torch.FloatTensor | None = None,
sde_type: Literal["sde", "cps"] = "sde",
return_logprobs: bool = True,
) -> FlowMatchSDEDiscreteSchedulerOutputForTest | tuple:
"""
Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
process from the learned model outputs (most often the predicted noise).
Modified from https://github.com/yifan123/flow_grpo/blob/main/flow_grpo/diffusers_patch/sd3_sde_with_logprob.py
Args:
model_output (`torch.FloatTensor`):
The direct output from learned diffusion model.
timestep (`float`):
The current discrete timestep in the diffusion chain.
sample (`torch.FloatTensor`):
A current instance of a sample created by the diffusion process.
s_churn (`float`):
s_tmin (`float`):
s_tmax (`float`):
s_noise (`float`, defaults to 1.0):
Scaling factor for noise added to the sample.
generator (`torch.Generator`, *optional*):
A random number generator.
per_token_timesteps (`torch.Tensor`, *optional*):
The timesteps for each token in the sample.
return_dict (`bool`):
Whether or not to return a
[`~schedulers.scheduling_flow_match_euler_discrete.FlowMatchSDEDiscreteSchedulerOutput`] or tuple.
noise_level (`float`, *optional*, defaults to 0.7):
The noise level used in the SDE.
prev_sample (`torch.FloatTensor`, *optional*):
The sample from the previous timestep. If not provided, it will be sampled inside the function.
sde_type (`str`, *optional*, defaults to "sde"):
The type of SDE to use. Choose between "sde" and "cps".
return_logprobs (`bool`, *optional*, defaults to True):
Whether to return log probabilities of the previous sample.
"""
if isinstance(timestep, (int, torch.IntTensor, torch.LongTensor)):
raise ValueError(
(
"Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
" `FlowMatchEulerDiscreteScheduler.step()` is not supported. Make sure to pass"
" one of the `scheduler.timesteps` as a timestep."
),
)
if self.step_index is None:
self._init_step_index(timestep)
# Upcast to avoid precision issues when computing prev_sample
sample = sample.to(torch.float32)
if prev_sample is not None:
prev_sample = prev_sample.to(torch.float32)
prev_sample, log_prob, prev_sample_mean, std_dev_t = self.sample_previous_step(
sample=sample,
model_output=model_output,
generator=generator,
per_token_timesteps=per_token_timesteps,
noise_level=noise_level,
prev_sample=prev_sample,
sde_type=sde_type,
return_logprobs=return_logprobs,
)
# upon completion increase step index by one
self._step_index += 1
if per_token_timesteps is None:
# Cast sample back to model compatible dtype
prev_sample = prev_sample.to(model_output.dtype)
if not return_dict:
return (prev_sample, log_prob, prev_sample_mean, std_dev_t)
return FlowMatchSDEDiscreteSchedulerOutputForTest(
prev_sample=prev_sample, log_prob=log_prob, prev_sample_mean=prev_sample_mean, std_dev_t=std_dev_t
)
def sample_previous_step(
self,
sample: torch.Tensor,
model_output: torch.Tensor,
timestep: torch.FloatTensor | None = None,
generator: torch.Generator | None = None,
per_token_timesteps: torch.Tensor | None = None,
noise_level: float = 0.7,
prev_sample: torch.Tensor | None = None,
sde_type: Literal["cps", "sde"] = "sde",
return_logprobs: bool = True,
):
assert sde_type in ["sde", "cps"]
assert sample.dtype == torch.float32
if prev_sample is not None:
assert prev_sample.dtype == torch.float32
if per_token_timesteps is not None:
raise NotImplementedError("per_token_timesteps is not supported yet for FlowMatchSDEDiscreteScheduler.")
else:
if timestep is None:
sigma_idx = self.step_index
sigma = self.sigmas[sigma_idx]
sigma_prev = self.sigmas[sigma_idx + 1]
else:
sigma_idx = torch.tensor([self.index_for_timestep(t) for t in timestep])
sigma = self.sigmas[sigma_idx].view(-1, *([1] * (len(sample.shape) - 1)))
sigma_prev = self.sigmas[sigma_idx + 1].view(-1, *([1] * (len(sample.shape) - 1)))
sigma_max = self.sigmas[1]
dt = sigma_prev - sigma
if sde_type == "sde":
std_dev_t = torch.sqrt(sigma / (1 - torch.where(sigma == 1, sigma_max, sigma))) * noise_level
prev_sample_mean = (
sample * (1 + std_dev_t**2 / (2 * sigma) * dt)
+ model_output * (1 + std_dev_t**2 * (1 - sigma) / (2 * sigma)) * dt
)
if prev_sample is None:
variance_noise = randn_tensor(
model_output.shape,
generator=generator,
device=model_output.device,
dtype=model_output.dtype,
)
prev_sample = prev_sample_mean + std_dev_t * torch.sqrt(-1 * dt) * variance_noise
if return_logprobs:
log_prob = (
-((prev_sample.detach() - prev_sample_mean) ** 2) / (2 * ((std_dev_t * torch.sqrt(-1 * dt)) ** 2))
- torch.log(std_dev_t * torch.sqrt(-1 * dt))
- torch.log(torch.sqrt(2 * torch.as_tensor(math.pi)))
)
else:
log_prob = None
elif sde_type == "cps":
std_dev_t = sigma_prev * math.sin(noise_level * math.pi / 2)
pred_original_sample = sample - sigma * model_output
noise_estimate = sample + model_output * (1 - sigma)
prev_sample_mean = pred_original_sample * (1 - sigma_prev) + noise_estimate * torch.sqrt(
sigma_prev**2 - std_dev_t**2
)
if prev_sample is None:
variance_noise = randn_tensor(
model_output.shape,
generator=generator,
device=model_output.device,
dtype=model_output.dtype,
)
prev_sample = prev_sample_mean + std_dev_t * variance_noise
if return_logprobs:
log_prob = -((prev_sample.detach() - prev_sample_mean) ** 2)
else:
log_prob = None
# mean along all but batch dimension
log_prob = log_prob.mean(dim=tuple(range(1, log_prob.ndim))) if log_prob is not None else None
return prev_sample, log_prob, prev_sample_mean, std_dev_t
@@ -1,418 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Detailed custom Qwen-Image pipeline for E2E tests.
This pipeline follows the structure of the user's reference implementation:
- supports pre-tokenized prompt IDs via OmniCustomPrompt-style dict input
- uses an SDE scheduler that can return step logprobs
- returns structured trajectory_* fields (latents, timesteps, log_probs)
consistent with the BAGEL trajectory recording design
"""
from __future__ import annotations
import os
from typing import Any, Literal
import torch
from tests.e2e.offline_inference.custom_pipeline.flow_match_sde_scheduler import FlowMatchSDEDiscreteSchedulerForTest
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.models.qwen_image import QwenImagePipeline
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
def _maybe_to_cpu(v):
if isinstance(v, torch.Tensor):
return v.detach().cpu()
return v
# Custom pipeline class for QwenImage that returns log probabilities during the diffusion process.
# This is for test
class QwenImagePipelineWithLogProbForTest(QwenImagePipeline):
supports_request_batch = False
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
super().__init__(od_config=od_config, prefix=prefix)
self.device = get_local_device()
model = od_config.model
# Check if model is a local path
local_files_only = os.path.exists(model)
self.scheduler = FlowMatchSDEDiscreteSchedulerForTest.from_pretrained(
model, subfolder="scheduler", local_files_only=local_files_only
)
def _get_qwen_prompt_embeds(
self,
prompt_ids: torch.Tensor,
attention_mask: torch.Tensor | None = None,
dtype: torch.dtype | None = None,
):
dtype = dtype or self.text_encoder.dtype
if attention_mask is None:
attention_mask = torch.ones_like(prompt_ids, dtype=torch.long)
prompt_ids = prompt_ids.unsqueeze(0) if prompt_ids.ndim == 1 else prompt_ids
attention_mask = attention_mask.unsqueeze(0) if attention_mask.ndim == 1 else attention_mask
drop_idx = self.prompt_template_encode_start_idx
encoder_hidden_states = self.text_encoder(
input_ids=prompt_ids.to(self.device),
attention_mask=attention_mask.to(self.device),
output_hidden_states=True,
)
hidden_states = encoder_hidden_states.hidden_states[-1]
split_hidden_states = self._extract_masked_hidden(hidden_states, attention_mask)
split_hidden_states = [e[drop_idx:] for e in split_hidden_states]
attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states]
max_seq_len = max([e.size(0) for e in split_hidden_states])
prompt_embeds = torch.stack(
[torch.cat([u, u.new_zeros(max_seq_len - u.size(0), u.size(1))]) for u in split_hidden_states]
)
encoder_attention_mask = torch.stack(
[torch.cat([u, u.new_zeros(max_seq_len - u.size(0))]) for u in attn_mask_list]
)
prompt_embeds = prompt_embeds.to(dtype=dtype)
return prompt_embeds, encoder_attention_mask
def encode_prompt(
self,
prompt_ids: torch.Tensor,
attention_mask: torch.Tensor | None = None,
num_images_per_prompt: int = 1,
prompt_embeds: torch.Tensor | None = None,
prompt_embeds_mask: torch.Tensor | None = None,
max_sequence_length: int = 1024,
):
prompt_ids = prompt_ids.unsqueeze(0) if prompt_ids.ndim == 1 else prompt_ids
attention_mask = (
attention_mask.unsqueeze(0) if attention_mask is not None and attention_mask.ndim == 1 else attention_mask
)
batch_size = prompt_ids.shape[0] if prompt_embeds is None else prompt_embeds.shape[0]
if prompt_embeds is None:
prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(prompt_ids, attention_mask=attention_mask)
prompt_embeds = prompt_embeds[:, :max_sequence_length]
prompt_embeds_mask = prompt_embeds_mask[:, :max_sequence_length]
_, seq_len, _ = prompt_embeds.shape
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
prompt_embeds_mask = prompt_embeds_mask.repeat(1, num_images_per_prompt, 1)
prompt_embeds_mask = prompt_embeds_mask.view(batch_size * num_images_per_prompt, seq_len)
return prompt_embeds, prompt_embeds_mask
def diffuse(
self,
prompt_embeds,
prompt_embeds_mask,
negative_prompt_embeds,
negative_prompt_embeds_mask,
latents,
img_shapes,
txt_seq_lens,
negative_txt_seq_lens,
timesteps,
do_true_cfg,
guidance,
true_cfg_scale,
noise_level,
sde_window,
sde_type,
generator,
logprobs,
):
all_latents = []
all_log_probs = []
all_timesteps = []
self.scheduler.set_begin_index(0)
for i, t in enumerate(timesteps):
if self.interrupt:
continue
if i < sde_window[0]:
cur_noise_level = 0.0
elif i == sde_window[0]:
cur_noise_level = noise_level
all_latents.append(latents)
elif i > sde_window[0] and i < sde_window[1]:
cur_noise_level = noise_level
else:
cur_noise_level = 0.0
self._current_timestep = t
# Broadcast timestep to match batch size
timestep = t.expand(latents.shape[0]).to(device=latents.device, dtype=latents.dtype)
# Forward pass for positive prompt (or unconditional if no CFG)
self.transformer.do_true_cfg = do_true_cfg
noise_pred = self.transformer(
hidden_states=latents,
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,
attention_kwargs=self.attention_kwargs,
return_dict=False,
)[0]
# Forward pass for negative prompt (CFG)
if do_true_cfg:
neg_noise_pred = self.transformer(
hidden_states=latents,
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,
attention_kwargs=self.attention_kwargs,
return_dict=False,
)[0]
comb_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
cond_norm = torch.norm(noise_pred, dim=-1, keepdim=True)
noise_norm = torch.norm(comb_pred, dim=-1, keepdim=True)
noise_pred = comb_pred * (cond_norm / noise_norm)
# compute the previous noisy sample x_t -> x_t-1
latents, log_prob, _, _ = self.scheduler.step(
noise_pred,
t,
latents,
generator=generator,
noise_level=cur_noise_level,
sde_type=sde_type,
return_logprobs=logprobs,
return_dict=False,
)
if i >= sde_window[0] and i < sde_window[1]:
all_latents.append(latents)
all_log_probs.append(log_prob)
all_timesteps.append(t)
all_latents = torch.stack(all_latents, dim=1)
if all_log_probs[0] is not None:
all_log_probs = torch.stack(all_log_probs, dim=1)
else:
all_log_probs = None
all_timesteps = torch.stack(all_timesteps).unsqueeze(0).expand(latents.shape[0], -1)
return latents, all_latents, all_log_probs, all_timesteps
def forward(
self,
req: DiffusionRequestBatch,
prompt_ids: torch.Tensor | list[int] | None = None,
prompt_mask: torch.Tensor | None = None,
negative_prompt_ids: torch.Tensor | list[int] | None = None,
negative_prompt_mask: torch.Tensor | None = None,
true_cfg_scale: float = 4.0,
height: int | None = None,
width: int | None = None,
num_inference_steps: int = 50,
sigmas: list[float] | None = None,
guidance_scale: float = 1.0,
num_images_per_prompt: int = 1,
generator: torch.Generator | list[torch.Generator] | None = None,
latents: torch.Tensor | None = None,
prompt_embeds: torch.Tensor | None = None,
prompt_embeds_mask: torch.Tensor | None = None,
negative_prompt_embeds: torch.Tensor | None = None,
negative_prompt_embeds_mask: torch.Tensor | None = None,
output_type: str | None = "pil",
attention_kwargs: dict[str, Any] | None = None,
callback_on_step_end_tensor_inputs: tuple[str, ...] = ("latents",),
max_sequence_length: int = 512,
noise_level: float = 0.7,
sde_window_size: int | None = None,
sde_window_range: tuple[int, int] = (0, 5),
sde_type: Literal["sde", "cps"] = "sde",
logprobs: bool = True,
) -> DiffusionOutput:
if req.num_reqs != 1:
raise ValueError("QwenImagePipelineWithLogProbForTest supports only single-request forward.")
request = req.requests[0]
# Extract prompt data from OmniCustomPrompt in req.prompt
custom_prompt = request.prompt if request.prompt is not None else {}
if isinstance(custom_prompt, dict):
prompt_ids = custom_prompt.get("prompt_ids", prompt_ids)
prompt_mask = custom_prompt.get("prompt_mask", prompt_mask)
negative_prompt_ids = custom_prompt.get("negative_prompt_ids", negative_prompt_ids)
negative_prompt_mask = custom_prompt.get("negative_prompt_mask", negative_prompt_mask)
# Read sampling params from req.sampling_params
sp = request.sampling_params
height = sp.height or self.default_sample_size * self.vae_scale_factor
width = sp.width or self.default_sample_size * self.vae_scale_factor
num_inference_steps = sp.num_inference_steps or num_inference_steps
max_sequence_length = sp.max_sequence_length or max_sequence_length
noise_level = sp.extra_args.get("noise_level", None) or noise_level
sde_window_size = sp.extra_args.get("sde_window_size", None) or sde_window_size
sde_window_range = sp.extra_args.get("sde_window_range", None) or sde_window_range
sde_type = sp.extra_args.get("sde_type", None) or sde_type
logprobs = sp.extra_args.get("logprobs", None) or logprobs
generator = sp.generator or generator
if generator is None and sp.seed is not None:
generator = torch.Generator(device=self.device).manual_seed(sp.seed)
true_cfg_scale = sp.true_cfg_scale or true_cfg_scale
req_num_outputs = getattr(sp, "num_outputs_per_prompt", None)
if req_num_outputs and req_num_outputs > 0:
num_images_per_prompt = req_num_outputs
self._guidance_scale = guidance_scale
self._attention_kwargs = attention_kwargs
self._current_timestep = None
self._interrupt = False
if prompt_ids is not None:
if isinstance(prompt_ids, list):
prompt_ids = torch.tensor(prompt_ids, device=self.device)
batch_size = prompt_ids.shape[0] if prompt_ids.ndim == 2 else 1
elif prompt_embeds is not None:
batch_size = prompt_embeds.shape[0]
else:
# Both prompt_ids and prompt_embeds are None (e.g. during warmup/dummy run).
# Return a minimal dummy output to avoid crashing.
return DiffusionOutput(output=None)
if isinstance(negative_prompt_ids, list):
negative_prompt_ids = torch.tensor(negative_prompt_ids, device=self.device)
has_neg_prompt = negative_prompt_ids is not None or (
negative_prompt_embeds is not None and negative_prompt_embeds_mask is not None
)
do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
prompt_embeds, prompt_embeds_mask = self.encode_prompt(
prompt_ids=prompt_ids,
attention_mask=prompt_mask,
prompt_embeds=prompt_embeds,
prompt_embeds_mask=prompt_embeds_mask,
num_images_per_prompt=num_images_per_prompt,
max_sequence_length=max_sequence_length,
)
if do_true_cfg:
negative_prompt_embeds, negative_prompt_embeds_mask = self.encode_prompt(
prompt_ids=negative_prompt_ids,
attention_mask=negative_prompt_mask,
prompt_embeds=negative_prompt_embeds,
prompt_embeds_mask=negative_prompt_embeds_mask,
num_images_per_prompt=num_images_per_prompt,
max_sequence_length=max_sequence_length,
)
num_channels_latents = self.transformer.in_channels // 4
latents = self.prepare_latents(
batch_size * num_images_per_prompt,
num_channels_latents,
height,
width,
prompt_embeds.dtype,
self.device,
generator,
latents,
)
img_shapes = [[(1, height // self.vae_scale_factor // 2, width // self.vae_scale_factor // 2)]] * batch_size
timesteps, num_inference_steps = self.prepare_timesteps(num_inference_steps, sigmas, latents.shape[1])
# num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
self._num_timesteps = len(timesteps)
# handle guidance
if self.transformer.guidance_embeds:
guidance = torch.full([1], guidance_scale, dtype=torch.float32)
guidance = guidance.expand(latents.shape[0])
else:
guidance = None
if self.attention_kwargs is None:
self._attention_kwargs = {}
txt_seq_lens = prompt_embeds_mask.sum(dim=1).tolist() if prompt_embeds_mask is not None else None
negative_txt_seq_lens = (
negative_prompt_embeds_mask.sum(dim=1).tolist() if negative_prompt_embeds_mask is not None else None
)
if sde_window_size is not None:
start = torch.randint(
sde_window_range[0],
sde_window_range[1] - sde_window_size + 1,
(1,),
generator=generator,
device=self.device,
).item()
end = start + sde_window_size
sde_window = (start, end)
else:
sde_window = (0, len(timesteps) - 1)
latents, all_latents, all_log_probs, all_timesteps = self.diffuse(
prompt_embeds,
prompt_embeds_mask,
negative_prompt_embeds,
negative_prompt_embeds_mask,
latents,
img_shapes,
txt_seq_lens,
negative_txt_seq_lens,
timesteps,
do_true_cfg,
guidance,
true_cfg_scale,
noise_level,
sde_window,
sde_type,
generator,
logprobs,
)
self._current_timestep = None
if output_type == "latent":
image = latents
else:
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
latents = latents.to(self.vae.dtype)
latents_mean = (
torch.tensor(self.vae.config.latents_mean)
.view(1, self.vae.config.z_dim, 1, 1, 1)
.to(latents.device, latents.dtype)
)
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
latents.device, latents.dtype
)
latents = latents / latents_std + latents_mean
image = self.vae.decode(latents, return_dict=False)[0][:, :, 0]
return DiffusionOutput(
output={
"payload": {
"image": _maybe_to_cpu(image),
},
"metadata": {
"prompt_embeddings": {
"prompt_embeds": _maybe_to_cpu(prompt_embeds),
"prompt_embeds_mask": _maybe_to_cpu(prompt_embeds_mask),
"negative_prompt_embeds": _maybe_to_cpu(negative_prompt_embeds),
"negative_prompt_embeds_mask": _maybe_to_cpu(negative_prompt_embeds_mask),
},
},
},
trajectory_latents=_maybe_to_cpu(all_latents),
trajectory_log_probs=_maybe_to_cpu(all_log_probs),
trajectory_timesteps=_maybe_to_cpu(all_timesteps),
)
@@ -1,252 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Regression tests for AsyncOmni collective_rpc in inline diffusion mode.
When AsyncOmni runs a single diffusion stage it activates "inline diffusion
mode", which skips stage worker subprocess creation and therefore never
attaches IPC queues (_in_q / _out_q) to the OmniStage. Methods like
list_loras(), add_lora(), sleep(), wake_up() all delegate to
collective_rpc(), which must handle this mode correctly instead of
trying to use the non-existent queues.
This is the same code path that verl's vLLMOmniHttpServer.generate()
exercises when it calls ``await self.engine.list_loras()`` before
dispatching a generation request.
Usage:
pytest tests/e2e/offline_inference/custom_pipeline/test_async_omni_collective_rpc.py -v -s
"""
from __future__ import annotations
import asyncio
import uuid
from contextlib import ExitStack
import pytest
import torch
from tests.helpers.mark import hardware_test
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.outputs import OmniRequestOutput
MODEL = "tiny-random/Qwen-Image"
CUSTOM_PIPELINE_CLASS = (
"tests.e2e.offline_inference.custom_pipeline.qwen_image_pipeline_with_logprob.QwenImagePipelineWithLogProbForTest"
)
WORKER_EXTENSION_CLASS = (
"tests.e2e.offline_inference.custom_pipeline.worker_extension.vLLMOmniColocateWorkerExtensionForTest"
)
def _create_inline_engine() -> AsyncOmni:
"""Create an AsyncOmni instance that uses inline diffusion mode.
A single diffusion stage triggers inline mode automatically.
"""
engine = AsyncOmni(
model=MODEL,
custom_pipeline_args={"pipeline_class": CUSTOM_PIPELINE_CLASS},
worker_extension_cls=WORKER_EXTENSION_CLASS,
enforce_eager=True,
)
return engine
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
@pytest.mark.core_model
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.asyncio
async def test_list_loras_inline_mode():
"""list_loras() must not crash in inline diffusion mode.
This is the exact call that vLLMOmniHttpServer.generate() makes
before every generation request.
"""
with ExitStack() as after:
engine = _create_inline_engine()
after.callback(engine.shutdown)
result = await engine.list_loras()
assert isinstance(result, list), f"Expected list, got {type(result)}"
@pytest.mark.core_model
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.asyncio
async def test_collective_rpc_inline_mode():
"""collective_rpc() must delegate to the inline engine, not stage queues."""
with ExitStack() as after:
engine = _create_inline_engine()
after.callback(engine.shutdown)
result = await engine.collective_rpc(method="list_loras")
assert isinstance(result, list), f"Expected list, got {type(result)}"
assert len(result) == 1, "Inline mode has exactly one stage"
@pytest.mark.core_model
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.asyncio
async def test_sleep_wake_up_inline_mode():
"""sleep() and wake_up() must work in inline diffusion mode."""
with ExitStack() as after:
engine = _create_inline_engine()
after.callback(engine.shutdown)
await engine.sleep(level=1)
assert await engine.is_sleeping()
await engine.wake_up()
assert not await engine.is_sleeping()
@pytest.mark.core_model
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.asyncio
async def test_generate_after_list_loras_inline_mode():
"""Full flow: list_loras() then generate(), matching vLLMOmniHttpServer.
This reproduces the exact sequence that caused the original crash:
1. list_loras() (was crashing with AssertionError on _out_q)
2. generate() (should succeed)
"""
with ExitStack() as after:
engine = _create_inline_engine()
after.callback(engine.shutdown)
# Step 1: list_loras (the call that was crashing)
loras = await engine.list_loras()
assert isinstance(loras, list)
# Step 2: generate (should still work after list_loras)
sampling_params = OmniDiffusionSamplingParams(
num_inference_steps=2,
guidance_scale=0.0,
height=256,
width=256,
seed=42,
)
last_output = None
async for output in engine.generate(
prompt={"prompt_ids": list(range(50))},
request_id=f"test_after_lora_{uuid.uuid4().hex[:8]}",
sampling_params_list=[sampling_params],
output_modalities=["image"],
):
last_output = output
assert last_output is not None
assert isinstance(last_output, OmniRequestOutput)
assert last_output.images, "Expected at least one generated image"
@pytest.mark.core_model
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.asyncio
async def test_sleep_memory_reclaimed_custom_pipeline():
"""sleep(level=1) must physically reclaim CuMemAllocator-tracked memory for
custom_pipeline.
Regression test for: custom pipelines constructed under ``with target_device:``
(CUDA default-device context) caused safetensors >=0.20.0 to use a
direct-to-GPU fast path (cudaMalloc via the driver API) that bypasses
CuMemAllocator, leaving weights invisible to sleep() and pinned in GPU
memory after the call.
The fix moves custom_pipeline init outside the CUDA context so all weights
go through the caching allocator and are therefore fully reclaimed by
sleep(level=1). A non-zero ``CuMemAllocator.get_current_usage()`` after
sleep is the direct signal that the bypass is still occurring.
"""
with ExitStack() as after:
engine = AsyncOmni(
model=MODEL,
custom_pipeline_args={"pipeline_class": CUSTOM_PIPELINE_CLASS},
worker_extension_cls=WORKER_EXTENSION_CLASS,
enforce_eager=True,
enable_sleep_mode=True,
)
after.callback(engine.shutdown)
assert not await engine.is_sleeping(), "Engine should be awake after creation"
# Measure global VRAM before sleep (driver view; includes inline worker
# thread since inline mode runs in the same process).
torch.accelerator.synchronize()
free_before, total = torch.cuda.mem_get_info()
used_before_gib = (total - free_before) / 1024**3
# Measure CuMemAllocator-tracked usage before sleep. In inline mode
# the worker runs in a thread pool inside this process, so the allocator
# singleton is shared and can be read directly.
allocator = None
tracked_before = 0
try:
from vllm.device_allocator.cumem import CuMemAllocator
allocator = CuMemAllocator.get_instance()
tracked_before = allocator.get_current_usage()
except Exception:
pass
# Put the engine to sleep; all weights should be offloaded via the pool.
acks = await engine.sleep(level=1)
await asyncio.sleep(0.5) # allow the CUDA driver to settle
torch.accelerator.synchronize()
# Measure after sleep.
free_after, _ = torch.cuda.mem_get_info()
used_after_gib = (total - free_after) / 1024**3
drop_gib = used_before_gib - used_after_gib
# --- Primary assertion: allocator reports zero tracked memory. ---
# If this fails it means weights were allocated outside the CuMem pool
# (safetensors direct-to-GPU bypass) — the exact regression this test
# is designed to catch.
if allocator is not None:
tracked_after = allocator.get_current_usage()
assert tracked_after == 0, (
f"CuMemAllocator still tracks {tracked_after / 1024**3:.3f} GiB "
f"after sleep(level=1) on custom_pipeline path "
f"(was {tracked_before / 1024**3:.3f} GiB before sleep). "
"Weights were allocated outside the CuMem pool via the "
"safetensors direct-to-GPU fast path — loader-context fix "
"may not be applied."
)
# --- Secondary assertion: physical VRAM or ACK freed_bytes confirms
# reclamation at the driver level.
total_freed_bytes = sum(
(ack.freed_bytes if hasattr(ack, "freed_bytes") else ack.get("freed_bytes", 0))
for ack in acks
if ack is not None
)
freed_gib = total_freed_bytes / 1024**3
assert freed_gib > 0 or drop_gib > 0, (
f"Expected GPU memory to be reclaimed after sleep(level=1) on "
f"custom_pipeline + enable_sleep_mode=True. "
f"CuMemAllocator tracked before={tracked_before / 1024**3:.3f} GiB, "
f"ACK freed={freed_gib:.3f} GiB, global VRAM drop={drop_gib:.3f} GiB."
)
# Engine must report it is sleeping.
assert await engine.is_sleeping()
# Wake up and confirm the engine is functional again.
await engine.wake_up()
assert not await engine.is_sleeping()
@@ -1,254 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""E2E tests for AsyncOmni Qwen-Image generation with trajectory_* fields.
Validates that the custom Qwen-Image pipeline returns structured trajectory
outputs (latents, timesteps, log_probs) via OmniRequestOutput's trajectory_*
fields instead of the legacy custom_output dict.
"""
from __future__ import annotations
import asyncio
import uuid
from contextlib import ExitStack
from functools import lru_cache
import numpy as np
import pytest
from transformers import AutoTokenizer
from tests.helpers.mark import hardware_test
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.outputs import OmniRequestOutput
CUSTOM_PIPELINE_CLASS = (
"tests.e2e.offline_inference.custom_pipeline.qwen_image_pipeline_with_logprob.QwenImagePipelineWithLogProbForTest"
)
WORKER_EXTENSION_CLASS = (
"tests.e2e.offline_inference.custom_pipeline.worker_extension.vLLMOmniColocateWorkerExtensionForTest"
)
# Use your specified HF repo name/path directly here
MODEL = "tiny-random/Qwen-Image"
TOKENIZER_MODEL = "Qwen/Qwen2-1.5B-Instruct"
# ---------------------------------------------------------------------
# 👇 Test Helper Functions & Fixtures 👇
# ---------------------------------------------------------------------
_MIN_PROMPT_TOKENS = 35
def normalize_token_ids(tokenized_output) -> list[int]:
"""Normalize tokenizer outputs into a flat ``list[int]``.
This handles Transformers 4/5 differences where ``apply_chat_template(tokenize=True)``
may return either ``list[int]`` or a ``BatchEncoding``/mapping with ``input_ids``.
"""
token_ids = tokenized_output
if isinstance(tokenized_output, dict):
if "input_ids" in tokenized_output:
token_ids = tokenized_output["input_ids"]
elif hasattr(tokenized_output, "input_ids"):
token_ids = tokenized_output.input_ids
if hasattr(token_ids, "tolist"):
token_ids = token_ids.tolist()
if isinstance(token_ids, tuple):
token_ids = list(token_ids)
if isinstance(token_ids, list) and len(token_ids) == 1 and isinstance(token_ids[0], list | tuple):
token_ids = list(token_ids[0])
if not isinstance(token_ids, list):
raise TypeError(f"token_ids must be list-like token ids, got {type(token_ids).__name__}: {token_ids!r}")
normalized_ids = []
for idx, token_id in enumerate(token_ids):
if hasattr(token_id, "item"):
token_id = token_id.item()
try:
normalized_ids.append(int(token_id))
except (TypeError, ValueError) as e:
raise TypeError(f"token_id must be int-convertible, got {type(token_id).__name__}: {token_id!r}") from e
return normalized_ids
@lru_cache(maxsize=1)
def _tokenize_prompt(text: str) -> list[int]:
"""Tokenize a text prompt into valid token IDs for the model."""
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_MODEL, trust_remote_code=True)
messages = [{"role": "user", "content": text}]
token_ids = normalize_token_ids(tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=False))
assert len(token_ids) > _MIN_PROMPT_TOKENS, (
f"Prompt too short ({len(token_ids)} tokens, need >{_MIN_PROMPT_TOKENS}). "
f"The pipeline drops the first 34 chat‑template prefix tokens; "
f"use a longer prompt so content tokens remain after the drop."
)
return token_ids
def _sampling_params(*, logprobs: bool = False, seed: int = 42) -> OmniDiffusionSamplingParams:
return OmniDiffusionSamplingParams(
num_inference_steps=2,
guidance_scale=0.0,
height=256,
width=256,
seed=seed,
extra_args={"logprobs": logprobs},
)
async def _generate_once(
engine: AsyncOmni,
prompt: str | list[int] | dict,
*,
request_id: str,
sampling_params: OmniDiffusionSamplingParams,
) -> OmniRequestOutput:
# Convert text prompt to dict with tokenized prompt_ids
if isinstance(prompt, str):
prompt_ids = _tokenize_prompt(prompt)
prompt = {"prompt_ids": prompt_ids}
elif isinstance(prompt, list):
prompt = {"prompt_ids": prompt}
# else: assume it's already a dict with prompt_ids
last_output = None
async for output in engine.generate(
prompt=prompt,
request_id=request_id,
sampling_params_list=[sampling_params],
output_modalities=["image"],
):
last_output = output
assert last_output is not None
assert isinstance(last_output, OmniRequestOutput)
return last_output
def _assert_valid_image_output(output: OmniRequestOutput) -> None:
assert output.final_output_type == "image"
assert output.images, "Expected at least one generated image"
image = output.images[0]
arr = np.asarray(image, dtype=np.float32) / 255.0
assert arr.ndim == 3 and arr.shape[2] == 3, f"Expected HWC RGB image, got shape={arr.shape}"
assert arr.shape[0] > 0 and arr.shape[1] > 0
assert 0.0 <= float(arr[0, 0, 0]) <= 1.0
@pytest.mark.core_model
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.asyncio
async def test_async_omni_generate():
with ExitStack() as after:
engine = AsyncOmni(
model=MODEL,
custom_pipeline_args={"pipeline_class": CUSTOM_PIPELINE_CLASS},
worker_extension_cls=WORKER_EXTENSION_CLASS,
enforce_eager=True,
max_num_seqs=1,
)
after.callback(engine.shutdown)
output = await _generate_once(
engine,
"a beautiful sunset over the ocean with vibrant orange and purple clouds "
"reflecting on the calm water surface near a rocky coastline",
request_id=f"test_{uuid.uuid4().hex[:8]}",
sampling_params=_sampling_params(logprobs=False, seed=42),
)
_assert_valid_image_output(output)
@pytest.mark.core_model
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.asyncio
async def test_async_omni_generate_with_logprobs():
with ExitStack() as after:
engine = AsyncOmni(
model=MODEL,
custom_pipeline_args={"pipeline_class": CUSTOM_PIPELINE_CLASS},
worker_extension_cls=WORKER_EXTENSION_CLASS,
enforce_eager=True,
max_num_seqs=1,
)
after.callback(engine.shutdown)
output = await _generate_once(
engine,
"a futuristic city at night with neon lights glowing on tall glass "
"skyscrapers and flying vehicles soaring between the buildings",
request_id=f"test_lp_{uuid.uuid4().hex[:8]}",
sampling_params=_sampling_params(logprobs=True, seed=123),
)
_assert_valid_image_output(output)
assert output.trajectory_latents is not None, "trajectory_latents should be present"
assert hasattr(output.trajectory_latents, "shape")
assert output.trajectory_latents.numel() > 0
assert output.trajectory_timesteps is not None, "trajectory_timesteps should be present"
assert hasattr(output.trajectory_timesteps, "shape")
assert output.trajectory_timesteps.numel() > 0
assert output.trajectory_log_probs is not None, "trajectory_log_probs should be present when logprobs=True"
assert hasattr(output.trajectory_log_probs, "shape")
assert output.trajectory_log_probs.numel() > 0
@pytest.mark.core_model
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.asyncio
async def test_async_omni_generate_concurrent():
with ExitStack() as after:
engine = AsyncOmni(
model=MODEL,
custom_pipeline_args={"pipeline_class": CUSTOM_PIPELINE_CLASS},
worker_extension_cls=WORKER_EXTENSION_CLASS,
enforce_eager=True,
max_num_seqs=1,
)
after.callback(engine.shutdown)
prompts = [
"a beautiful sunset over the ocean with vibrant orange and purple clouds "
"reflecting on the calm water surface near a rocky coastline",
"a fluffy orange cat sitting on a wooden windowsill looking outside at "
"a garden full of colorful flowers on a bright sunny afternoon",
"a majestic mountain landscape covered with fresh white snow under a "
"clear blue sky with pine trees in the foreground and a frozen lake",
"a futuristic city at night with neon lights glowing on tall glass "
"skyscrapers and flying vehicles soaring between the buildings",
]
tasks = [
_generate_once(
engine,
prompt,
request_id=f"concurrent_{i}_{uuid.uuid4().hex[:8]}",
sampling_params=_sampling_params(logprobs=False, seed=100 + i),
)
for i, prompt in enumerate(prompts)
]
outputs = await asyncio.gather(*tasks)
assert len(outputs) == len(prompts)
for output in outputs:
_assert_valid_image_output(output)
@@ -1,57 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from contextlib import ExitStack
import pytest
from tests.e2e.offline_inference.custom_pipeline.qwen_image_pipeline_with_logprob import (
QwenImagePipelineWithLogProbForTest,
)
from tests.e2e.offline_inference.custom_pipeline.worker_extension import (
vLLMOmniColocateWorkerExtensionForTest,
)
from tests.helpers.mark import hardware_test
from vllm_omni.diffusion.worker.diffusion_worker import CustomPipelineWorkerExtension
from vllm_omni.entrypoints.async_omni import AsyncOmni
CUSTOM_PIPELINE_CLASS = QwenImagePipelineWithLogProbForTest
WORKER_EXTENSION_CLASS = (
"tests.e2e.offline_inference.custom_pipeline.worker_extension.vLLMOmniColocateWorkerExtensionForTest"
)
MODEL = "tiny-random/Qwen-Image"
pytestmark = [pytest.mark.core_model]
@pytest.mark.cpu
def test_worker_extension_inheritance():
assert issubclass(vLLMOmniColocateWorkerExtensionForTest, CustomPipelineWorkerExtension)
@pytest.mark.cpu
def test_worker_extension_test_function():
assert (
vLLMOmniColocateWorkerExtensionForTest.test_extension_name() == "vllm-omni-colocate-worker-extension-for-test"
)
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.asyncio
async def test_collective_rpc_test_extension_name():
with ExitStack() as after:
engine = AsyncOmni(
model=MODEL,
custom_pipeline_args={"pipeline_class": CUSTOM_PIPELINE_CLASS},
worker_extension_cls=WORKER_EXTENSION_CLASS,
enforce_eager=True,
)
after.callback(engine.shutdown)
result = await engine.collective_rpc(method="test_extension_name")
assert isinstance(result, list), f"Expected list, got {type(result)}"
assert result == [["vllm-omni-colocate-worker-extension-for-test"]]
@@ -1,77 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Test worker extension that mirrors
``verl_omni.workers.rollout.vllm_rollout.utils.vLLMOmniColocateWorkerExtension``
Fidelity goals:
* ``__new__`` calls ``set_death_signal()`` (Linux ``PR_SET_PDEATHSIG``) so
spawned vLLM workers die with the parent.
* ``__new__`` calls ``VLLMOmniHijackForTest.hijack()`` which monkey-patches
``vllm_omni.diffusion.lora.manager.DiffusionLoRAManager._load_adapter``
to accept in-memory LoRA tensors (verbatim port of
``verl_omni.utils.vllm_omni.utils.VLLMOmniHijack.hijack``).
The ``verl.utils.vllm.VLLMHijack.hijack()`` call (which patches vLLM's
``LRUCacheWorkerLoRAManager._load_adapter`` for AR/text mode) is
intentionally skipped because (a) ``verl`` is not importable from this
repo and (b) the diffusion test path never reaches that manager.
"""
from __future__ import annotations
import ctypes
import logging
import os
import platform
import signal
from msgspec import field
from vllm_omni.diffusion.worker.diffusion_worker import CustomPipelineWorkerExtension
from vllm_omni.lora.request import LoRARequest as OmniLoRARequest
logger = logging.getLogger(__name__)
class OmniTensorLoRARequestForTest(OmniLoRARequest):
peft_config: dict = field(default=None)
lora_tensors: dict = field(default=None)
def set_death_signal() -> None:
"""Verbatim port of ``verl.workers.rollout.vllm_rollout.utils.set_death_signal``."""
if platform.system() != "Linux":
return
try:
libc = ctypes.CDLL("libc.so.6")
libc.prctl(1, signal.SIGKILL)
if os.getppid() == 1:
os.kill(os.getpid(), signal.SIGKILL)
except Exception: # noqa: BLE001
# libc.so.6 may not be present (musl, alpine) — best-effort only.
pass
# ---------------------------------------------------------------------
# The worker extension itself
# ---------------------------------------------------------------------
class vLLMOmniColocateWorkerExtensionForTest(CustomPipelineWorkerExtension):
"""Mirror of ``vLLMOmniColocateWorkerExtension`` (verl-omni).
The production ``__new__`` runs ``set_death_signal`` + ``VLLMOmniHijack.hijack``
on every vLLM worker process. Replicating both ensures this test
reproduces the same monkey-patched environment.
"""
def __new__(cls, **kwargs):
set_death_signal()
return super().__new__(cls)
@staticmethod
def test_extension_name() -> str:
"""Return a stable identifier for assertions in unit tests."""
return "vllm-omni-colocate-worker-extension-for-test"
Whitespace-only changes.
@@ -1,592 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""E2E test that follows the EXACT same flow as
``verl-omni/tests/workers/rollout/rollout_vllm/test_vllm_omni_generate.py``
but inlines all the ``verl`` / ``verl_omni`` symbols the flow depends on
(stripped down to only what the diffusion-mode test actually exercises).
Flow (identical to the verl-omni test):
1. Build two ``OmegaConf`` configs (``DiffusionRolloutConfig`` /
``DiffusionModelConfig`` shape).
2. ``ServerCls = ray.remote(vLLMOmniHttpServerLocal)`` then
``ServerCls.options(...).remote(config=..., model_config=...,
rollout_mode=RolloutMode.STANDALONE, workers=[], replica_rank=0,
node_rank=0, gpus_per_node=1, nnodes=1, cuda_visible_devices="0")``.
3. ``ray.get(server.launch_server.remote())``.
4. ``server.generate.remote(prompt_ids=..., sampling_params=..., request_id=...)``
and assert the returned ``DiffusionOutput``.
The inlined classes / helpers mirror their ``verl`` / ``verl_omni``
counterparts; bits not reached by this test (AR mode, LoRA,
quantization, run_uvicorn, headless, profiler, port wiring) are removed.
Usage:
pytest tests/e2e/offline_inference/rlhf_test/\
test_ray_async_omni_qwen_image_generate.py -v -s
"""
from __future__ import annotations
import argparse
import json
import logging
import os
from dataclasses import asdict
from enum import Enum
from functools import lru_cache
from typing import Any
from uuid import uuid4
import pytest
import ray
import torch
import torchvision.transforms as T
from huggingface_hub import snapshot_download
from omegaconf import DictConfig, OmegaConf
from pydantic import BaseModel, ConfigDict
from transformers import AutoTokenizer
from vllm.entrypoints.openai.api_server import build_app
from vllm.utils.argparse_utils import FlexibleArgumentParser
import vllm_omni.entrypoints.cli.serve
from tests.helpers.mark import hardware_test
from vllm_omni.engine.arg_utils import OmniEngineArgs
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.entrypoints.openai.api_server import omni_init_app_state
from vllm_omni.inputs.data import OmniCustomPrompt, OmniDiffusionSamplingParams
from vllm_omni.outputs import OmniRequestOutput
logger = logging.getLogger(__name__)
CUSTOM_PIPELINE_CLASS = (
"tests.e2e.offline_inference.custom_pipeline.qwen_image_pipeline_with_logprob.QwenImagePipelineWithLogProbForTest"
)
WORKER_EXTENSION_CLASS = (
"tests.e2e.offline_inference.custom_pipeline.worker_extension.vLLMOmniColocateWorkerExtensionForTest"
)
# Use your specified HF repo name/path directly here
MODEL = "tiny-random/Qwen-Image"
TOKENIZER_MODEL = "Qwen/Qwen2-1.5B-Instruct"
def _resolve_model_path(repo_id: str) -> str:
"""Resolve an HF repo ID to a local snapshot path, downloading if needed."""
# Allow overriding with a pre-existing local path (skips download).
if os.path.isdir(repo_id):
return repo_id
return snapshot_download(repo_id=repo_id)
_MIN_PROMPT_TOKENS = 35
# ---------------------------------------------------------------------
# Inlined: verl.workers.rollout.replica.RolloutMode
# ---------------------------------------------------------------------
class RolloutMode(Enum):
HYBRID = "hybrid"
COLOCATED = "colocated"
STANDALONE = "standalone"
# ---------------------------------------------------------------------
# Inlined: verl_omni.workers.rollout.replica.DiffusionOutput
# ---------------------------------------------------------------------
class DiffusionOutput(BaseModel):
"""Pydantic mirror of ``verl_omni.workers.rollout.replica.DiffusionOutput``."""
model_config = ConfigDict(arbitrary_types_allowed=True)
diffusion_output: Any
log_probs: Any | None = None
stop_reason: str | None = None
num_preempted: int | None = None
extra_fields: dict[str, Any] = {}
# ---------------------------------------------------------------------
# Inlined: verl.utils.tokenizer.normalize_token_ids
# ---------------------------------------------------------------------
def normalize_token_ids(tokenized_output) -> list[int]:
token_ids = tokenized_output
if isinstance(tokenized_output, dict):
if "input_ids" in tokenized_output:
token_ids = tokenized_output["input_ids"]
elif hasattr(tokenized_output, "input_ids"):
token_ids = tokenized_output.input_ids
if hasattr(token_ids, "tolist"):
token_ids = token_ids.tolist()
if isinstance(token_ids, tuple):
token_ids = list(token_ids)
if isinstance(token_ids, list) and len(token_ids) == 1 and isinstance(token_ids[0], (list, tuple)):
token_ids = list(token_ids[0])
if not isinstance(token_ids, list):
raise TypeError(f"token_ids must be list-like, got {type(token_ids).__name__}")
out: list[int] = []
for tid in token_ids:
if hasattr(tid, "item"):
tid = tid.item()
out.append(int(tid))
return out
# ---------------------------------------------------------------------
# Inlined: verl.workers.rollout.vllm_rollout.utils.build_cli_args_from_config
# ---------------------------------------------------------------------
def build_cli_args_from_config(config: dict[str, Any]) -> list[str]:
cli_args: list[str] = []
for k, v in config.items():
if v is None:
continue
if isinstance(v, bool):
if v:
cli_args.append(f"--{k}")
elif isinstance(v, list):
if not v:
continue
cli_args.append(f"--{k}")
cli_args.extend([str(item) for item in v])
else:
cli_args.append(f"--{k}")
cli_args.append(json.dumps(v) if isinstance(v, dict) else str(v))
return cli_args
# ---------------------------------------------------------------------
# Tokenizer helper (test-side)
# ---------------------------------------------------------------------
@lru_cache(maxsize=1)
def _get_tokenizer():
return AutoTokenizer.from_pretrained(TOKENIZER_MODEL, trust_remote_code=True)
def _tokenize_prompt(text: str) -> list[int]:
tokenizer = _get_tokenizer()
messages = [{"role": "user", "content": text}]
token_ids = normalize_token_ids(tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=False))
assert len(token_ids) > _MIN_PROMPT_TOKENS, (
f"Prompt too short ({len(token_ids)} tokens, need >{_MIN_PROMPT_TOKENS}). "
"The pipeline drops the first 34 chat-template prefix tokens; "
"use a longer prompt so content tokens remain after the drop."
)
return token_ids
# ---------------------------------------------------------------------
# Inlined: vLLMOmniHttpServer (verl-omni) + relevant vLLMHttpServer (verl)
# bits, stripped to the diffusion-mode path the test exercises.
# ---------------------------------------------------------------------
def _cfg_get(cfg: Any, key: str, default: Any = None) -> Any:
"""Uniform getter that works for both DictConfig and dataclass-like objects."""
if isinstance(cfg, DictConfig):
return cfg.get(key, default)
return getattr(cfg, key, default)
class vLLMOmniHttpServerLocal:
"""Self-contained simulation of ``vLLMOmniHttpServer`` for diffusion mode.
Constructor signature matches ``vLLMHttpServer.__init__`` exactly so the
Ray-actor call site in the test is identical to the verl-omni one.
"""
# ------------------------------------------------------------------ init
def __init__(
self,
config,
model_config,
rollout_mode: RolloutMode,
workers: list,
replica_rank: int,
node_rank: int,
gpus_per_node: int,
nnodes: int,
cuda_visible_devices: str,
):
os.environ.setdefault("CUDA_VISIBLE_DEVICES", cuda_visible_devices)
os.environ["VERL_REPLICA_RANK"] = str(replica_rank)
# Resolve configs. verl uses omega_conf_to_dataclass; here we keep
# them as DictConfig — every read site below uses ``_cfg_get``.
self.config = OmegaConf.create(config) if not isinstance(config, DictConfig) else config
self.model_config = OmegaConf.create(model_config) if not isinstance(model_config, DictConfig) else model_config
self.rollout_mode = rollout_mode
self.workers = workers
self.replica_rank = replica_rank
self.node_rank = node_rank
self.gpus_per_node = gpus_per_node
self.nnodes = nnodes
self.global_steps = 0
self.engine: AsyncOmni | None = None
# Diffusion-mode parity with ``vLLMOmniHttpServer._post_init``.
self._to_tensor = T.PILToTensor()
logger.info(
"%s, replica_rank: %d, node_rank: %d, CUDA_VISIBLE_DEVICES: %s",
self.__class__.__name__,
replica_rank,
node_rank,
cuda_visible_devices,
)
# ---------------------------------------------------------- launch_server
async def launch_server(self) -> None:
"""Diffusion-only mirror of ``vLLMHttpServer.launch_server``."""
# vLLMOmniHttpServer._get_engine_kwargs_key() returns "vllm_omni".
engine_kwargs_root = _cfg_get(self.config, "engine_kwargs", {}) or {}
if isinstance(engine_kwargs_root, (dict, DictConfig)):
engine_kwargs = engine_kwargs_root.get("vllm_omni", {}) or {}
else:
engine_kwargs = {}
engine_kwargs = {k: v for k, v in dict(engine_kwargs).items() if v is not None}
# vLLMOmniHttpServer._preprocess_engine_kwargs (diffusion path).
engine_kwargs.pop("output_mode", None)
# ``compilation_config`` handling — verbatim from parent launch_server.
compilation_config = engine_kwargs.pop("compilation_config", None) or {}
if isinstance(compilation_config, str):
compilation_config = json.loads(compilation_config)
if isinstance(compilation_config, DictConfig):
compilation_config = OmegaConf.to_container(compilation_config, resolve=True)
compilation_config.setdefault("cudagraph_mode", "FULL_AND_PIECEWISE")
compilation_config = json.dumps(compilation_config)
# Args dict (subset of parent's; the diffusion override drops AR-only
# entries via ``_get_override_generation_config`` returning ``{}``).
args = {
"dtype": _cfg_get(self.config, "dtype", "bfloat16"),
"load_format": _cfg_get(self.config, "load_format", "auto"),
"skip_tokenizer_init": False,
"distributed_executor_backend": "mp",
"worker_extension_cls": WORKER_EXTENSION_CLASS,
"trust_remote_code": _cfg_get(self.model_config, "trust_remote_code", True),
"max_model_len": _cfg_get(self.config, "max_model_len", 1058),
"max_num_seqs": _cfg_get(self.config, "max_num_seqs", 1),
"enable_chunked_prefill": _cfg_get(self.config, "enable_chunked_prefill", False),
"max_num_batched_tokens": _cfg_get(self.config, "max_num_batched_tokens", 8192),
"enable_prefix_caching": _cfg_get(self.config, "enable_prefix_caching", False),
"enable_sleep_mode": _cfg_get(self.config, "enable_sleep_mode", False),
"logprobs_mode": _cfg_get(self.config, "logprobs_mode", "processed_logprobs"),
"enforce_eager": _cfg_get(self.config, "enforce_eager", True),
"gpu_memory_utilization": _cfg_get(self.config, "gpu_memory_utilization", 0.8),
"disable_log_stats": _cfg_get(self.config, "disable_log_stats", True),
"tensor_parallel_size": _cfg_get(self.config, "tensor_model_parallel_size", 1),
"seed": self.replica_rank + int(_cfg_get(self.config, "seed", 0) or 0),
"override_generation_config": json.dumps({}),
"scheduling_policy": _cfg_get(self.config, "scheduling_policy", "fcfs"),
"compilation_config": compilation_config,
**engine_kwargs,
}
model_path = str(_cfg_get(self.model_config, "local_path", None) or _cfg_get(self.model_config, "path"))
server_args_list = ["serve", model_path] + build_cli_args_from_config(args)
# Same parser pipeline as parent launch_server (with vllm-omni's
# cmd_init injected, matching ``_get_cli_modules`` + ``_get_cli_description``).
parser = FlexibleArgumentParser(description="vLLM-Omni CLI")
subparsers = parser.add_subparsers(required=False, dest="subparser")
cmds: dict[str, Any] = {}
for cmd in vllm_omni.entrypoints.cli.serve.cmd_init():
cmd.subparser_init(subparsers).set_defaults(dispatch_function=cmd.cmd)
cmds[cmd.name] = cmd
parsed = parser.parse_args(args=server_args_list)
parsed.model = parsed.model_tag
if parsed.subparser in cmds:
cmds[parsed.subparser].validate(parsed)
# node_rank == 0 → run_server (the test never sets node_rank != 0).
await self.run_server(parsed)
# ------------------------------------------------------------- run_server
async def run_server(self, args: argparse.Namespace) -> None:
"""Diffusion branch of ``vLLMOmniHttpServer.run_server``."""
engine_args = OmniEngineArgs.from_cli_args(args)
engine_args = asdict(engine_args)
# Diffusion path: pin the in-repo test pipeline. The production code
# calls ``VllmOmniPipelineBase.get_pipeline_path(architecture)``; we
# bypass the registry and bind the test pipeline directly.
engine_args["enable_dummy_pipeline"] = True
engine_args["custom_pipeline_args"] = {"pipeline_class": CUSTOM_PIPELINE_CLASS}
engine_client = AsyncOmni(**engine_args)
app = build_app(args)
await omni_init_app_state(engine_client, app.state, args)
self.engine = engine_client
# ``run_uvicorn`` intentionally skipped — the test drives the engine
# via Ray RPC, not HTTP.
# ---------------------------------------------------------------- generate
async def generate(
self,
prompt_ids: list[int],
sampling_params: dict[str, Any],
request_id: str,
image_data: list[Any] | None = None,
video_data: list[Any] | None = None,
negative_prompt_ids: list[int] | None = None,
priority: int = 0, # noqa: ARG002 (signature parity)
) -> DiffusionOutput:
# Verbatim copy of ``vLLMOmniHttpServer._generate_diffusion`` minus
# the LoRA branch (the test does not enable ``lora_as_adapter``).
prompt_ids = normalize_token_ids(prompt_ids)
multi_modal_data: dict[str, Any] = {}
if image_data is not None:
multi_modal_data["image"] = image_data
if video_data is not None:
multi_modal_data["video"] = video_data
custom_prompt: OmniCustomPrompt = {"prompt_ids": prompt_ids}
if negative_prompt_ids is not None:
custom_prompt["negative_prompt_ids"] = negative_prompt_ids
if multi_modal_data:
custom_prompt["extra_args"] = {"multi_modal_data": multi_modal_data}
sampling_kwargs: dict[str, Any] = {}
extra_args: dict[str, Any] = {}
for k, v in sampling_params.items():
if hasattr(OmniDiffusionSamplingParams, k):
sampling_kwargs[k] = v
else:
extra_args[k] = v
sampling_kwargs["extra_args"] = extra_args
diffusion_sampling_params = OmniDiffusionSamplingParams(**sampling_kwargs)
generator = self.engine.generate(
prompt=custom_prompt,
request_id=request_id,
sampling_params_list=[diffusion_sampling_params],
)
final_res: OmniRequestOutput | None = None
async for output in generator:
final_res = output
assert final_res is not None
diffusion_output = self._to_tensor(final_res.images[0]).float() / 255.0
metadata = (
final_res.multimodal_output.get("metadata", {}) if isinstance(final_res.multimodal_output, dict) else {}
)
prompt_embeddings = metadata.get("prompt_embeddings", {}) if isinstance(metadata, dict) else {}
if sampling_params.get("logprobs", False):
all_log_probs = final_res.trajectory_log_probs
log_probs = all_log_probs[0] if all_log_probs is not None else None
else:
log_probs = None
all_latents = final_res.trajectory_latents
all_timesteps = final_res.trajectory_timesteps
prompt_embeds = prompt_embeddings.get("prompt_embeds")
prompt_embeds_mask = prompt_embeddings.get("prompt_embeds_mask")
negative_prompt_embeds = prompt_embeddings.get("negative_prompt_embeds")
negative_prompt_embeds_mask = prompt_embeddings.get("negative_prompt_embeds_mask")
extra_fields = {
"all_latents": all_latents[0] if all_latents is not None else None,
"all_timesteps": all_timesteps[0] if all_timesteps is not None else None,
"prompt_embeds": prompt_embeds[0] if prompt_embeds is not None else None,
"prompt_embeds_mask": prompt_embeds_mask[0] if prompt_embeds_mask is not None else None,
"negative_prompt_embeds": negative_prompt_embeds[0] if negative_prompt_embeds is not None else None,
"negative_prompt_embeds_mask": (
negative_prompt_embeds_mask[0] if negative_prompt_embeds_mask is not None else None
),
"global_steps": self.global_steps,
}
req_output = final_res.request_output
if req_output is not None and hasattr(req_output, "finish_reason"):
finish_reason = req_output.finish_reason or "stop"
else:
finish_reason = "stop"
if finish_reason == "abort":
stop_reason = "aborted"
elif finish_reason in ("stop", "length"):
stop_reason = "completed"
else:
stop_reason = finish_reason
num_preempted = None
if req_output is not None and hasattr(req_output, "num_preempted"):
num_preempted = req_output.num_preempted
return DiffusionOutput(
diffusion_output=diffusion_output,
log_probs=log_probs,
stop_reason=stop_reason,
num_preempted=num_preempted,
extra_fields=extra_fields,
)
# ---------------------------------------------------------------------
# Fixtures & tests
# ---------------------------------------------------------------------
@pytest.fixture
def init_server():
"""Create and launch a vLLMOmniHttpServerLocal Ray actor with Qwen-Image."""
model_path = _resolve_model_path(MODEL)
ray.init(
runtime_env={
"env_vars": {
"TOKENIZERS_PARALLELISM": "true",
"NCCL_DEBUG": "WARN",
"VLLM_LOGGING_LEVEL": "INFO",
}
},
ignore_reinit_error=True,
)
rollout_cfg = OmegaConf.create(
{
"name": "vllm_omni",
"mode": "async",
"tensor_model_parallel_size": 1,
"data_parallel_size": 1,
"pipeline_model_parallel_size": 1,
"gpu_memory_utilization": 0.8,
"max_num_batched_tokens": 8192,
# The custom log-prob pipeline only supports serial requests.
"max_num_seqs": 1,
"max_model_len": 1058,
"dtype": "bfloat16",
"load_format": "auto",
"enforce_eager": True,
"enable_chunked_prefill": False,
"enable_prefix_caching": False,
"enable_sleep_mode": False,
"free_cache_engine": True,
"disable_log_stats": True,
"logprobs_mode": "processed_logprobs",
"scheduling_policy": "fcfs",
"seed": 0,
"n": 4,
"pipeline": {
"height": 512,
"width": 512,
"num_inference_steps": 10,
},
}
)
model_cfg = OmegaConf.create(
{
"path": str(model_path),
"local_path": str(model_path),
"tokenizer_path": TOKENIZER_MODEL,
"trust_remote_code": True,
"load_tokenizer": True,
}
)
ServerCls = ray.remote(vLLMOmniHttpServerLocal)
server = ServerCls.options(
runtime_env={
"env_vars": {
"RAY_EXPERIMENTAL_NOSET_CUDA_VISIBLE_DEVICES": "1",
"RAY_EXPERIMENTAL_NOSET_ASCEND_RT_VISIBLE_DEVICES": "1",
"NCCL_CUMEM_ENABLE": "0",
}
},
max_concurrency=10,
num_gpus=1,
).remote(
config=rollout_cfg,
model_config=model_cfg,
rollout_mode=RolloutMode.STANDALONE,
workers=[],
replica_rank=0,
node_rank=0,
gpus_per_node=1,
nnodes=1,
cuda_visible_devices="0",
)
ray.get(server.launch_server.remote())
yield server
ray.shutdown()
@pytest.mark.core_model
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4"}, num_cards=1)
def test_generate(init_server):
"""Concurrent generate() calls covering basic output, logprobs, and multi-request correctness."""
server = init_server
prompts = [
"a beautiful sunset over the ocean with vibrant orange and purple clouds "
"reflecting on the calm water surface near a rocky coastline",
"a fluffy orange cat sitting on a wooden windowsill looking outside at "
"a garden full of colorful flowers on a bright sunny afternoon",
"a majestic mountain landscape covered with fresh white snow under a "
"clear blue sky with pine trees in the foreground and a frozen lake",
"a futuristic city at night with neon lights glowing on tall glass "
"skyscrapers and flying vehicles soaring between the buildings",
]
refs = []
for i, prompt in enumerate(prompts):
rid = f"test_{i}_{uuid4().hex[:8]}"
ref = server.generate.remote(
prompt_ids=_tokenize_prompt(prompt),
sampling_params={
"num_inference_steps": 10,
"true_cfg_scale": 4.0,
"height": 512,
"width": 512,
"logprobs": i == 0, # first request includes logprobs
},
request_id=rid,
)
refs.append(ref)
results = ray.get(refs, timeout=600)
for i, output in enumerate(results):
assert isinstance(output, DiffusionOutput), f"Request {i}: expected DiffusionOutput"
img = output.diffusion_output
assert isinstance(img, torch.Tensor) and img.ndim == 3, (
f"Request {i}: expected CHW torch.Tensor, got {type(img).__name__} ndim={getattr(img, 'ndim', None)}"
)
c, h, w = img.shape
assert c == 3, f"Request {i}: expected 3 channels (CHW), got {c}"
assert h > 0 and w > 0, f"Request {i}: image dimensions must be positive"
assert output.stop_reason in ("completed", "aborted", None), (
f"Request {i}: unexpected stop_reason {output.stop_reason!r}"
)
assert 0.0 <= float(img[0, 0, 0]) <= 1.0, f"Request {i}: pixel values must be in [0, 1]"
print(f"All {len(prompts)} concurrent requests returned valid DiffusionOutput")
@@ -1,37 +0,0 @@
# Stage config for Step-Audio2 CI tests
# Single Thinker stage (audio/text understanding → text). ASR/text-output
# tests don't need Token2Wav; a two-stage config would deadlock on stage-1 skip.
# The following config has been verified on 2x 24GB GPU (L4/RTX3090/RTX4090).
stage_args:
- stage_id: 0
runtime:
process: true
devices: "0"
max_batch_size: 1
engine_args:
model_stage: thinker
model_arch: StepAudio2ThinkerForConditionalGeneration
tensor_parallel_size: 1
worker_cls: vllm_omni.worker.gpu_ar_worker.GPUARWorker
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
max_model_len: 4096
max_num_batched_tokens: 4096
max_num_seqs: 1
gpu_memory_utilization: 0.8
skip_mm_profiling: true
enforce_eager: true
trust_remote_code: true
enable_prefix_caching: false
engine_output_type: text # Output text + audio tokens
is_comprehension: true
final_output: true
final_output_type: text
default_sampling_params:
temperature: 0.7
top_p: 0.9
top_k: -1
max_tokens: 256
seed: 42
detokenize: true
repetition_penalty: 1.05
@@ -38,7 +38,7 @@ if not PROMPT_AUDIO.is_file() or not TARGET_AUDIO.is_file():
allow_module_level=True,
)
pytestmark = [pytest.mark.advanced_model, pytest.mark.diffusion, pytest.mark.tts]
pytestmark = [pytest.mark.slow, pytest.mark.diffusion, pytest.mark.tts]
_CASES = (
pytest.param(
@@ -6,7 +6,6 @@ E2E expansion tests for Step-Audio2 offline inference (nightly CI).
Full-model inference with audio input and audio output.
"""
from pathlib import Path
from typing import Any
import numpy as np
@@ -15,10 +14,11 @@ import pytest
from tests.helpers.mark import hardware_test
from tests.helpers.media import generate_synthetic_audio
from tests.helpers.runtime import OmniRunner
from tests.helpers.stage_config import get_deploy_config_path
from vllm_omni.outputs import OmniRequestOutput
MODEL = "stepfun-ai/Step-Audio-2-mini"
STAGE_CONFIG = str(Path(__file__).parent / "stage_configs" / "step_audio2_ci.yaml")
STAGE_CONFIG = get_deploy_config_path("step_audio2_thinker_ci.yaml")
TEST_PARAMS = [(MODEL, STAGE_CONFIG)]
pytestmark = [pytest.mark.slow, pytest.mark.tts]