Merge remote-tracking branch 'origin/main' into dev/vllm-align
This commit is contained in:
commit
97899c6c98
47 files changed
+4161
-470
No files matched your search
@@ -82,6 +82,15 @@ DIFFUSION_SINGLE_SAMPLING_PARAMS = DiffusionSamplingParams(
|
||||
}
|
||||
)
|
||||
|
||||
DIFFUSION_VIDEO_SINGLE_SAMPLING_PARAMS = DiffusionSamplingParams(
|
||||
{
|
||||
"num_inference_steps": 30,
|
||||
"guidance_scale": 6.0,
|
||||
"true_cfg_scale": 1.5,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
AR_LIST_SAMPLING_PARAMS = [
|
||||
AutoregressionSamplingParams(
|
||||
{
|
||||
@@ -310,8 +319,8 @@ def _build_mock_outputs(outputs: Iterable[OmniRequestOutput], sampling_case: Sam
|
||||
)
|
||||
elif sampling_case.kind is SamplingKind.VIDEO_DIFFUSION_SINGLE:
|
||||
assert len(received_sampling_params_list) == 1
|
||||
expected = DIFFUSION_SINGLE_SAMPLING_PARAMS.copy()
|
||||
expected["num_outputs_per_prompt"] = expected.pop("n") # convert from n to num_outputs_per_prompt
|
||||
expected = DIFFUSION_VIDEO_SINGLE_SAMPLING_PARAMS.copy()
|
||||
# expected["num_outputs_per_prompt"] = expected.pop("n") # convert from n to num_outputs_per_prompt
|
||||
_assert_sampling_param_values(
|
||||
received_sampling_params_list[0],
|
||||
{
|
||||
@@ -690,7 +699,7 @@ async def test_tts_nodes(api_server: str, node_cls, call_kwargs: dict, sampling_
|
||||
pytest.param(
|
||||
SamplingCase(
|
||||
kind=SamplingKind.VIDEO_DIFFUSION_SINGLE,
|
||||
sampling_params=DIFFUSION_SINGLE_SAMPLING_PARAMS,
|
||||
sampling_params=DIFFUSION_VIDEO_SINGLE_SAMPLING_PARAMS,
|
||||
lora=LORA_PARAMS,
|
||||
),
|
||||
id="single-diffusion-sampling-params",
|
||||
|
||||
@@ -17,12 +17,14 @@ import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
# import pytest
|
||||
import torch
|
||||
from PIL import Image
|
||||
from vllm.distributed.parallel_state import cleanup_dist_env_and_memory
|
||||
|
||||
from tests.utils import DeviceMemoryMonitor, hardware_test
|
||||
# from tests.utils import DeviceMemoryMonitor, hardware_test
|
||||
from tests.utils import DeviceMemoryMonitor
|
||||
from vllm_omni import Omni
|
||||
from vllm_omni.diffusion.data import DiffusionParallelConfig
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
@@ -155,69 +157,69 @@ def _run_zimage_generate(
|
||||
cleanup_dist_env_and_memory()
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.parallel
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards={"cuda": 4, "rocm": 2})
|
||||
def test_zimage_tensor_parallel_tp2(tmp_path: Path):
|
||||
if current_omni_platform.is_npu() or current_omni_platform.is_rocm():
|
||||
pytest.skip("Z-Image TP e2e test is only supported on CUDA for now.")
|
||||
if not current_omni_platform.is_available() or current_omni_platform.device_count() < 2:
|
||||
pytest.skip("Z-Image TP=2 requires >= 2 devices.")
|
||||
# @pytest.mark.advanced_model
|
||||
# @pytest.mark.diffusion
|
||||
# @pytest.mark.parallel
|
||||
# @hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards={"cuda": 4, "rocm": 2})
|
||||
# def test_zimage_tensor_parallel_tp2(tmp_path: Path):
|
||||
# if current_omni_platform.is_npu() or current_omni_platform.is_rocm():
|
||||
# pytest.skip("Z-Image TP e2e test is only supported on CUDA for now.")
|
||||
# if not current_omni_platform.is_available() or current_omni_platform.device_count() < 2:
|
||||
# pytest.skip("Z-Image TP=2 requires >= 2 devices.")
|
||||
|
||||
enforce_eager = False
|
||||
# enforce_eager = False
|
||||
|
||||
height = 512
|
||||
width = 512
|
||||
num_inference_steps = 2
|
||||
seed = 42
|
||||
# height = 512
|
||||
# width = 512
|
||||
# num_inference_steps = 2
|
||||
# seed = 42
|
||||
|
||||
tp1_img, tp1_time_s, tp1_peak_mem = _run_zimage_generate(
|
||||
tp_size=1,
|
||||
height=height,
|
||||
width=width,
|
||||
num_inference_steps=num_inference_steps,
|
||||
seed=seed,
|
||||
enforce_eager=enforce_eager,
|
||||
)
|
||||
tp2_img, tp2_time_s, tp2_peak_mem = _run_zimage_generate(
|
||||
tp_size=2,
|
||||
height=height,
|
||||
width=width,
|
||||
num_inference_steps=num_inference_steps,
|
||||
seed=seed,
|
||||
enforce_eager=enforce_eager,
|
||||
)
|
||||
# tp1_img, tp1_time_s, tp1_peak_mem = _run_zimage_generate(
|
||||
# tp_size=1,
|
||||
# height=height,
|
||||
# width=width,
|
||||
# num_inference_steps=num_inference_steps,
|
||||
# seed=seed,
|
||||
# enforce_eager=enforce_eager,
|
||||
# )
|
||||
# tp2_img, tp2_time_s, tp2_peak_mem = _run_zimage_generate(
|
||||
# tp_size=2,
|
||||
# height=height,
|
||||
# width=width,
|
||||
# num_inference_steps=num_inference_steps,
|
||||
# seed=seed,
|
||||
# enforce_eager=enforce_eager,
|
||||
# )
|
||||
|
||||
tp1_path = tmp_path / "zimage_tp1.png"
|
||||
tp2_path = tmp_path / "zimage_tp2.png"
|
||||
tp1_img.save(tp1_path)
|
||||
tp2_img.save(tp2_path)
|
||||
# tp1_path = tmp_path / "zimage_tp1.png"
|
||||
# tp2_path = tmp_path / "zimage_tp2.png"
|
||||
# tp1_img.save(tp1_path)
|
||||
# tp2_img.save(tp2_path)
|
||||
|
||||
assert tp1_img.width == width and tp1_img.height == height
|
||||
assert tp2_img.width == width and tp2_img.height == height
|
||||
# assert tp1_img.width == width and tp1_img.height == height
|
||||
# assert tp2_img.width == width and tp2_img.height == height
|
||||
|
||||
mean_abs_diff, p99_abs_diff = _diff_metrics(tp1_img, tp2_img)
|
||||
mean_threshold = 3e-2
|
||||
p99_threshold = 2.5e-1
|
||||
print(
|
||||
"Z-Image TP image diff stats (TP=1 vs TP=2): "
|
||||
f"mean_abs_diff={mean_abs_diff:.6e}, p99_abs_diff={p99_abs_diff:.6e}; "
|
||||
f"thresholds: mean<={mean_threshold:.6e}, p99<={p99_threshold:.6e}; "
|
||||
f"tp1_img={tp1_path}, tp2_img={tp2_path}"
|
||||
)
|
||||
assert mean_abs_diff <= mean_threshold and p99_abs_diff <= p99_threshold, (
|
||||
f"Image diff exceeded threshold: mean_abs_diff={mean_abs_diff:.6e}, p99_abs_diff={p99_abs_diff:.6e} "
|
||||
f"(thresholds: mean<={mean_threshold:.6e}, p99<={p99_threshold:.6e})"
|
||||
)
|
||||
# mean_abs_diff, p99_abs_diff = _diff_metrics(tp1_img, tp2_img)
|
||||
# mean_threshold = 3e-2
|
||||
# p99_threshold = 2.5e-1
|
||||
# print(
|
||||
# "Z-Image TP image diff stats (TP=1 vs TP=2): "
|
||||
# f"mean_abs_diff={mean_abs_diff:.6e}, p99_abs_diff={p99_abs_diff:.6e}; "
|
||||
# f"thresholds: mean<={mean_threshold:.6e}, p99<={p99_threshold:.6e}; "
|
||||
# f"tp1_img={tp1_path}, tp2_img={tp2_path}"
|
||||
# )
|
||||
# assert mean_abs_diff <= mean_threshold and p99_abs_diff <= p99_threshold, (
|
||||
# f"Image diff exceeded threshold: mean_abs_diff={mean_abs_diff:.6e}, p99_abs_diff={p99_abs_diff:.6e} "
|
||||
# f"(thresholds: mean<={mean_threshold:.6e}, p99<={p99_threshold:.6e})"
|
||||
# )
|
||||
|
||||
print(f"Z-Image TP perf (lower is better): tp1_time_s={tp1_time_s:.6f}, tp2_time_s={tp2_time_s:.6f}")
|
||||
assert tp2_time_s < tp1_time_s, f"Expected TP=2 to be faster than TP=1 (tp1={tp1_time_s}, tp2={tp2_time_s})"
|
||||
# print(f"Z-Image TP perf (lower is better): tp1_time_s={tp1_time_s:.6f}, tp2_time_s={tp2_time_s:.6f}")
|
||||
# assert tp2_time_s < tp1_time_s, f"Expected TP=2 to be faster than TP=1 (tp1={tp1_time_s}, tp2={tp2_time_s})"
|
||||
|
||||
print(f"Z-Image TP peak memory (MB): tp1_peak_mem={tp1_peak_mem:.2f}, tp2_peak_mem={tp2_peak_mem:.2f}")
|
||||
assert tp2_peak_mem < tp1_peak_mem, (
|
||||
f"Expected TP=2 to use less peak memory than TP=1 (tp1={tp1_peak_mem}, tp2={tp2_peak_mem})"
|
||||
)
|
||||
# print(f"Z-Image TP peak memory (MB): tp1_peak_mem={tp1_peak_mem:.2f}, tp2_peak_mem={tp2_peak_mem:.2f}")
|
||||
# assert tp2_peak_mem < tp1_peak_mem, (
|
||||
# f"Expected TP=2 to use less peak memory than TP=1 (tp1={tp1_peak_mem}, tp2={tp2_peak_mem})"
|
||||
# )
|
||||
|
||||
|
||||
# @pytest.mark.integration
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
E2E online serving tests for the async video generation API.
|
||||
|
||||
These tests exercise the real `/v1/videos` job lifecycle against a running
|
||||
diffusion model, including create, retrieve, list, download, and delete flows.
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tests.conftest import OmniServer
|
||||
from tests.utils import hardware_test
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
|
||||
|
||||
MODEL = "Wan-AI/Wan2.2-T2V-A14B-Diffusers"
|
||||
VIDEO_POLL_INTERVAL_S = 2.0
|
||||
VIDEO_TIMEOUT_S = 900.0
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def video_server():
|
||||
"""Start a real video generation server for async video API tests."""
|
||||
with OmniServer(
|
||||
MODEL,
|
||||
[
|
||||
"--num-gpus",
|
||||
"1",
|
||||
"--boundary-ratio",
|
||||
"0.875",
|
||||
"--flow-shift",
|
||||
"5.0",
|
||||
"--disable-log-stats",
|
||||
],
|
||||
) as server:
|
||||
yield server
|
||||
|
||||
|
||||
def _video_api_url(server: OmniServer, suffix: str = "") -> str:
|
||||
return f"http://{server.host}:{server.port}/v1/videos{suffix}"
|
||||
|
||||
|
||||
def _multipart_fields(payload: dict[str, Any]) -> list[tuple[str, tuple[None, str]]]:
|
||||
return [(key, (None, str(value))) for key, value in payload.items() if value is not None]
|
||||
|
||||
|
||||
def _create_video_job(
|
||||
server: OmniServer,
|
||||
*,
|
||||
prompt: str | None = None,
|
||||
**overrides: Any,
|
||||
) -> requests.Response:
|
||||
payload: dict[str, Any] = {
|
||||
"prompt": prompt or f"video api e2e {uuid.uuid4().hex[:8]}",
|
||||
"width": 640,
|
||||
"height": 480,
|
||||
"num_frames": 5,
|
||||
"fps": 8,
|
||||
"num_inference_steps": 2,
|
||||
"guidance_scale": 1.0,
|
||||
"guidance_scale_2": 1.0,
|
||||
"boundary_ratio": 0.875,
|
||||
"flow_shift": 5.0,
|
||||
"seed": 42,
|
||||
}
|
||||
payload.update(overrides)
|
||||
return requests.post(
|
||||
_video_api_url(server),
|
||||
files=_multipart_fields(payload),
|
||||
timeout=VIDEO_TIMEOUT_S,
|
||||
)
|
||||
|
||||
|
||||
def _retrieve_video_job(server: OmniServer, video_id: str) -> requests.Response:
|
||||
return requests.get(_video_api_url(server, f"/{video_id}"), timeout=VIDEO_TIMEOUT_S)
|
||||
|
||||
|
||||
def _wait_for_video_status(server: OmniServer, video_id: str, expected_status: str) -> dict[str, Any]:
|
||||
deadline = time.time() + VIDEO_TIMEOUT_S
|
||||
last_payload: dict[str, Any] | None = None
|
||||
|
||||
while time.time() < deadline:
|
||||
response = _retrieve_video_job(server, video_id)
|
||||
assert response.status_code == 200, response.text
|
||||
last_payload = response.json()
|
||||
status = last_payload["status"]
|
||||
if status == expected_status:
|
||||
return last_payload
|
||||
if status == "failed":
|
||||
raise AssertionError(f"Video job {video_id} failed unexpectedly: {last_payload}")
|
||||
time.sleep(VIDEO_POLL_INTERVAL_S)
|
||||
|
||||
raise AssertionError(
|
||||
f"Timed out waiting for video job {video_id} to reach status={expected_status}. Last payload: {last_payload}"
|
||||
)
|
||||
|
||||
|
||||
def _wait_for_video_missing(server: OmniServer, video_id: str) -> None:
|
||||
deadline = time.time() + 30.0
|
||||
last_status: int | None = None
|
||||
|
||||
while time.time() < deadline:
|
||||
response = _retrieve_video_job(server, video_id)
|
||||
last_status = response.status_code
|
||||
if response.status_code == 404:
|
||||
return
|
||||
time.sleep(0.5)
|
||||
|
||||
raise AssertionError(f"Timed out waiting for video job {video_id} to disappear. Last status={last_status}")
|
||||
|
||||
|
||||
def _delete_video_job(server: OmniServer, video_id: str) -> requests.Response:
|
||||
return requests.delete(_video_api_url(server, f"/{video_id}"), timeout=VIDEO_TIMEOUT_S)
|
||||
|
||||
|
||||
def _delete_video_job_with_retry(server: OmniServer, video_id: str) -> requests.Response:
|
||||
deadline = time.time() + 30.0
|
||||
last_response: requests.Response | None = None
|
||||
|
||||
while time.time() < deadline:
|
||||
response = _delete_video_job(server, video_id)
|
||||
last_response = response
|
||||
if response.status_code != 409:
|
||||
return response
|
||||
time.sleep(1.0)
|
||||
|
||||
raise AssertionError(
|
||||
f"Timed out waiting to delete video job {video_id}. "
|
||||
f"Last response: {None if last_response is None else last_response.text}"
|
||||
)
|
||||
|
||||
|
||||
def _best_effort_delete(server: OmniServer, video_id: str) -> None:
|
||||
try:
|
||||
response = _delete_video_job_with_retry(server, video_id)
|
||||
if response.status_code not in (200, 404):
|
||||
print(f"Cleanup delete for {video_id} returned {response.status_code}: {response.text}")
|
||||
except Exception as exc:
|
||||
print(f"Cleanup delete for {video_id} failed: {exc}")
|
||||
|
||||
|
||||
def _assert_mp4_payload(content: bytes) -> None:
|
||||
assert len(content) > 32, f"Downloaded video payload is unexpectedly small: {len(content)} bytes"
|
||||
assert content[4:8] == b"ftyp", "Downloaded payload does not look like an MP4 file."
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
|
||||
def test_create_list_retrieve_download_video(video_server: OmniServer, tmp_path: Path) -> None:
|
||||
video_id: str | None = None
|
||||
try:
|
||||
create_response = _create_video_job(video_server, prompt="A small paper airplane gliding over a lake at dawn.")
|
||||
assert create_response.status_code == 200, create_response.text
|
||||
|
||||
created = create_response.json()
|
||||
video_id = created["id"]
|
||||
assert created["object"] == "video"
|
||||
assert created["status"] == "queued"
|
||||
assert created["model"] == MODEL
|
||||
|
||||
completed = _wait_for_video_status(video_server, video_id, "completed")
|
||||
assert completed["file_name"] is not None
|
||||
assert completed["completed_at"] is not None
|
||||
assert completed["progress"] == 100
|
||||
|
||||
retrieve_response = _retrieve_video_job(video_server, video_id)
|
||||
assert retrieve_response.status_code == 200, retrieve_response.text
|
||||
retrieved = retrieve_response.json()
|
||||
assert retrieved["id"] == video_id
|
||||
assert retrieved["status"] == "completed"
|
||||
|
||||
list_response = requests.get(_video_api_url(video_server), timeout=VIDEO_TIMEOUT_S)
|
||||
assert list_response.status_code == 200, list_response.text
|
||||
listed = list_response.json()
|
||||
assert listed["object"] == "list"
|
||||
assert any(item["id"] == video_id for item in listed["data"])
|
||||
|
||||
download_response = requests.get(
|
||||
_video_api_url(video_server, f"/{video_id}/content"),
|
||||
timeout=VIDEO_TIMEOUT_S,
|
||||
)
|
||||
assert download_response.status_code == 200, download_response.text
|
||||
assert download_response.headers["content-type"].startswith("video/mp4")
|
||||
assert completed["file_name"] in download_response.headers.get("content-disposition", "")
|
||||
_assert_mp4_payload(download_response.content)
|
||||
|
||||
output_path = tmp_path / completed["file_name"]
|
||||
output_path.write_bytes(download_response.content)
|
||||
assert output_path.stat().st_size == len(download_response.content)
|
||||
finally:
|
||||
if video_id is not None:
|
||||
_best_effort_delete(video_server, video_id)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
|
||||
def test_delete_video_while_queued_or_in_progress(video_server: OmniServer) -> None:
|
||||
create_response = _create_video_job(
|
||||
video_server,
|
||||
prompt="A toy boat sailing through fog.",
|
||||
num_frames=13,
|
||||
num_inference_steps=4,
|
||||
)
|
||||
assert create_response.status_code == 200, create_response.text
|
||||
|
||||
created = create_response.json()
|
||||
video_id = created["id"]
|
||||
assert created["status"] == "queued"
|
||||
|
||||
# Delete immediately so the job is still queued or just entering execution.
|
||||
delete_response = _delete_video_job_with_retry(video_server, video_id)
|
||||
assert delete_response.status_code == 200, delete_response.text
|
||||
deleted = delete_response.json()
|
||||
assert deleted["id"] == video_id
|
||||
assert deleted["deleted"] is True
|
||||
assert deleted["object"] == "video.deleted"
|
||||
|
||||
_wait_for_video_missing(video_server, video_id)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "H100", "rocm": "MI325"})
|
||||
def test_delete_video_after_processing(video_server: OmniServer) -> None:
|
||||
create_response = _create_video_job(
|
||||
video_server,
|
||||
prompt="A lantern drifting above a quiet forest.",
|
||||
seed=43,
|
||||
)
|
||||
assert create_response.status_code == 200, create_response.text
|
||||
|
||||
video_id = create_response.json()["id"]
|
||||
completed = _wait_for_video_status(video_server, video_id, "completed")
|
||||
assert completed["file_name"] is not None
|
||||
|
||||
delete_response = _delete_video_job_with_retry(video_server, video_id)
|
||||
assert delete_response.status_code == 200, delete_response.text
|
||||
deleted = delete_response.json()
|
||||
assert deleted["id"] == video_id
|
||||
assert deleted["deleted"] is True
|
||||
assert deleted["object"] == "video.deleted"
|
||||
|
||||
_wait_for_video_missing(video_server, video_id)
|
||||
|
||||
download_response = requests.get(
|
||||
_video_api_url(video_server, f"/{video_id}/content"),
|
||||
timeout=VIDEO_TIMEOUT_S,
|
||||
)
|
||||
assert download_response.status_code == 404, download_response.text
|
||||
@@ -4,19 +4,31 @@
|
||||
Unit tests for OpenAI-compatible video generation endpoints.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from PIL import Image
|
||||
from pydantic import ValidationError
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from vllm_omni.entrypoints.openai import api_server
|
||||
from vllm_omni.entrypoints.openai.api_server import router
|
||||
from vllm_omni.entrypoints.openai.protocol.videos import VideoGenerationRequest, VideoResponseFormat
|
||||
from vllm_omni.entrypoints.openai.protocol.videos import (
|
||||
VideoGenerationRequest,
|
||||
VideoGenerationStatus,
|
||||
VideoResponse,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.serving_video import OmniOpenAIServingVideo
|
||||
from vllm_omni.entrypoints.openai.storage import LocalStorageManager
|
||||
from vllm_omni.entrypoints.openai.stores import AsyncDictStore, TaskRegistry
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
@@ -44,6 +56,38 @@ class FakeAsyncOmni:
|
||||
yield MockVideoResult(videos)
|
||||
|
||||
|
||||
class BlockingVideoHandler:
|
||||
def __init__(self):
|
||||
self.model_name = "Wan-AI/Wan2.2-T2V-A14B-Diffusers"
|
||||
self.stage_configs = None
|
||||
self.started = threading.Event()
|
||||
self.cancelled = threading.Event()
|
||||
|
||||
def set_stage_configs_if_missing(self, stage_configs):
|
||||
if self.stage_configs is None:
|
||||
self.stage_configs = stage_configs
|
||||
|
||||
async def generate_videos(self, request, reference_id, *, reference_image=None):
|
||||
self.started.set()
|
||||
try:
|
||||
await asyncio.Future()
|
||||
except asyncio.CancelledError:
|
||||
self.cancelled.set()
|
||||
raise
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolated_video_backends(tmp_path, monkeypatch):
|
||||
"""Use isolated in-memory metadata and local storage for each test."""
|
||||
store: AsyncDictStore[VideoResponse] = AsyncDictStore()
|
||||
tasks = TaskRegistry()
|
||||
storage = LocalStorageManager(storage_path=str(tmp_path / "storage"))
|
||||
monkeypatch.setattr(api_server, "VIDEO_STORE", store)
|
||||
monkeypatch.setattr(api_server, "VIDEO_TASKS", tasks)
|
||||
monkeypatch.setattr(api_server, "STORAGE_MANAGER", storage)
|
||||
return store, tasks, storage
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_client():
|
||||
app = FastAPI()
|
||||
@@ -52,7 +96,8 @@ def test_client():
|
||||
diffusion_engine=FakeAsyncOmni(),
|
||||
model_name="Wan-AI/Wan2.2-T2V-A14B-Diffusers",
|
||||
)
|
||||
return TestClient(app)
|
||||
with TestClient(app) as client:
|
||||
yield client
|
||||
|
||||
|
||||
def _make_test_image_bytes(size=(64, 64)) -> bytes:
|
||||
@@ -62,6 +107,34 @@ def _make_test_image_bytes(size=(64, 64)) -> bytes:
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _make_test_image_data_url(size=(64, 64)) -> str:
|
||||
image_bytes = _make_test_image_bytes(size)
|
||||
encoded = base64.b64encode(image_bytes).decode("utf-8")
|
||||
return f"data:image/png;base64,{encoded}"
|
||||
|
||||
|
||||
def _wait_for_status(client: TestClient, video_id: str, status: str, timeout_s: float = 2.0):
|
||||
deadline = time.time() + timeout_s
|
||||
last_payload = None
|
||||
while time.time() < deadline:
|
||||
response = client.get(f"/v1/videos/{video_id}")
|
||||
assert response.status_code == 200
|
||||
last_payload = response.json()
|
||||
if last_payload["status"] == status:
|
||||
return last_payload
|
||||
time.sleep(0.02)
|
||||
raise AssertionError(f"Timed out waiting for status={status}. Last payload: {last_payload}")
|
||||
|
||||
|
||||
def _wait_until(predicate, timeout_s: float = 2.0, interval_s: float = 0.02):
|
||||
deadline = time.time() + timeout_s
|
||||
while time.time() < deadline:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(interval_s)
|
||||
raise AssertionError("Timed out waiting for condition")
|
||||
|
||||
|
||||
def test_t2v_video_generation_form(test_client, mocker: MockerFixture):
|
||||
fps_values = []
|
||||
|
||||
@@ -80,24 +153,22 @@ def test_t2v_video_generation_form(test_client, mocker: MockerFixture):
|
||||
"size": "640x360",
|
||||
"seconds": "2",
|
||||
"fps": "12",
|
||||
"n": "2",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "data" in data and len(data["data"]) == 2
|
||||
assert all(item["b64_json"] == "Zg==" for item in data["data"])
|
||||
video_id = response.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
captured = engine.captured_sampling_params_list[0]
|
||||
assert captured.num_outputs_per_prompt == 2
|
||||
assert captured.num_outputs_per_prompt == 1
|
||||
assert captured.width == 640
|
||||
assert captured.height == 360
|
||||
assert captured.num_frames == 24
|
||||
assert captured.fps == 12
|
||||
assert captured.frame_rate == 12.0
|
||||
assert fps_values == [12, 12]
|
||||
assert fps_values == [12]
|
||||
|
||||
|
||||
def test_i2v_video_generation_form(test_client, mocker: MockerFixture):
|
||||
@@ -114,9 +185,8 @@ def test_i2v_video_generation_form(test_client, mocker: MockerFixture):
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "data" in data and len(data["data"]) == 1
|
||||
assert data["data"][0]["b64_json"] == "Zg=="
|
||||
video_id = response.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
prompt = engine.captured_prompt
|
||||
@@ -145,6 +215,8 @@ def test_i2v_video_generation_resizes_input_to_requested_dimensions(test_client,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
video_id = response.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
prompt = engine.captured_prompt
|
||||
@@ -153,6 +225,30 @@ def test_i2v_video_generation_resizes_input_to_requested_dimensions(test_client,
|
||||
assert input_image.size == (96, 64)
|
||||
|
||||
|
||||
def test_i2v_video_generation_with_image_reference_form(test_client, mocker: MockerFixture):
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.openai.serving_video.encode_video_base64",
|
||||
return_value="Zg==",
|
||||
)
|
||||
response = test_client.post(
|
||||
"/v1/videos",
|
||||
data={
|
||||
"prompt": "A fox running through snow.",
|
||||
"image_reference": json.dumps({"image_url": _make_test_image_data_url((40, 24))}),
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
video_id = response.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
prompt = engine.captured_prompt
|
||||
input_image = prompt["multi_modal_data"]["image"]
|
||||
assert isinstance(input_image, Image.Image)
|
||||
assert input_image.size == (40, 24)
|
||||
|
||||
|
||||
def test_seconds_defaults_fps_and_frames(test_client, mocker: MockerFixture):
|
||||
fps_values = []
|
||||
|
||||
@@ -173,10 +269,13 @@ def test_seconds_defaults_fps_and_frames(test_client, mocker: MockerFixture):
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
video_id = response.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
captured = engine.captured_sampling_params_list[0]
|
||||
assert captured.num_frames == 72
|
||||
assert captured.fps == 24
|
||||
assert captured.frame_rate == 24.0
|
||||
assert fps_values == [24]
|
||||
|
||||
|
||||
@@ -194,16 +293,50 @@ def test_size_param_sets_width_height(test_client, mocker: MockerFixture):
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
video_id = response.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
captured = engine.captured_sampling_params_list[0]
|
||||
assert captured.width == 320
|
||||
assert captured.height == 240
|
||||
|
||||
|
||||
def test_sampling_params_pass_through(test_client, mocker: MockerFixture):
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.openai.serving_video.encode_video_base64",
|
||||
return_value="Zg==",
|
||||
)
|
||||
response = test_client.post(
|
||||
"/v1/videos",
|
||||
data={
|
||||
"prompt": "param pass",
|
||||
"num_inference_steps": "30",
|
||||
"guidance_scale": "6.5",
|
||||
"guidance_scale_2": "8.0",
|
||||
"true_cfg_scale": "4.0",
|
||||
"boundary_ratio": "0.7",
|
||||
"flow_shift": "0.25",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
video_id = response.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
captured = engine.captured_sampling_params_list[0]
|
||||
assert captured.num_inference_steps == 30
|
||||
assert captured.guidance_scale == 6.5
|
||||
assert captured.guidance_scale_2 == 8.0
|
||||
assert captured.true_cfg_scale == 4.0
|
||||
assert captured.boundary_ratio == 0.7
|
||||
assert captured.extra_args["flow_shift"] == 0.25
|
||||
|
||||
|
||||
def test_audio_sample_rate_comes_from_model_config(test_client, mocker: MockerFixture):
|
||||
audio_sample_rates = []
|
||||
|
||||
def _fake_encode(video, fps, audio=None, audio_sample_rate=None):
|
||||
del video, fps, audio
|
||||
audio_sample_rates.append(audio_sample_rate)
|
||||
return "Zg=="
|
||||
|
||||
@@ -233,38 +366,11 @@ def test_audio_sample_rate_comes_from_model_config(test_client, mocker: MockerFi
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
video_id = response.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
assert audio_sample_rates == [16000]
|
||||
|
||||
|
||||
def test_sampling_params_pass_through(test_client, mocker: MockerFixture):
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.openai.serving_video.encode_video_base64",
|
||||
return_value="Zg==",
|
||||
)
|
||||
response = test_client.post(
|
||||
"/v1/videos",
|
||||
data={
|
||||
"prompt": "param pass",
|
||||
"num_inference_steps": "30",
|
||||
"guidance_scale": "6.5",
|
||||
"guidance_scale_2": "8.0",
|
||||
"true_cfg_scale": "4.0",
|
||||
"boundary_ratio": "0.7",
|
||||
"flow_shift": "0.25",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
captured = engine.captured_sampling_params_list[0]
|
||||
assert captured.num_inference_steps == 30
|
||||
assert captured.guidance_scale == 6.5
|
||||
assert captured.guidance_scale_2 == 8.0
|
||||
assert captured.true_cfg_scale == 4.0
|
||||
assert captured.boundary_ratio == 0.7
|
||||
assert captured.extra_args["flow_shift"] == 0.25
|
||||
|
||||
|
||||
def test_missing_handler_returns_503():
|
||||
app = FastAPI()
|
||||
app.include_router(router)
|
||||
@@ -287,29 +393,29 @@ def test_missing_prompt_returns_422(test_client):
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
def test_invalid_size_format_raises_validation_error(test_client):
|
||||
with pytest.raises(ValidationError):
|
||||
test_client.post(
|
||||
"/v1/videos",
|
||||
data={"prompt": "bad size", "size": "invalid"},
|
||||
)
|
||||
|
||||
|
||||
def test_invalid_size_parse_returns_500(test_client):
|
||||
def test_invalid_size_parse_returns_422(test_client):
|
||||
response = test_client.post(
|
||||
"/v1/videos",
|
||||
data={"prompt": "bad size", "size": "640x"},
|
||||
)
|
||||
assert response.status_code == 500
|
||||
assert "video generation failed" in response.json()["detail"].lower()
|
||||
assert response.status_code == 422
|
||||
body = response.json()
|
||||
assert body["detail"][0]["loc"] == ["body", "size"]
|
||||
assert body["detail"][0]["type"] == "string_pattern_mismatch"
|
||||
assert body["detail"][0]["input"] == "640x"
|
||||
|
||||
|
||||
def test_invalid_response_format_raises_validation_error(test_client):
|
||||
with pytest.raises(ValidationError):
|
||||
test_client.post(
|
||||
"/v1/videos",
|
||||
data={"prompt": "bad format", "response_format": "url"},
|
||||
)
|
||||
def test_rejects_input_reference_and_image_reference_together(test_client):
|
||||
response = test_client.post(
|
||||
"/v1/videos",
|
||||
data={
|
||||
"prompt": "bad refs",
|
||||
"image_reference": '{"image_url": "https://example.com/cat.png"}',
|
||||
},
|
||||
files={"input_reference": ("input.png", _make_test_image_bytes(), "image/png")},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "either input_reference or image_reference" in response.json()["detail"].lower()
|
||||
|
||||
|
||||
def test_invalid_seconds_returns_422(test_client):
|
||||
@@ -320,20 +426,6 @@ def test_invalid_seconds_returns_422(test_client):
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
def test_invalid_n_raises_validation_error(test_client):
|
||||
with pytest.raises(ValidationError):
|
||||
test_client.post(
|
||||
"/v1/videos",
|
||||
data={"prompt": "bad n", "n": "0"},
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
test_client.post(
|
||||
"/v1/videos",
|
||||
data={"prompt": "bad n", "n": "5"},
|
||||
)
|
||||
|
||||
|
||||
def test_negative_prompt_and_seed_pass_through(test_client, mocker: MockerFixture):
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.openai.serving_video.encode_video_base64",
|
||||
@@ -349,6 +441,8 @@ def test_negative_prompt_and_seed_pass_through(test_client, mocker: MockerFixtur
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
video_id = response.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
engine = test_client.app.state.openai_serving_video._engine_client
|
||||
captured_prompt = engine.captured_prompt
|
||||
captured_params = engine.captured_sampling_params_list[0]
|
||||
@@ -364,19 +458,38 @@ def test_invalid_lora_returns_400(test_client):
|
||||
"lora": '{"name": "bad-lora"}',
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
video_id = response.json()["id"]
|
||||
failed = _wait_for_status(test_client, video_id, VideoGenerationStatus.FAILED.value)
|
||||
assert failed["error"]["code"] == "HTTPException"
|
||||
assert "lora object" in failed["error"]["message"].lower()
|
||||
|
||||
|
||||
def test_unsupported_image_reference_file_id_returns_400(test_client):
|
||||
response = test_client.post(
|
||||
"/v1/videos",
|
||||
data={
|
||||
"prompt": "unsupported ref",
|
||||
"image_reference": '{"file_id": "file-123"}',
|
||||
},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "lora" in response.json()["detail"].lower()
|
||||
assert response.json()["detail"] == "Invalid image_reference: file_id is not supported yet."
|
||||
|
||||
|
||||
def test_invalid_uploaded_input_reference_returns_400(test_client):
|
||||
response = test_client.post(
|
||||
"/v1/videos",
|
||||
data={"prompt": "bad upload"},
|
||||
files={"input_reference": ("input.png", b"not-an-image", "image/png")},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json()["detail"] == "Invalid input_reference: provided content is not a valid image."
|
||||
|
||||
|
||||
def test_video_request_validation():
|
||||
req = VideoGenerationRequest(prompt="test")
|
||||
assert req.prompt == "test"
|
||||
assert req.n == 1
|
||||
assert req.response_format == VideoResponseFormat.B64_JSON
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
VideoGenerationRequest(prompt="test", response_format="url")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
VideoGenerationRequest(prompt="test", size="invalid")
|
||||
|
||||
@@ -384,4 +497,144 @@ def test_video_request_validation():
|
||||
VideoGenerationRequest(prompt="test", seconds="abc")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
VideoGenerationRequest(prompt="test", n=0)
|
||||
VideoGenerationRequest(prompt="test", image_reference={"file_id": "file-1", "image_url": "https://example.com"})
|
||||
|
||||
|
||||
def test_list_videos_supports_order_after_and_limit(test_client, mocker: MockerFixture):
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.openai.serving_video.encode_video_base64",
|
||||
return_value="Zg==",
|
||||
)
|
||||
ids = []
|
||||
for i in range(3):
|
||||
create_resp = test_client.post("/v1/videos", data={"prompt": f"video-{i}"})
|
||||
assert create_resp.status_code == 200
|
||||
video_id = create_resp.json()["id"]
|
||||
_wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
ids.append(video_id)
|
||||
|
||||
asyncio.run(api_server.VIDEO_STORE.update_fields(ids[0], {"created_at": 100}))
|
||||
asyncio.run(api_server.VIDEO_STORE.update_fields(ids[1], {"created_at": 200}))
|
||||
asyncio.run(api_server.VIDEO_STORE.update_fields(ids[2], {"created_at": 300}))
|
||||
|
||||
asc_resp = test_client.get("/v1/videos", params={"order": "asc"})
|
||||
assert asc_resp.status_code == 200
|
||||
asc_body = asc_resp.json()
|
||||
asc_ids = [item["id"] for item in asc_body["data"]]
|
||||
assert asc_ids == [ids[0], ids[1], ids[2]]
|
||||
assert asc_body["object"] == "list"
|
||||
assert asc_body["first_id"] == ids[0]
|
||||
assert asc_body["last_id"] == ids[2]
|
||||
assert asc_body["has_more"] is False
|
||||
|
||||
desc_resp = test_client.get("/v1/videos", params={"order": "desc", "limit": 2})
|
||||
assert desc_resp.status_code == 200
|
||||
desc_body = desc_resp.json()
|
||||
desc_ids = [item["id"] for item in desc_body["data"]]
|
||||
assert desc_ids == [ids[2], ids[1]]
|
||||
assert desc_body["object"] == "list"
|
||||
assert desc_body["first_id"] == ids[2]
|
||||
assert desc_body["last_id"] == ids[1]
|
||||
assert desc_body["has_more"] is True
|
||||
|
||||
after_resp = test_client.get("/v1/videos", params={"order": "asc", "after": ids[0]})
|
||||
assert after_resp.status_code == 200
|
||||
after_body = after_resp.json()
|
||||
after_ids = [item["id"] for item in after_body["data"]]
|
||||
assert after_ids == [ids[1], ids[2]]
|
||||
assert after_body["object"] == "list"
|
||||
assert after_body["first_id"] == ids[1]
|
||||
assert after_body["last_id"] == ids[2]
|
||||
assert after_body["has_more"] is False
|
||||
|
||||
zero_limit_resp = test_client.get("/v1/videos", params={"order": "asc", "limit": 0})
|
||||
assert zero_limit_resp.status_code == 200
|
||||
zero_limit_body = zero_limit_resp.json()
|
||||
assert zero_limit_body["data"] == []
|
||||
assert zero_limit_body["object"] == "list"
|
||||
assert zero_limit_body["first_id"] is None
|
||||
assert zero_limit_body["last_id"] is None
|
||||
assert zero_limit_body["has_more"] is True
|
||||
|
||||
zero_limit_after_resp = test_client.get(
|
||||
"/v1/videos",
|
||||
params={"order": "asc", "after": ids[2], "limit": 0},
|
||||
)
|
||||
assert zero_limit_after_resp.status_code == 200
|
||||
zero_limit_after_body = zero_limit_after_resp.json()
|
||||
assert zero_limit_after_body["data"] == []
|
||||
assert zero_limit_after_body["object"] == "list"
|
||||
assert zero_limit_after_body["first_id"] is None
|
||||
assert zero_limit_after_body["last_id"] is None
|
||||
assert zero_limit_after_body["has_more"] is False
|
||||
|
||||
|
||||
def test_delete_completed_job_removes_file_and_metadata(test_client, mocker: MockerFixture):
|
||||
mocker.patch(
|
||||
"vllm_omni.entrypoints.openai.serving_video.encode_video_base64",
|
||||
return_value="Zg==",
|
||||
)
|
||||
create_resp = test_client.post("/v1/videos", data={"prompt": "Delete this video"})
|
||||
assert create_resp.status_code == 200
|
||||
video_id = create_resp.json()["id"]
|
||||
|
||||
final = _wait_for_status(test_client, video_id, VideoGenerationStatus.COMPLETED.value)
|
||||
file_name = final["file_name"]
|
||||
assert file_name is not None
|
||||
file_path = os.path.join(api_server.STORAGE_MANAGER.storage_path, file_name)
|
||||
assert os.path.exists(file_path)
|
||||
|
||||
delete_resp = test_client.delete(f"/v1/videos/{video_id}")
|
||||
assert delete_resp.status_code == 200
|
||||
assert delete_resp.json()["id"] == video_id
|
||||
assert delete_resp.json()["deleted"] is True
|
||||
assert delete_resp.json()["object"] == "video.deleted"
|
||||
assert not os.path.exists(file_path)
|
||||
|
||||
|
||||
def test_delete_in_progress_job_cancels_task_and_removes_metadata(test_client):
|
||||
handler = BlockingVideoHandler()
|
||||
test_client.app.state.openai_serving_video = handler
|
||||
|
||||
create_resp = test_client.post("/v1/videos", data={"prompt": "Cancel this video"})
|
||||
assert create_resp.status_code == 200
|
||||
video_id = create_resp.json()["id"]
|
||||
|
||||
assert handler.started.wait(timeout=2.0)
|
||||
|
||||
delete_resp = test_client.delete(f"/v1/videos/{video_id}")
|
||||
assert delete_resp.status_code == 200
|
||||
assert delete_resp.json()["id"] == video_id
|
||||
assert delete_resp.json()["deleted"] is True
|
||||
assert delete_resp.json()["object"] == "video.deleted"
|
||||
|
||||
assert handler.cancelled.wait(timeout=2.0)
|
||||
_wait_until(lambda: asyncio.run(api_server.VIDEO_TASKS.get(video_id)) is None)
|
||||
assert asyncio.run(api_server.VIDEO_STORE.get(video_id)) is None
|
||||
|
||||
retrieve_resp = test_client.get(f"/v1/videos/{video_id}")
|
||||
assert retrieve_resp.status_code == 404
|
||||
|
||||
|
||||
def test_video_response_file_extension_is_robust():
|
||||
response = VideoResponse(model="test-model", prompt="Make something beautiful")
|
||||
assert response.file_extension == "mp4"
|
||||
|
||||
with_params = VideoResponse.model_construct(
|
||||
model="test-model",
|
||||
media_type="video/mp4; charset=binary",
|
||||
)
|
||||
assert with_params.file_extension == "mp4"
|
||||
|
||||
webm = VideoResponse.model_construct(
|
||||
model="test-model",
|
||||
media_type="video/webm",
|
||||
)
|
||||
assert webm.file_extension == "webm"
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
unknown = VideoResponse.model_construct(
|
||||
model="test-model",
|
||||
media_type="application/x-custom-video",
|
||||
)
|
||||
_ = unknown.file_extension
|
||||
Reference in new issue
Block a user