Merge main and align text encoder TP regression documentation
Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
commit
afc4decaca
53 files changed
+10815
-57
No files matched your search
@@ -0,0 +1,798 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Unit tests for the LingBot-World realtime streaming benchmark.
|
||||
|
||||
The arithmetic is tested against the server's own formulas rather than against
|
||||
hand-copied expectations, and the protocol handling runs against a real
|
||||
WebSocket server that replays ``/v1/realtime/video`` with scripted delays -- so
|
||||
a benchmark number can be wrong only if the server itself is, not because the
|
||||
client parsed incorrectly an event or timed the wrong edge.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# ruff: noqa: E402, I001
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(REPO_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
from benchmarks.lingbot_world.benchmark_lingbot_world_realtime import (
|
||||
BenchmarkError,
|
||||
build_workload,
|
||||
print_report,
|
||||
endpoint_url,
|
||||
parse_args,
|
||||
resolve_image_reference,
|
||||
run_session,
|
||||
)
|
||||
from benchmarks.lingbot_world.workload import (
|
||||
DEFAULT_WARMUP_CHUNKS,
|
||||
FRAMES_PER_BLOCK,
|
||||
ChunkRecord,
|
||||
PromptUpdate,
|
||||
Workload,
|
||||
aggregate_metrics,
|
||||
build_camera_script,
|
||||
chunks_for_num_frames,
|
||||
compute_metrics,
|
||||
default_workload,
|
||||
load_workload,
|
||||
num_frames_for_chunks,
|
||||
percentile,
|
||||
pixel_frames_in_chunk,
|
||||
simulate_playback,
|
||||
steady_chunk_deadline_ms,
|
||||
)
|
||||
|
||||
_IMAGE = "data:image/png;base64,Zm9v"
|
||||
|
||||
|
||||
def _workload(num_chunks: int = 8, fps: int = 16) -> Workload:
|
||||
return default_workload(image_reference=_IMAGE, num_chunks=num_chunks, fps=fps)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Chunk and frame arithmetic
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_chunks", list(range(1, 33)))
|
||||
def test_frame_count_round_trips_through_the_server_formula(num_chunks: int) -> None:
|
||||
"""``num_frames`` must land on a rollout of exactly the requested chunks.
|
||||
|
||||
The server derives chunk count as ``((num_frames - 1) // 4 + 1) // 3``; if
|
||||
the benchmark's inverse is off by one frame the run silently generates a
|
||||
different number of blocks than it reports.
|
||||
"""
|
||||
assert chunks_for_num_frames(num_frames_for_chunks(num_chunks)) == num_chunks
|
||||
|
||||
|
||||
def test_recipe_frame_counts_match_the_documented_chunk_counts() -> None:
|
||||
# The recipe states three chunks for num_frames 33 and seven for 81.
|
||||
assert chunks_for_num_frames(33) == 3
|
||||
assert chunks_for_num_frames(81) == 7
|
||||
assert num_frames_for_chunks(3) == 33
|
||||
assert num_frames_for_chunks(7) == 81
|
||||
|
||||
|
||||
def test_first_chunk_is_short_because_the_decoder_expands_it_once() -> None:
|
||||
assert pixel_frames_in_chunk(0) == 9
|
||||
assert pixel_frames_in_chunk(1) == 12
|
||||
assert pixel_frames_in_chunk(7) == 12
|
||||
# A whole rollout's frames are the sum of its chunks' frames.
|
||||
assert sum(pixel_frames_in_chunk(index) for index in range(5)) == num_frames_for_chunks(5)
|
||||
|
||||
|
||||
def test_camera_script_holds_one_three_entry_action_list_per_chunk() -> None:
|
||||
script = build_camera_script(4, "orbit")
|
||||
assert len(script) == 4
|
||||
assert all(len(actions) == FRAMES_PER_BLOCK for actions in script)
|
||||
# orbit advances through the action keys so successive chunks differ.
|
||||
assert script[0] != script[1]
|
||||
|
||||
|
||||
def test_unknown_camera_pattern_is_rejected() -> None:
|
||||
with pytest.raises(ValueError, match="Unknown camera pattern"):
|
||||
build_camera_script(2, "sideways")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Workload
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_session_start_payload_matches_the_documented_protocol() -> None:
|
||||
workload = _workload(num_chunks=3)
|
||||
payload = workload.session_start_payload("robbyant/lingbot-world-v2-14b-causal-fast-diffusers")
|
||||
assert payload["type"] == "session.start"
|
||||
assert payload["num_frames"] == 33
|
||||
assert payload["image_reference"] == {"image_url": _IMAGE}
|
||||
assert payload["extra_params"]["flow_shift"] == 5.0
|
||||
assert len(payload["extra_params"]["camera_action_script"]) == 3
|
||||
|
||||
|
||||
def test_workload_rejects_a_camera_script_with_the_wrong_block_width() -> None:
|
||||
with pytest.raises(ValueError, match="exactly 3 action lists"):
|
||||
Workload(prompt="p", image_reference=_IMAGE, camera_script=[[["w"], ["w"]]])
|
||||
|
||||
|
||||
def test_workload_rejects_geometry_the_cache_cannot_serve() -> None:
|
||||
with pytest.raises(ValueError, match="multiples of 16"):
|
||||
Workload(prompt="p", image_reference=_IMAGE, camera_script=build_camera_script(1, "forward"), width=831)
|
||||
|
||||
|
||||
def test_prompt_update_beyond_the_rollout_is_rejected() -> None:
|
||||
with pytest.raises(ValueError, match="never fires"):
|
||||
Workload(
|
||||
prompt="p",
|
||||
image_reference=_IMAGE,
|
||||
camera_script=build_camera_script(2, "forward"),
|
||||
prompt_updates=(PromptUpdate(after_chunk=5, prompt="later"),),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("from_file", [False, True])
|
||||
def test_duplicate_prompt_update_boundaries_are_rejected(tmp_path: Path, from_file: bool) -> None:
|
||||
updates = [
|
||||
{"after_chunk": 1, "prompt": "Rain begins"},
|
||||
{"after_chunk": 0, "prompt": "Clouds gather"},
|
||||
{"after_chunk": 1, "prompt": "Rain stops"},
|
||||
]
|
||||
with pytest.raises(ValueError, match="Duplicate prompt update after chunk 1"):
|
||||
if from_file:
|
||||
path = tmp_path / "rollout.json"
|
||||
path.write_text(json.dumps({"image": _IMAGE, "num_chunks": 3, "prompt_updates": updates}))
|
||||
build_workload(parse_args(["--workload", str(path)]))
|
||||
else:
|
||||
Workload(
|
||||
prompt="p",
|
||||
image_reference=_IMAGE,
|
||||
camera_script=build_camera_script(3, "forward"),
|
||||
prompt_updates=(
|
||||
PromptUpdate(after_chunk=1, prompt="Rain begins"),
|
||||
PromptUpdate(after_chunk=0, prompt="Clouds gather"),
|
||||
PromptUpdate(after_chunk=1, prompt="Rain stops"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_workload_file_is_loaded_and_cli_overrides_win(tmp_path: Path) -> None:
|
||||
path = tmp_path / "rollout.json"
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"prompt": "A quiet street",
|
||||
"image": "https://example.invalid/frame.png",
|
||||
"num_chunks": 4,
|
||||
"camera_pattern": "hold",
|
||||
"fps": 12,
|
||||
"seed": 7,
|
||||
"prompt_updates": [{"after_chunk": 1, "prompt": "Rain begins", "transition_chunks": 2}],
|
||||
}
|
||||
)
|
||||
)
|
||||
workload = load_workload(path, overrides={"fps": 24, "seed": None})
|
||||
assert workload.prompt == "A quiet street"
|
||||
assert workload.num_chunks == 4
|
||||
assert workload.fps == 24, "an explicit CLI value must beat the file"
|
||||
assert workload.seed == 7, "a None override must leave the file value alone"
|
||||
assert workload.prompt_updates[0].transition_chunks == 2
|
||||
|
||||
|
||||
def test_workload_file_without_a_rollout_length_is_rejected(tmp_path: Path) -> None:
|
||||
path = tmp_path / "rollout.json"
|
||||
path.write_text(json.dumps({"image": "https://example.invalid/frame.png"}))
|
||||
with pytest.raises(ValueError, match="camera_action_script or num_chunks"):
|
||||
load_workload(path)
|
||||
|
||||
|
||||
def test_local_image_is_inlined_as_a_data_url(tmp_path: Path) -> None:
|
||||
image = tmp_path / "frame.png"
|
||||
image.write_bytes(b"\x89PNG\r\n\x1a\n")
|
||||
reference = resolve_image_reference(str(image))
|
||||
assert reference.startswith("data:image/png;base64,")
|
||||
assert resolve_image_reference("https://example.invalid/a.png") == "https://example.invalid/a.png"
|
||||
with pytest.raises(BenchmarkError, match="neither a URL nor a readable file"):
|
||||
resolve_image_reference(str(tmp_path / "missing.png"))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Metric math
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_rtf_is_a_cost_not_a_speed() -> None:
|
||||
"""RTF must match vLLM-Omni's own formula, where lower is better.
|
||||
|
||||
``vllm_omni/metrics/definitions.py::compute_audio_rtf`` is
|
||||
``latency / duration`` with the docstring "SLO red line < 1", and
|
||||
``benchmarks/patch/patch.py`` sets ``video_rtf = generation_s /
|
||||
video_duration``. Emitting the reciprocal under the same field name would
|
||||
silently invert every dashboard that aggregates it, so the direction is
|
||||
pinned here rather than left to a comment.
|
||||
"""
|
||||
# Two chunks, 9 + 12 = 21 frames at 12 fps = 1.75 s of video, generated in 3.5 s.
|
||||
slow = compute_metrics(_records([1.0, 2.5]), fps=12, warmup_chunks=0, session_wall_s=3.5)
|
||||
assert slow["video_seconds"] == pytest.approx(1.75)
|
||||
assert slow["video_rtf"] == pytest.approx(2.0), "twice as slow as real time"
|
||||
assert slow["video_rtfx"] == pytest.approx(0.5)
|
||||
|
||||
fast = compute_metrics(_records([0.4, 0.475]), fps=12, warmup_chunks=0, session_wall_s=0.875)
|
||||
assert fast["video_rtf"] == pytest.approx(0.5), "twice as fast as real time"
|
||||
assert fast["video_rtf"] < 1.0 < slow["video_rtf"]
|
||||
assert fast["video_rtf"] * fast["video_rtfx"] == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_steady_rtf_is_the_chunk_interval_over_its_deadline() -> None:
|
||||
"""A steady chunk's RTF is just its interval divided by its video duration."""
|
||||
metrics = compute_metrics(_records([1.0] + [1.357] * 15), fps=12, warmup_chunks=6)
|
||||
# 12 frames at 12 fps = 1000 ms of video per steady chunk.
|
||||
assert metrics["chunk_deadline_ms"] == pytest.approx(1000.0)
|
||||
assert metrics["steady_video_rtf"] == pytest.approx(1.357, abs=1e-3)
|
||||
|
||||
|
||||
def test_percentile_interpolates_so_short_runs_still_report_tails() -> None:
|
||||
values = [10.0, 20.0, 30.0, 40.0]
|
||||
assert percentile(values, 0.0) == 10.0
|
||||
assert percentile(values, 1.0) == 40.0
|
||||
assert percentile(values, 0.5) == 25.0
|
||||
assert percentile([5.0], 0.99) == 5.0
|
||||
|
||||
|
||||
def _records(intervals: list[float]) -> list[ChunkRecord]:
|
||||
"""One record per entry; ``intervals[0]`` is the TTFC, the rest are gaps."""
|
||||
records: list[ChunkRecord] = []
|
||||
arrival = 0.0
|
||||
for index, interval in enumerate(intervals):
|
||||
arrival += interval
|
||||
records.append(
|
||||
ChunkRecord(
|
||||
index=index,
|
||||
arrival_s=arrival,
|
||||
inter_arrival_s=interval,
|
||||
byte_length=1000,
|
||||
num_frames=pixel_frames_in_chunk(index),
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def test_steady_state_excludes_the_unsaturated_attention_window() -> None:
|
||||
"""Warmup chunks must not drag the steady-state mean down.
|
||||
|
||||
The first six chunks attend over a growing window, so they are genuinely
|
||||
cheaper. A benchmark that averages them in reports a cadence the session
|
||||
will never sustain.
|
||||
"""
|
||||
intervals = [1.0] + [0.2] * (DEFAULT_WARMUP_CHUNKS - 1) + [0.8] * 4
|
||||
metrics = compute_metrics(_records(intervals), fps=16, warmup_chunks=DEFAULT_WARMUP_CHUNKS)
|
||||
assert metrics["interval_steady"]["count"] == 3
|
||||
assert metrics["interval_steady"]["mean_ms"] == pytest.approx(800.0)
|
||||
assert metrics["interval_all"]["mean_ms"] < metrics["interval_steady"]["mean_ms"]
|
||||
|
||||
|
||||
def test_short_rollouts_report_that_steady_state_was_never_reached() -> None:
|
||||
metrics = compute_metrics(_records([1.0, 0.5, 0.5]), fps=16, warmup_chunks=DEFAULT_WARMUP_CHUNKS)
|
||||
assert metrics["steady_state_reached"] is False
|
||||
assert metrics["interval_steady"] == {}
|
||||
assert "slo_attainment" not in metrics
|
||||
|
||||
|
||||
def test_real_time_factor_and_deadline_use_the_true_frame_counts() -> None:
|
||||
# Eight chunks: 9 + 7*12 = 93 frames at 16 fps = 5.8125 s of video.
|
||||
metrics = compute_metrics(_records([1.0] + [0.5] * 7), fps=16, warmup_chunks=0, session_wall_s=5.8125)
|
||||
assert metrics["total_frames"] == 93
|
||||
assert metrics["video_seconds"] == pytest.approx(5.8125)
|
||||
assert metrics["video_rtf"] == pytest.approx(1.0)
|
||||
assert metrics["video_rtfx"] == pytest.approx(1.0)
|
||||
# A steady chunk carries 12 frames, so real time allows 750 ms at 16 fps.
|
||||
assert metrics["chunk_deadline_ms"] == pytest.approx(750.0)
|
||||
assert steady_chunk_deadline_ms(12) == pytest.approx(1000.0)
|
||||
|
||||
|
||||
def test_slo_attainment_counts_only_steady_chunks() -> None:
|
||||
intervals = [1.0] + [0.1] * 5 + [0.7, 0.9, 0.7, 0.9]
|
||||
metrics = compute_metrics(_records(intervals), fps=16, warmup_chunks=6, slo_ms=750.0)
|
||||
assert metrics["slo_attainment"] == pytest.approx(2 / 3)
|
||||
assert metrics["slo_violations"] == 1
|
||||
|
||||
|
||||
def test_playback_simulation_finds_stalls_a_percentile_would_hide() -> None:
|
||||
"""One late chunk behind a one-chunk buffer is a visible stall."""
|
||||
# 12 frames at 16 fps = 750 ms of playback per chunk; chunk 3 takes 2 s.
|
||||
intervals = [1.0, 0.5, 0.5, 2.0, 0.5]
|
||||
result = simulate_playback(_records(intervals), fps=16, buffer_chunks=1)
|
||||
assert result.underrun_count >= 1
|
||||
assert result.first_underrun_chunk == 3
|
||||
assert result.total_stall_s > 0.0
|
||||
|
||||
|
||||
def test_a_deeper_buffer_absorbs_the_same_jitter() -> None:
|
||||
intervals = [1.0, 0.5, 0.5, 1.4, 0.2, 0.2]
|
||||
fast = simulate_playback(_records(intervals), fps=16, buffer_chunks=1)
|
||||
buffered = simulate_playback(_records(intervals), fps=16, buffer_chunks=3)
|
||||
assert buffered.underrun_count < fast.underrun_count
|
||||
|
||||
|
||||
def test_playback_rejects_a_buffer_deeper_than_the_rollout() -> None:
|
||||
with pytest.raises(ValueError, match="exceeds"):
|
||||
simulate_playback(_records([1.0, 0.5]), fps=16, buffer_chunks=9)
|
||||
|
||||
|
||||
def test_aggregate_pools_sessions_and_reports_spread() -> None:
|
||||
fast = compute_metrics(_records([1.0] + [0.1] * 5 + [0.6] * 4), fps=16, warmup_chunks=6)
|
||||
slow = compute_metrics(_records([1.0] + [0.1] * 5 + [0.9] * 4), fps=16, warmup_chunks=6)
|
||||
aggregate = aggregate_metrics([fast, slow], fps=16)
|
||||
assert aggregate["sessions"] == 2
|
||||
assert aggregate["steady_interval_ms_mean"] == pytest.approx(750.0)
|
||||
assert aggregate["steady_interval_ms_spread"] == pytest.approx(300.0)
|
||||
assert aggregate["video_rtf_best"] <= aggregate["video_rtf_mean"] <= aggregate["video_rtf_worst"]
|
||||
|
||||
|
||||
def test_single_session_aggregate_is_the_session_itself() -> None:
|
||||
metrics = compute_metrics(_records([1.0] + [0.5] * 3), fps=16, warmup_chunks=0)
|
||||
aggregate = aggregate_metrics([metrics], fps=16)
|
||||
assert aggregate["sessions"] == 1
|
||||
assert aggregate["video_rtf"] == metrics["video_rtf"]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# CLI
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_endpoint_url_normalizes_http_and_appends_the_ws_path() -> None:
|
||||
assert endpoint_url(parse_args([])) == "ws://127.0.0.1:8000/v1/realtime/video"
|
||||
assert endpoint_url(parse_args(["--host", "h", "--port", "9"])) == "ws://h:9/v1/realtime/video"
|
||||
args = parse_args(["--base-url", "http://example.invalid:8099"])
|
||||
assert endpoint_url(args) == "ws://example.invalid:8099/v1/realtime/video"
|
||||
args = parse_args(["--base-url", "ws://example.invalid:8099/v1/realtime/video"])
|
||||
assert endpoint_url(args) == "ws://example.invalid:8099/v1/realtime/video"
|
||||
|
||||
|
||||
def test_cli_rejects_a_zero_chunk_buffer() -> None:
|
||||
with pytest.raises(SystemExit):
|
||||
parse_args(["--playback-buffer-chunks", "0"])
|
||||
with pytest.raises(SystemExit):
|
||||
parse_args(["--target-fps", "0"])
|
||||
|
||||
|
||||
def test_the_real_time_basis_is_independent_of_the_mux_label() -> None:
|
||||
"""The checkpoint declares no frame rate, so the basis must be statable.
|
||||
|
||||
The same measured cadence has RTF 1.809 at 16 fps and 1.357 at 12 fps;
|
||||
tying that verdict to the fps sent to the muxer would let a playback label
|
||||
silently decide whether a run passes.
|
||||
"""
|
||||
records = _records([1.0] + [1.357] * 15)
|
||||
at_16 = compute_metrics(records, fps=16, warmup_chunks=6)
|
||||
at_12 = compute_metrics(records, fps=12, warmup_chunks=6)
|
||||
assert at_16["chunk_deadline_ms"] == pytest.approx(750.0)
|
||||
assert at_12["chunk_deadline_ms"] == pytest.approx(1000.0)
|
||||
# RTF is cost, so the harsher 16 fps basis scores WORSE (higher).
|
||||
assert at_16["video_rtf"] > at_12["video_rtf"]
|
||||
# Same wall clock, same bytes: only the basis moved.
|
||||
assert at_16["video_rtf"] / at_12["video_rtf"] == pytest.approx(16 / 12)
|
||||
assert parse_args([]).target_fps is None, "default defers to the workload fps"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Protocol handling against a scripted server
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def _serve(script):
|
||||
"""Return an async context manager yielding a ws:// URL for ``script``."""
|
||||
from websockets.asyncio.server import Server, serve
|
||||
|
||||
class _Server:
|
||||
def __init__(self) -> None:
|
||||
self.server: Server | None = None
|
||||
self.start_payloads: list[dict] = []
|
||||
|
||||
async def __aenter__(self) -> str:
|
||||
async def handler(websocket) -> None:
|
||||
self.start_payloads.append(json.loads(await websocket.recv()))
|
||||
await script(websocket, self.start_payloads[-1])
|
||||
|
||||
self.server = await serve(handler, "127.0.0.1", 0)
|
||||
port = next(iter(self.server.sockets)).getsockname()[1]
|
||||
return f"ws://127.0.0.1:{port}/v1/realtime/video"
|
||||
|
||||
async def __aexit__(self, *exc) -> None:
|
||||
assert self.server is not None
|
||||
self.server.close()
|
||||
await self.server.wait_closed()
|
||||
|
||||
return _Server()
|
||||
|
||||
|
||||
async def _emit_rollout(websocket, payload, *, intervals=None, chunks=None, trailer=True) -> None:
|
||||
"""Replay the documented event order: start, metadata+binary per chunk, done."""
|
||||
num_chunks = chunks if chunks is not None else len(payload["extra_params"]["camera_action_script"])
|
||||
await websocket.send(json.dumps({"type": "video.start", "request_id": "req-1", "format": "m4s"}))
|
||||
for index in range(num_chunks):
|
||||
if intervals is not None:
|
||||
await asyncio.sleep(intervals[index])
|
||||
frames = pixel_frames_in_chunk(index)
|
||||
body = bytes([index % 256]) * (100 + index)
|
||||
await websocket.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "video.chunk_metadata",
|
||||
"request_id": "req-1",
|
||||
"kind": "media",
|
||||
"num_frames": frames,
|
||||
"byte_length": len(body),
|
||||
"generation_chunk_index": index,
|
||||
}
|
||||
)
|
||||
)
|
||||
await websocket.send(body)
|
||||
if trailer:
|
||||
tail = b"\x00" * 8
|
||||
await websocket.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "video.chunk_metadata",
|
||||
"request_id": "req-1",
|
||||
"kind": "trailer",
|
||||
"num_frames": 0,
|
||||
"byte_length": len(tail),
|
||||
"generation_chunk_index": None,
|
||||
}
|
||||
)
|
||||
)
|
||||
await websocket.send(tail)
|
||||
await websocket.send(json.dumps({"type": "session.done", "stopped": False, "chunks": num_chunks}))
|
||||
|
||||
|
||||
def _run(coro):
|
||||
return asyncio.run(asyncio.wait_for(coro, timeout=30))
|
||||
|
||||
|
||||
def test_session_records_one_chunk_per_block_and_ignores_the_trailer() -> None:
|
||||
workload = _workload(num_chunks=4)
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(_emit_rollout)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
result = await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0,
|
||||
collect_media=True,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
|
||||
assert [record.index for record in result.records] == [0, 1, 2, 3]
|
||||
assert [record.num_frames for record in result.records] == [9, 12, 12, 12]
|
||||
assert result.request_id == "req-1"
|
||||
assert result.ttfc_s is not None and result.ttfc_s > 0
|
||||
# The trailer's bytes are kept for remuxing but carry no chunk record.
|
||||
assert len(result.media) == sum(record.byte_length for record in result.records) + 8
|
||||
assert server.start_payloads[0]["num_frames"] == workload.num_frames
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_measured_intervals_track_the_server_cadence() -> None:
|
||||
workload = _workload(num_chunks=3)
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
await _emit_rollout(websocket, payload, intervals=[0.05, 0.30, 0.05])
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
result = await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
|
||||
intervals = [record.inter_arrival_s for record in result.records]
|
||||
assert intervals[1] == pytest.approx(0.30, abs=0.15)
|
||||
assert intervals[2] < intervals[1], "a fast chunk must not inherit the slow one's interval"
|
||||
assert result.records[0].arrival_s == pytest.approx(result.ttfc_s)
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_a_short_rollout_fails_loudly_instead_of_reporting_a_partial_cadence() -> None:
|
||||
workload = _workload(num_chunks=4)
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
await _emit_rollout(websocket, payload, chunks=2)
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
with pytest.raises(BenchmarkError, match="Expected 4 chunks"):
|
||||
await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_a_server_error_event_aborts_the_session() -> None:
|
||||
workload = _workload(num_chunks=2)
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
await websocket.send(json.dumps({"type": "error", "message": "resolution mismatch"}))
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
with pytest.raises(BenchmarkError, match="resolution mismatch.*requested 2 chunks"):
|
||||
await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_a_stalled_server_times_out_rather_than_hanging() -> None:
|
||||
workload = _workload(num_chunks=2)
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
await websocket.send(json.dumps({"type": "video.start", "request_id": "req-1", "format": "m4s"}))
|
||||
await asyncio.sleep(5)
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
with pytest.raises(BenchmarkError, match="No media chunk for"):
|
||||
await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=0.4,
|
||||
chunk_timeout=0.4,
|
||||
ping_interval=0,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_keepalive_pings_reach_the_server_during_a_slow_first_chunk() -> None:
|
||||
"""A compiled first block can outlast the server's stall timeout."""
|
||||
workload = _workload(num_chunks=1)
|
||||
seen: list[str] = []
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
await websocket.send(json.dumps({"type": "video.start", "request_id": "req-1", "format": "m4s"}))
|
||||
|
||||
async def drain() -> None:
|
||||
async for message in websocket:
|
||||
event = json.loads(message)
|
||||
seen.append(event["type"])
|
||||
if event["type"] == "session.ping":
|
||||
await websocket.send(json.dumps({"type": "session.pong"}))
|
||||
|
||||
drainer = asyncio.create_task(drain())
|
||||
await asyncio.sleep(0.35)
|
||||
await _emit_rollout(websocket, payload, trailer=False)
|
||||
drainer.cancel()
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
result = await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0.1,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
assert len(result.records) == 1
|
||||
assert "session.ping" in seen
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_prompt_updates_are_sent_on_their_chunk_boundary() -> None:
|
||||
workload = Workload(
|
||||
prompt="start",
|
||||
image_reference=_IMAGE,
|
||||
camera_script=build_camera_script(3, "forward"),
|
||||
prompt_updates=(PromptUpdate(after_chunk=0, prompt="Rain begins", transition_chunks=1),),
|
||||
)
|
||||
received: list[dict] = []
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
async def drain() -> None:
|
||||
async for message in websocket:
|
||||
received.append(json.loads(message))
|
||||
|
||||
drainer = asyncio.create_task(drain())
|
||||
await _emit_rollout(websocket, payload, intervals=[0.02, 0.15, 0.02], trailer=False)
|
||||
await asyncio.sleep(0.05)
|
||||
drainer.cancel()
|
||||
|
||||
async def scenario() -> None:
|
||||
server = _serve(script)
|
||||
url = await server.__aenter__()
|
||||
try:
|
||||
await run_session(
|
||||
url,
|
||||
"model",
|
||||
workload,
|
||||
first_chunk_timeout=10,
|
||||
chunk_timeout=10,
|
||||
ping_interval=0,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
)
|
||||
finally:
|
||||
await server.__aexit__(None, None, None)
|
||||
interactions = [event for event in received if event.get("type") == "session.interaction"]
|
||||
assert len(interactions) == 1
|
||||
assert interactions[0]["interaction"]["event"]["prompt"] == "Rain begins"
|
||||
assert interactions[0]["interaction"]["transition_chunks"] == 1
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("delivered", [0, 1])
|
||||
def test_pongs_do_not_extend_media_deadlines(delivered) -> None:
|
||||
seen = []
|
||||
|
||||
async def script(websocket, payload) -> None:
|
||||
if delivered:
|
||||
await websocket.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "video.chunk_metadata",
|
||||
"kind": "media",
|
||||
"generation_chunk_index": 0,
|
||||
"num_frames": 9,
|
||||
}
|
||||
)
|
||||
)
|
||||
await websocket.send(b"media")
|
||||
async for message in websocket:
|
||||
seen.append(json.loads(message)["type"])
|
||||
await websocket.send(json.dumps({"type": "session.pong"}))
|
||||
|
||||
async def scenario() -> None:
|
||||
async with _serve(script) as url:
|
||||
with pytest.raises(BenchmarkError, match=f"after {delivered} chunk"):
|
||||
await asyncio.wait_for(
|
||||
run_session(
|
||||
url,
|
||||
"model",
|
||||
_workload(num_chunks=2),
|
||||
first_chunk_timeout=0.25,
|
||||
chunk_timeout=0.25,
|
||||
ping_interval=0.03,
|
||||
collect_media=False,
|
||||
print_chunks=False,
|
||||
),
|
||||
timeout=2,
|
||||
)
|
||||
assert "session.ping" in seen
|
||||
|
||||
_run(scenario())
|
||||
|
||||
|
||||
def test_terminal_chunk_is_only_excluded_from_steady_metrics() -> None:
|
||||
records = _records([1.0] + [0.1] * 5 + [1.2, 0.8, 0.1])
|
||||
metrics = compute_metrics(records, fps=12, warmup_chunks=6)
|
||||
assert metrics["steady_chunks"] == 2
|
||||
assert metrics["interval_steady"]["mean_ms"] == pytest.approx(1000)
|
||||
assert metrics["steady_video_rtf"] == pytest.approx(1)
|
||||
assert metrics["slo_attainment"] == pytest.approx(0.5)
|
||||
assert metrics["interval_all"]["count"] == 8
|
||||
assert metrics["total_frames"] == 105
|
||||
assert metrics["wall_seconds"] == pytest.approx(records[-1].arrival_s)
|
||||
assert metrics["playback"]["total_stall_ms"] == pytest.approx(
|
||||
simulate_playback(records, fps=12).total_stall_s * 1000
|
||||
)
|
||||
|
||||
|
||||
def test_terminal_chunk_alone_does_not_establish_steady_state() -> None:
|
||||
metrics = compute_metrics(_records([1.0] * 7), fps=12, warmup_chunks=6)
|
||||
assert not metrics["steady_state_reached"]
|
||||
assert "steady_video_rtf" not in metrics
|
||||
|
||||
|
||||
def test_aggregate_preserves_custom_deadline_and_weights_intervals() -> None:
|
||||
fast = compute_metrics(_records([1.0, 0.5, 0.1]), fps=12, warmup_chunks=0, slo_ms=700)
|
||||
slow = compute_metrics(_records([1.0, 0.9, 0.9, 0.9, 0.1]), fps=12, warmup_chunks=0, slo_ms=700)
|
||||
aggregate = aggregate_metrics([fast, slow], fps=12)
|
||||
assert aggregate["chunk_deadline_ms"] == 700
|
||||
assert aggregate["steady_interval_ms_mean"] == pytest.approx(800)
|
||||
slow["chunk_deadline_ms"] = 800
|
||||
with pytest.raises(ValueError, match="different chunk deadlines"):
|
||||
aggregate_metrics([fast, slow], fps=12)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"flags, expected_shift, expected_negative",
|
||||
[
|
||||
([], 7.0, "file negative"),
|
||||
(["--flow-shift", "5", "--negative-prompt", "CLI negative"], 5.0, "CLI negative"),
|
||||
(["--negative-prompt", ""], 7.0, ""),
|
||||
],
|
||||
)
|
||||
def test_cli_workload_generation_overrides(tmp_path, flags, expected_shift, expected_negative) -> None:
|
||||
path = tmp_path / "workload.json"
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"image": _IMAGE,
|
||||
"num_chunks": 3,
|
||||
"flow_shift": 7.0,
|
||||
"negative_prompt": "file negative",
|
||||
}
|
||||
)
|
||||
)
|
||||
workload = build_workload(parse_args(["--workload", str(path), *flags]))
|
||||
assert workload.flow_shift == expected_shift
|
||||
assert workload.negative_prompt == expected_negative
|
||||
|
||||
|
||||
def test_builtin_workload_keeps_default_flow_shift() -> None:
|
||||
assert build_workload(parse_args(["--image", _IMAGE])).flow_shift == 5.0
|
||||
|
||||
|
||||
def test_short_sample_report_qualifies_tail_percentiles(capsys) -> None:
|
||||
metrics = compute_metrics(_records([1.0] * 16), fps=12)
|
||||
print_report(metrics, workload=_workload(num_chunks=16), endpoint="ws://test", sessions=1, target_fps=12)
|
||||
assert "not reliable tail estimates" in capsys.readouterr().out
|
||||
+4
-2
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Hunyuan-Image stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py``.
|
||||
|
||||
@@ -34,8 +37,7 @@ server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) i
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.diffusion
|
||||
# Pytest marks (hardware, local_model, slow, diffusion) come from test_hunyuan_image.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_hunyuan_image(omni_server, stability_benchmark_params):
|
||||
@@ -0,0 +1,70 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""
|
||||
HunyuanVideo-1.5 I2V stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py`` / ``v1/videos``.
|
||||
|
||||
Configuration: ``tests/dfx/stability/tests/test_hunyuanvideo15.json``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.dfx.conftest import (
|
||||
create_benchmark_indices,
|
||||
create_test_parameter_mapping,
|
||||
create_unique_server_pytest_params,
|
||||
load_configs,
|
||||
)
|
||||
from tests.dfx.stability.helpers import _run_one_diffusion_batch, run_stability_benchmark_loop
|
||||
|
||||
STABILITY_DIR = Path(__file__).resolve().parent.parent
|
||||
DEPLOY_CONFIGS_DIR = STABILITY_DIR / "deploy"
|
||||
CONFIG_FILE_PATH = str(STABILITY_DIR / "tests" / "test_hunyuanvideo15.json")
|
||||
DEFAULT_NUM_PROMPTS_PER_BATCH = 50
|
||||
STABILITY_SERVER_TIMEOUT_ARGS = ["--stage-init-timeout", "600", "--init-timeout", "900"]
|
||||
|
||||
try:
|
||||
BENCHMARK_CONFIGS = load_configs(CONFIG_FILE_PATH)
|
||||
except FileNotFoundError:
|
||||
BENCHMARK_CONFIGS = []
|
||||
|
||||
test_params = create_unique_server_pytest_params(BENCHMARK_CONFIGS, DEPLOY_CONFIGS_DIR) if BENCHMARK_CONFIGS else []
|
||||
server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) if BENCHMARK_CONFIGS else {}
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
# Pytest marks (hardware, local_model, slow, diffusion) come from test_hunyuanvideo15.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_hunyuanvideo15(omni_server, stability_benchmark_params):
|
||||
test_name = stability_benchmark_params["test_name"]
|
||||
params = stability_benchmark_params["params"]
|
||||
duration_sec = params.get("duration_sec", 300)
|
||||
num_prompts_per_batch = params.get("num_prompts_per_batch", DEFAULT_NUM_PROMPTS_PER_BATCH)
|
||||
request_rate = params.get("request_rate")
|
||||
max_concurrency = params.get("max_concurrency")
|
||||
|
||||
bench_params = {
|
||||
k: v
|
||||
for k, v in params.items()
|
||||
if k not in ("duration_sec", "request_rate", "max_concurrency", "num_prompts_per_batch")
|
||||
}
|
||||
|
||||
result = run_stability_benchmark_loop(
|
||||
host=omni_server.host,
|
||||
port=omni_server.port,
|
||||
model=omni_server.model,
|
||||
duration_sec=duration_sec,
|
||||
params=bench_params,
|
||||
request_rate=request_rate,
|
||||
max_concurrency=max_concurrency,
|
||||
result_dir=str(STABILITY_DIR),
|
||||
num_prompts_per_batch=num_prompts_per_batch,
|
||||
run_one_batch=_run_one_diffusion_batch,
|
||||
)
|
||||
|
||||
assert result.get("failed", 0) == 0, f"[{test_name}] Failed requests detected: {result.get('errors', [])}"
|
||||
assert result.get("completed", 0) > 0, f"[{test_name}] No requests completed"
|
||||
@@ -0,0 +1,71 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
MiniCPM-o-4.5 stability: OmniServer + ``vllm bench serve --omni`` for a fixed duration.
|
||||
|
||||
Configuration: ``tests/dfx/stability/tests/test_minicpmo_4_5.json``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.dfx.conftest import (
|
||||
create_benchmark_indices,
|
||||
create_test_parameter_mapping,
|
||||
create_unique_server_pytest_params,
|
||||
load_configs,
|
||||
)
|
||||
from tests.dfx.stability.helpers import _run_one_vllm_bench_batch, run_stability_benchmark_loop
|
||||
|
||||
STABILITY_DIR = Path(__file__).resolve().parent.parent
|
||||
DEPLOY_CONFIGS_DIR = STABILITY_DIR / "deploy"
|
||||
CONFIG_FILE_PATH = str(STABILITY_DIR / "tests" / "test_minicpmo_4_5.json")
|
||||
DEFAULT_NUM_PROMPTS_PER_BATCH = 20
|
||||
STABILITY_SERVER_TIMEOUT_ARGS = ["--stage-init-timeout", "600"]
|
||||
|
||||
try:
|
||||
BENCHMARK_CONFIGS = load_configs(CONFIG_FILE_PATH)
|
||||
except FileNotFoundError:
|
||||
BENCHMARK_CONFIGS = []
|
||||
|
||||
test_params = create_unique_server_pytest_params(BENCHMARK_CONFIGS, DEPLOY_CONFIGS_DIR) if BENCHMARK_CONFIGS else []
|
||||
server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) if BENCHMARK_CONFIGS else {}
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
# Pytest marks (hardware, local_model, slow, omni) come from test_minicpmo_4_5.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_minicpmo_4_5(omni_server, stability_benchmark_params):
|
||||
test_name = stability_benchmark_params["test_name"]
|
||||
params = stability_benchmark_params["params"]
|
||||
duration_sec = params.get("duration_sec", 300)
|
||||
num_prompts_per_batch = params.get("num_prompts_per_batch", DEFAULT_NUM_PROMPTS_PER_BATCH)
|
||||
request_rate = params.get("request_rate")
|
||||
max_concurrency = params.get("max_concurrency")
|
||||
|
||||
bench_params = {
|
||||
k: v
|
||||
for k, v in params.items()
|
||||
if k not in ("duration_sec", "request_rate", "max_concurrency", "num_prompts_per_batch")
|
||||
}
|
||||
|
||||
result = run_stability_benchmark_loop(
|
||||
host=omni_server.host,
|
||||
port=omni_server.port,
|
||||
model=omni_server.model,
|
||||
duration_sec=duration_sec,
|
||||
params=bench_params,
|
||||
request_rate=request_rate,
|
||||
max_concurrency=max_concurrency,
|
||||
result_dir=str(STABILITY_DIR),
|
||||
num_prompts_per_batch=num_prompts_per_batch,
|
||||
run_one_batch=_run_one_vllm_bench_batch,
|
||||
)
|
||||
|
||||
assert result.get("failed", 0) == 0, f"[{test_name}] Failed requests detected: {result.get('errors', [])}"
|
||||
assert result.get("completed", 0) > 0, f"[{test_name}] No requests completed"
|
||||
@@ -0,0 +1,91 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
MiniMax-H3 T2V stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py`` / ``v1/videos``.
|
||||
|
||||
Configuration: ``tests/dfx/stability/tests/test_minimax_h3.json``.
|
||||
|
||||
``--lora-path`` is resolved like e2e FastH3 / Buildkite ``test-merge.yml``:
|
||||
set ``VLLM_TEST_MINIMAX_H3_FASTH3_LORA`` to the adapter file, or populate the local
|
||||
HF cache for ``FastVideo/FastVideo-FastH3-4-step-Preview-v1-LoRA``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.dfx.conftest import (
|
||||
create_benchmark_indices,
|
||||
create_test_parameter_mapping,
|
||||
create_unique_server_pytest_params,
|
||||
load_configs,
|
||||
)
|
||||
from tests.dfx.stability.helpers import _run_one_diffusion_batch, run_stability_benchmark_loop
|
||||
from tests.e2e.online_serving.minimax_h3._common import FASTH3_LORA
|
||||
|
||||
STABILITY_DIR = Path(__file__).resolve().parent.parent
|
||||
DEPLOY_CONFIGS_DIR = STABILITY_DIR / "deploy"
|
||||
CONFIG_FILE_PATH = str(STABILITY_DIR / "tests" / "test_minimax_h3.json")
|
||||
DEFAULT_NUM_PROMPTS_PER_BATCH = 20
|
||||
STABILITY_SERVER_TIMEOUT_ARGS = ["--stage-init-timeout", "1800", "--init-timeout", "1800"]
|
||||
|
||||
|
||||
def _inject_fasth3_lora_path(configs: list[dict]) -> list[dict]:
|
||||
"""Fill serve_args.lora-path from VLLM_TEST_MINIMAX_H3_FASTH3_LORA / HF cache."""
|
||||
if not FASTH3_LORA:
|
||||
return configs
|
||||
for config in configs:
|
||||
serve_args = config.setdefault("server_params", {}).setdefault("serve_args", {})
|
||||
serve_args["lora-path"] = FASTH3_LORA
|
||||
return configs
|
||||
|
||||
|
||||
try:
|
||||
BENCHMARK_CONFIGS = _inject_fasth3_lora_path(load_configs(CONFIG_FILE_PATH))
|
||||
except FileNotFoundError:
|
||||
BENCHMARK_CONFIGS = []
|
||||
|
||||
test_params = create_unique_server_pytest_params(BENCHMARK_CONFIGS, DEPLOY_CONFIGS_DIR) if BENCHMARK_CONFIGS else []
|
||||
server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) if BENCHMARK_CONFIGS else {}
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
# Pytest marks (hardware, local_model, slow, diffusion) come from test_minimax_h3.json.
|
||||
@pytest.mark.skipif(
|
||||
FASTH3_LORA is None,
|
||||
reason="set VLLM_TEST_MINIMAX_H3_FASTH3_LORA or populate the local HF cache",
|
||||
)
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_minimax_h3(omni_server, stability_benchmark_params):
|
||||
test_name = stability_benchmark_params["test_name"]
|
||||
params = stability_benchmark_params["params"]
|
||||
duration_sec = params.get("duration_sec", 300)
|
||||
num_prompts_per_batch = params.get("num_prompts_per_batch", DEFAULT_NUM_PROMPTS_PER_BATCH)
|
||||
request_rate = params.get("request_rate")
|
||||
max_concurrency = params.get("max_concurrency")
|
||||
|
||||
bench_params = {
|
||||
k: v
|
||||
for k, v in params.items()
|
||||
if k not in ("duration_sec", "request_rate", "max_concurrency", "num_prompts_per_batch")
|
||||
}
|
||||
|
||||
result = run_stability_benchmark_loop(
|
||||
host=omni_server.host,
|
||||
port=omni_server.port,
|
||||
model=omni_server.model,
|
||||
duration_sec=duration_sec,
|
||||
params=bench_params,
|
||||
request_rate=request_rate,
|
||||
max_concurrency=max_concurrency,
|
||||
result_dir=str(STABILITY_DIR),
|
||||
num_prompts_per_batch=num_prompts_per_batch,
|
||||
run_one_batch=_run_one_diffusion_batch,
|
||||
)
|
||||
|
||||
assert result.get("failed", 0) == 0, f"[{test_name}] Failed requests detected: {result.get('errors', [])}"
|
||||
assert result.get("completed", 0) > 0, f"[{test_name}] No requests completed"
|
||||
+4
-2
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Qwen3-Omni stability: OmniServer + ``vllm bench serve --omni`` for a fixed duration.
|
||||
|
||||
@@ -34,8 +37,7 @@ server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) i
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.omni
|
||||
# Pytest marks (hardware, local_model, slow, omni) come from test_qwen3_omni.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_qwen3_omni(omni_server, stability_benchmark_params):
|
||||
+4
-2
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Qwen3-TTS stability: OmniServer + ``vllm bench serve --omni`` for a fixed duration.
|
||||
|
||||
@@ -34,8 +37,7 @@ server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) i
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.tts
|
||||
# Pytest marks (hardware, local_model, slow, tts) come from test_qwen3_tts.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_qwen3_tts(omni_server, stability_benchmark_params):
|
||||
+4
-2
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Qwen-Image stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py``.
|
||||
|
||||
@@ -34,8 +37,7 @@ server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) i
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.diffusion
|
||||
# Pytest marks (hardware, local_model, slow, diffusion) come from test_qwen_image.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_qwen_image(omni_server, stability_benchmark_params):
|
||||
+4
-2
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Wan2.2 T2V stability: OmniServer (diffusion) + ``diffusion_benchmark_serving.py`` / ``v1/videos``.
|
||||
|
||||
@@ -34,8 +37,7 @@ server_to_benchmark_mapping = create_test_parameter_mapping(BENCHMARK_CONFIGS) i
|
||||
benchmark_indices = create_benchmark_indices(BENCHMARK_CONFIGS, server_to_benchmark_mapping)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.diffusion
|
||||
# Pytest marks (hardware, local_model, slow, diffusion) come from test_wan22.json.
|
||||
@pytest.mark.parametrize("omni_server", test_params, indirect=True)
|
||||
@pytest.mark.parametrize("stability_benchmark_params", benchmark_indices, indirect=True)
|
||||
def test_stability_wan22(omni_server, stability_benchmark_params):
|
||||
@@ -7,10 +7,11 @@
|
||||
"res": {
|
||||
"cuda": "H800"
|
||||
},
|
||||
"num_cards": 2
|
||||
"num_cards": 4
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
@@ -44,5 +45,53 @@
|
||||
"enable_negative_prompt": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"test_name": "test_hunyuan_image_stability_tp2_sp2_a3",
|
||||
"description": "A3: same as perf test_hunyuan_image_tp2_sp2 — DiT-only, TP=2 USP=2, 4 dies, no fp8",
|
||||
"mark": [
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"npu": "A3"
|
||||
},
|
||||
"num_cards": 4
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
"model": "tencent/HunyuanImage-3.0-Instruct",
|
||||
"serve_args": {
|
||||
"deploy-config": "vllm_omni/deploy/hunyuan_image3_dit.yaml",
|
||||
"tensor-parallel-size": 2,
|
||||
"ulysses-degree": 2,
|
||||
"vae-patch-parallel-size": 4,
|
||||
"vae-use-tiling": true,
|
||||
"enable-diffusion-pipeline-profiler": true
|
||||
}
|
||||
},
|
||||
"benchmark_params": [
|
||||
{
|
||||
"dataset": "random",
|
||||
"task": "t2i",
|
||||
"backend": "vllm-omni",
|
||||
"duration_sec": 86400,
|
||||
"max_concurrency": 1,
|
||||
"num_prompts_per_batch": 50,
|
||||
"width": {
|
||||
"min": 512,
|
||||
"max": 1024
|
||||
},
|
||||
"height": {
|
||||
"min": 512,
|
||||
"max": 1024
|
||||
},
|
||||
"num_inference_steps": 50,
|
||||
"enable_negative_prompt": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,57 @@
|
||||
[
|
||||
{
|
||||
"test_name": "test_hunyuanvideo15_i2v_cachedit_tp2_vae_patch2_stability",
|
||||
"description": "HunyuanVideo-1.5 I2V 24h: CacheDiT + TP=2 + VAE patch parallel=2 + VAE tiling",
|
||||
"mark": [
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"cuda": ["H800"]
|
||||
},
|
||||
"num_cards": 2
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
"model": "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_i2v",
|
||||
"serve_args": {
|
||||
"flow-shift": 5.0,
|
||||
"cache-backend": "cache_dit",
|
||||
"tensor-parallel-size": 2,
|
||||
"vae-patch-parallel-size": 2,
|
||||
"vae-use-tiling": true,
|
||||
"enable-diffusion-pipeline-profiler": true
|
||||
}
|
||||
},
|
||||
"benchmark_params": [
|
||||
{
|
||||
"dataset": "random",
|
||||
"task": "i2v",
|
||||
"backend": "v1/videos",
|
||||
"duration_sec": 86400,
|
||||
"max_concurrency": 1,
|
||||
"num_prompts_per_batch": 50,
|
||||
"num_input_images": 1,
|
||||
"seed": 42,
|
||||
"enable_negative_prompt": true,
|
||||
"random_request_config": [
|
||||
{
|
||||
"width": 832,
|
||||
"height": 480,
|
||||
"num_inference_steps": 4,
|
||||
"num_frames": 33,
|
||||
"fps": 24,
|
||||
"weight": 1
|
||||
}
|
||||
],
|
||||
"extra_body": {
|
||||
"guidance_scale": 6.0,
|
||||
"flow_shift": 5.0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,53 @@
|
||||
[
|
||||
{
|
||||
"test_name": "test_minicpmo_4_5_stability_ready",
|
||||
"description": "MiniCPM-o-4.5 ready deploy + seed-tts chat/audio stability (from perf test_minicpmo_4_5_ready)",
|
||||
"mark": [
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"cuda": "H800"
|
||||
},
|
||||
"num_cards": 1
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"omni"
|
||||
],
|
||||
"server_params": {
|
||||
"model": "openbmb/MiniCPM-o-4_5",
|
||||
"extra_cli_args": [
|
||||
"--deploy-config",
|
||||
"vllm_omni/deploy/minicpmo_4_5.yaml",
|
||||
"--trust-remote-code"
|
||||
]
|
||||
},
|
||||
"benchmark_params": [
|
||||
{
|
||||
"dataset_name": "seed-tts",
|
||||
"dataset_path": "zhaochenyang20/seed-tts-eval",
|
||||
"backend": "openai-chat-omni",
|
||||
"endpoint": "/v1/chat/completions",
|
||||
"duration_sec": 86400,
|
||||
"max_concurrency": 1,
|
||||
"num_prompts_per_batch": 50,
|
||||
"no_oversample": true,
|
||||
"disable_shuffle": true,
|
||||
"trust_remote_code": true,
|
||||
"seed_tts_locale": "en",
|
||||
"extra_body": {
|
||||
"modalities": [
|
||||
"text",
|
||||
"audio"
|
||||
],
|
||||
"chat_template_kwargs": {
|
||||
"enable_thinking": false,
|
||||
"use_tts_template": true
|
||||
}
|
||||
},
|
||||
"percentile-metrics": "ttft,e2el,audio_ttfp,audio_rtf,audio_duration"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,62 @@
|
||||
[
|
||||
{
|
||||
"test_name": "test_minimax_h3_t2v_stability_4gpu",
|
||||
"description": "MiniMax-H3 FastH3 T2VA on 4 GPUs (USP4 + HSDP4, encoder-TP4, VAE-PP4 tile); fused lora-path from VLLM_TEST_MINIMAX_H3_FASTH3_LORA; requests must use num_inference_steps=4",
|
||||
"mark": [
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"cuda": "H800"
|
||||
},
|
||||
"num_cards": 4
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
"model": "MiniMaxAI/MiniMax-H3",
|
||||
"serve_args": {
|
||||
"trust-remote-code": true,
|
||||
"task-type": "fl2va",
|
||||
"num-gpus": 4,
|
||||
"usp": 4,
|
||||
"ring": 1,
|
||||
"use-hsdp": true,
|
||||
"hsdp-shard-size": 4,
|
||||
"text-encoder-tp-size": 4,
|
||||
"vae-patch-parallel-size": 4,
|
||||
"vae-parallel-mode": "tile",
|
||||
"vae-use-tiling": true,
|
||||
"stage-init-timeout": 1800,
|
||||
"init-timeout": 1800
|
||||
}
|
||||
},
|
||||
"benchmark_params": [
|
||||
{
|
||||
"dataset": "random",
|
||||
"task": "t2v",
|
||||
"backend": "v1/videos",
|
||||
"duration_sec": 86400,
|
||||
"max_concurrency": 1,
|
||||
"num_prompts_per_batch": 50,
|
||||
"seed": 42,
|
||||
"random_request_config": [
|
||||
{
|
||||
"width": 1344,
|
||||
"height": 768,
|
||||
"prompt": "Cinematic drone shot pushing through misty mountain ridges at sunrise, golden light catching the clouds, slow and smooth.",
|
||||
"num_inference_steps": 4,
|
||||
"num_frames": 209,
|
||||
"fps": 24,
|
||||
"weight": 1
|
||||
}
|
||||
],
|
||||
"extra_body": {
|
||||
"extra_params": "{\"task\":\"t2va\",\"duration\":8.7,\"aspect_ratio\":\"16:9\"}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -5,12 +5,14 @@
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"cuda": "H800"
|
||||
"cuda": "H800",
|
||||
"npu": "A3"
|
||||
},
|
||||
"num_cards": 2
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"omni"
|
||||
],
|
||||
"server_params": {
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"tts"
|
||||
],
|
||||
"server_params": {
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
@@ -36,5 +37,44 @@
|
||||
"enable_negative_prompt": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"test_name": "test_qwen_image_stability_a3",
|
||||
"mark": [
|
||||
{
|
||||
"hardware_marks": {
|
||||
"res": {
|
||||
"npu": "A3"
|
||||
},
|
||||
"num_cards": 1
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
"model": "Qwen/Qwen-Image"
|
||||
},
|
||||
"benchmark_params": [
|
||||
{
|
||||
"dataset": "random",
|
||||
"task": "t2i",
|
||||
"backend": "vllm-omni",
|
||||
"duration_sec": 86400,
|
||||
"max_concurrency": 1,
|
||||
"num_prompts_per_batch": 50,
|
||||
"width": {
|
||||
"min": 512,
|
||||
"max": 1000
|
||||
},
|
||||
"height": {
|
||||
"min": 512,
|
||||
"max": 1000
|
||||
},
|
||||
"num_inference_steps": 50,
|
||||
"enable_negative_prompt": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -12,6 +12,7 @@
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
@@ -54,6 +55,7 @@
|
||||
}
|
||||
},
|
||||
"local_model",
|
||||
"slow",
|
||||
"diffusion"
|
||||
],
|
||||
"server_params": {
|
||||
|
||||
@@ -493,6 +493,84 @@ def test_dist_zero_pad_only_applies_global_width_edges(monkeypatch: pytest.Monke
|
||||
assert last.shape == (1, 1, 2, 3)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
class _PlainDecoder(torch.nn.Module):
|
||||
"""A decoder with nothing to patch, so the install only wraps ``forward``."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.calls: list[dict] = []
|
||||
|
||||
def forward(self, x, feat_cache=None, feat_idx=None, first_chunk=False):
|
||||
self.calls.append({"feat_cache": feat_cache, "feat_idx": feat_idx, "first_chunk": first_chunk})
|
||||
return x
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
@pytest.mark.parametrize("world_size, dst", [(4, -1), (4, 4), (4, 5), (1, 1), (4, 1.5)])
|
||||
def test_install_rejects_invalid_destination_before_mutating_decoder(monkeypatch, world_size, dst):
|
||||
monkeypatch.setattr(wan_spatial_shard, "_rank_world", lambda group: (0, world_size))
|
||||
vae = SimpleNamespace(decoder=torch.nn.Identity())
|
||||
original_forward = vae.decoder.forward
|
||||
|
||||
def unexpected_patch(*args, **kwargs):
|
||||
pytest.fail("invalid destination must fail before patching modules")
|
||||
|
||||
monkeypatch.setattr(wan_spatial_shard, "_patch_decoder_modules", unexpected_patch)
|
||||
with pytest.raises(ValueError, match="dst must be None or an integer"):
|
||||
wan_spatial_shard.install_wan_spatial_shard_decode(vae, object(), dst=dst)
|
||||
assert vae.decoder.forward == original_forward
|
||||
assert not getattr(vae, "_vllm_omni_wan_spatial_shard_installed", False)
|
||||
|
||||
|
||||
def _install_on_plain_decoder(monkeypatch: pytest.MonkeyPatch, *, dst):
|
||||
monkeypatch.setattr(wan_spatial_shard, "_rank_world", lambda group: (1, 2))
|
||||
monkeypatch.setattr(
|
||||
wan_spatial_shard,
|
||||
"split_for_parallel_decode",
|
||||
lambda x, *, upsample_count, split_dim, group: (x, x.shape[wan_spatial_shard._spatial_dim(split_dim)]),
|
||||
)
|
||||
gathers: list[dict] = []
|
||||
|
||||
def gather(x, *, expected_extent, split_dim, group, dst=None):
|
||||
gathers.append({"expected_extent": expected_extent, "split_dim": split_dim, "dst": dst})
|
||||
return x
|
||||
|
||||
monkeypatch.setattr(wan_spatial_shard, "gather_and_trim_extent", gather)
|
||||
vae = SimpleNamespace(decoder=_PlainDecoder())
|
||||
wan_spatial_shard.install_wan_spatial_shard_decode(vae, object(), split_dim="width", dst=dst)
|
||||
return vae, gathers
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
@pytest.mark.parametrize("dst", [0, 1, None])
|
||||
def test_install_passes_the_assembling_rank_through_to_the_gather(monkeypatch: pytest.MonkeyPatch, dst):
|
||||
vae, gathers = _install_on_plain_decoder(monkeypatch, dst=dst)
|
||||
cache = [None]
|
||||
|
||||
out = vae.decoder(torch.zeros(1, 3, 1, 4, 6), feat_cache=cache, feat_idx=[0], first_chunk=True)
|
||||
|
||||
assert out.shape == (1, 3, 1, 4, 6)
|
||||
assert gathers == [{"expected_extent": 6, "split_dim": "width", "dst": dst}]
|
||||
# The streaming arguments reach the wrapped decoder untouched.
|
||||
assert vae.decoder.calls == [{"feat_cache": cache, "feat_idx": [0], "first_chunk": True}]
|
||||
assert vae._vllm_omni_wan_spatial_shard_dst == dst
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
def test_install_refuses_to_change_the_assembling_rank(monkeypatch: pytest.MonkeyPatch):
|
||||
vae, _ = _install_on_plain_decoder(monkeypatch, dst=None)
|
||||
|
||||
# Same settings again: a no-op, as before.
|
||||
wan_spatial_shard.install_wan_spatial_shard_decode(vae, object(), split_dim="width", dst=None)
|
||||
with pytest.raises(ValueError, match="already patched to assemble on None"):
|
||||
wan_spatial_shard.install_wan_spatial_shard_decode(vae, object(), split_dim="width", dst=0)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
def test_spatial_shard_height_gate_falls_back_for_partial_group(monkeypatch: pytest.MonkeyPatch):
|
||||
@@ -626,6 +704,105 @@ def _spatial_shard_decode_worker(rank: int, split_dim: str, return_dict, master_
|
||||
dist.destroy_process_group()
|
||||
|
||||
|
||||
_STREAMING_SHARD_CHUNKS = 3
|
||||
|
||||
|
||||
def _streaming_shard_worker(rank: int, return_dict, master_port: str) -> None:
|
||||
"""Sharded streaming decode with every rank keeping the frame, against an unsharded streaming reference.
|
||||
|
||||
Two sessions are interleaved chunk by chunk, so the per-session temporal cache
|
||||
and the halo exchange are exercised across successive calls, then one session
|
||||
is reset and must reproduce its opening chunk. Every rank checks every chunk.
|
||||
"""
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
destroy_model_parallel,
|
||||
get_sp_group,
|
||||
init_distributed_environment,
|
||||
initialize_model_parallel,
|
||||
)
|
||||
from vllm_omni.experimental.ar_diffusion.streaming_decode import WanStreamingDecoder
|
||||
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = master_port
|
||||
device = current_omni_platform.get_torch_device(rank)
|
||||
current_omni_platform.set_device(device)
|
||||
dtype = torch.float32
|
||||
backend = current_omni_platform.dist_backend
|
||||
init_distributed_environment(world_size=_SPATIAL_SHARD_WORLD_SIZE, rank=rank, local_rank=rank, backend=backend)
|
||||
initialize_model_parallel(
|
||||
sequence_parallel_size=_SPATIAL_SHARD_WORLD_SIZE, ulysses_degree=_SPATIAL_SHARD_WORLD_SIZE, backend=backend
|
||||
)
|
||||
# VLLM_OMNI_TEST_WAN_VAE may point at a local diffusers checkpoint (with or
|
||||
# without a ``vae`` subfolder) for machines without hub access.
|
||||
model = os.environ.get("VLLM_OMNI_TEST_WAN_VAE", _SPATIAL_SHARD_MODEL)
|
||||
local_vae_only = os.path.isdir(model) and not os.path.isdir(os.path.join(model, "vae"))
|
||||
load = {"torch_dtype": dtype} if local_vae_only else {"subfolder": _SPATIAL_SHARD_SUBFOLDER, "torch_dtype": dtype}
|
||||
try:
|
||||
reference_vae = DistributedAutoencoderKLWan.from_pretrained(model, **load).to(device=device, dtype=dtype).eval()
|
||||
sharded_vae = DistributedAutoencoderKLWan.from_pretrained(model, **load).to(device=device, dtype=dtype).eval()
|
||||
wan_spatial_shard.install_wan_spatial_shard_decode(
|
||||
sharded_vae, get_sp_group().device_group, split_dim="width", dst=None
|
||||
)
|
||||
reference = WanStreamingDecoder(reference_vae, bytes_per_pixel_fp32=1.0)
|
||||
sharded = WanStreamingDecoder(sharded_vae, bytes_per_pixel_fp32=1.0)
|
||||
|
||||
generator = torch.Generator(device=device).manual_seed(0)
|
||||
# Width 104 latents = 832 px: not divisible by two ranks' halo-padded shards without padding.
|
||||
shape = (1, reference_vae.config.z_dim, 1, _SPATIAL_SHARD_LATENT_HEIGHT, _SPATIAL_SHARD_LATENT_WIDTH)
|
||||
chunks = {
|
||||
name: [
|
||||
torch.randn(shape, generator=generator, device=device, dtype=dtype)
|
||||
for _ in range(_STREAMING_SHARD_CHUNKS)
|
||||
]
|
||||
for name in ("a", "b")
|
||||
}
|
||||
max_diff = 0.0
|
||||
with torch.inference_mode():
|
||||
ref_states = {name: reference.new_decode_state(name) for name in chunks}
|
||||
shard_states = {name: sharded.new_decode_state(name) for name in chunks}
|
||||
for index in range(_STREAMING_SHARD_CHUNKS):
|
||||
for name in ("a", "b"):
|
||||
expected = reference.decode_chunk(chunks[name][index], ref_states[name]).float()
|
||||
got = sharded.decode_chunk(chunks[name][index], shard_states[name]).float()
|
||||
if got.shape != expected.shape:
|
||||
raise AssertionError(
|
||||
f"rank {rank} {name}[{index}]: {tuple(got.shape)} != {tuple(expected.shape)}"
|
||||
)
|
||||
max_diff = max(max_diff, (got - expected).abs().max().item())
|
||||
# Reset session a: a fresh state must reproduce its opening chunk, on this rank too.
|
||||
shard_states["a"].release()
|
||||
ref_states["a"].release()
|
||||
shard_states["a"] = sharded.new_decode_state("a")
|
||||
ref_states["a"] = reference.new_decode_state("a")
|
||||
expected = reference.decode_chunk(chunks["a"][0], ref_states["a"]).float()
|
||||
got = sharded.decode_chunk(chunks["a"][0], shard_states["a"]).float()
|
||||
max_diff = max(max_diff, (got - expected).abs().max().item())
|
||||
return_dict[f"max_abs_diff_rank{rank}"] = max_diff
|
||||
return_dict[f"shape_rank{rank}"] = tuple(got.shape)
|
||||
finally:
|
||||
destroy_model_parallel()
|
||||
if dist.is_initialized():
|
||||
dist.destroy_process_group()
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.parallel
|
||||
@hardware_test(res={"cuda": ["H100", "B200"]}, num_cards=_SPATIAL_SHARD_WORLD_SIZE)
|
||||
def test_streaming_shard_decode_matches_unsharded_streaming_on_every_rank():
|
||||
manager = mp.get_context("spawn").Manager()
|
||||
return_dict = manager.dict()
|
||||
mp.spawn(_streaming_shard_worker, args=(return_dict, "29510"), nprocs=_SPATIAL_SHARD_WORLD_SIZE, join=True)
|
||||
|
||||
for rank in range(_SPATIAL_SHARD_WORLD_SIZE):
|
||||
assert f"max_abs_diff_rank{rank}" in return_dict, f"rank {rank} did not report"
|
||||
diff = return_dict[f"max_abs_diff_rank{rank}"]
|
||||
shape = return_dict[f"shape_rank{rank}"]
|
||||
print(f"streaming shard rank {rank}: max_abs_diff={diff:.6e} shape={shape}")
|
||||
assert shape[-1] == _SPATIAL_SHARD_LATENT_WIDTH * 8 and shape[-2] == _SPATIAL_SHARD_LATENT_HEIGHT * 8
|
||||
assert diff <= _SPATIAL_SHARD_TOLERANCE, f"rank {rank}: {diff} exceeds {_SPATIAL_SHARD_TOLERANCE}"
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.diffusion
|
||||
@pytest.mark.parallel
|
||||
|
||||
@@ -134,6 +134,8 @@ def _install_vllm_stubs() -> None:
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.quant_config = kwargs.pop("quant_config", None)
|
||||
self.prefix = kwargs.pop("prefix", "")
|
||||
del kwargs
|
||||
self.return_bias = return_bias
|
||||
self.weight = nn.Parameter(torch.empty(output_size, input_size))
|
||||
@@ -164,6 +166,8 @@ def _install_vllm_stubs() -> None:
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.quant_config = kwargs.pop("quant_config", None)
|
||||
self.prefix = kwargs.pop("prefix", "")
|
||||
del kwargs
|
||||
self.num_heads = total_num_heads
|
||||
self.num_kv_heads = total_num_kv_heads or total_num_heads
|
||||
|
||||
@@ -35,6 +35,8 @@ def _tiny_model(
|
||||
num_layers: int = 2,
|
||||
num_frames_per_block: int = 1,
|
||||
sliding_window_num_frames: int = 3,
|
||||
quant_config=None,
|
||||
prefix: str = "",
|
||||
attention_head_dim: int = 2,
|
||||
rope_max_seq_len: int = 16,
|
||||
):
|
||||
@@ -55,6 +57,8 @@ def _tiny_model(
|
||||
num_frames_per_block=num_frames_per_block,
|
||||
sliding_window_num_frames=sliding_window_num_frames,
|
||||
local_attn_size=-1,
|
||||
quant_config=quant_config,
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
|
||||
@@ -485,11 +489,52 @@ def test_constructor_rejects_non_null_image_embedding_fields(field: str) -> None
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_constructor_rejects_unsupported_quantization_with_runtime_error() -> None:
|
||||
@pytest.mark.parametrize("prefix", ["", "transformer"])
|
||||
@pytest.mark.parametrize("quantized", [False, True])
|
||||
def test_constructor_propagates_quantization_to_parallel_linears(prefix: str, quantized: bool) -> None:
|
||||
module = attention_tests._load_module()
|
||||
quant_config = object() if quantized else None
|
||||
model = _tiny_model(module, num_layers=1, quant_config=quant_config, prefix=prefix)
|
||||
block = model.blocks[0]
|
||||
quantized_linears = [
|
||||
model.c2ws_hidden_states_layer1,
|
||||
model.c2ws_hidden_states_layer2,
|
||||
block.self_attn.qkv,
|
||||
block.self_attn.o,
|
||||
block.cross_attn.q,
|
||||
block.cross_attn.k,
|
||||
block.cross_attn.v,
|
||||
block.cross_attn.o,
|
||||
block.ffn[0],
|
||||
block.ffn[2],
|
||||
block.cam_injector_layer1,
|
||||
block.cam_injector_layer2,
|
||||
]
|
||||
|
||||
with pytest.raises(RuntimeError, match="quant_config.*not supported"):
|
||||
module.CausalLingBotWorldTransformer3DModel(quant_config=object())
|
||||
assert len(quantized_linears) == 12
|
||||
assert all(layer.quant_config is quant_config for layer in quantized_linears)
|
||||
expected_names = {
|
||||
"c2ws_hidden_states_layer1",
|
||||
"c2ws_hidden_states_layer2",
|
||||
*(
|
||||
f"blocks.0.{name}"
|
||||
for name in (
|
||||
"self_attn.qkv",
|
||||
"self_attn.o",
|
||||
"cross_attn.q",
|
||||
"cross_attn.k",
|
||||
"cross_attn.v",
|
||||
"cross_attn.o",
|
||||
"ffn.0",
|
||||
"ffn.2",
|
||||
"cam_injector_layer1",
|
||||
"cam_injector_layer2",
|
||||
)
|
||||
),
|
||||
}
|
||||
assert {layer.prefix for layer in quantized_linears} == {
|
||||
f"{prefix}.{name}" if prefix else name for name in expected_names
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
|
||||
@@ -737,6 +737,99 @@ def test_component_discovery_uses_official_checkpoint_contract() -> None:
|
||||
assert module._loader_state.prefetch_calls == [("checkpoint", ("tokenizer", "text_encoder", "vae"), False)]
|
||||
|
||||
|
||||
def _ulysses_config(size: int):
|
||||
parallel_config = _od_config().parallel_config
|
||||
parallel_config.sequence_parallel_size = size
|
||||
parallel_config.ulysses_degree = size
|
||||
return _od_config(parallel_config=parallel_config)
|
||||
|
||||
|
||||
def _record_shard_install(monkeypatch, module, *, world_size: int):
|
||||
"""Stand in for the Ulysses group and the decoder patch; return what the install was asked for."""
|
||||
installs: list[dict] = []
|
||||
group = object()
|
||||
|
||||
def install(vae, group_arg, split_dim, *, dst):
|
||||
installs.append({"vae": vae, "group": group_arg, "split_dim": split_dim, "dst": dst})
|
||||
|
||||
monkeypatch.setattr(module, "install_wan_spatial_shard_decode", install)
|
||||
monkeypatch.setattr(module.LingBotWorldCausalDMDPipeline, "_vae_shard_group", lambda self: (group, world_size))
|
||||
return installs, group
|
||||
|
||||
|
||||
def test_a_multi_rank_deployment_shards_the_decoder_across_the_ulysses_ranks(monkeypatch) -> None:
|
||||
"""Multi-rank deployments shard decode by default."""
|
||||
module = _load_pipeline_module()
|
||||
installs, group = _record_shard_install(monkeypatch, module, world_size=2)
|
||||
|
||||
pipeline = module.LingBotWorldCausalDMDPipeline(od_config=_ulysses_config(2))
|
||||
|
||||
# Along the width, and assembled on every rank: each rank's post_decode consumes the frame.
|
||||
assert installs == [{"vae": pipeline.vae, "group": group, "split_dim": "width", "dst": None}]
|
||||
assert pipeline._vae_shard_split_dim == "width"
|
||||
|
||||
|
||||
def test_a_single_rank_deployment_leaves_the_decoder_alone(monkeypatch) -> None:
|
||||
module = _load_pipeline_module()
|
||||
installs, _ = _record_shard_install(monkeypatch, module, world_size=1)
|
||||
|
||||
pipeline = module.LingBotWorldCausalDMDPipeline(od_config=_ulysses_config(1))
|
||||
|
||||
assert installs == [] and pipeline._vae_shard_split_dim is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [True, False])
|
||||
@pytest.mark.parametrize("width, local_width", [(832, 208), (840, 216)])
|
||||
def test_streaming_decode_reservation_uses_padded_shards(monkeypatch, enabled, width, local_width):
|
||||
module = _load_pipeline_module()
|
||||
installs, _ = _record_shard_install(monkeypatch, module, world_size=4)
|
||||
config = _ulysses_config(4)
|
||||
config.model_config.update(lingbot_vae_spatial_sharding=enabled, ar_diffusion_height=480, ar_diffusion_width=width)
|
||||
pipeline = module.LingBotWorldCausalDMDPipeline(od_config=config)
|
||||
from vllm_omni.experimental.ar_diffusion.streaming_decode import WanStreamingDecoder
|
||||
|
||||
# Exercise the real byte estimator without constructing a checkpoint VAE.
|
||||
decoder = object.__new__(WanStreamingDecoder)
|
||||
decoder._bytes_per_pixel_fp32 = 16.0
|
||||
monkeypatch.setattr(pipeline, "_streaming_decoder", lambda: decoder)
|
||||
expected_width = local_width if enabled else width
|
||||
assert pipeline._streaming_decode_bytes_per_session() == 16 * 480 * expected_width
|
||||
assert len(installs) == int(enabled)
|
||||
assert pipeline._vae_shard_world_size == (4 if enabled else 1)
|
||||
assert config.parallel_config.sequence_parallel_size == config.parallel_config.ulysses_degree == 4
|
||||
|
||||
|
||||
def test_disabling_vae_sharding_does_not_require_a_shard_group(monkeypatch):
|
||||
module = _load_pipeline_module()
|
||||
config = _ulysses_config(4)
|
||||
config.model_config["lingbot_vae_spatial_sharding"] = False
|
||||
|
||||
def unexpected_group(self):
|
||||
pytest.fail("disabled VAE sharding must not access its process group")
|
||||
|
||||
monkeypatch.setattr(module.LingBotWorldCausalDMDPipeline, "_vae_shard_group", unexpected_group)
|
||||
pipeline = module.LingBotWorldCausalDMDPipeline(od_config=config)
|
||||
assert pipeline._vae_shard_split_dim is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["false", 0, None])
|
||||
def test_vae_sharding_switch_requires_a_boolean(value):
|
||||
module = _load_pipeline_module()
|
||||
config = _ulysses_config(4)
|
||||
config.model_config["lingbot_vae_spatial_sharding"] = value
|
||||
with pytest.raises(ValueError, match="lingbot_vae_spatial_sharding must be a boolean"):
|
||||
module.LingBotWorldCausalDMDPipeline(od_config=config)
|
||||
|
||||
|
||||
def test_vae_shard_refuses_a_group_of_the_wrong_size(monkeypatch) -> None:
|
||||
module = _load_pipeline_module()
|
||||
installs, _ = _record_shard_install(monkeypatch, module, world_size=4)
|
||||
|
||||
with pytest.raises(RuntimeError, match="sequence_parallel_size=2 but the Ulysses group has 4 ranks"):
|
||||
module.LingBotWorldCausalDMDPipeline(od_config=_ulysses_config(2))
|
||||
assert installs == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value", "feature"),
|
||||
[
|
||||
@@ -758,8 +851,9 @@ def test_unsupported_parallel_modes_fail_before_component_loading(field: str, va
|
||||
assert module._loader_state.prefetch_calls == []
|
||||
|
||||
|
||||
def test_pure_ulysses_parallel_config_is_supported() -> None:
|
||||
def test_pure_ulysses_parallel_config_is_supported(monkeypatch) -> None:
|
||||
module = _load_pipeline_module()
|
||||
_record_shard_install(monkeypatch, module, world_size=2)
|
||||
parallel_config = _od_config().parallel_config
|
||||
parallel_config.sequence_parallel_size = 2
|
||||
parallel_config.ulysses_degree = 2
|
||||
@@ -795,13 +889,14 @@ def test_unsupported_sp_config_fails_before_component_loading(overrides):
|
||||
assert module._loader_state.prefetch_calls == []
|
||||
|
||||
|
||||
def test_unsupported_quantization_fails_before_component_loading() -> None:
|
||||
def test_quantization_reaches_transformer_factory() -> None:
|
||||
module = _load_pipeline_module()
|
||||
quant_config = object()
|
||||
|
||||
with pytest.raises(NotImplementedError, match="quantization"):
|
||||
module.LingBotWorldCausalDMDPipeline(od_config=_od_config(quantization_config=object()))
|
||||
pipeline = module.LingBotWorldCausalDMDPipeline(od_config=_od_config(quantization_config=quant_config))
|
||||
|
||||
assert module._loader_state.prefetch_calls == []
|
||||
assert pipeline.transformer is not None
|
||||
assert _FakeTransformerFactory.last_call[1:] == (quant_config, "transformer")
|
||||
|
||||
|
||||
def test_official_scheduler_config_matches_fixed_dmd_contract() -> None:
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Minimal mock of vLLM-Omni's ``/v1/videos`` API for e2e tests.
|
||||
|
||||
Records every received multipart field to ``MOCK_STATE_FILE`` (JSON) so a test
|
||||
can assert exactly what the client serialized, and returns a synthetic MP4.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import Response
|
||||
from starlette.datastructures import UploadFile
|
||||
|
||||
app = FastAPI()
|
||||
_JOBS: dict[str, dict] = {}
|
||||
_STATE_FILE = os.environ.get("MOCK_STATE_FILE")
|
||||
|
||||
|
||||
def _record(fields: dict) -> None:
|
||||
if _STATE_FILE:
|
||||
with open(_STATE_FILE, "w") as f:
|
||||
json.dump(fields, f)
|
||||
|
||||
|
||||
def _synthetic_mp4() -> bytes:
|
||||
return subprocess.run(
|
||||
[
|
||||
"ffmpeg",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-y",
|
||||
"-f",
|
||||
"lavfi",
|
||||
"-i",
|
||||
"testsrc2=size=320x240:rate=24:duration=1",
|
||||
"-f",
|
||||
"lavfi",
|
||||
"-i",
|
||||
"sine=frequency=440:sample_rate=32000:duration=1",
|
||||
"-map",
|
||||
"0:v",
|
||||
"-map",
|
||||
"1:a",
|
||||
"-shortest",
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-ar",
|
||||
"32000",
|
||||
"-ac",
|
||||
"2",
|
||||
"-movflags",
|
||||
"frag_keyframe+empty_moov",
|
||||
"-f",
|
||||
"mp4",
|
||||
"pipe:1",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
).stdout
|
||||
|
||||
|
||||
@app.post("/v1/videos")
|
||||
async def create_video(request: Request):
|
||||
form = await request.form()
|
||||
fields = {}
|
||||
for key, value in form.items():
|
||||
if isinstance(value, UploadFile):
|
||||
data = await value.read()
|
||||
fields[key] = {
|
||||
"file": True,
|
||||
"size": len(data),
|
||||
"filename": value.filename,
|
||||
"content_type": value.content_type,
|
||||
}
|
||||
if value.content_type == "application/json":
|
||||
fields[key]["json"] = json.loads(data)
|
||||
else:
|
||||
fields[key] = str(value)
|
||||
_record(fields)
|
||||
|
||||
job_id = str(uuid.uuid4())
|
||||
_JOBS[job_id] = {"status": "queued"}
|
||||
return {"id": job_id, "status": "queued"}
|
||||
|
||||
|
||||
@app.get("/v1/videos/{job_id}")
|
||||
async def get_video(job_id: str):
|
||||
if job_id not in _JOBS:
|
||||
return {"status": "failed", "error": "unknown job"}
|
||||
return {"id": job_id, "status": "completed"}
|
||||
|
||||
|
||||
@app.get("/v1/videos/{job_id}/content")
|
||||
async def get_video_content(job_id: str):
|
||||
if job_id not in _JOBS:
|
||||
return Response(status_code=404)
|
||||
mp4 = await asyncio.to_thread(_synthetic_mp4)
|
||||
return Response(content=mp4, media_type="video/mp4")
|
||||
|
||||
|
||||
@app.delete("/v1/videos/{job_id}")
|
||||
async def delete_video(job_id: str):
|
||||
_JOBS.pop(job_id, None)
|
||||
return {"deleted": True}
|
||||
@@ -0,0 +1,80 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Unit tests for latent-mask serialization helpers."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from comfyui_vllm_omni.utils.latent_mask import scalar_mask_to_json, video_mask_to_grid_json
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_scalar_mask_to_json():
|
||||
assert scalar_mask_to_json(0.5) == "0.5"
|
||||
assert scalar_mask_to_json(1.0) == "1.0"
|
||||
with pytest.raises(ValueError):
|
||||
scalar_mask_to_json(1.5)
|
||||
with pytest.raises(ValueError):
|
||||
scalar_mask_to_json(-0.1)
|
||||
|
||||
|
||||
def test_video_mask_grid_shape():
|
||||
mask = torch.zeros(256, 448)
|
||||
grid = json.loads(video_mask_to_grid_json(mask, width=448, height=256, num_frames=107))
|
||||
assert len(grid) == 2 + 5 * ((107 - 5) // 17)
|
||||
assert len(grid[0]) == 256 // 16
|
||||
assert len(grid[0][0]) == 448 // 16
|
||||
|
||||
|
||||
def test_video_mask_grid_shape_non_aligned_frames():
|
||||
# 96 snaps up to 107 (17n+5), so Tv == 32, matching the server.
|
||||
grid = json.loads(video_mask_to_grid_json(torch.zeros(256, 448), width=448, height=256, num_frames=96))
|
||||
assert len(grid) == 32
|
||||
|
||||
|
||||
def test_video_mask_grid_shape_short_clip():
|
||||
# num_frames <= 5 -> Tv == 2.
|
||||
grid = json.loads(video_mask_to_grid_json(torch.zeros(64, 64), width=64, height=64, num_frames=1))
|
||||
assert len(grid) == 2
|
||||
|
||||
|
||||
def test_video_mask_grid_shape_unaligned_width():
|
||||
# width=500 floors to 480 (multiple of 32) -> gw == 30, not 31.
|
||||
grid = json.loads(video_mask_to_grid_json(torch.zeros(64, 64), width=500, height=256, num_frames=22))
|
||||
assert len(grid[0][0]) == 30
|
||||
|
||||
|
||||
def test_video_mask_3d_input():
|
||||
grid = json.loads(video_mask_to_grid_json(torch.ones(1, 256, 448), width=448, height=256, num_frames=107))
|
||||
assert grid[0][0][0] == 1.0
|
||||
|
||||
|
||||
def test_video_mask_temporal():
|
||||
# 3D mask: first half 0 (preserve), second half 1 (regenerate).
|
||||
mask = torch.zeros(7, 64, 64)
|
||||
mask[4:] = 1.0
|
||||
grid = json.loads(video_mask_to_grid_json(mask, width=64, height=64, num_frames=22))
|
||||
assert len(grid) == 7
|
||||
assert all(v == 0.0 for row in grid[0] for v in row)
|
||||
assert all(v == 1.0 for row in grid[-1] for v in row)
|
||||
|
||||
|
||||
def test_video_mask_temporal_resize():
|
||||
# 2 temporal slices resize to tv == 7.
|
||||
mask = torch.zeros(2, 64, 64)
|
||||
mask[1] = 1.0
|
||||
grid = json.loads(video_mask_to_grid_json(mask, width=64, height=64, num_frames=22))
|
||||
assert len(grid) == 7
|
||||
|
||||
|
||||
def test_video_mask_uniform_preserved():
|
||||
grid = json.loads(video_mask_to_grid_json(torch.full((64, 64), 0.5), width=64, height=64, num_frames=107))
|
||||
assert all(v == 0.5 for row in grid for cell in row for v in cell)
|
||||
|
||||
|
||||
def test_video_mask_values_in_range():
|
||||
grid = json.loads(video_mask_to_grid_json(torch.rand(128, 128), width=128, height=128, num_frames=22))
|
||||
assert all(0.0 <= v <= 1.0 for row in grid for cell in row for v in cell)
|
||||
@@ -0,0 +1,99 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""End-to-end test for latent-mask editing serialization.
|
||||
|
||||
Exercises ``VLLMOmniClient.generate_video`` with a ``latent_edit`` payload
|
||||
against a mock ``/v1/videos`` server and asserts the multipart fields the
|
||||
client produced. Runs on CPU: the ComfyUI ``comfy_api`` / ``comfy_extras``
|
||||
modules are mocked by this directory's ``conftest.py``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from comfy_api.input import VideoInput
|
||||
from comfyui_vllm_omni.utils.api_client import VLLMOmniClient
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_server(tmp_path):
|
||||
port = _free_port()
|
||||
state_file = tmp_path / "state.json"
|
||||
env = dict(os.environ, MOCK_STATE_FILE=str(state_file))
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "mock_videos_server:app", "--host", "127.0.0.1", "--port", str(port)],
|
||||
cwd=_TESTS_DIR,
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
try:
|
||||
deadline = time.time() + 30
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=1):
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.2)
|
||||
yield f"http://127.0.0.1:{port}/v1", state_file
|
||||
finally:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=10)
|
||||
|
||||
|
||||
def test_latent_edit_serialization(mock_server):
|
||||
base_url, state_file = mock_server
|
||||
|
||||
# A non-trivial video mask requires a source video. The mocked VideoInput
|
||||
# only needs to provide ``save_to`` for the client's multipart upload.
|
||||
source_video = VideoInput(b"mock_source_video")
|
||||
mask = torch.zeros(1, 120, 160)
|
||||
latent_edit = {"source_video": source_video, "video_mask": mask, "audio_mask": 0.5}
|
||||
|
||||
async def run():
|
||||
client = VLLMOmniClient(base_url)
|
||||
return await client.generate_video(
|
||||
model="MiniMaxAI/MiniMax-H3",
|
||||
prompt="restyle the clip",
|
||||
width=160,
|
||||
height=120,
|
||||
num_frames=22,
|
||||
fps=24,
|
||||
latent_edit=latent_edit,
|
||||
)
|
||||
|
||||
out = asyncio.run(run())
|
||||
assert out is not None
|
||||
|
||||
with open(state_file) as f:
|
||||
fields = json.load(f)
|
||||
|
||||
assert fields["source_video"]["file"] is True
|
||||
assert fields["source_video"]["content_type"] == "video/mp4"
|
||||
for name in ("video_noise_mask", "audio_noise_mask"):
|
||||
assert fields[name]["file"] is True
|
||||
assert fields[name]["content_type"] == "application/json"
|
||||
assert fields["audio_noise_mask"]["json"] == 0.5
|
||||
|
||||
video_mask = fields["video_noise_mask"]["json"]
|
||||
assert len(video_mask) == 7 # num_frames=22 aligns to 22 (17n+5) -> Tv = 7
|
||||
assert len(video_mask[0]) == 6 # height 120 floors to 96 (multiple of 32) -> gh 6
|
||||
assert len(video_mask[0][0]) == 10 # width 160 -> gw 10
|
||||
@@ -563,10 +563,11 @@ def test_from_cli_args_preserves_text_encoder_tp_size():
|
||||
def test_text_encoder_tp_size_reaches_default_diffusion_parallel_config():
|
||||
"""The preserved CLI value must land in DiffusionParallelConfig.
|
||||
|
||||
Forward the explicitly supplied override after from_cli_args, without
|
||||
injecting unrelated LLM defaults from the full EngineArgs dataclass into
|
||||
the strict diffusion ingress. The generic diffusion fallback resolves
|
||||
the field through ``DiffusionParallelConfig.from_stage_overrides``.
|
||||
Forward the preserved explicit override to the generic diffusion
|
||||
fallback, which resolves it through
|
||||
``DiffusionParallelConfig.from_stage_overrides``. Serializing all engine
|
||||
defaults would also forward unrelated LLM-only fields to strict diffusion
|
||||
ingress, unlike the explicit-kwargs library entrypoint.
|
||||
"""
|
||||
from vllm_omni.config.config_factory import StageConfigFactory
|
||||
|
||||
|
||||
Reference in new issue
Block a user