Merge remote-tracking branch 'origin/main' into qwen-image-2.1

# Conflicts:
#	vllm_omni/diffusion/executor/multiproc_executor.py
#	vllm_omni/diffusion/offloader/sequential_backend.py
This commit is contained in:
Isotr0py committed 2026-09-21 07:32:04 +00:00
commit 9174554e40
1332 files changed
+160051 -60504

No files matched your search

+10
View File
@@ -3,6 +3,7 @@
import pytest
import torch
from vllm.platforms import current_platform
from vllm_omni.attention import fish_kvcache_attn, fish_kvcache_backend
@@ -113,6 +114,15 @@ def test_fish_kvcache_enabled_by_default(monkeypatch):
assert not fish_kvcache_attn.is_fish_kvcache_attn_required()
def test_fish_kvcache_fast_path_is_unavailable_off_cuda(monkeypatch):
monkeypatch.setattr(current_platform, "is_cuda", lambda: False)
monkeypatch.setattr(
fish_kvcache_attn, "_triton_backend", lambda: pytest.fail("Triton backend must not load off CUDA")
)
assert not fish_kvcache_attn.is_available()
@pytest.mark.parametrize("value", ["", "1", "true", "yes", "on", "required"])
def test_fish_kvcache_enabled_values_are_consistent(monkeypatch, value):
monkeypatch.setenv("VLLM_OMNI_FISH_KVCACHE_ATTN", value)
@@ -0,0 +1,202 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Benchmark newline-split and fixed-size chunking of image file responses.
Both variants stream the exact payload `ImageGenerationResponse.stream_response()`
produces, so the measurement isolates the response layer: PNG encoding and ZIP
building are shared by the variants and excluded from the timings.
"""
from __future__ import annotations
import argparse
import asyncio
import base64
import hashlib
import io
import json
import statistics
import time
from collections.abc import AsyncIterator, Callable, Iterable
from dataclasses import dataclass
from pathlib import Path
from typing import cast
import numpy as np
from PIL import Image
from starlette.responses import StreamingResponse
from vllm_omni.entrypoints.openai.protocol.images import (
_FILE_RESPONSE_CHUNK_SIZE,
ImageData,
ImageGenerationResponse,
_iter_file_chunks,
)
@dataclass(frozen=True)
class BenchmarkVariant:
label: str
content: Callable[[bytes], Iterable[bytes] | AsyncIterator[memoryview]]
def _positive_int(value: str) -> int:
parsed = int(value)
if parsed < 1:
raise argparse.ArgumentTypeError("value must be at least 1")
return parsed
def _encode_png(*, width: int, height: int, seed: int) -> bytes:
"""Encode incompressible noise, so the payload looks like a real photo."""
rng = np.random.default_rng(seed)
pixels = rng.integers(0, 256, size=(height, width, 3), dtype=np.uint8)
buffer = io.BytesIO()
Image.fromarray(pixels, mode="RGB").save(buffer, format="png")
return buffer.getvalue()
async def _drain(response: StreamingResponse) -> tuple[bytes, int]:
"""Run a response through ASGI, returning its body and non-empty frame count."""
body = bytearray()
frames = 0
async def send(message: dict[str, object]) -> None:
nonlocal frames
if message["type"] == "http.response.body" and message["body"]:
frames += 1
body.extend(cast(bytes, message["body"]))
async def receive() -> dict[str, str]:
return {"type": "http.disconnect"}
scope = {"type": "http", "method": "GET", "asgi": {"spec_version": "2.4"}}
await response(scope, receive, send)
return bytes(body), frames
async def _build_payload(*, images: int, width: int, height: int, seed: int) -> bytes:
png = _encode_png(width=width, height=height, seed=seed)
response = ImageGenerationResponse(
created=0,
data=[ImageData(b64_json=base64.b64encode(png).decode()) for _ in range(images)],
output_format="png",
size=f"{width}x{height}",
)
payload, _ = await _drain(response.stream_response())
return payload
async def _measure(variant: BenchmarkVariant, payload: bytes) -> dict[str, object]:
response = StreamingResponse(variant.content(payload), media_type="application/octet-stream")
cpu_start = time.process_time_ns()
wall_start = time.perf_counter_ns()
body, frames = await _drain(response)
wall_ms = (time.perf_counter_ns() - wall_start) / 1_000_000
process_cpu_ms = (time.process_time_ns() - cpu_start) / 1_000_000
return {
"label": variant.label,
"wall_ms": wall_ms,
"process_cpu_ms": process_cpu_ms,
"body_frames": frames,
"output_bytes": len(body),
"output_sha256": hashlib.sha256(body).hexdigest(),
}
def _summarize(records: list[dict[str, object]], label: str) -> dict[str, object]:
selected = [record for record in records if record["label"] == label]
wall_values = [cast(float, record["wall_ms"]) for record in selected]
cpu_values = [cast(float, record["process_cpu_ms"]) for record in selected]
return {
"runs": len(selected),
"body_frames": cast(int, selected[0]["body_frames"]),
"wall_ms": {
"median": statistics.median(wall_values),
"min": min(wall_values),
"max": max(wall_values),
},
"process_cpu_ms": {
"median": statistics.median(cpu_values),
"min": min(cpu_values),
"max": max(cpu_values),
},
}
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--images", type=_positive_int, default=1, help="2 or more streams a ZIP archive")
parser.add_argument("--width", type=_positive_int, default=1024)
parser.add_argument("--height", type=_positive_int, default=1024)
parser.add_argument("--warmup", type=int, default=1)
parser.add_argument("--rounds", type=_positive_int, default=3)
parser.add_argument("--seed", type=int, default=20260912)
parser.add_argument("--output-json", type=Path)
args = parser.parse_args()
if args.warmup < 0:
parser.error("--warmup must be non-negative")
return args
async def _run(args: argparse.Namespace) -> dict[str, object]:
payload = await _build_payload(images=args.images, width=args.width, height=args.height, seed=args.seed)
baseline = BenchmarkVariant("newline_split", io.BytesIO)
candidate = BenchmarkVariant("fixed_size_chunks", _iter_file_chunks)
for _ in range(args.warmup):
for variant in (baseline, candidate):
await _measure(variant, payload)
records: list[dict[str, object]] = []
for round_index in range(args.rounds):
order = (baseline, candidate) if round_index % 2 == 0 else (candidate, baseline)
for variant in order:
record = await _measure(variant, payload)
record["round"] = round_index + 1
records.append(record)
output_hashes = {str(record["output_sha256"]) for record in records}
if len(output_hashes) != 1:
raise RuntimeError(f"benchmark variants produced different outputs: {sorted(output_hashes)}")
baseline_summary = _summarize(records, baseline.label)
candidate_summary = _summarize(records, candidate.label)
baseline_ms = cast(float, cast(dict[str, object], baseline_summary["wall_ms"])["median"])
candidate_ms = cast(float, cast(dict[str, object], candidate_summary["wall_ms"])["median"])
return {
"config": {
"images": args.images,
"width": args.width,
"height": args.height,
"warmup": args.warmup,
"rounds": args.rounds,
"seed": args.seed,
"chunk_size": _FILE_RESPONSE_CHUNK_SIZE,
"payload_bytes": len(payload),
"payload_newline_bytes": payload.count(b"\n"),
},
"records": records,
"summary": {
baseline.label: baseline_summary,
candidate.label: candidate_summary,
"median_wall_speedup": baseline_ms / candidate_ms,
"body_frame_ratio": (
cast(int, baseline_summary["body_frames"]) / cast(int, candidate_summary["body_frames"])
),
"output_sha256": output_hashes.pop(),
},
}
def main() -> None:
args = _parse_args()
result = asyncio.run(_run(args))
output_json = json.dumps(result, indent=2, sort_keys=True)
if args.output_json is not None:
args.output_json.write_text(output_json + "\n", encoding="utf-8")
print(output_json)
if __name__ == "__main__":
main()
@@ -64,6 +64,177 @@ def test_hugging_face_subset_names_are_splits(monkeypatch):
assert sample.task_type == "correction"
def test_local_hf_dataset_directory_is_routed_to_hf_loader(tmp_path, monkeypatch):
# An existing local Hugging Face dataset layout (directory with a
# ``data/*.parquet`` file) must be loaded through ``datasets.load_dataset``
# instead of being parsed as a JSON/JSONL manifest.
hf_dir = tmp_path / "Omni-DuplexEval"
data_dir = hf_dir / "data"
data_dir.mkdir(parents=True)
(data_dir / "train-00000-of-00001.parquet").write_bytes(b"PAR1")
calls = []
def fake_load_dataset(name, **kwargs):
calls.append((name, kwargs))
return [{"id": "pr", "split": "PR_correction", "question_text": "Correct this."}]
monkeypatch.setitem(sys.modules, "datasets", SimpleNamespace(load_dataset=fake_load_dataset))
samples = load_samples(hf_dir)
assert calls == [(str(hf_dir), {})]
assert len(samples) == 1
assert samples[0].task_type == "correction"
def test_local_parquet_file_is_routed_to_hf_loader(tmp_path, monkeypatch):
parquet = tmp_path / "samples.parquet"
parquet.write_bytes(b"PAR1")
calls = []
def fake_load_dataset(name, **kwargs):
calls.append((name, kwargs))
return [{"id": "pr", "split": "PR_correction", "question_text": "Correct this."}]
monkeypatch.setitem(sys.modules, "datasets", SimpleNamespace(load_dataset=fake_load_dataset))
samples = load_samples(str(parquet))
assert calls == [("parquet", {"data_files": str(parquet)})]
assert len(samples) == 1
assert samples[0].family == "pr"
def test_hf_collapse_to_train_keeps_row_split_identity(tmp_path, monkeypatch):
# datasets.load_dataset collapses a config-less local mirror (a bare data/
# directory) into a single generic ``train`` split. Rows that already carry
# their own split/subset identity must keep it so family inference is not
# poisoned by the generic name (regression for the direct-read path).
hf_dir = tmp_path / "Omni-DuplexEval"
data_dir = hf_dir / "data"
data_dir.mkdir(parents=True)
(data_dir / "train-00000-of-00021.parquet").write_bytes(b"PAR1")
def fake_load_dataset(name, **kwargs):
return {
"train": [
{"id": "pr", "split": "PR_correction", "question_text": "Correct this."},
{"id": "pr-subset", "subset": "PR_event_reminder", "question_text": "Remind me."},
{"id": "rtd", "split": "RTD_OCR", "question_text": "Read this."},
]
}
monkeypatch.setitem(sys.modules, "datasets", SimpleNamespace(load_dataset=fake_load_dataset))
samples = load_samples(hf_dir)
by_id = {sample.id: sample for sample in samples}
assert by_id["pr"].split == "PR_correction"
assert by_id["pr"].family == "pr"
assert by_id["pr"].task_type == "correction"
assert by_id["pr-subset"].split == "PR_event_reminder"
assert by_id["pr-subset"].family == "pr"
assert by_id["pr-subset"].task_type == "proactive_reminder"
assert by_id["rtd"].split == "RTD_OCR"
assert by_id["rtd"].family == "rtd"
def test_hf_config_layout_stamps_split_name_when_row_has_none(tmp_path, monkeypatch):
# With a proper config-per-split mirror the loader still stamps the Hugging
# Face split name onto rows that do not identify themselves (unchanged).
hf_dir = tmp_path / "Omni-DuplexEval"
data_dir = hf_dir / "data"
data_dir.mkdir(parents=True)
(data_dir / "RTD_OCR-00000-of-00001.parquet").write_bytes(b"PAR1")
(data_dir / "PR_correction-00000-of-00001.parquet").write_bytes(b"PAR1")
def fake_load_dataset(name, **kwargs):
return {
"RTD_OCR": [{"id": "rtd", "question_text": "Read this."}],
"PR_correction": [{"id": "pr", "question_text": "Correct this."}],
}
monkeypatch.setitem(sys.modules, "datasets", SimpleNamespace(load_dataset=fake_load_dataset))
samples = load_samples(hf_dir)
by_id = {sample.id: sample for sample in samples}
assert by_id["rtd"].split == "RTD_OCR"
assert by_id["rtd"].family == "rtd"
assert by_id["pr"].split == "PR_correction"
assert by_id["pr"].family == "pr"
assert by_id["pr"].task_type == "correction"
def test_hf_collapse_to_train_without_row_identity_raises_actionable_error(tmp_path, monkeypatch):
# A row that carries no split/family/task_type and lands in a generic
# collapsed ``train`` split cannot be routed; the loader must raise a clear,
# actionable ValueError instead of the bare family_for_split message.
hf_dir = tmp_path / "Omni-DuplexEval"
data_dir = hf_dir / "data"
data_dir.mkdir(parents=True)
(data_dir / "train-00000-of-00021.parquet").write_bytes(b"PAR1")
def fake_load_dataset(name, **kwargs):
return {"train": [{"id": "x", "question_text": "What is this?"}]}
monkeypatch.setitem(sys.modules, "datasets", SimpleNamespace(load_dataset=fake_load_dataset))
with pytest.raises(ValueError, match="Hugging Face splits"):
load_samples(hf_dir)
def test_non_manifest_file_raises_clear_error(tmp_path):
# A plain non-JSON file (e.g. a README) must surface a clear ValueError
# listing the accepted inputs instead of a raw JSONDecodeError.
bad = tmp_path / "README.md"
bad.write_text("# readme\nnot a manifest", encoding="utf-8")
with pytest.raises(ValueError, match="JSON/JSONL manifest"):
load_samples(str(bad))
def _write_parquet(path, rows):
pyarrow = pytest.importorskip("pyarrow")
pyarrow.parquet.write_table(pyarrow.Table.from_pylist(rows), str(path))
def test_local_parquet_split_filters_rows_by_identity(tmp_path):
# Regression: a single ``.parquet`` file is exposed by ``load_dataset`` as a
# generic ``train`` physical split, so ``--split RTD_OCR`` used to raise
# ``Unknown split "RTD_OCR"``. The requested split must instead filter the
# rows by their preserved identity.
pytest.importorskip("datasets")
parquet = tmp_path / "samples.parquet"
_write_parquet(
parquet,
[
{"id": "rtd", "split": "RTD_OCR", "question_text": "Read this."},
{"id": "pr", "split": "PR_correction", "question_text": "Correct this."},
],
)
assert {sample.id for sample in load_samples(str(parquet))} == {"rtd", "pr"}
rtd = load_samples(str(parquet), split="RTD_OCR")
assert [sample.id for sample in rtd] == ["rtd"]
assert rtd[0].family == "rtd"
pr = load_samples(str(parquet), split="PR_correction")
assert [sample.id for sample in pr] == ["pr"]
assert pr[0].family == "pr"
assert pr[0].task_type == "correction"
def test_local_directory_named_splits_resolve_without_row_identity(tmp_path):
# Regression: a single-configuration mirror whose data files are named after
# the benchmark splits must resolve each split for real (no fake loader) and
# without any per-row identity.
pytest.importorskip("datasets")
hf_dir = tmp_path / "Omni-DuplexEval"
data_dir = hf_dir / "data"
data_dir.mkdir(parents=True)
_write_parquet(data_dir / "RTD_OCR-00000-of-00001.parquet", [{"id": "rtd", "question_text": "Read this."}])
_write_parquet(
data_dir / "PR_correction-00000-of-00001.parquet",
[{"id": "pr", "question_text": "Correct this."}],
)
by_id = {sample.id: sample for sample in load_samples(hf_dir)}
assert by_id["rtd"].split == "RTD_OCR"
assert by_id["rtd"].family == "rtd"
assert by_id["pr"].split == "PR_correction"
assert by_id["pr"].family == "pr"
assert by_id["pr"].task_type == "correction"
assert [sample.id for sample in load_samples(hf_dir, split="RTD_OCR")] == ["rtd"]
def test_response_aliases_and_clock_guard():
assert split_text("One. Two!") == ["One.", "Two!"]
assert normalize_response_items({"chunks": [{"text": "x", "current_time": 800}]}) == [
@@ -141,3 +312,113 @@ def test_frame_sample_content_passes_frames(tmp_path, monkeypatch):
judge_video_mode="frame-sample",
)
assert score["content"]["frame_count"] == 2
def test_local_directory_collapsed_train_with_row_identity_and_split_filter(tmp_path):
# Reviewer-pointed gap: a collapsed local mirror (data/train-*.parquet)
# whose rows carry their own split identity must correctly filter by
# --split RTD_OCR.
pytest.importorskip("datasets")
hf_dir = tmp_path / "Omni-DuplexEval"
data_dir = hf_dir / "data"
data_dir.mkdir(parents=True)
_write_parquet(
data_dir / "train-00000-of-00001.parquet",
[
{"id": "rtd", "split": "RTD_OCR", "question_text": "Read this."},
{"id": "pr", "split": "PR_correction", "question_text": "Correct this."},
],
)
all_samples = load_samples(hf_dir)
assert {s.id for s in all_samples} == {"rtd", "pr"}
rtd = load_samples(hf_dir, split="RTD_OCR")
assert [s.id for s in rtd] == ["rtd"]
assert rtd[0].family == "rtd"
def test_local_directory_mistyped_split_raises_clear_error(tmp_path):
# A named-shard mirror with --split RTD_TYPO must raise ValueError
# listing the observed splits instead of silently returning nothing.
pytest.importorskip("datasets")
hf_dir = tmp_path / "Omni-DuplexEval"
data_dir = hf_dir / "data"
data_dir.mkdir(parents=True)
_write_parquet(
data_dir / "RTD_OCR-00000-of-00001.parquet",
[{"id": "rtd", "question_text": "Read this."}],
)
_write_parquet(
data_dir / "PR_correction-00000-of-00001.parquet",
[{"id": "pr", "question_text": "Correct this."}],
)
with pytest.raises(ValueError) as exc_info:
load_samples(hf_dir, split="RTD_TYPO")
message = str(exc_info.value)
assert "matched zero" in message
assert "RTD_OCR" in message or "PR_correction" in message
def test_manifest_without_split_identity_split_override_still_works(tmp_path):
# Manifest rows without split/subset/config identity must keep the
# base override behaviour: --split RTD_OCR stamps the split so rows
# are kept instead of rejected (regression test for P2).
manifest = tmp_path / "samples.json"
manifest.write_text(
json.dumps([{"id": "a", "video": "clip.mp4"}, {"id": "b", "video": "clip2.mp4"}]),
encoding="utf-8",
)
samples = load_samples(manifest, split="RTD_OCR")
assert len(samples) == 2
assert all(s.split == "RTD_OCR" for s in samples)
assert all(s.family == "rtd" for s in samples)
def test_iterable_without_split_identity_split_override_still_works():
# Iterable rows without split/subset/config identity must keep the
# base override behaviour (regression test for F5/P2).
data = [{"id": "a", "video": "clip.mp4"}, {"id": "b", "video": "clip2.mp4"}]
samples = load_samples(data, split="RTD_OCR")
assert len(samples) == 2
assert all(s.split == "RTD_OCR" for s in samples)
assert all(s.family == "rtd" for s in samples)
def test_audio_feature_decode_false_preserves_bytes_key(tmp_path):
# When a parquet file carries an Audio feature column, the loader
# must recast it with decode=False so rows contain the ``bytes`` key
# instead of ``array``/``sampling_rate``.
pytest.importorskip("datasets")
pytest.importorskip("pyarrow")
import datasets
audio_bytes = b"\x00\x01\x02"
ds = datasets.Dataset.from_dict(
{
"id": ["a"],
"question_text": ["Hello"],
"task_type": ["pr_correction"],
"audio": [{"bytes": audio_bytes, "path": None}],
},
features=datasets.Features(
{
"id": datasets.Value("string"),
"question_text": datasets.Value("string"),
"task_type": datasets.Value("string"),
"audio": datasets.Audio(sampling_rate=16000),
}
),
)
parquet = tmp_path / "audio_sample.parquet"
ds.to_parquet(str(parquet))
samples = load_samples(str(parquet))
assert len(samples) == 1
raw = samples[0].raw
assert raw is not None
audio_val = raw.get("audio")
assert audio_val is not None
# The Audio feature was decoded with decode=False, so the struct
# keeps the ``bytes`` key that materialize_media needs.
assert isinstance(audio_val, dict) and "bytes" in audio_val
assert audio_val["bytes"] == audio_bytes
assert "path" in audio_val
@@ -0,0 +1,341 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Tests for omni_duplex_eval_media — PyAV-backed media helpers."""
from __future__ import annotations
import io
from pathlib import Path
import av
import numpy as np
import pytest
from vllm_omni.benchmarks.duplex.omni_duplex_eval_media import (
_ffmpeg_q_to_pil_quality,
extract_jpeg,
materialize_media,
read_audio_pcm16,
video_duration,
)
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
# ---------------------------------------------------------------------------
# Helpers: synthetic test media generated with PyAV (no external files)
# ---------------------------------------------------------------------------
def _make_synthetic_mp4(duration: float = 1.0, fps: int = 30) -> bytes:
"""Return an MP4 byte blob with a solid-color pattern.
Uses the built-in ``mpeg4`` encoder — available everywhere PyAV's bundled
FFmpeg is present — so no external codec dependency.
"""
buf = io.BytesIO()
total_frames = int(duration * fps)
with av.open(buf, mode="w", format="mp4") as container:
stream = container.add_stream("mpeg4", rate=fps)
stream.width = 64
stream.height = 64
stream.pix_fmt = "yuv420p"
for i in range(total_frames):
frame = av.VideoFrame.from_ndarray(np.full((64, 64, 3), (i * 8) % 256, dtype=np.uint8), format="rgb24")
for pkt in stream.encode(frame):
container.mux(pkt)
for pkt in stream.encode():
container.mux(pkt)
return buf.getvalue()
def _make_synthetic_wav(duration: float = 1.0, sample_rate: int = 16000) -> bytes:
"""Return a 16-bit mono PCM WAV byte blob (440 Hz sine wave)."""
import wave as _wave
n = int(sample_rate * duration)
samples = (np.sin(2 * np.pi * 440 * np.arange(n) / sample_rate) * 32767).astype(np.int16)
buf = io.BytesIO()
with _wave.open(buf, "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(sample_rate)
wf.writeframes(samples.tobytes())
return buf.getvalue()
def _make_synthetic_ogg(duration: float = 1.0, sample_rate: int = 16000) -> bytes:
"""Return an OGG Vorbis byte blob (440 Hz sine wave).
Uses ``libopus`` as a fallback if ``libvorbis`` is unavailable in the
bundled FFmpeg (e.g. PyAV wheels from an older build).
"""
buf = io.BytesIO()
n = int(sample_rate * duration)
samples = (np.sin(2 * np.pi * 440 * np.arange(n) / sample_rate) * 0.3).astype(np.float32)
with av.open(buf, mode="w", format="ogg") as container:
codec_name = "libopus" if "libvorbis" not in av.codecs_available else "libvorbis"
stream = container.add_stream(codec_name, rate=sample_rate, layout="mono")
frame = av.AudioFrame.from_ndarray(samples[np.newaxis, :], format="fltp", layout="mono")
frame.sample_rate = sample_rate
for pkt in stream.encode(frame):
container.mux(pkt)
for pkt in stream.encode():
container.mux(pkt)
return buf.getvalue()
# ---------------------------------------------------------------------------
# video_duration
# ---------------------------------------------------------------------------
class TestVideoDuration:
@staticmethod
def test_returns_duration(tmp_path: Path) -> None:
mp4 = _make_synthetic_mp4(duration=2.0, fps=30)
path = tmp_path / "test.mp4"
path.write_bytes(mp4)
dur = video_duration(path)
assert abs(dur - 2.0) < 0.05, f"expected ~2.0s, got {dur}"
@staticmethod
def test_raises_for_missing_file(tmp_path: Path) -> None:
with pytest.raises((OSError, ValueError)):
video_duration(tmp_path / "nonexistent.mp4")
@staticmethod
def test_raises_for_broken_file(tmp_path: Path) -> None:
broken = tmp_path / "broken.mp4"
broken.write_bytes(b"\x00\x00\x00\x00")
with pytest.raises((OSError, ValueError)):
video_duration(broken)
# ---------------------------------------------------------------------------
# extract_jpeg
# ---------------------------------------------------------------------------
class TestExtractJpeg:
@staticmethod
def test_returns_valid_jpeg(tmp_path: Path) -> None:
mp4 = _make_synthetic_mp4(duration=1.0, fps=30)
path = tmp_path / "test.mp4"
path.write_bytes(mp4)
jpeg = extract_jpeg(path, timestamp=0.5, quality=3)
assert jpeg.startswith(b"\xff\xd8"), "not a valid JPEG header"
assert len(jpeg) > 100
@staticmethod
def test_quality_maps_to_pil_scale(tmp_path: Path) -> None:
"""Higher ffmpeg quality (lower q value) produces a larger JPEG."""
mp4 = _make_synthetic_mp4(duration=1.0, fps=30)
path = tmp_path / "test.mp4"
path.write_bytes(mp4)
high = extract_jpeg(path, timestamp=0.5, quality=1)
low = extract_jpeg(path, timestamp=0.5, quality=31)
assert len(high) > len(low), "quality=1 should produce larger JPEG than quality=31"
@staticmethod
def test_negative_timestamp_clamped(tmp_path: Path) -> None:
"""Negative timestamps are clamped to 0."""
mp4 = _make_synthetic_mp4(duration=1.0, fps=30)
path = tmp_path / "test.mp4"
path.write_bytes(mp4)
jpeg = extract_jpeg(path, timestamp=-1.0, quality=3)
assert jpeg.startswith(b"\xff\xd8")
@staticmethod
def test_raises_value_error_for_no_video(tmp_path: Path) -> None:
wav = _make_synthetic_wav()
path = tmp_path / "test.wav"
path.write_bytes(wav)
with pytest.raises(ValueError):
extract_jpeg(path, timestamp=0.0)
@staticmethod
def test_long_gop_returns_different_frames_for_different_timestamps(tmp_path: Path) -> None:
"""Long GOP: different timestamps must return different frame content (P2)."""
# Create a long-GOP video: 3s @ 10fps = 30 frames, gop_size=30 (1 keyframe)
buf = io.BytesIO()
fps = 10
duration = 3.0
total_frames = int(duration * fps)
with av.open(buf, mode="w", format="mp4") as container:
stream = container.add_stream("mpeg4", rate=fps)
stream.width = 64
stream.height = 64
stream.pix_fmt = "yuv420p"
stream.gop_size = 30 # 3 seconds per keyframe
for i in range(total_frames):
frame = av.VideoFrame.from_ndarray(np.full((64, 64, 3), (i * 64) % 256, dtype=np.uint8), format="rgb24")
for pkt in stream.encode(frame):
container.mux(pkt)
for pkt in stream.encode():
container.mux(pkt)
mp4 = buf.getvalue()
path = tmp_path / "long_gop.mp4"
path.write_bytes(mp4)
# Extract frames at different timestamps
frame0 = extract_jpeg(path, timestamp=0.0, quality=3)
frame1 = extract_jpeg(path, timestamp=1.0, quality=3)
frame2 = extract_jpeg(path, timestamp=2.0, quality=3)
# Verify all are valid JPEGs
assert frame0.startswith(b"\xff\xd8")
assert frame1.startswith(b"\xff\xd8")
assert frame2.startswith(b"\xff\xd8")
# Verify content differs: decode JPEGs and compare mean brightness
from PIL import Image
img0 = np.asarray(Image.open(io.BytesIO(frame0)))
img1 = np.asarray(Image.open(io.BytesIO(frame1)))
img2 = np.asarray(Image.open(io.BytesIO(frame2)))
means = [img.mean() for img in (img0, img1, img2)]
assert len(set(round(m, 1) for m in means)) >= 2, (
f"timestamps 0/1/2s should give different frames, got means {means}"
)
# ---------------------------------------------------------------------------
# read_audio_pcm16
# ---------------------------------------------------------------------------
class TestReadAudioPcm16:
@staticmethod
def test_wav_fast_path(tmp_path: Path) -> None:
"""WAV with matching params uses the fast wave module path."""
wav = _make_synthetic_wav(duration=1.0, sample_rate=16000)
path = tmp_path / "test.wav"
path.write_bytes(wav)
pcm = read_audio_pcm16(path)
assert len(pcm) == 16000 * 2, f"expected 32000 bytes, got {len(pcm)}"
assert isinstance(pcm, bytes)
@staticmethod
def test_wav_different_rate_resamples(tmp_path: Path) -> None:
"""A 48 kHz WAV is resampled down to 16 kHz — exact sample count after flush."""
wav = _make_synthetic_wav(duration=1.0, sample_rate=48000)
path = tmp_path / "test.wav"
path.write_bytes(wav)
pcm = read_audio_pcm16(path)
assert len(pcm) > 0
assert len(pcm) % 2 == 0
# 1s @ 48kHz → 1s @ 16kHz = 16000 samples = 32000 bytes (±1 sample)
assert abs(len(pcm) - 32000) <= 4, f"expected ~32000 bytes, got {len(pcm)}"
@staticmethod
def test_non_wav_ogg(tmp_path: Path) -> None:
"""Non-WAV audio (OGG) is decoded and resampled via PyAV."""
ogg = _make_synthetic_ogg(duration=1.0, sample_rate=16000)
path = tmp_path / "test.ogg"
path.write_bytes(ogg)
pcm = read_audio_pcm16(path)
assert len(pcm) > 0
assert len(pcm) % 2 == 0
@staticmethod
def test_non_wav_ogg_resample_accuracy(tmp_path: Path) -> None:
"""OGG resample should produce exact sample count after flush."""
ogg = _make_synthetic_ogg(duration=1.5, sample_rate=48000)
path = tmp_path / "test.ogg"
path.write_bytes(ogg)
pcm = read_audio_pcm16(path)
# 1.5s @ 48kHz → 1.5s @ 16kHz = 24000 samples = 48000 bytes (±1 sample)
expected = int(1.5 * 16000) * 2
assert abs(len(pcm) - expected) <= 4, f"expected ~{expected} bytes, got {len(pcm)}"
@staticmethod
def test_raises_for_broken_file(tmp_path: Path) -> None:
"""Corrupt audio must raise, not return empty bytes (L1)."""
broken = tmp_path / "broken.mp3"
broken.write_bytes(b"\x00\x00\x00\x00")
with pytest.raises((OSError, ValueError)):
read_audio_pcm16(broken)
# ---------------------------------------------------------------------------
# _ffmpeg_q_to_pil_quality
# ---------------------------------------------------------------------------
class TestFfmpegQToPilQuality:
@staticmethod
def test_q1_maps_to_best() -> None:
assert _ffmpeg_q_to_pil_quality(1) >= 90
@staticmethod
def test_q31_maps_to_lowest() -> None:
assert _ffmpeg_q_to_pil_quality(31) <= 10
@staticmethod
def test_monotonic() -> None:
"""Higher ffmpeg q → lower PIL quality (monotonically non-increasing)."""
prev = 100
for q in range(1, 32):
p = _ffmpeg_q_to_pil_quality(q)
assert p <= prev, f"quality.increase at q={q}: {prev} → {p}"
prev = p
def test_dict_with_bytes_materializes_a_real_file(tmp_path):
# A Hugging Face Audio/Video feature value {"bytes": ..., "path": ...} used
# to short-circuit on ``path`` (the artifact name inside the dataset, which
# does not exist on disk), so downstream ffmpeg saw a missing file. Inline
# bytes must win and be written to a real file whose content equals bytes.
payload = b"\x00\xff\x01RIFFfake-content"
resolved = materialize_media({"bytes": payload, "path": "question_audio.wav"}, tmp_path, "s1_question", ".wav")
assert resolved.is_file()
assert resolved.read_bytes() == payload
assert resolved.parent == tmp_path
assert resolved.name == "s1_question.wav"
def test_dict_extension_comes_from_path_safely(tmp_path):
payload = b"flac-ish-bytes"
resolved = materialize_media({"bytes": payload, "path": "audio/clip.FLAC"}, tmp_path, "s1", ".wav")
assert resolved.name == "s1.flac"
assert resolved.read_bytes() == payload
# A path with no usable extension falls back to the caller's suffix.
resolved = materialize_media({"bytes": payload, "path": "audio/clip"}, tmp_path, "s2", ".wav")
assert resolved.name == "s2.wav"
assert resolved.read_bytes() == payload
def test_materialization_is_idempotent_and_updated(tmp_path):
payload = b"abc"
first = materialize_media({"bytes": payload, "path": "q.wav"}, tmp_path, "s", ".wav")
second = materialize_media({"bytes": payload, "path": "q.wav"}, tmp_path, "s", ".wav")
assert first == second
assert first.read_bytes() == payload
replacement = b"xyz"
third = materialize_media({"bytes": replacement, "path": "q.wav"}, tmp_path, "s", ".wav")
assert third == first
assert third.read_bytes() == replacement
def test_str_path_and_path_only_mapping_returned_as_is(tmp_path):
existing = tmp_path / "clip.mp4"
existing.write_bytes(b"video")
assert materialize_media(str(existing), tmp_path, "s", ".mp4") == existing
assert materialize_media({"path": str(existing)}, tmp_path, "s", ".mp4") == existing
def test_raw_bytes_value_is_written(tmp_path):
payload = b"raw-media"
resolved = materialize_media(payload, tmp_path, "r", ".bin")
assert resolved.name == "r.bin"
assert resolved.read_bytes() == payload
def test_unresolvable_value_raises_clear_error(tmp_path):
with pytest.raises(ValueError, match="cannot materialize"):
materialize_media(None, tmp_path, "s", ".wav")
with pytest.raises(ValueError, match="cannot materialize"):
materialize_media({"path": None}, tmp_path, "s", ".wav")
+17 -17
View File
@@ -150,16 +150,16 @@ def test_unmeasured_duplex_latency_does_not_add_zero_samples():
measured.audio_ttfp = 0.2
measured.audio_rtf = 0.5
measured.duplex_session_metrics = {
"mean_ttft_ms": 100.0,
"mean_ttfp_ms": 200.0,
"mean_rtf": 0.5,
"ttft_ms": 100.0,
"ttfp_ms": 200.0,
"rtf": 0.5,
}
listen_only = _make_output(100, output_tokens=0)
listen_only.ttft = listen_only.audio_ttfp = listen_only.audio_rtf = 0.0
listen_only.duplex_session_metrics = {
"mean_ttft_ms": None,
"mean_ttfp_ms": None,
"mean_rtf": None,
"ttft_ms": None,
"ttfp_ms": None,
"rtf": None,
}
metrics = _calculate_test_metrics([measured, listen_only], {"ttft": 150.0})
@@ -174,9 +174,9 @@ def test_unmeasured_duplex_latency_does_not_add_zero_samples():
def test_all_unmeasured_duplex_latency_is_not_reported_as_zero():
listen_only = _make_output(100, output_tokens=0)
listen_only.duplex_session_metrics = {
"mean_ttft_ms": None,
"mean_ttfp_ms": None,
"mean_rtf": None,
"ttft_ms": None,
"ttfp_ms": None,
"rtf": None,
}
metrics = _calculate_test_metrics(
@@ -196,13 +196,13 @@ def test_unmeasured_duplex_tpot_does_not_add_zero_or_misalign_goodput():
missing_tpot.itl = []
missing_tpot.text_latency = missing_tpot.ttft = 0.1
missing_tpot.tpot_measured = False
missing_tpot.duplex_session_metrics = {"mean_ttft_ms": 100.0}
missing_tpot.duplex_session_metrics = {"ttft_ms": 100.0}
slow_ttft = _make_output(100, output_tokens=5)
slow_ttft.ttft = 1.0
slow_ttft.text_latency = 1.4
slow_ttft.itl = [0.1] * 4
slow_ttft.duplex_session_metrics = {"mean_ttft_ms": 1000.0}
slow_ttft.duplex_session_metrics = {"ttft_ms": 1000.0}
metrics = _calculate_test_metrics(
[missing_tpot, slow_ttft],
@@ -219,7 +219,7 @@ def test_all_unmeasured_duplex_token_timing_is_not_reported_as_zero():
output.itl = []
output.text_latency = output.ttft
output.tpot_measured = False
output.duplex_session_metrics = {"mean_ttft_ms": 100.0}
output.duplex_session_metrics = {"ttft_ms": 100.0}
metrics = _calculate_test_metrics([output], {"tpot": float("inf")})
@@ -236,7 +236,7 @@ def test_duplex_response_timings_do_not_build_a_session_token_timeline():
{"response_id": "r1", "stage0_tokens": {"itls_ms": [100.0, 100.0]}},
{"response_id": "r2", "stage0_tokens": {"itls_ms": [100.0, 100.0]}},
]
output.duplex_session_metrics = {"mean_ttft_ms": 100.0}
output.duplex_session_metrics = {"ttft_ms": 100.0}
metrics = _calculate_test_metrics([output])
@@ -252,7 +252,7 @@ def test_unmeasured_tpot_stays_missing_after_tokenizer_fallback():
output.itl = []
output.text_latency = output.ttft
output.tpot_measured = False
output.duplex_session_metrics = {"mean_ttft_ms": 100.0}
output.duplex_session_metrics = {"ttft_ms": 100.0}
def tokenizer(text, *, add_special_tokens):
assert text == output.generated_text
@@ -282,7 +282,7 @@ def test_unmeasured_tpot_stays_missing_after_tokenizer_fallback():
def test_zero_itl_does_not_create_zero_tpot():
output = _make_output(100, output_tokens=3)
output.itl = [0.0, 0.0]
output.duplex_session_metrics = {"mean_ttft_ms": 100.0}
output.duplex_session_metrics = {"ttft_ms": 100.0}
metrics = _calculate_test_metrics([output], {"tpot": 1.0})
@@ -357,9 +357,9 @@ def test_single_token_responses_do_not_report_zero_tpot(capsys):
def test_duplex_goodput_does_not_pair_measurements_from_different_requests():
text_only, audio_only = _make_output(100), _make_output(100)
text_only.ttft, text_only.audio_ttfp = 0.1, 0.0
text_only.duplex_session_metrics = {"mean_ttft_ms": 100.0, "mean_ttfp_ms": None, "mean_rtf": None}
text_only.duplex_session_metrics = {"ttft_ms": 100.0, "ttfp_ms": None, "rtf": None}
audio_only.ttft, audio_only.audio_ttfp = 0.0, 0.2
audio_only.duplex_session_metrics = {"mean_ttft_ms": None, "mean_ttfp_ms": 200.0, "mean_rtf": None}
audio_only.duplex_session_metrics = {"ttft_ms": None, "ttfp_ms": 200.0, "rtf": None}
metrics = _calculate_test_metrics([text_only, audio_only], {"ttft": 500.0, "audio_ttft": 500.0})
@@ -0,0 +1,74 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Verify metric sample counts survive benchmark JSON serialization."""
import asyncio
import json
import time
import pytest
from vllm.benchmarks.datasets import SampleRequest
from vllm.benchmarks.serve import TaskType
from vllm_omni.benchmarks.patch import patch
pytestmark = [pytest.mark.core_model, pytest.mark.benchmark, pytest.mark.cpu]
@pytest.mark.parametrize("selected_metrics", [["ttft", "tpot", "itl"], []])
@pytest.mark.parametrize("measured", [True, False])
def test_benchmark_result_preserves_tpot_sample_count(monkeypatch, measured, selected_metrics):
async def request_func(**kwargs):
return patch.MixRequestFuncOutput(
success=True,
prompt_len=2,
output_tokens=3,
generated_text="hello world!",
start_time=time.perf_counter(),
ttft=0.01,
latency=0.03,
text_latency=0.03,
itl=[0.01, 0.01] if measured else [0.0, 0.0],
)
monkeypatch.setitem(patch.ASYNC_REQUEST_FUNCS, "test-result", request_func)
result = asyncio.run(
patch.benchmark(
task_type=TaskType.GENERATION,
endpoint_type="test-result",
api_url="http://unused/v1/chat/completions",
base_url="http://unused",
model_id="test-model",
model_name="test-model",
tokenizer=None,
input_requests=[SampleRequest(prompt="hi", prompt_len=2, expected_output_len=3)],
logprobs=None,
request_rate=float("inf"),
burstiness=1.0,
disable_tqdm=True,
num_warmups=0,
profile=False,
selected_percentile_metrics=selected_metrics,
selected_percentiles=[50.0],
ignore_eos=False,
goodput_config_dict={},
max_concurrency=1,
lora_modules=None,
extra_headers=None,
extra_body=None,
ready_check_timeout_sec=0,
)
)
# DFX reads this dictionary from the benchmark's JSON result file.
saved_result = json.loads(json.dumps(result))
assert saved_result["completed"] == 1
assert saved_result.get("num_tpot_samples") == int(measured)
assert saved_result["num_ttft_samples"] == 1
assert saved_result["num_itl_samples"] == 2
assert "num_audio_ttfp_samples" in saved_result
assert "num_audio_rtf_samples" in saved_result
if measured and "tpot" in selected_metrics:
assert saved_result["mean_tpot_ms"] == pytest.approx(10.0)
else:
assert "mean_tpot_ms" not in saved_result
+55 -36
View File
@@ -135,6 +135,7 @@ class MockResponse:
async def test_seed_tts_realtime_duplex_exports_per_request_metrics(monkeypatch):
class FakeRealtimeClient:
last_instance = None
instances: list = []
def __init__(self, url):
assert url == "ws://localhost:8000/v1/realtime?duplex=1"
@@ -143,6 +144,9 @@ async def test_seed_tts_realtime_duplex_exports_per_request_metrics(monkeypatch)
self.sent = []
self.response_count = 0
self.ack_count = 0
self.silence_seconds = []
self.closed = 0
type(self).instances.append(self)
type(self).last_instance = self
async def __aenter__(self):
@@ -155,10 +159,22 @@ async def test_seed_tts_realtime_duplex_exports_per_request_metrics(monkeypatch)
assert model == "openbmb/MiniCPM-o-4_5"
self.configure_kwargs = kwargs
async def stream_silence(self, *, seconds, chunk_ms=200, until=None):
# A model-native session speaks off its seeded context once audio
# units arrive; the silence itself carries no content. The probe
# stops the silence as soon as the turn settles.
self.silence_seconds.append(seconds)
self._emit_response()
assert until is not None and until()
return 1.0
async def send(self, event):
self.sent.append(event)
if event["type"] != "response.create":
return
self._emit_response()
def _emit_response(self):
self.response_count += 1
response_id = f"resp-{self.response_count}"
now = time.monotonic()
@@ -168,7 +184,7 @@ async def test_seed_tts_realtime_duplex_exports_per_request_metrics(monkeypatch)
)
self.events.add(
{
"type": "response.audio_transcript.delta",
"type": "response.output_audio_transcript.delta",
"response_id": response_id,
"delta": f"turn {self.response_count}",
},
@@ -176,7 +192,7 @@ async def test_seed_tts_realtime_duplex_exports_per_request_metrics(monkeypatch)
)
self.events.add(
{
"type": "response.audio.delta",
"type": "response.output_audio.delta",
"response_id": response_id,
"delta": base64.b64encode(b"\x00\x00" * 2400).decode(),
"sample_rate_hz": 24_000,
@@ -210,7 +226,7 @@ async def test_seed_tts_realtime_duplex_exports_per_request_metrics(monkeypatch)
self.ack_count += 1
async def close_session(self, **_kwargs):
return None
self.closed += 1
monkeypatch.setattr(
"vllm_omni.benchmarks.patch.patch._RealtimeTTSProbe",
@@ -239,30 +255,27 @@ async def test_seed_tts_realtime_duplex_exports_per_request_metrics(monkeypatch)
session=None,
)
client = FakeRealtimeClient.last_instance
assert client.configure_kwargs["native_duplex"] is False
assert client.configure_kwargs["extra_body"] == {
"ref_audio": "data:audio/wav;base64,AAAA",
"return_stage_metrics": True,
}
assert client.sent == [
event
for index in range(4)
for event in (
{
"type": "conversation.item.create",
"item": {
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": f"text {index}"}],
},
},
{"type": "response.create"},
)
]
assert client.ack_count == 4
# One session per utterance: a model-native duplex session takes its text
# once, in the session context, so it cannot be re-seeded for a second one.
sessions = FakeRealtimeClient.instances
assert len(sessions) == 4
for index, client in enumerate(sessions):
assert "native_duplex" not in client.configure_kwargs
assert client.configure_kwargs["extra_body"] == {
"ref_audio": "data:audio/wav;base64,AAAA",
"return_stage_metrics": True,
"duplex_initial_user_text": f"text {index}",
"force_listen_count": 0,
}
# The target text rides the session context, never a conversation item:
# a text-only response.create is rejected by a model-native session.
assert client.sent == []
assert client.silence_seconds and all(seconds > 0 for seconds in client.silence_seconds)
assert client.ack_count == 1
assert client.closed == 1
assert output.success is True
assert output.generated_text == "turn 1 turn 2 turn 3 turn 4"
assert output.generated_text == "turn 1 turn 1 turn 1 turn 1"
assert output.audio_duration == pytest.approx(0.4)
assert output.ttft > 0
assert output.audio_ttfp > output.ttft
@@ -281,26 +294,32 @@ async def test_seed_tts_realtime_duplex_exports_per_request_metrics(monkeypatch)
"session_id": session_id,
"request_index": index,
"utterance_id": f"utt-{index}",
"response_id": f"resp-{index + 1}",
# Response ids are per session, and each utterance now gets its own.
"response_id": "resp-1",
"source": "client_monotonic_receive",
"measurement_origin": {
"ttft": "conversation.item.create client send to first non-empty text delta",
"ttfp": "conversation.item.create client send to first audio packet",
"ttft": "first silence append client send to first non-empty text delta",
"ttfp": "first silence append client send to first audio packet",
"rtf": "request-start-to-last-audio receive time divided by emitted audio duration",
"tpot": "Stage-0 engine mean time per output token",
},
"ttft_ms": pytest.approx(20.0, abs=2.0),
"tpot_ms": 10.0,
"ttfp_ms": pytest.approx(30.0, abs=2.0),
"rtf": pytest.approx(0.3, abs=0.03),
"audio_generation_ms": pytest.approx(30.0, abs=2.0),
"audio_duration_ms": 100.0,
}
assert output.duplex_session_metrics == {
"session_id": session_id,
"audio_turn_count": 4,
"mean_ttft_ms": pytest.approx(20.0, abs=2.0),
"mean_ttfp_ms": pytest.approx(30.0, abs=2.0),
"mean_rtf": pytest.approx(0.3, abs=0.03),
}
session = output.duplex_session_metrics
assert session["session_id"] == session_id
assert session["audio_turn_count"] == 4
assert session["ttft_ms"]["count"] == 4
assert session["ttft_ms"]["mean"] == pytest.approx(20.0, abs=2.0)
assert session["tpot_ms"] == {"count": 4, "mean": 10.0, "p50": 10.0, "p99": 10.0}
assert session["ttfp_ms"]["count"] == 4
assert session["ttfp_ms"]["mean"] == pytest.approx(30.0, abs=2.0)
assert session["rtf"]["count"] == 4
assert session["rtf"]["mean"] == pytest.approx(0.3, abs=0.03)
def test_stage0_token_timings_use_weighted_tpot_when_itls_are_incomplete():
@@ -47,11 +47,50 @@ from benchmarks.accuracy.text_to_image.gbench import (
from tests.e2e.accuracy.qwen3_omni.qwen3_omni_acc_bench_core import (
build_serve_common_argv,
seed_tts_bench_argv,
videomme_bench_argv,
)
from tests.e2e.accuracy.qwen3_omni.run_qwen_omni_acc_benchmark import sync_dataset_env_from_ns
from vllm_omni.benchmarks.data_modules.seed_tts_dataset import resolve_seed_tts_root
def test_videomme_bench_argv_preserves_hf_repo_id_from_env(monkeypatch):
monkeypatch.setenv("VLLM_VIDEOMME_DATASET_PATH", "lmms-eval/Video-MME")
monkeypatch.delenv("VLLM_VIDEOMME_REPO", raising=False)
monkeypatch.delenv("VIDEOMME_ROOT", raising=False)
argv = videomme_bench_argv()
dataset_idx = argv.index("--dataset-path")
assert argv[argv.index("--dataset-name") + 1] == "videomme"
assert argv[dataset_idx + 1] == "lmms-eval/Video-MME"
def test_videomme_bench_argv_uses_local_directory(monkeypatch, tmp_path: Path):
monkeypatch.setenv("VLLM_VIDEOMME_DATASET_PATH", str(tmp_path))
monkeypatch.delenv("VIDEOMME_ROOT", raising=False)
argv = videomme_bench_argv()
assert argv[argv.index("--dataset-path") + 1] == str(tmp_path.resolve())
def test_sync_dataset_env_preserves_videomme_hf_repo_id(monkeypatch):
ns = argparse.Namespace(
daily_omni_repo=None,
daily_omni_qa_json=None,
daily_omni_video_dir=None,
videomme_repo=None,
videomme_dataset_path="lmms-eval/Video-MME",
seed_tts_dataset_path=None,
seed_tts_root=None,
)
monkeypatch.delenv("VLLM_VIDEOMME_DATASET_PATH", raising=False)
sync_dataset_env_from_ns(ns)
assert os.environ["VLLM_VIDEOMME_DATASET_PATH"] == "lmms-eval/Video-MME"
def test_seed_tts_bench_argv_preserves_hf_repo_id_from_env(monkeypatch):
monkeypatch.setenv("VLLM_SEED_TTS_DATASET_PATH", "zhaochenyang20/seed-tts-eval")
monkeypatch.delenv("VLLM_SEED_TTS_REPO", raising=False)
@@ -0,0 +1,128 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import importlib
import sys
import pytest
from benchmarks.diffusion import backends
from benchmarks.diffusion.backends import RequestFuncInput, RequestFuncOutput
pytestmark = [pytest.mark.core_model, pytest.mark.benchmark, pytest.mark.cpu, pytest.mark.asyncio]
ENDPOINT = "/v1/chat/completions"
TEST_MODEL = "test-model"
@pytest.fixture
def diffusion_benchmark(monkeypatch):
# The standalone script imports its sibling backend module by name.
monkeypatch.setitem(sys.modules, "backends", backends)
return importlib.import_module("benchmarks.diffusion.diffusion_benchmark_serving")
@pytest.fixture
def warmup_args(diffusion_benchmark):
from benchmarks.diffusion.diffusion_benchmark_serving import build_parser
parser = build_parser()
return parser.parse_args(
[
f"--endpoint={ENDPOINT}",
"--dataset=random",
"--task=t2i",
"--warmup-requests=2",
"--warmup-num-inference-steps=4",
]
)
@pytest.fixture
def input_requests():
return [
RequestFuncInput(
prompt=prompt,
api_url=f"http://test.local{ENDPOINT}",
model=TEST_MODEL,
num_inference_steps=20,
)
for prompt in ("first", "second")
]
async def test_disabled_warmup_sends_no_requests(diffusion_benchmark, warmup_args, input_requests):
warmup_args.warmup_requests = 0
async def unexpected_request(*args):
pytest.fail("disabled warmup must not send requests")
pairs = await diffusion_benchmark._run_warmups(input_requests, warmup_args, None, unexpected_request)
assert pairs == []
async def test_successful_warmups_preserve_request_output_pairs(diffusion_benchmark, warmup_args, input_requests):
outputs = [RequestFuncOutput(success=True, latency=0.5), RequestFuncOutput(success=True, latency=1.0)]
pending_outputs = iter(outputs)
async def successful_request(req, session, pbar):
return next(pending_outputs)
pairs = await diffusion_benchmark._run_warmups(input_requests, warmup_args, None, successful_request)
assert [request.prompt for request, _ in pairs] == ["first", "second"]
assert [request.num_inference_steps for request, _ in pairs] == [4, 4]
assert [output for _, output in pairs] == outputs
assert [request.num_inference_steps for request in input_requests] == [20, 20]
@pytest.mark.parametrize("failed_count", [1, 2], ids=["partial-failure", "all-failed"])
@pytest.mark.parametrize(
"error",
["HTTP 503: private prompt rejected", "Cannot connect to https://test.local/?token=private"],
ids=["http-error", "transport-error"],
)
async def test_failed_warmups_abort_without_exposing_response_errors(
diffusion_benchmark, warmup_args, input_requests, failed_count, error
):
outputs = iter(
[RequestFuncOutput(success=False, error=error) for _ in range(failed_count)]
+ [RequestFuncOutput(success=True) for _ in range(2 - failed_count)]
)
async def request(req, session, pbar):
return next(outputs)
with pytest.raises(RuntimeError, match=f"{failed_count}/2 warmup requests failed") as exc_info:
await diffusion_benchmark._run_warmups(input_requests, warmup_args, None, request)
assert error not in str(exc_info.value)
assert "server logs" in str(exc_info.value)
async def test_benchmark_does_not_start_measurement_after_failed_warmup(
monkeypatch, mocker, diffusion_benchmark, warmup_args, input_requests
):
sent = []
async def failed_request(req, session, pbar):
sent.append(req)
return RequestFuncOutput(success=False, error="HTTP 503: unavailable")
monkeypatch.setitem(
diffusion_benchmark.backends_function_mapping["2i"],
warmup_args.endpoint,
(failed_request, warmup_args.endpoint),
)
dataset = mocker.Mock(spec=diffusion_benchmark.RandomDataset)
dataset.get_requests.return_value = input_requests
monkeypatch.setattr(diffusion_benchmark, "RandomDataset", mocker.Mock(return_value=dataset))
timer = mocker.Mock(spec=diffusion_benchmark.time)
timer.perf_counter.side_effect = AssertionError("measurement started after failed warmup")
monkeypatch.setattr(diffusion_benchmark, "time", timer)
with pytest.raises(RuntimeError, match="2/2 warmup requests failed"):
await diffusion_benchmark.benchmark(warmup_args)
assert len(sent) == warmup_args.warmup_requests
+95 -8
View File
@@ -65,7 +65,7 @@ def _audio(
value: int = 1,
) -> dict[str, object]:
event: dict[str, object] = {
"type": "response.audio.delta",
"type": "response.output_audio.delta",
"response_id": response_id,
"format": "pcm16",
"delta": base64.b64encode(bytes((value, 0)) * samples).decode(),
@@ -76,7 +76,7 @@ def _audio(
def _text(response_id: str = "r1", value: str = "hello") -> dict[str, object]:
return {"type": "response.audio_transcript.delta", "response_id": response_id, "delta": value}
return {"type": "response.output_audio_transcript.delta", "response_id": response_id, "delta": value}
def _listen(*, buffering: bool = False) -> dict[str, object]:
@@ -148,6 +148,72 @@ def _successful_output(
return case, collector, result
def test_response_metrics_include_engine_tpot_and_stream_window():
first_audio = _audio("r1")
first_audio["metadata"] = {
"audio_duration_ms": 100,
"vllm_omni": {
"stage_metrics": {
"0": {
"num_tokens_out": 3,
"vllm_tpot_ms": 10.0,
"vllm_itls_ms": [10.0, 10.0],
}
}
},
}
second_audio = _audio("r2")
second_audio["metadata"] = {
"audio_duration_ms": 200,
"vllm_omni": {
"stage_metrics": {
"0": {
"num_tokens_out": 2,
"vllm_tpot_ms": 20.0,
"vllm_itls_ms": [20.0],
}
}
},
}
collector = _collector(
(_created("r1"), 10.1),
(_text("r1", "first"), 10.2),
(first_audio, 10.3),
(_done("r1"), 10.4),
(_created("r2"), 12.1),
(_text("r2", "second"), 12.2),
(second_audio, 12.5),
(_done("r2"), 12.6),
)
result = oi.OmniInteractCaseResult("1q1a", "video.mp4", "", session_id="session")
oi._populate_response_metrics(result, collector, stream_start=10.0)
assert result.output_tokens == 5
assert [metric["tpot_ms"] for metric in result.duplex_request_metrics] == [10.0, 20.0]
assert result.duplex_session_metrics == {
"session_id": "session",
"audio_turn_count": 2,
"ttft_ms": {"count": 2, "mean": 100.0, "p50": 100.0, "p99": 100.0},
"tpot_ms": {"count": 2, "mean": 15.0, "p50": 10.0, "p99": 20.0},
"ttfp_ms": {"count": 2, "mean": 300.0, "p50": 200.0, "p99": 400.0},
"rtf": {"count": 2, "mean": 2.0, "p50": 2.0, "p99": 2.0},
"stream_ttft_ms": 200.0,
"stream_ttfp_ms": 300.0,
"stream_rtf": 8.333333,
"stream_audio_generation_ms": 2500.0,
"stream_audio_duration_ms": 300.0,
"stream_measurement_origin": {
"ttft": "input stream start to first non-empty text delta",
"ttfp": "input stream start to first audio packet",
"rtf": (
"input stream start-to-last-audio receive time divided by total emitted audio duration; "
"includes concurrent realtime input"
),
},
}
def _write_success(
root: Path,
case: data.OmniInteractCase,
@@ -401,6 +467,27 @@ def test_tolerated_playback_ack_rejection_is_a_warning_not_a_failure():
oi._raise_if_session_terminated(collector, 0, warnings=warnings)
def test_our_own_close_is_expected_even_though_the_server_stamps_a_reason():
"""``session.close`` is answered with ``session.closed`` carrying ``client_close``.
The guard exists to catch a session that ended for a reason we did not ask
for. A close we requested is not that, whether or not the server names it.
"""
collector = _collector(({"type": "session.closed", "reason": "client_close"}, 1.0))
oi._raise_if_session_terminated(collector, 0, explicit_close_from=0)
collector = _collector(({"type": "session.closed", "event": {"reason": "client_close"}}, 1.0))
oi._raise_if_session_terminated(collector, 0, explicit_close_from=0)
collector = _collector(({"type": "session.closed", "reason": "disconnect"}, 1.0))
with pytest.raises(RuntimeError, match="Unexpected session.closed: disconnect"):
oi._raise_if_session_terminated(collector, 0, explicit_close_from=0)
collector = _collector(({"type": "session.expired", "reason": "timeout"}, 1.0))
with pytest.raises(RuntimeError, match="session.expired: timeout"):
oi._raise_if_session_terminated(collector, 0, explicit_close_from=0)
@pytest.mark.parametrize(
("event", "match"),
[
@@ -427,7 +514,7 @@ def test_artifacts_publish_official_bundle_and_sparse_deferred_state(tmp_path: P
assert result.success and result.eligible_for_official_eval
assert summary["scene_type"] == "multi_turn"
assert context and context.spans
assert all("delta" not in event for event in context.events if event["type"] == "response.audio.delta")
assert all("delta" not in event for event in context.events if event["type"] == "response.output_audio.delta")
oi.publish_deferred_case_artifacts(tmp_path / "out", case, result)
directory = oi._output_dir(tmp_path / "out", case)
assert all((directory / name).is_file() for name in oi.SUCCESS_ARTIFACTS)
@@ -495,8 +582,8 @@ class _RealtimeClient(oi._RealtimeSession):
instances: list[_RealtimeClient] = []
def __init__(self, config: oi.OmniInteractBenchmarkConfig, session_id: str, reference_audio: str):
super().__init__(config, session_id, reference_audio)
def __init__(self, config: oi.OmniInteractBenchmarkConfig, reference_audio: str):
super().__init__(config, reference_audio)
self.acks: list[tuple[str, int]] = []
self.instances.append(self)
@@ -555,7 +642,7 @@ async def test_public_runner_executes_one_prepared_session(tmp_path: Path, monke
assert "autostart=0" in _RealtimeClient.instances[-1].url
session_config = _RealtimeClient.instances[-1].session_config
assert session_config.extra_body["custom"] == "value"
assert session_config.extra_body["native_duplex"] is True
assert "native_duplex" not in session_config.extra_body
assert session_config.ref_audio == "data:audio/wav;base64,ref"
acks = _RealtimeClient.instances[-1].acks
# Cumulative acks for the one response: an optional 0 ms checkpoint the
@@ -645,7 +732,7 @@ async def test_adapter_requires_and_forwards_exact_prepared_payload(tmp_path: Pa
transcript="timing metadata missing",
output_tokens=0,
duplex_request_metrics=[{"request_metrics": {"ttft_ms": 1.0}}],
duplex_session_metrics={"mean_ttft_ms": 10.0},
duplex_session_metrics={"ttft_ms": 10.0},
)
monkeypatch.setattr(benchmark_patch, "run_omniinteract_case", run)
@@ -713,7 +800,7 @@ async def test_adapter_reports_exact_or_weighted_token_timing(
success=True,
output_tokens=5,
duplex_request_metrics=request_metrics,
duplex_session_metrics={"mean_ttft_ms": 100.0},
duplex_session_metrics={"ttft_ms": 100.0},
)
monkeypatch.setattr(benchmark_patch, "run_omniinteract_case", run)
+179
View File
@@ -0,0 +1,179 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""The Seed-TTS Realtime probe queues for a duplex session slot instead of failing."""
from __future__ import annotations
import pytest
from vllm_omni.benchmarks.patch import patch as bench_patch
from vllm_omni.clients import duplex as duplex_client
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
class _AdmissionGate:
"""Stands in for ``DuplexClient``: refuses admission ``refusals`` times, then admits."""
instances: list[_AdmissionGate] = []
refusals = 0
refusal_code = "resource_exhausted"
def __init__(self, url: str, **kwargs: object) -> None:
del url, kwargs
self.entered = False
type(self).instances.append(self)
async def __aenter__(self) -> _AdmissionGate:
cls = type(self)
if cls.refusals > 0:
cls.refusals -= 1
raise duplex_client.DuplexProtocolError("duplex_session_capacity_exhausted: limit=4", code=cls.refusal_code)
self.entered = True
return self
async def __aexit__(self, exc_type, exc, tb) -> None:
del exc_type, exc, tb
async def events(self): # the collector's consume loop ends at once
return
yield # pragma: no cover
@pytest.fixture
def gate(monkeypatch: pytest.MonkeyPatch) -> type[_AdmissionGate]:
_AdmissionGate.instances = []
_AdmissionGate.refusals = 0
_AdmissionGate.refusal_code = "resource_exhausted"
monkeypatch.setattr(duplex_client, "DuplexClient", _AdmissionGate)
return _AdmissionGate
async def _configure(probe: bench_patch._RealtimeTTSProbe) -> None:
try:
await probe.configure("test-model", auto_response=True)
finally:
await probe.__aexit__(None, None, None)
@pytest.mark.asyncio
async def test_configure_waits_for_a_free_session_slot(gate) -> None:
"""Two refusals, then a slot: the request is served, not counted as failed."""
gate.refusals = 2
probe = bench_patch._RealtimeTTSProbe("ws://test/v1/realtime?duplex=1")
await _configure(probe)
assert len(gate.instances) == 3
assert gate.instances[-1].entered is True
assert probe._client is gate.instances[-1]
@pytest.mark.asyncio
async def test_configure_raises_other_rejections_at_once(gate) -> None:
gate.refusals = 1
gate.refusal_code = "unsupported_turn_detection"
probe = bench_patch._RealtimeTTSProbe("ws://test/v1/realtime?duplex=1")
with pytest.raises(duplex_client.DuplexProtocolError):
await _configure(probe)
assert len(gate.instances) == 1
@pytest.mark.asyncio
async def test_configure_gives_up_when_the_slot_wait_budget_is_spent(gate, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(bench_patch._RealtimeTTSProbe, "_SESSION_SLOT_WAIT_S", 0.0)
gate.refusals = 5
probe = bench_patch._RealtimeTTSProbe("ws://test/v1/realtime?duplex=1")
with pytest.raises(duplex_client.DuplexProtocolError) as excinfo:
await _configure(probe)
assert excinfo.value.code == "resource_exhausted"
assert len(gate.instances) == 1
class _SilenceSink:
"""Stands in for a configured ``DuplexClient``: records every appended chunk."""
def __init__(self) -> None:
self.config = duplex_client.SessionConfig()
self.chunks: list[bytes] = []
async def append_audio(self, pcm: bytes, *, is_speech: bool | None = None, video_frames=None) -> None:
del video_frames
assert is_speech is False
self.chunks.append(pcm)
@pytest.mark.asyncio
async def test_stream_silence_stops_at_the_turn_end(monkeypatch: pytest.MonkeyPatch) -> None:
"""Silence is fed until the turn settles, not for the whole cap."""
probe = bench_patch._RealtimeTTSProbe("ws://test/v1/realtime?duplex=1")
sink = _SilenceSink()
probe._client = sink
async def no_wait(_: float) -> None:
return
monkeypatch.setattr(bench_patch.asyncio, "sleep", no_wait)
streamed = await probe.stream_silence(seconds=12.0, chunk_ms=200, until=lambda: len(sink.chunks) >= 3)
assert len(sink.chunks) == 3
assert streamed == pytest.approx(0.6)
assert all(len(chunk) == sink.config.input_audio.byte_count(200) for chunk in sink.chunks)
@pytest.mark.asyncio
async def test_stream_silence_runs_to_the_cap_when_the_turn_never_settles(monkeypatch: pytest.MonkeyPatch) -> None:
probe = bench_patch._RealtimeTTSProbe("ws://test/v1/realtime?duplex=1")
sink = _SilenceSink()
probe._client = sink
async def no_wait(_: float) -> None:
return
monkeypatch.setattr(bench_patch.asyncio, "sleep", no_wait)
streamed = await probe.stream_silence(seconds=1.0, chunk_ms=200, until=lambda: False)
assert len(sink.chunks) == 5
assert streamed == pytest.approx(1.0)
class _TurnEvents:
def __init__(self, response_ids: list[str], audio: dict[str, bytes], text: dict[str, str] | None = None) -> None:
self.response_ids = response_ids
self._audio = audio
self._text = text or {}
def audio_bytes(self, response_id: str) -> bytes:
return self._audio.get(response_id, b"")
def response_text(self, response_id: str) -> str:
return self._text.get(response_id, "")
def test_turn_response_is_the_first_one_with_audio_even_if_the_model_spoke_again(caplog) -> None:
events = _TurnEvents(["r0", "r1", "r2"], {"r1": b"\x01\x00", "r2": b"\x02\x00"})
with caplog.at_level("WARNING", logger=bench_patch.logger.name):
assert bench_patch._seed_tts_turn_response_id(events, 0, 0) == "r1"
assert "spoke again" in caplog.text
def test_turn_response_ignores_responses_from_before_the_turn() -> None:
events = _TurnEvents(["r0", "r1"], {"r0": b"\x01\x00", "r1": b"\x02\x00"})
assert bench_patch._seed_tts_turn_response_id(events, 1, 0) == "r1"
def test_turn_without_audio_is_an_error() -> None:
events = _TurnEvents(["r0"], {})
with pytest.raises(RuntimeError, match="no audio response"):
bench_patch._seed_tts_turn_response_id(events, 0, 0)
def test_stall_report_says_the_model_never_answered() -> None:
events = _TurnEvents(["r0"], {"r0": b"\x01\x00"})
report = bench_patch._seed_tts_turn_stall_report(events, 1, 3, 30.0)
assert "turn 3 never started a response" in report
assert "30.0s of silence" in report
def test_stall_report_lists_a_response_that_never_finished() -> None:
events = _TurnEvents(["r1"], {"r1": b"\x01\x00\x02\x00"}, {"r1": "hello"})
report = bench_patch._seed_tts_turn_stall_report(events, 0, 0, 4.2)
assert "started 1 response(s) after 4.2s of silence" in report
assert "r1 (4 audio bytes, text 'hello')" in report
@@ -0,0 +1,546 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Offline Video-MME sources: local mirrors must not fall back to a Hub id."""
from __future__ import annotations
import os
import zipfile
from argparse import Namespace
from pathlib import Path
from typing import Any
from urllib.parse import unquote, urlparse
import pytest
from PIL import Image
from tests.e2e.accuracy.qwen3_omni.run_qwen_omni_acc_benchmark import _validate_videomme
from vllm_omni.benchmarks.data_modules.videomme_dataset import (
VideoMMEDataset,
VideoMMESampleRequest,
cached_videomme_snapshots,
ensure_videomme_hub_root,
ensure_videomme_videos_extracted,
resolve_videomme_local_root,
videomme_local_parquet,
videomme_local_subtitle_dir,
videomme_local_video_dir,
)
from vllm_omni.benchmarks.data_modules.videomme_eval import (
compute_videomme_accuracy_metrics,
extract_characters_regex,
normalize_gold_answer,
)
from vllm_omni.benchmarks.patch.patch import _looks_like_hf_dataset_id, _videomme_repo_from_args, get_samples
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.benchmark]
def _write_parquet_placeholder(root: Path) -> Path:
path = root / "videomme" / "test-00000-of-00001.parquet"
path.parent.mkdir(parents=True)
path.write_bytes(b"parquet")
return path
def test_resolve_local_root_returns_none_for_hub_id() -> None:
assert resolve_videomme_local_root("lmms-eval/Video-MME") is None
assert resolve_videomme_local_root("") is None
assert resolve_videomme_local_root(None) is None
def test_plain_local_mirror(tmp_path: Path) -> None:
pq = _write_parquet_placeholder(tmp_path)
video = tmp_path / "video" / "abc.mp4"
video.parent.mkdir()
video.write_bytes(b"fake")
(tmp_path / "subtitle").mkdir()
(tmp_path / "subtitle" / "abc.srt").write_text("1\n", encoding="utf-8")
root = resolve_videomme_local_root(str(tmp_path))
assert root == tmp_path.resolve()
assert videomme_local_parquet(root) == pq.resolve()
assert videomme_local_video_dir(root) == tmp_path.resolve() / "video"
assert videomme_local_subtitle_dir(root) == tmp_path.resolve() / "subtitle"
def test_hf_cache_dir_resolves_to_snapshot(tmp_path: Path) -> None:
cache_dir = tmp_path / "datasets--lmms-eval--Video-MME"
snapshot = cache_dir / "snapshots" / "deadbeef"
snapshot.mkdir(parents=True)
_write_parquet_placeholder(snapshot)
(cache_dir / "refs").mkdir()
(cache_dir / "refs" / "main").write_text("deadbeef", encoding="utf-8")
root = resolve_videomme_local_root(str(cache_dir))
assert root == snapshot.resolve()
assert videomme_local_parquet(root) is not None
def test_hf_cache_dir_with_unusable_ref_falls_back_to_revision(tmp_path: Path) -> None:
cache_dir = tmp_path / "datasets--lmms-eval--Video-MME"
snapshot = cache_dir / "snapshots" / "deadbeef"
snapshot.mkdir(parents=True)
_write_parquet_placeholder(snapshot)
(cache_dir / "refs").mkdir()
# An empty ref must not resolve to snapshots/, which holds no dataset files.
(cache_dir / "refs" / "main").write_text("", encoding="utf-8")
assert resolve_videomme_local_root(str(cache_dir)) == snapshot.resolve()
def _stub_failing_hub(monkeypatch: pytest.MonkeyPatch, hub_cache: Path) -> dict[str, object]:
"""Point the Hub cache at ``hub_cache`` and make every snapshot_download miss."""
from huggingface_hub import constants as hf_constants
from huggingface_hub.errors import LocalEntryNotFoundError
from vllm_omni.transformers_utils import repo_utils
seen: dict[str, object] = {}
class _Api:
def snapshot_download(self, **kwargs: object) -> str:
seen.update(kwargs)
raise LocalEntryNotFoundError("no cached snapshot")
monkeypatch.setattr(hf_constants, "HF_HUB_OFFLINE", True)
monkeypatch.setattr(hf_constants, "HF_HUB_CACHE", str(hub_cache))
monkeypatch.setattr(repo_utils, "hf_api", lambda: _Api())
return seen
def test_hub_root_offline_without_cache_points_at_local_options(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
seen = _stub_failing_hub(monkeypatch, tmp_path)
with pytest.raises(FileNotFoundError, match="--videomme-video-dir") as excinfo:
ensure_videomme_hub_root("lmms-lab/Video-MME")
# Offline runs must consult the cache directly instead of resolving over the network.
assert seen["local_files_only"] is True
assert "already cached under another repo id" not in str(excinfo.value)
def test_hub_root_offline_names_snapshot_cached_under_another_repo_id(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
sibling = tmp_path / "datasets--lmms-eval--Video-MME" / "snapshots" / "deadbeef"
sibling.mkdir(parents=True)
_write_parquet_placeholder(sibling)
_stub_failing_hub(monkeypatch, tmp_path)
with pytest.raises(FileNotFoundError) as excinfo:
ensure_videomme_hub_root("lmms-lab/Video-MME")
assert str(sibling.resolve()) in str(excinfo.value)
def test_cached_videomme_snapshots_skips_partial_download(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
from huggingface_hub import constants as hf_constants
(tmp_path / "datasets--lmms-eval--Video-MME" / "snapshots" / "deadbeef").mkdir(parents=True)
monkeypatch.setattr(hf_constants, "HF_HUB_CACHE", str(tmp_path))
assert cached_videomme_snapshots() == []
def test_extract_videos_rejects_empty_tree(tmp_path: Path) -> None:
(tmp_path / "video").mkdir()
with pytest.raises(FileNotFoundError):
ensure_videomme_videos_extracted(tmp_path)
assert not (tmp_path / ".videomme_videos_extracted").exists()
def test_nested_unzipped_videos_are_discovered(tmp_path: Path) -> None:
nested = tmp_path / "videos" / "videos_chunked_01" / "data" / "xyz.mp4"
nested.parent.mkdir(parents=True)
nested.write_bytes(b"fake")
assert videomme_local_video_dir(tmp_path) == tmp_path / "videos"
def test_extract_characters_regex_matches_official_prefixes() -> None:
assert extract_characters_regex("The best answer is B.") == "B"
assert extract_characters_regex("Answer: C") == "C"
assert extract_characters_regex("I think D is correct") == "D"
assert extract_characters_regex("no letter here at all in this long sentence") is None
def test_normalize_gold_answer() -> None:
assert normalize_gold_answer("a") == "A"
assert normalize_gold_answer("B. content") == "B"
assert normalize_gold_answer("") is None
class _Out:
def __init__(self, text: str, *, success: bool = True) -> None:
self.generated_text = text
self.success = success
self.error = "" if success else "http fail"
def test_compute_videomme_accuracy_metrics() -> None:
reqs = [
VideoMMESampleRequest(
prompt="q",
prompt_len=1,
expected_output_len=8,
videomme_gold_answer="A",
videomme_video_id="v1",
videomme_question_id="q1",
videomme_duration="short",
videomme_domain="Knowledge",
videomme_sub_category="Science",
videomme_task_type="QA",
),
VideoMMESampleRequest(
prompt="q",
prompt_len=1,
expected_output_len=8,
videomme_gold_answer="B",
videomme_video_id="v2",
videomme_question_id="q2",
videomme_duration="long",
videomme_domain="Knowledge",
videomme_sub_category="Science",
videomme_task_type="QA",
),
]
metrics = compute_videomme_accuracy_metrics(reqs, [_Out("A"), _Out("The answer is C")])
assert metrics is not None
assert metrics["videomme_correct"] == 1
assert metrics["videomme_evaluated_ok"] == 2
assert metrics["videomme_accuracy"] == 0.5
assert metrics["videomme_submitted"] == 2
assert metrics["videomme_unique_question_ids"] == 2
assert _validate_videomme(metrics, min_accuracy=0.4) == []
assert "videomme_eval_items" not in metrics
assert metrics["videomme_per_duration_accuracy"]["short"] == 1.0
assert metrics["videomme_per_duration_accuracy"]["long"] == 0.0
def test_compute_videomme_accuracy_metrics_http_fail_excluded_from_default() -> None:
reqs = [
VideoMMESampleRequest(
prompt="q",
prompt_len=1,
expected_output_len=8,
videomme_gold_answer="A",
videomme_question_id="q1",
),
VideoMMESampleRequest(
prompt="q",
prompt_len=1,
expected_output_len=8,
videomme_gold_answer="B",
videomme_question_id="q2",
),
]
metrics = compute_videomme_accuracy_metrics(reqs, [_Out("A"), _Out("", success=False)])
assert metrics is not None
assert metrics["videomme_accuracy"] == 1.0
assert metrics["videomme_accuracy_incl_http_fail"] == 0.5
assert metrics["videomme_request_failed"] == 1
errs = _validate_videomme(metrics, min_accuracy=0.68)
assert any("videomme_request_failed" in err for err in errs)
def test_compute_videomme_accuracy_metrics_saves_eval_items() -> None:
req = VideoMMESampleRequest(
prompt="q",
prompt_len=1,
expected_output_len=8,
videomme_gold_answer="A",
videomme_question_id="q1",
)
metrics = compute_videomme_accuracy_metrics([req], [_Out("A")], include_per_item=True)
assert metrics is not None
assert metrics["videomme_eval_items"][0]["question_id"] == "q1"
def test_videomme_save_eval_items_cli_sets_env(monkeypatch: pytest.MonkeyPatch) -> None:
from vllm_omni.benchmarks import serve
seen: dict[str, str | None] = {}
async def fake_main_async(args: Namespace) -> dict[str, str]:
seen["env"] = os.environ.get("VIDEOMME_SAVE_EVAL_ITEMS")
return {"ok": "1"}
monkeypatch.delenv("VIDEOMME_SAVE_EVAL_ITEMS", raising=False)
monkeypatch.setattr(serve, "main_async", fake_main_async)
args = Namespace(
videomme_save_eval_items=True,
seed_tts_wer_eval=False,
seed_tts_wer_save_items=False,
daily_omni_save_eval_items=False,
omni_request_timeout_s=None,
endpoint=None,
backend="openai-chat-omni",
explicit_keys=frozenset(),
extra_body=None,
print_stage=False,
dataset_name="videomme",
)
assert serve.main(args) == {"ok": "1"}
assert seen["env"] == "1"
def _file_uri_path(url: str) -> Path:
parsed = urlparse(url)
assert parsed.scheme == "file"
return Path(unquote(parsed.path))
def test_relative_video_dir_emits_absolute_file_uris_cold_and_warm(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
videos = tmp_path / "videos"
videos.mkdir()
(videos / "vid1.mp4").write_bytes(b"fake")
def fake_extract(cls, video_path, *, include_audio, max_num_frames): # noqa: ANN001
return [Image.new("RGB", (4, 4), color="red")], []
monkeypatch.chdir(tmp_path)
monkeypatch.setattr(VideoMMEDataset, "load_data", lambda self: None)
monkeypatch.setattr(VideoMMEDataset, "_extract_frames_and_audio", classmethod(fake_extract))
ds = VideoMMEDataset(parquet_path="dummy.parquet", video_dir="videos", max_frames=1)
assert ds.video_dir == videos.resolve()
cold = ds._get_minicpm_frame_parts("vid1", include_audio=False)
assert cold is not None
cold_path = _file_uri_path(cold[0]["image_url"]["url"])
assert cold_path.is_absolute()
assert cold_path.is_file()
warm_ds = VideoMMEDataset(parquet_path="dummy.parquet", video_dir="videos", max_frames=1)
warm = warm_ds._get_minicpm_frame_parts("vid1", include_audio=False)
assert warm is not None
warm_path = _file_uri_path(warm[0]["image_url"]["url"])
assert warm_path.is_absolute()
assert warm_path == cold_path
def test_videomme_repo_from_args_honors_custom_hub_id() -> None:
args = Namespace(dataset_name="videomme", dataset_path="my-org/custom-videomme", hf_name=None)
assert _videomme_repo_from_args(args, explicit=True) == "my-org/custom-videomme"
def test_videomme_repo_from_args_defaults_when_path_omitted() -> None:
args = Namespace(dataset_name="videomme", dataset_path=None, hf_name=None)
assert _videomme_repo_from_args(args, explicit=True) is None
def test_videomme_repo_from_args_rejects_unsupported_path() -> None:
args = Namespace(dataset_name="videomme", dataset_path="not-a-local-dir-or-hub-id", hf_name=None)
with pytest.raises(ValueError, match="Unsupported Video-MME"):
_videomme_repo_from_args(args, explicit=True)
def test_get_samples_rejects_unsupported_videomme_dataset_path() -> None:
args = Namespace(
dataset_name="videomme",
dataset_path="not-a-local-dir-or-hub-id",
hf_name=None,
backend="openai-chat-omni",
seed=0,
)
with pytest.raises(ValueError, match="Unsupported Video-MME"):
get_samples(args, None)
def test_hf_dataset_name_does_not_auto_detect_custom_repo() -> None:
args = Namespace(dataset_name="hf", dataset_path="my-org/custom-videomme", hf_name=None)
assert _videomme_repo_from_args(args) is None
assert _looks_like_hf_dataset_id("my-org/custom-videomme")
assert not _looks_like_hf_dataset_id("./videos")
official = Namespace(dataset_name="hf", dataset_path="lmms-eval/Video-MME", hf_name=None)
assert _videomme_repo_from_args(official) == "lmms-eval/Video-MME"
@pytest.mark.parametrize("max_frames", [0, -1])
def test_rejects_nonpositive_max_frames(max_frames: int, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(VideoMMEDataset, "load_data", lambda self: None)
with pytest.raises(ValueError, match="max_frames must be positive"):
VideoMMEDataset(parquet_path="unused.parquet", max_frames=max_frames)
def test_frame_cache_rebuild_overwrites_incomplete_files(tmp_path: Path) -> None:
frame = tmp_path / "frame_0000.jpg"
frame.write_bytes(b"interrupted JPEG")
VideoMMEDataset._emit_media(tmp_path, frame.name, b"complete JPEG", "image_url", "image/jpeg")
assert frame.read_bytes() == b"complete JPEG"
def test_frame_cache_rejects_empty_media(tmp_path: Path) -> None:
(tmp_path / "manifest.json").write_text('{"count": 1}', encoding="utf-8")
(tmp_path / "frame_0000.jpg").touch()
dataset = object.__new__(VideoMMEDataset)
assert dataset._cached_parts_from_disk(tmp_path, include_audio=False) is None
@pytest.mark.parametrize("case", ["duplicates", "missing_gold"])
def test_accuracy_gate_rejects_incomplete_question_coverage(case: str) -> None:
def request(question_id: str, gold: str) -> VideoMMESampleRequest:
return VideoMMESampleRequest(
prompt="q",
prompt_len=1,
expected_output_len=8,
videomme_question_id=question_id,
videomme_gold_answer=gold,
)
requests = [
request("q1", "A"),
request("q1" if case == "duplicates" else "q2", "" if case == "missing_gold" else "A"),
]
metrics = compute_videomme_accuracy_metrics(requests, [_Out("A"), _Out("A")])
assert metrics is not None
assert metrics["videomme_accuracy"] == 1.0
errors = _validate_videomme(metrics, min_accuracy=0.68)
assert any(("unique" if case == "duplicates" else "no_gold") in error for error in errors)
@pytest.fixture
def videomme_mirror(tmp_path: Path) -> Path:
import pandas as pd
parquet = tmp_path / "videomme" / "test-00000-of-00001.parquet"
parquet.parent.mkdir()
pd.DataFrame(
[
{
"videoID": f"v{i}",
"question_id": f"q{i}",
"question": "Which option is correct?",
"options": ["A. first", "B. second", "C. third", "D. fourth"],
"answer": "A",
"duration": duration,
}
for i, duration in enumerate(("short", "long"), start=1)
]
).to_parquet(parquet)
videos = tmp_path / "video"
videos.mkdir()
for i in (1, 2):
(videos / f"v{i}.mp4").write_bytes(b"video")
return tmp_path
def _sample_video_urls(dataset: VideoMMEDataset, monkeypatch: pytest.MonkeyPatch, **kwargs: Any) -> list:
monkeypatch.setattr(
"vllm_omni.benchmarks.data_modules.videomme_dataset.get_cached_tokenizer", lambda tokenizer: tokenizer
)
return dataset.sample(Namespace(encode=lambda text: [1]), **kwargs)
@pytest.mark.parametrize("no_oversample", [True, False])
def test_missing_video_cannot_pass_accuracy_gate(
videomme_mirror: Path, monkeypatch: pytest.MonkeyPatch, no_oversample: bool
) -> None:
(videomme_mirror / "video" / "v2.mp4").unlink()
dataset = VideoMMEDataset(dataset_path=str(videomme_mirror), pack_mode="video_url", disable_shuffle=True)
requests = _sample_video_urls(dataset, monkeypatch, num_requests=2, no_oversample=no_oversample)
metrics = compute_videomme_accuracy_metrics(requests, [_Out("A") for _ in requests])
assert metrics is not None
assert metrics["videomme_accuracy"] == 1.0
assert metrics["videomme_submitted"] == (1 if no_oversample else 2)
assert metrics["videomme_skipped_rows"] == 1
assert any("videomme_skipped_rows" in error for error in _validate_videomme(metrics, min_accuracy=0.68))
def test_complete_duration_subset_can_pass_accuracy_gate(
videomme_mirror: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
dataset = VideoMMEDataset(dataset_path=str(videomme_mirror), pack_mode="video_url", duration_filter="short")
requests = _sample_video_urls(dataset, monkeypatch, num_requests=2700, no_oversample=True)
metrics = compute_videomme_accuracy_metrics(requests, [_Out("A") for _ in requests])
assert metrics is not None
assert metrics["videomme_submitted"] == 1
assert metrics["videomme_skipped_rows"] == 0
assert _validate_videomme(metrics, min_accuracy=0.68) == []
def test_dataset_direct_hub_loading_resolves_video_assets(
videomme_mirror: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
downloaded = []
def download(repo_id: str) -> Path:
downloaded.append(repo_id)
return videomme_mirror
monkeypatch.setattr("vllm_omni.benchmarks.data_modules.videomme_dataset.ensure_videomme_hub_root", download)
dataset = VideoMMEDataset(dataset_path="my-org/custom-videomme", pack_mode="video_url")
assert downloaded == ["my-org/custom-videomme"]
assert dataset.video_dir == videomme_mirror / "video"
assert len(dataset.data) == 2
def test_local_source_with_explicit_parquet_keeps_video_root(videomme_mirror: Path) -> None:
dataset = VideoMMEDataset(
dataset_path=str(videomme_mirror),
parquet_path=str(videomme_local_parquet(videomme_mirror)),
pack_mode="video_url",
)
assert dataset.video_dir == videomme_mirror / "video"
assert len(dataset.data) == 2
def test_local_source_without_parquet_fails_locally(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
def unexpected_hub(*args, **kwargs):
pytest.fail("An explicitly selected local mirror must not fall back to Hub loading")
monkeypatch.setattr("vllm_omni.benchmarks.data_modules.videomme_dataset.load_dataset", unexpected_hub)
with pytest.raises(FileNotFoundError, match="No Video-MME parquet"):
VideoMMEDataset(dataset_path=str(tmp_path))
def test_get_samples_prefers_local_root_over_hf_name(videomme_mirror: Path, monkeypatch: pytest.MonkeyPatch) -> None:
args = Namespace(
dataset_name="videomme",
dataset_path=str(videomme_mirror),
hf_name="unused-hf-name",
backend="openai-chat-omni",
seed=0,
videomme_pack_mode="video_url",
num_prompts=2,
request_id_prefix="",
no_oversample=True,
)
monkeypatch.setattr(
"vllm_omni.benchmarks.data_modules.videomme_dataset.get_cached_tokenizer", lambda tokenizer: tokenizer
)
requests = get_samples(args, Namespace(encode=lambda text: [1]))
assert len(requests) == 2
assert {request.videomme_question_id for request in requests} == {"q1", "q2"}
def test_extraction_replaces_truncated_video(tmp_path: Path) -> None:
video = tmp_path / "video" / "v1.mp4"
video.parent.mkdir()
video.write_bytes(b"partial")
with zipfile.ZipFile(tmp_path / "videos_chunked_01.zip", "w") as archive:
archive.writestr("nested/v1.mp4", b"complete video")
assert ensure_videomme_videos_extracted(tmp_path) == video.parent
assert video.read_bytes() == b"complete video"
def test_failed_extraction_does_not_publish_partial_video(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
with zipfile.ZipFile(tmp_path / "videos_chunked_01.zip", "w") as archive:
archive.writestr("v1.mp4", b"complete video")
def interrupted_copy(src, dst):
dst.write(b"partial")
raise OSError("interrupted")
monkeypatch.setattr("vllm_omni.benchmarks.data_modules.videomme_dataset.shutil.copyfileobj", interrupted_copy)
with pytest.raises(OSError, match="interrupted"):
ensure_videomme_videos_extracted(tmp_path)
assert list((tmp_path / "video").iterdir()) == []
assert not (tmp_path / ".videomme_videos_extracted").exists()
+1 -1
View File
@@ -136,7 +136,7 @@ def test_label_lookup_selects_tiers(tmp_path, labels, expected_levels):
] == expected_levels
@pytest.mark.parametrize("debug_test_yaml", ["ready,ready", "nightly", ", ,", " \t"])
@pytest.mark.parametrize("debug_test_yaml", ["ready,ready", "nightly,nightly", ", ,", " \t"])
def test_invalid_debug_override_fails_without_label_lookup(tmp_path, debug_test_yaml):
result = _run_bootstrap(tmp_path, debug_test_yaml=debug_test_yaml, curl_status=22)
+39 -2
View File
@@ -10,10 +10,13 @@ import yaml
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
AMD_MERGE_PIPELINE = Path(".buildkite/amd/test-amd-merge.yml")
AMD_NIGHTLY_PIPELINE = Path(".buildkite/amd/test-amd-nightly.yml")
AMD_READY_PIPELINE = Path(".buildkite/amd/test-amd-ready.yml")
AMD_TEMPLATE = Path(".buildkite/amd/test-template-amd-omni.j2")
def _find_step(label: str) -> dict:
pipeline = yaml.safe_load(AMD_MERGE_PIPELINE.read_text(encoding="utf-8"))
def _find_step(label: str, pipeline_path: Path = AMD_MERGE_PIPELINE) -> dict:
pipeline = yaml.safe_load(pipeline_path.read_text(encoding="utf-8"))
def walk(steps: list[dict]) -> dict | None:
for step in steps:
@@ -40,3 +43,37 @@ def test_qwen3_tts_base_preserves_advanced_model_arguments() -> None:
run_level_index = argv.index("--run-level")
assert argv[marker_index + 1] == "advanced_model and cuda"
assert argv[run_level_index + 1] == "advanced_model"
def test_qwen3_accuracy_defers_artifact_path_expansion() -> None:
step = _find_step("Qwen3-Omni Accuracy", AMD_NIGHTLY_PIPELINE)
staging_command = next(command for command in step["commands"] if "artifact_dir=" in command)
# Dynamic pipelines are interpolated once during upload. Double dollars
# preserve these variables for the GPU job's runtime shell.
assert '"$$PWD"' in staging_command
assert '"$${BUILDKITE_BUILD_CHECKOUT_PATH:?}"' in staging_command
assert '"$$artifact_dir"' in staging_command
assert step["artifact_paths"] == ["tests/e2e/accuracy/qwen3_omni/results/qwen_omni_acc/*.json"]
def test_ready_diffusion_cpu_suite_is_sharded() -> None:
step = _find_step("Simple · Diffusion Test · Shard %N/%t", AMD_READY_PIPELINE)
pytest_command = next(command for command in step["commands"] if "pytest" in command)
assert step["parallelism"] == 4
assert step["timeout_in_minutes"] == 45
assert "--num-shards=$$BUILDKITE_PARALLEL_JOB_COUNT" in pytest_command
assert "--shard-id=$$BUILDKITE_PARALLEL_JOB" in pytest_command
def test_cosyvoice_gpu_abort_gets_one_fresh_job_retry() -> None:
step = _find_step("CosyVoice3-TTS E2E Test", AMD_READY_PIPELINE)
assert step["retry"] == {"automatic": [{"exit_status": 134, "limit": 1}]}
template = AMD_TEMPLATE.read_text(encoding="utf-8")
# Both grouped and top-level AMD steps must preserve an explicit retry
# policy when the source suite is rendered into the uploaded pipeline.
assert template.count("{% if step.retry %}") == 2
assert template.count("{% for retry_rule in step.retry.automatic %}") == 2
+72
View File
@@ -0,0 +1,72 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from pathlib import Path
from shlex import split
import pytest
import yaml
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
AMD_READY_PIPELINE = Path(".buildkite/amd/test-amd-ready.yml")
R2_01_LABEL = "ROCm · Engine & Model Executor GPU Coverage (R2-01)"
SINGLE_GPU_MARKERS = (
"core_model and cuda and not (cards_2 or cards_3 or cards_4 or cards_5 or cards_6 or cards_7 or cards_8)"
)
EXCLUDED_TEST = "test_code2wav_streaming_batch_matches_ragged_flow_numerics"
def _find_step(label: str) -> dict:
pipeline = yaml.safe_load(AMD_READY_PIPELINE.read_text(encoding="utf-8"))
def walk(steps: list[dict]) -> dict | None:
for step in steps:
if step.get("label") == label:
return step
if nested := walk(step.get("steps", [])):
return nested
return None
step = walk(pipeline.get("steps", []))
assert step is not None, f"missing AMD pipeline step: {label}"
return step
def _assert_single_gpu_selection(command: str) -> None:
argv = split(command)
assert "tests/engine/" in argv
assert "tests/model_executor/" in argv
assert "tests/worker/test_batched_omni_output.py" not in argv
assert argv[argv.index("-m") + 1] == SINGLE_GPU_MARKERS
assert argv[argv.index("-k") + 1] == f"not {EXCLUDED_TEST}"
assert argv[argv.index("--run-level") + 1] == "core_model"
def test_r2_01_is_nonblocking_single_gpu_coverage() -> None:
step = _find_step(R2_01_LABEL)
assert step["agent_pool"] == "mi300_1"
assert step["grade"] == "NonBlocking"
assert step["timeout_in_minutes"] == 20
assert step["mirror_hardwares"] == ["amdproduction"]
assert step["artifact_paths"] == ["artifacts/rocm-r2-01/**/*"]
def test_r2_01_runs_once_fails_closed_and_publishes_results() -> None:
commands = _find_step(R2_01_LABEL)["commands"]
pytest_commands = [command for command in commands if command.lstrip().startswith("pytest ")]
assert len(pytest_commands) == 1
run_command = pytest_commands[0]
artifact_dir = "$$BUILDKITE_BUILD_CHECKOUT_PATH/artifacts/rocm-r2-01"
_assert_single_gpu_selection(run_command)
assert "--collect-only" not in "\n".join(commands)
assert "VLLM_CI_ALLOW_NO_TESTS" not in "\n".join(commands)
assert any(artifact_dir in command for command in commands)
assert "-v" in split(run_command)
assert "-ra" in split(run_command)
assert "--durations=0" in split(run_command)
assert "--junitxml=$$R2_01_ARTIFACT_DIR/pytest.xml" in split(run_command)
assert "$$R2_01_ARTIFACT_DIR/pytest.log" in run_command
assert any("$$R2_01_ARTIFACT_DIR/pytest-summary.txt" in command for command in commands)
+15 -4
View File
@@ -24,10 +24,12 @@ SPEC.loader.exec_module(SELECTOR)
("feature", ("ready",), ("ready",)),
("feature", ("merge-test",), ("merge",)),
("feature", ("merge-test", "ready"), ("ready", "merge")),
("feature", ("nightly-test",), ("nightly",)),
("feature", ("ready", "merge-test", "nightly-test"), ("ready", "merge", "nightly")),
("feature", ("amd-test",), ("ready",)),
("feature", ("amd-test", "merge-test"), ("merge",)),
("feature", ("amd-test", "ready", "merge-test"), ("ready", "merge")),
("feature", ("nightly-test",), ("ready",)),
("feature", ("amd-test", "nightly-test"), ("nightly",)),
("feature", ("not-ready", "merge-test-extra"), ("ready",)),
],
)
@@ -39,8 +41,17 @@ def test_debug_override_takes_precedence_and_normalizes_input():
assert SELECTOR.select_amd_test_suites(
branch="main",
labels=("ready",),
debug_test_yaml=" MERGE, ready,",
) == ("merge", "ready")
debug_test_yaml=" NIGHTLY, merge, ready,",
nightly=False,
) == ("nightly", "merge", "ready")
def test_scheduled_main_selects_only_nightly():
assert SELECTOR.select_amd_test_suites(
branch="main",
labels=(),
nightly=True,
) == ("nightly",)
def test_empty_debug_override_uses_normal_selection():
@@ -51,7 +62,7 @@ def test_empty_debug_override_uses_normal_selection():
) == ("merge",)
@pytest.mark.parametrize("value", ["ready,ready", "nightly", ", ,", " \t"])
@pytest.mark.parametrize("value", ["ready,ready", "nightly,nightly", "weekly", ", ,", " \t"])
def test_invalid_debug_override(value):
with pytest.raises(ValueError):
SELECTOR.select_amd_test_suites(
+126
View File
@@ -0,0 +1,126 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from pathlib import Path
import pytest
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
REPO_ROOT = Path(__file__).resolve().parents[2]
AMD_TEMPLATE = REPO_ROOT / ".buildkite/amd/test-template-amd-omni.j2"
AMD_BUILD_SCRIPT = REPO_ROOT / ".buildkite/amd/scripts/build-ci-image.sh"
CI_DOCKERFILE = REPO_ROOT / "docker/Dockerfile.ci"
ROCM_DOCKERFILE = REPO_ROOT / "docker/Dockerfile.rocm"
ROCM_DOCKERIGNORE = REPO_ROOT / "docker/Dockerfile.rocm.dockerignore"
def _docker_arg(path: Path, name: str) -> str:
prefix = f"ARG {name}="
matches = [
line.removeprefix(prefix) for line in path.read_text(encoding="utf-8").splitlines() if line.startswith(prefix)
]
assert len(matches) == 1, f"expected one {name} declaration in {path}, found {len(matches)}"
return matches[0]
def _line_index(lines: list[str], prefix: str) -> int:
matches = [index for index, line in enumerate(lines) if line.startswith(prefix)]
assert len(matches) == 1, f"expected one line starting with {prefix!r}, found {len(matches)}"
return matches[0]
def test_rocm_base_tracks_ci_vllm_release() -> None:
ci_release = _docker_arg(CI_DOCKERFILE, "VLLM_BASE_TAG")
rocm_base = _docker_arg(ROCM_DOCKERFILE, "BASE_IMAGE")
image_ref, separator, image_tag = rocm_base.rpartition(":")
assert separator, f"expected a tagged ROCm base image, got {rocm_base}"
assert image_ref.rsplit("/", 1)[-1] == "vllm-openai-rocm", image_ref
assert image_tag == ci_release
def test_rocm_defaults_to_prebuilt_base_image() -> None:
assert _docker_arg(ROCM_DOCKERFILE, "USE_NIGHTLY_BUILD") == "0"
def test_amd_build_uses_registry_cache() -> None:
template = AMD_TEMPLATE.read_text(encoding="utf-8")
script_command = '"bash .buildkite/amd/scripts/build-ci-image.sh"'
script = AMD_BUILD_SCRIPT.read_text(encoding="utf-8")
assert template.count(script_command) == 1
assert "docker buildx build --push" in script
assert '--cache-from "type=registry,ref=${CACHE_REF}"' in script
assert '--cache-to "type=registry,ref=${CACHE_REF}' in script
assert "mode=max" in script
def test_amd_cache_key_tracks_dependency_inputs_and_architecture() -> None:
script = AMD_BUILD_SCRIPT.read_text(encoding="utf-8")
for cache_input in (
"docker/Dockerfile.rocm",
"${DOCKERFILE}.dockerignore",
"pyproject.toml",
"setup.py",
"requirements",
"tools/install_torchcodec_rocm.sh",
"ROCM_ARCH",
):
assert cache_input in script
def test_amd_build_uses_rocm_dockerfile_defaults() -> None:
build_script = AMD_BUILD_SCRIPT.read_text(encoding="utf-8")
assert 'DOCKERFILE="docker/Dockerfile.rocm"' in build_script
for arg_name in ("BASE_IMAGE", "USE_NIGHTLY_BUILD"):
assert f"--build-arg {arg_name}" not in build_script
assert f"--build-arg={arg_name}" not in build_script
def test_rocm_source_copy_preserves_dependency_cache() -> None:
dockerfile = ROCM_DOCKERFILE.read_text(encoding="utf-8")
lines = dockerfile.splitlines()
source_copy_index = _line_index(lines, "COPY --link . .")
test_stage_index = _line_index(lines, "FROM base AS test")
assert "FROM deps AS base" in lines[:source_copy_index]
assert any('-e ".[dev]"' in line for line in lines[:source_copy_index])
assert not any(
line.startswith(("RUN ", "COPY ", "ADD ")) for line in lines[source_copy_index + 1 : test_stage_index]
)
def test_rocm_build_context_excludes_git_history() -> None:
patterns = {
line.strip()
for line in ROCM_DOCKERIGNORE.read_text(encoding="utf-8").splitlines()
if line.strip() and not line.lstrip().startswith("#")
}
assert ".git" in patterns
def test_rocm_source_ref_tracks_ci_vllm_release() -> None:
ci_release = _docker_arg(CI_DOCKERFILE, "VLLM_BASE_TAG")
rocm_source_ref = _docker_arg(ROCM_DOCKERFILE, "VLLM_VERSION_OR_COMMIT_HASH")
assert rocm_source_ref == ci_release
def test_rocm_dockerfile_contains_vllm_api_canary() -> None:
dockerfile = ROCM_DOCKERFILE.read_text(encoding="utf-8")
lines = dockerfile.splitlines()
nightly_start = _line_index(lines, 'RUN if [ "${USE_NIGHTLY_BUILD}" = "1" ]; then')
canary = (
'RUN python3 -c "import vllm; '
"from vllm.v1.kv_cache_interface import compute_layout_strides; "
"from vllm.v1.kv_cache_layout import KVCacheLayout;"
)
canary_index = _line_index(lines, canary)
assert any(line.strip() == "fi" for line in lines[nightly_start + 1 : canary_index]), (
"vLLM API canary must follow the optional nightly source reinstall block"
)
+8
View File
@@ -144,6 +144,14 @@ def test_npu_nightly_only_skips_all_l23() -> None:
assert not decision.is_run("npu", "l3")
def test_amd_nightly_only_skips_all_l23() -> None:
decision = _decision([".buildkite/amd/test-amd-nightly.yml"])
assert _is_yaml_gated(decision)
assert _all_l23_skipped(decision)
assert not decision.is_run("amd", "l2")
assert not decision.is_run("amd", "l3")
def test_nightly_and_weekly_skips_all_l23() -> None:
decision = _decision(
[
+381 -2
View File
@@ -13,16 +13,21 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / ".buildkite" / "com
from skip_ci import resolve_ci_decision # noqa: E402
from upload_pipeline import ( # noqa: E402
CUDA_HF_TOKEN_EXPORT,
NIGHTLY_LABEL_IF,
_changed_files_for_source_filter,
_expand_mirror_hardwares,
_get_mirror_hw_selector,
_load_bootstrap_steps,
_load_source_file_dependencies,
_render_bootstrap_pipeline,
_render_test_pipeline,
_resolve_source_file_dependencies,
)
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
CUDA_BOOTSTRAP_STEPS = Path(".buildkite/cuda/bootstrap-upload-steps.yml")
NIGHTLY_YAML = Path(".buildkite/cuda/test-nightly.yml")
BOOTSTRAP_STEPS_TEMPLATE = """steps:
- key: image-build
- key: upload-ready-pipeline
@@ -101,6 +106,26 @@ def test_npu_docs_only_does_not_upload_ready_on_nightly() -> None:
assert 'build.env("NIGHTLY") == "1"' in by_key["upload-nightly-pipeline"]["if"]
def test_nightly_label_if_is_only_nightly_test() -> None:
assert 'labels includes "nightly-test"' in NIGHTLY_LABEL_IF
forbidden = (
'includes "omni-test"',
'includes "tts-test"',
'includes "diffusion-x2iat-test"',
'includes "diffusion-x2v-test"',
)
for needle in forbidden:
assert needle not in NIGHTLY_LABEL_IF
for path in (
Path(".buildkite/cuda/test-nightly.yml"),
Path(".buildkite/npu/test-npu-nightly.yml"),
Path(".buildkite/common/scripts/upload_pipeline.py"),
):
text = path.read_text(encoding="utf-8")
for needle in forbidden:
assert needle not in text, f"{path} still references {needle}"
def test_yaml_gated_l45_only_does_not_unconditionally_build_image() -> None:
rendered = _render([".buildkite/cuda/test-nightly.yml"])
assert "if: true" not in rendered
@@ -344,6 +369,52 @@ def test_cpu_step_without_mirror_hardwares_is_unchanged() -> None:
assert _expand_mirror_hardwares(step) is step
def _leaf_steps(steps: list) -> list[dict]:
leaves: list[dict] = []
for step in steps:
if not isinstance(step, dict):
continue
nested = step.get("steps")
if nested is not None:
leaves.extend(_leaf_steps(nested))
else:
leaves.append(step)
return leaves
def test_nightly_yaml_infers_h100_l4_and_b200(monkeypatch: pytest.MonkeyPatch) -> None:
"""Nightly inferred jobs share card counts across H100/L4 and B200 mirrors."""
src = yaml.safe_load(NIGHTLY_YAML.read_text(encoding="utf-8"))
pytest_leaves = [step for step in _leaf_steps(src["steps"]) if "pytest" in str(step.get("commands"))]
inferred_leaves = [step for step in pytest_leaves if "mirror_hardwares" not in step]
pinned_leaves = [step for step in pytest_leaves if "mirror_hardwares" in step]
assert inferred_leaves
monkeypatch.setattr("upload_pipeline._get_mirror_hw_selector", lambda: "")
default_by_label = {
step["label"]: step for step in _leaf_steps(_render_test_pipeline(src, changed_files=None)["steps"])
}
monkeypatch.setattr("upload_pipeline._get_mirror_hw_selector", lambda: "b200")
b200_src = yaml.safe_load(NIGHTLY_YAML.read_text(encoding="utf-8"))
b200_by_label = {
step["label"]: step for step in _leaf_steps(_render_test_pipeline(b200_src, changed_files=None)["steps"])
}
pytest_labels = {step["label"] for step in inferred_leaves}
pinned_labels = {step["label"] for step in pinned_leaves}
assert pinned_labels <= set(default_by_label)
assert pinned_labels.isdisjoint(b200_by_label)
assert pytest_labels <= set(default_by_label)
assert pytest_labels <= set(b200_by_label)
for label in pytest_labels:
default_step = default_by_label[label]
b200_step = b200_by_label[label]
assert default_step["agents"]["queue"] in {"mithril-h100-pool", "l4-k8s"}
assert b200_step["agents"]["queue"] == "b200-k8s"
assert _gpu_limit(default_step) == _gpu_limit(b200_step)
@pytest.mark.parametrize(("raw", "expected"), [("", ""), (" ", ""), ("b200", "b200"), ("B200", "b200")])
def test_mirror_hw_selector_empty_or_b200(monkeypatch: pytest.MonkeyPatch, raw: str, expected: str) -> None:
monkeypatch.setenv("MIRROR_HW", raw)
@@ -366,8 +437,17 @@ def test_mirror_hw_typo_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:
)
def _surviving_labels(doc: dict, changed_files: list[str]) -> set[str]:
rendered = _render_test_pipeline(doc, changed_files=changed_files)
def _surviving_labels(
doc: dict,
changed_files: list[str],
*,
pipeline_path: Path | None = None,
) -> set[str]:
rendered = _render_test_pipeline(
doc,
changed_files=changed_files,
pipeline_path=pipeline_path,
)
labels: set[str] = set()
def walk(steps: list | None) -> None:
@@ -382,6 +462,17 @@ def _surviving_labels(doc: dict, changed_files: list[str]) -> set[str]:
return labels
def _iter_steps(doc: dict):
def walk(steps: list | None):
for step in steps or []:
if not isinstance(step, dict):
continue
yield step
yield from walk(step.get("steps"))
yield from walk(doc.get("steps"))
# Synthetic coverage-style job: shared inputs that change what the split measures.
_COVERAGE_SHARED_INPUTS_DOC = {
"steps": [
@@ -426,3 +517,291 @@ def test_coverage_shared_inputs_ignored_for_unrelated_change() -> None:
)
assert "Coverage Pilot" not in labels
assert "Unrelated Model Test" not in labels
def _pipeline_dep_keys(path: Path) -> set[str]:
doc = yaml.safe_load(path.read_text(encoding="utf-8"))
keys: set[str] = set()
def walk(steps: list | None) -> None:
for step in steps or []:
if not isinstance(step, dict):
continue
deps = step.get("source_file_dependencies")
if isinstance(deps, str) and "/" not in deps:
keys.add(deps)
elif isinstance(deps, list) and deps and all("/" not in item for item in deps):
keys.update(deps)
walk(step.get("steps"))
walk((doc or {}).get("steps"))
return keys
def test_pipeline_source_file_dependency_keys_are_registered() -> None:
_load_source_file_dependencies.cache_clear()
registry = _load_source_file_dependencies()
used = (
_pipeline_dep_keys(Path(".buildkite/cuda/test-ready.yml"))
| _pipeline_dep_keys(Path(".buildkite/cuda/test-merge.yml"))
| _pipeline_dep_keys(Path(".buildkite/cuda/test-nightly.yml"))
| _pipeline_dep_keys(Path(".buildkite/cuda/test-weekly.yml"))
| _pipeline_dep_keys(Path(".buildkite/npu/test-npu-nightly.yml"))
)
missing = used - set(registry)
assert not missing, f"unregistered source_file_dependencies keys: {sorted(missing)}"
def test_source_file_dependencies_key_expands_from_registry() -> None:
doc = {
"steps": [
{
"label": "Diffusion · Qwen Image Test",
"source_file_dependencies": "diffusion_qwen_image_function",
"commands": ["pytest"],
},
],
}
assert "Diffusion · Qwen Image Test" in _surviving_labels(
doc,
["vllm_omni/diffusion/models/qwen_image/transformer.py"],
)
assert "Diffusion · Qwen Image Test" not in _surviving_labels(doc, ["vllm_omni/unrelated.py"])
def test_registry_lists_pytest_targets() -> None:
_load_source_file_dependencies.cache_clear()
resolved = _resolve_source_file_dependencies(
{
"label": "Diffusion · Wan22 Test",
"source_file_dependencies": "diffusion_wan22_function",
"commands": [
"pytest -s -v tests/e2e/offline_inference/test_wan22_t2v.py "
"tests/e2e/online_serving/test_wan22_t2v.py -m 'advanced_model'",
],
},
)
assert resolved is not None
assert "tests/e2e/offline_inference/test_wan22_t2v.py" in resolved
assert "tests/e2e/online_serving/test_wan22_t2v.py" in resolved
assert "vllm_omni/diffusion/models/wan2_2/" in resolved
def test_coverage_key_lists_offline_online_scripts() -> None:
resolved = _resolve_source_file_dependencies(
{
"label": "TTS · Qwen3-TTS Base Test",
"source_file_dependencies": "tts_qwen3_tts_cov",
"commands": [
".buildkite/common/scripts/run_cov_split.sh \\\n"
" --offline tests/e2e/offline_inference/test_qwen3_tts_base.py \\\n"
" --online tests/e2e/online_serving/test_qwen3_tts_base.py",
],
},
)
assert resolved is not None
assert "tests/e2e/offline_inference/test_qwen3_tts_base.py" in resolved
assert "tests/e2e/online_serving/test_qwen3_tts_base.py" in resolved
assert ".buildkite/common/scripts/run_cov_split.sh" in resolved
assert "pyproject.toml" in resolved
def test_source_file_dependencies_list_of_keys_concatenates() -> None:
resolved = _resolve_source_file_dependencies(
{
"label": "composed",
"source_file_dependencies": ["omni_qwen3_omni_function", "tts_qwen3_tts_function"],
},
)
assert resolved is not None
assert "vllm_omni/model_executor/models/qwen3_omni/" in resolved
assert "vllm_omni/model_executor/models/qwen3_tts/" in resolved
assert resolved.count("vllm_omni/model_executor/models/common/snake_activation.py") == 1
def test_unknown_source_file_dependencies_key() -> None:
with pytest.raises(ValueError, match="unknown source_file_dependencies"):
_render_test_pipeline(
{"steps": [{"label": "bad", "source_file_dependencies": "not_a_real_key"}]},
changed_files=None,
)
def test_source_file_dependencies_rejects_mixed_keys_and_paths() -> None:
with pytest.raises(ValueError, match="mixes registry keys and path prefixes"):
_resolve_source_file_dependencies(
{
"label": "bad",
"source_file_dependencies": ["omni_qwen3_omni_function", "tests/e2e/online_serving/test_qwen3_omni.py"],
},
)
# Synthetic pipeline: selection depends only on listed deps, not on live job names.
_SOURCE_FILTER_DOC = {
"steps": [
{
"group": "E2E Tests",
"if": 'build.env("NON_CRITICAL") == "1"',
"steps": [
{
"label": "Dedicated E2E",
"commands": ["pytest -sv tests/e2e/online_serving/test_magi2.py"],
},
],
},
{
"label": "Omni Sweep",
"source_file_dependencies": ["tests/e2e/online_serving/test_qwen3_omni.py"],
"commands": ["pytest -sv tests/e2e/ -m omni"],
},
{
"label": "Z-Image Function",
"source_file_dependencies": [
"tests/e2e/online_serving/test_zimage_expansion.py",
"vllm_omni/diffusion/models/z_image/",
],
"mirror_hardwares": "l4_4",
"commands": ["pytest -sv tests/e2e/online_serving/test_zimage_expansion.py"],
},
{
"label": "Tiny Model",
"source_file_dependencies": ["tests/e2e/online_serving/test_tiny.py"],
"commands": ["pytest -sv tests/e2e/ -m tiny"],
},
{
"label": "Wan Function",
"source_file_dependencies": [
"tests/e2e/offline_inference/test_wan22_t2v.py",
"tests/e2e/online_serving/test_wan22_t2v.py",
"vllm_omni/diffusion/models/wan2_2/",
],
"commands": ["pytest -sv tests/e2e/offline_inference/test_wan22_t2v.py"],
},
{
"label": "Wan Perf",
"source_file_dependencies": ["vllm_omni/diffusion/models/wan2_2/"],
"commands": ["pytest -sv tests/dfx/perf/scripts/run_benchmark.py"],
},
{
"label": "Doc Test",
"source_file_dependencies": [
"tests/examples/offline_inference/test_text_to_image.py",
"tests/examples/online_serving/test_text_to_image.py",
"vllm_omni/diffusion/models/qwen_image/",
"vllm_omni/diffusion/models/z_image/",
],
"commands": ["pytest -sv tests/examples/*/test_text_to_image.py"],
},
],
}
def test_source_filter_ignores_unrelated_e2e_file() -> None:
"""A sweep command is not a dependency; only listed paths select a keyed job."""
labels = _surviving_labels(_SOURCE_FILTER_DOC, ["tests/e2e/online_serving/test_magi2.py"])
assert labels == {"Dedicated E2E"}
def test_source_filter_selects_job_by_listed_script_not_sibling() -> None:
labels = _surviving_labels(_SOURCE_FILTER_DOC, ["tests/e2e/online_serving/test_zimage_expansion.py"])
assert labels == {"Dedicated E2E", "Z-Image Function"}
def test_source_filter_selects_every_job_sharing_a_path() -> None:
labels = _surviving_labels(_SOURCE_FILTER_DOC, ["vllm_omni/diffusion/models/wan2_2/transformer.py"])
assert labels == {"Dedicated E2E", "Wan Function", "Wan Perf"}
def test_source_filter_selects_composed_doc_job_by_example_or_model() -> None:
for changed in (
"tests/examples/online_serving/test_text_to_image.py",
"vllm_omni/diffusion/models/z_image/transformer.py",
"vllm_omni/diffusion/models/qwen_image/foo.py",
):
labels = _surviving_labels(_SOURCE_FILTER_DOC, [changed])
assert "Doc Test" in labels, changed
assert "Tiny Model" not in labels
assert "Omni Sweep" not in labels
assert "Doc Test" not in _surviving_labels(_SOURCE_FILTER_DOC, ["tests/e2e/online_serving/test_magi2.py"])
def test_source_filter_strips_deps_and_expands_hardware(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("upload_pipeline._get_mirror_hw_selector", lambda: "")
rendered = _render_test_pipeline(
_SOURCE_FILTER_DOC,
changed_files=["tests/e2e/online_serving/test_zimage_expansion.py"],
)
dumped = yaml.safe_dump(rendered)
assert "source_file_dependencies" not in dumped
assert "mirror_hardwares" not in dumped
z_image = next(step for step in _iter_steps(rendered) if step.get("label") == "Z-Image Function")
assert z_image["agents"]["queue"] == "l4-k8s"
def test_source_filter_respects_force_all_and_uses_diff_on_main(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class _Ctx:
changed_files = ["vllm_omni/unrelated.py"]
# Post-merge main L3 must still filter by the commit diff.
monkeypatch.setenv("BUILDKITE_BRANCH", "main")
assert _changed_files_for_source_filter(_Ctx(), force_all=False, e2e_only=False) == [
"vllm_omni/unrelated.py",
]
monkeypatch.setenv("BUILDKITE_BRANCH", "feat/source-filter")
assert _changed_files_for_source_filter(_Ctx(), force_all=False, e2e_only=False) == [
"vllm_omni/unrelated.py",
]
assert _changed_files_for_source_filter(_Ctx(), force_all=True, e2e_only=False) is None
assert _changed_files_for_source_filter(_Ctx(), force_all=False, e2e_only=True) is None
def test_source_filter_fallback_is_fallback_when_no_job_key_matches(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Fallback only when no listed prefix matched; a matching prefix still wins."""
monkeypatch.setattr("upload_pipeline._get_mirror_hw_selector", lambda: "")
monkeypatch.setenv("BUILDKITE_BRANCH", "feat/nightly-yaml")
pipeline_yaml = Path(".buildkite/npu/test-npu-nightly.yml")
shared_paths = _load_source_file_dependencies()["source_filter_fallback"]
# Synthetic steps only — do not pin live Buildkite job labels.
doc = {
"steps": [
{"key": "ungated", "commands": ["true"]},
{
"key": "gated_a",
"source_file_dependencies": ["pkg/model_a/"],
"commands": ["true"],
},
{
"key": "gated_b",
"source_file_dependencies": ["pkg/model_b/"],
"commands": ["true"],
},
],
}
def surviving_keys(changed_files: list[str]) -> set[str]:
rendered = _render_test_pipeline(
doc,
changed_files=changed_files,
pipeline_path=pipeline_yaml,
)
return {step["key"] for step in _iter_steps(rendered) if isinstance(step.get("key"), str)}
# Only pipeline YAML / fallback paths → no listed prefix match → keep every step.
for changed in [pipeline_yaml.as_posix(), *shared_paths]:
assert surviving_keys([changed]) == {"ungated", "gated_a", "gated_b"}, changed
# A different pipeline YAML is not a fallback for this upload.
assert surviving_keys([".buildkite/cuda/test-nightly.yml"]) == {"ungated"}
# A matching source prefix wins over fallback files in the same diff.
assert surviving_keys(["pkg/model_a/transformer.py", *shared_paths[:1]]) == {
"ungated",
"gated_a",
}
File diff suppressed because it is too large. Load diff
+4 -3
View File
@@ -18,13 +18,13 @@ from vllm_omni.clients.personaplex import (
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
def test_minicpmo45_session_config_matches_native_duplex_deployment():
def test_minicpmo45_session_config_matches_duplex_deployment():
config = create_minicpmo45_session_config(ref_audio="data:audio/wav;base64,AAA=", temperature=0.0)
payload = config.to_session_payload(model="openbmb/MiniCPM-o-4_5")
assert payload["ref_audio"] == "data:audio/wav;base64,AAA="
assert payload["overlap_policy"] == "listen_only"
assert payload["playback_commit_policy"] == "ack_only"
assert payload["extra_body"]["native_duplex"] is True
assert "native_duplex" not in payload["extra_body"]
assert payload["extra_body"]["auto_response"] is True
assert payload["temperature"] == 0.0
@@ -41,8 +41,9 @@ def test_personaplex_session_config_matches_deployment():
@pytest.mark.parametrize(
"duplex_package",
[
# PersonaPlex and Nemotron VoiceChat rejoin this list with the follow-up
# PRs that port them to the duplex plugin framework.
"vllm_omni.model_executor.models.minicpmo_4_5.duplex",
"vllm_omni.model_executor.models.personaplex.duplex",
],
)
def test_model_duplex_packages_stay_clear_of_client_library(duplex_package: str):
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Integration tests: strategy overlay on the real merge_pipeline_deploy seam."""
from __future__ import annotations
@@ -20,6 +20,7 @@ from vllm_omni.config.composable_parallel import (
apply_strategy_specs,
)
from vllm_omni.config.config_factory import StageConfigFactory
from vllm_omni.config.omni_config import VllmOmniConfig
from vllm_omni.config.pipeline_registry import OMNI_PIPELINES
from vllm_omni.config.stage_config import load_deploy_config, merge_pipeline_deploy
@@ -137,3 +138,31 @@ def test_cli_overrides_strategy_with_warning():
assert _resolved(stages, "talker").runtime.num_replicas == 3
# ...and the override was warned about, naming the conflicting field.
assert any("num_replicas" in m and "overrides the strategy-derived" in m for m in messages)
def test_typed_cli_overrides_strategy():
pipeline = OMNI_PIPELINES["qwen2_5_omni"]
config = VllmOmniConfig.from_pipeline_config(
pipeline,
user_deploy_config=load_deploy_config(_DEPLOY),
cli_overrides={"stage_1_num_replicas": 3},
strategy_specs={"talker": [_stage_replica(2, "round_robin")]},
)
talker = next(stage for stage in config.stage_configs if stage.model_stage == "talker")
assert talker.runtime_config.num_replicas == 3
assert config.orchestrator_config.omni_lb_policy == "round-robin"
assert config.strategy_omni_lb_policy == "round-robin"
def test_typed_tp_only_strategy_has_no_derived_lb_policy():
pipeline = OMNI_PIPELINES["qwen2_5_omni"]
config = VllmOmniConfig.from_pipeline_config(
pipeline,
user_deploy_config=load_deploy_config(_DEPLOY),
cli_overrides={"omni_lb_policy": "round-robin"},
strategy_specs={"thinker": [_tp(1)]},
)
assert config.orchestrator_config.omni_lb_policy == "round-robin"
assert config.strategy_omni_lb_policy is None
+228 -5
View File
@@ -197,6 +197,25 @@ class TestStageConfig:
omega_config = config.to_omegaconf()
assert omega_config.engine_args.max_num_seqs == 32
def test_to_omegaconf_dict_override_deep_merges_yaml_dict(self):
"""A partial dict CLI override (e.g. --no-guardrails riding on
model_config) must layer onto the YAML dict, not clobber siblings."""
config = StageConfig(
stage_id=0,
model_stage="diffusion",
stage_type=StageType.DIFFUSION,
yaml_engine_args={
"model_config": {
"guardrails": True,
"policy_server_config": {"action_space": "joint_position"},
}
},
runtime_overrides={"model_config": {"guardrails": False}},
)
omega_config = config.to_omegaconf()
assert omega_config.engine_args.model_config.guardrails is False
assert omega_config.engine_args.model_config.policy_server_config.action_space == "joint_position"
def test_to_omegaconf_diffusion_parallel_overrides_replace_nested_values(self):
config = StageConfig(
stage_id=1,
@@ -623,6 +642,58 @@ class TestPipelineDiscovery:
assert p.hf_architectures == ("SomeCollidingArch",)
class TestCosmos3PolicyPipeline:
"""Cosmos3 policy serving resolves via deploy yaml selection (π0 precedent)."""
def test_registered_without_capturing_base_cosmos3_checkpoints(self):
assert "cosmos3_policy" in OMNI_PIPELINES
# T2I/video Cosmos3 checkpoints report model_type=cosmos3_omni and the
# same model_index.json _class_name as policy checkpoints; they must
# keep resolving through the single-stage diffusion fallback, so the
# policy pipeline must not be reachable by auto-detection.
assert "cosmos3_omni" not in OMNI_PIPELINES
pipeline = OMNI_PIPELINES["cosmos3_policy"]
assert pipeline.hf_architectures == ()
assert pipeline.diffusers_class_name is None
def test_droid_deploy_yaml_carries_policy_server_config(self):
deploy = load_deploy_config(get_deploy_config_path("cosmos3_policy_droid.yaml"))
assert deploy.pipeline == "cosmos3_policy"
stages = merge_pipeline_deploy(OMNI_PIPELINES["cosmos3_policy"], deploy)
assert len(stages) == 1
stage = stages[0].to_omegaconf()
assert stage.stage_type == "diffusion"
assert stage.final_output_type == "action"
assert stage.engine_args.model_class_name == "Cosmos3OmniDiffusersPipeline"
# OpenPI websocket handshake metadata must reach the serving layer via
# engine_args.model_config (ServingRealtimeRobotOpenPI reads it there).
psc = stage.engine_args.model_config.policy_server_config
assert list(psc.image_resolution) == [540, 640]
assert psc.n_external_cameras == 2
assert psc.needs_wrist_camera is True
assert psc.needs_stereo_camera is False
assert psc.needs_session_id is True
assert psc.action_space == "joint_position"
# The DROID checkpoint's training recipe expects JSON-formatted prompts.
assert stage.default_sampling_params.extra_args.format_prompt_as_json is True
def test_no_guardrails_cli_flag_keeps_policy_server_config(self):
"""--no-guardrails becomes a partial model_config CLI override; it must
deep-merge with the deploy yaml's model_config, not clobber the
policy_server_config the OpenPI handshake depends on."""
deploy = load_deploy_config(get_deploy_config_path("cosmos3_policy_droid.yaml"))
stages, _ = StageConfigFactory._create_legacy_from_registry(
OMNI_PIPELINES["cosmos3_policy"],
{"model_config": {"guardrails": False}},
user_deploy_config=deploy,
)
stage = stages[0].to_omegaconf()
assert stage.engine_args.model_config.guardrails is False
assert stage.engine_args.model_config.policy_server_config.action_space == "joint_position"
class TestStagePipelineConfig:
def test_frozen(self):
s = StagePipelineConfig(stage_id=0, model_stage="a")
@@ -1257,10 +1328,18 @@ class TestDeployConfigLoading:
stages = merge_pipeline_deploy(pipeline, deploy)
assert deploy.session_mode == "duplex"
assert deploy.active_stream_window == max_sessions
# ``0`` disables the limiter: the configured session/stage capacity is
# what bounds the pipeline. Any positive window serializes concurrent
# audio first-packet generation (measured: TTFP -23% at 0 vs 4 on
# L20X, 128 requests / concurrency 8).
assert deploy.active_stream_window == 0
assert deploy.duplex_session.max_sessions == max_sessions
assert [stage.session_mode for stage in stages] == ["duplex", "duplex", "duplex"]
assert [stage.to_omegaconf().session_mode for stage in stages] == ["duplex", "duplex", "duplex"]
assert stages[0].yaml_extras["default_sampling_params"]["stop_token_ids"] == [
151704,
151645,
]
def test_load_minicpmo_default_deploy_config(self):
deploy_path = Path(get_deploy_config_path("minicpmo_4_5.yaml"))
@@ -1350,6 +1429,9 @@ stages:
assert deploy.async_chunk is True
assert deploy.connectors is not None
assert deploy.platforms is not None
connector = deploy.connectors["connector_of_shared_memory"]
assert "async_chunk_batch_min_size" not in connector["extra"]
assert "async_chunk_batch_max_wait_ms" not in connector["extra"]
@pytest.mark.parametrize(
("hf_config", "model"),
@@ -1483,7 +1565,10 @@ stages:
monkeypatch.setattr(stage_init_utils, "resolve_worker_cls", lambda _engine_args: None)
deploy = load_deploy_config(get_deploy_config_path("minimax_h3_disaggregated.yaml"))
assert deploy.stages[1].engine_extras["model_loaded"] == {"text_encoder": False}
assert deploy.stages[1].engine_extras["model_loaded"] == {
"text_encoder": False,
"vae_encoder": False,
}
stages = merge_pipeline_deploy(OMNI_PIPELINES["minimax_h3_disaggregated"], deploy)
resolved = [stage_init_utils.build_engine_args_dict(stage.to_omegaconf(), str(model_root)) for stage in stages]
@@ -1508,12 +1593,20 @@ stages:
deploy = load_deploy_config(Path(get_deploy_config_path("minimax_h3_disaggregated.yaml")))
stages = merge_pipeline_deploy(pipeline, deploy)
assert stages[0].yaml_engine_args["model_arch"] == "MiniMaxH3TextEncoder"
assert stages[0].yaml_engine_args["model_arch"] == "MiniMaxH3Encoder"
assert stages[1].yaml_engine_args["model_arch"] == "MiniMaxH3Pipeline"
assert stages[0].yaml_runtime["num_replicas"] == 1
assert stages[1].yaml_runtime["num_replicas"] == 1
assert stages[1].yaml_engine_args["model_loaded"] == {"text_encoder": False}
assert stages[1].yaml_engine_args["model_loaded"] == {
"text_encoder": False,
"vae_encoder": False,
}
assert stages[0].yaml_engine_args["max_num_seqs"] == 1
assert stages[0].yaml_engine_args["hf_overrides"]["minimax_h3_encoder_components"] == {
"text_encoder": {"parallel_mode": "tp"},
"video_vae": {"parallel_mode": "patch"},
"audio_vae": {"parallel_mode": "leader"},
}
assert stages[0].yaml_engine_args["model_path_resolver"].endswith(".resolve_minimax_h3_model_root")
assert stages[1].yaml_engine_args["model_path_resolver"].endswith(".resolve_minimax_h3_diffusion_model_path")
parallel = stages[1].yaml_engine_args["parallel_config"]
@@ -1525,6 +1618,9 @@ stages:
turbo = load_deploy_config(Path(get_deploy_config_path("minimax_h3_disaggregated_turbo.yaml")))
turbo_stages = merge_pipeline_deploy(pipeline, turbo)
assert turbo_stages[0].yaml_engine_args["model_arch"] == stages[0].yaml_engine_args["model_arch"]
assert turbo_stages[1].yaml_engine_args["model_loaded"] == stages[1].yaml_engine_args["model_loaded"]
assert turbo_stages[0].yaml_engine_args["hf_overrides"] == stages[0].yaml_engine_args["hf_overrides"]
turbo_sampling = turbo_stages[1].yaml_extras["default_sampling_params"]
assert turbo_sampling["num_inference_steps"] == 5
assert turbo_sampling["extra_args"] == {"flow_shift": 6.0, "audio_flow_shift": 3.0}
@@ -2512,6 +2608,35 @@ class TestPlatformOverrides:
assert rocm.stages[0].enforce_eager is None
assert rocm.stages[1].enforce_eager is True
@pytest.mark.parametrize("deploy_name", ["qwen3_tts.yaml", "qwen3_tts_high_concurrency.yaml"])
@pytest.mark.parametrize("platform", ["cuda", "npu", "rocm"])
def test_qwen3_tts_default_code2wav_dtype_is_bf16(self, deploy_name, platform):
deploy = load_deploy_config(Path(get_deploy_config_path(deploy_name)))
deploy = _apply_platform_overrides(deploy, platform=platform)
stages = merge_pipeline_deploy(resolve_pipeline_config("qwen3_tts"), deploy)
assert stages[1].yaml_engine_args["dtype"] == "bfloat16"
@pytest.mark.parametrize("deploy_name", ["qwen3_tts.yaml", "qwen3_tts_high_concurrency.yaml"])
@pytest.mark.parametrize("platform", ["cuda", "npu"])
@pytest.mark.parametrize("dtype", ["float32", "bfloat16", "float16"])
def test_qwen3_tts_propagates_explicit_code2wav_dtype(self, deploy_name, platform, dtype):
deploy = load_deploy_config(Path(get_deploy_config_path(deploy_name)))
deploy.stages[1].engine_extras["dtype"] = dtype
deploy = _apply_platform_overrides(deploy, platform=platform)
stages = merge_pipeline_deploy(resolve_pipeline_config("qwen3_tts"), deploy)
assert stages[1].yaml_engine_args["dtype"] == dtype
def test_moss_tts_rocm_disables_codec_cudagraph(self):
deploy_path = Path(get_deploy_config_path("moss_tts.yaml"))
base = load_deploy_config(deploy_path)
assert base.stages[1].enforce_eager is False
rocm = _apply_platform_overrides(base, platform="rocm")
assert rocm.stages[1].enforce_eager is True
def test_higgs_audio_v3_rocm_uses_triton_attention(self):
deploy_path = Path(get_deploy_config_path("higgs_multimodal_qwen3.yaml"))
@@ -2575,6 +2700,63 @@ class TestPlatformOverrides:
# Explicit null clears the inherited single-GPU 2 GiB CUDA cap.
assert replica_stages[1].yaml_engine_args.get("kv_cache_memory_bytes") is None
def test_fish_speech_npu_uses_ascend_kv_block_size(self):
deploy_path = Path(get_deploy_config_path("fish_qwen3_omni.yaml"))
deploy = _apply_platform_overrides(load_deploy_config(deploy_path), platform="npu")
assert deploy.stages[0].engine_extras["block_size"] == 128
@pytest.mark.parametrize("platform", ["cuda", "npu"])
def test_recommended_native_runner_platform_defaults(self, platform):
filename, pipeline_key = "qwen3_tts_mrv2.yaml", "qwen3_tts"
deploy = load_deploy_config(Path(get_deploy_config_path(filename)))
deploy = _apply_platform_overrides(deploy, platform=platform)
expect_v2 = platform == "cuda"
assert deploy.model_runner == ("v2" if expect_v2 else "v1")
# The selection must reach the live worker-dispatch consumer, not just
# the transport-level DeployConfig field.
pipeline = resolve_pipeline_config(pipeline_key)
stages = merge_pipeline_deploy(pipeline, deploy)
assert [stage.yaml_engine_args["use_v2_model_runner"] for stage in stages] == [expect_v2] * len(stages)
if expect_v2 and pipeline.stages and deploy.async_chunk:
# v2 only engages the native plane on stages declaring support.
assert all(ps.supports_native_mrv2_data_plane for ps in pipeline.stages)
@pytest.mark.parametrize("runner,native", [("v1", False), ("v2", False), ("v2", True)])
def test_mrv2_undeclared_transport_warns(self, monkeypatch, runner, native):
from unittest.mock import Mock
warning = Mock()
monkeypatch.setattr("vllm_omni.config.stage_config.logger.warning", warning)
pipeline = PipelineConfig(
model_type="custom_pipeline",
stages=[
StagePipelineConfig(
stage_id=0, model_stage="custom_ar", final_output=True, supports_native_mrv2_data_plane=native
)
],
)
merge_pipeline_deploy(pipeline, DeployConfig(model_runner=runner))
assert warning.call_count == int(runner == "v2" and not native)
if warning.called:
assert "legacy transport path" in warning.call_args.args[0]
def test_runner_selection_rejects_engine_extras_override(self):
pipeline = PipelineConfig(
model_type="runner_selection_reserved",
stages=SINGLE_STAGE_PIPE_CFG,
)
for reserved in ("use_v2_model_runner", "supports_native_mrv2_data_plane"):
deploy = DeployConfig(
model_runner="v2",
stages=[StageDeployConfig(stage_id=0, engine_extras={reserved: False})],
)
with pytest.raises(ValueError, match=f"{reserved!r} must not be set"):
merge_pipeline_deploy(pipeline, deploy)
def test_npu_overrides(self):
deploy_path = Path(get_deploy_config_path("qwen3_omni_moe.yaml"))
if not deploy_path.exists():
@@ -3141,7 +3323,7 @@ class TestSentinelDefaultPrecedence:
class TestSamplingConstraintsPrecedence:
"""Test that pipeline sampling_constraints override deploy defaults."""
"""Test scalar constraint precedence and additive required stop tokens."""
def test_constraints_win(self):
deploy_path = Path(get_deploy_config_path("qwen3_omni_moe.yaml"))
@@ -3161,6 +3343,47 @@ class TestSamplingConstraintsPrecedence:
# Pipeline says stop_token_ids=[2150] for talker
assert stages[1].yaml_extras["default_sampling_params"]["stop_token_ids"] == [2150]
def test_required_stop_tokens_extend_yaml_defaults(self, tmp_path):
pipeline = PipelineConfig(
model_type="required_stop_tokens",
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="thinker",
final_output=True,
sampling_constraints={
"detokenize": True,
"stop_token_ids": [151704, 151645],
},
),
),
)
deploy_path = tmp_path / "required-stop-tokens.yaml"
deploy_path.write_text(
"""
stages:
- stage_id: 0
default_sampling_params:
max_tokens: 7
stop_token_ids: [100, 151704]
""",
encoding="utf-8",
)
legacy_stage = merge_pipeline_deploy(pipeline, load_deploy_config(deploy_path))[0]
structured_stage = VllmOmniConfig.from_pipeline_config(
pipeline,
deploy_config_path=str(deploy_path),
).stage_by_id(0)
expected = {
"max_tokens": 7,
"detokenize": True,
"stop_token_ids": [100, 151704, 151645],
}
assert legacy_stage.yaml_extras["default_sampling_params"] == expected
assert structured_stage.model_config.default_sampling_params == expected
class TestPipelineConfigResolvers:
@pytest.mark.parametrize("resolver", [obj for obj in OMNI_PIPELINES.values() if callable(obj)])
+27 -1
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Tests for endpoint restrictions logic."""
import pytest
@@ -44,6 +44,32 @@ def test_restricted_completions_returns_400():
assert body["error"]["type"] == "BadRequestError"
def test_restricted_image_edits_returns_400():
"""Ensure pipelines can reject image edits independently of generation."""
app = FastAPI()
@app.post("/v1/images/edits")
async def existing_handler():
return {"ok": True}
@app.post("/v1/images/generations")
async def generations_handler():
return {"ok": True}
restrictions = (EndpointRestriction(OmniServingCapability.IMAGE_EDITS, REJECTION_REASON),)
shutdown_unsupported_routes(app, restrictions)
client = TestClient(app)
resp = client.post("/v1/images/edits")
assert resp.status_code == 400
assert resp.json()["error"]["message"] == REJECTION_REASON
# The restriction is endpoint-specific and must not remove generations.
resp = client.post("/v1/images/generations")
assert resp.status_code == 200
assert resp.json() == {"ok": True}
def test_unrestricted_completions_not_blocked():
"""Ensure that if we don't shutdown any routes, the route stays."""
app = _make_app_with_server_route()
+7 -7
View File
@@ -164,11 +164,11 @@ def test_inventory_matches_reviewed_snapshot_counts():
"""Make an inventory expansion an explicit review decision."""
category_counts = Counter(item.category for item in ENVIRONMENT_VARIABLE_INVENTORY.values())
assert category_counts == {
EnvironmentVariableCategory.PUBLIC_OMNI: 24,
EnvironmentVariableCategory.PUBLIC_OMNI: 29,
EnvironmentVariableCategory.INHERITED_VLLM: 20,
EnvironmentVariableCategory.PLATFORM_EXTERNAL: 27,
EnvironmentVariableCategory.MODEL_SPECIFIC: 61,
EnvironmentVariableCategory.BENCHMARK_TRANSITIONAL: 20,
EnvironmentVariableCategory.MODEL_SPECIFIC: 57,
EnvironmentVariableCategory.BENCHMARK_TRANSITIONAL: 21,
EnvironmentVariableCategory.INTERNAL: 2,
}
@@ -178,11 +178,11 @@ def test_inventory_matches_reviewed_snapshot_counts():
if item.category is EnvironmentVariableCategory.MODEL_SPECIFIC
)
assert {disposition: disposition_counts[disposition] for disposition in ModelEnvironmentVariableDisposition} == {
ModelEnvironmentVariableDisposition.PROMOTE: 37,
ModelEnvironmentVariableDisposition.REQUEST_SCOPE: 6,
ModelEnvironmentVariableDisposition.PROMOTE: 31,
ModelEnvironmentVariableDisposition.REQUEST_SCOPE: 5,
ModelEnvironmentVariableDisposition.EXTERNAL: 0,
ModelEnvironmentVariableDisposition.INTERNALIZE: 13,
ModelEnvironmentVariableDisposition.DEPRECATE_REMOVE: 5,
ModelEnvironmentVariableDisposition.INTERNALIZE: 14,
ModelEnvironmentVariableDisposition.DEPRECATE_REMOVE: 7,
}
@@ -1,11 +1,20 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import pytest
from vllm.pooling_params import PoolingParams
import vllm_omni.config.pipeline_registry # noqa: F401 (populate registry)
from vllm_omni.config.omni_config import VllmOmniConfig
from vllm_omni.config.pipeline_registry import OMNI_PIPELINES as _PIPELINE_REGISTRY
from vllm_omni.config.stage_config import (
DeployConfig,
StageExecutionType,
)
from vllm_omni.engine.stage_init_utils import (
build_engine_args_dict_from_omni_stage_config,
extract_stage_metadata_from_omni_stage_config,
)
from vllm_omni.model_executor.stage_input_processors.forced_aligner import (
POOLING_OUTPUT_DECODER_PATH,
TIMESTAMPS_MODALITY,
@@ -69,3 +78,55 @@ def test_inject_noop_without_forced_aligner():
assert ext_pipeline is pipeline
assert len(ext_deploy.stages) == 0
@pytest.mark.parametrize("async_chunk", [True, False])
@pytest.mark.parametrize("cli_async_chunk", [None, True, False])
def test_aligner_uses_completed_audio_without_disabling_upstream_chunks(async_chunk, cli_async_chunk):
from vllm_omni.config.config_factory import StageConfigFactory
pipeline = _PIPELINE_REGISTRY["qwen3_tts"]
deploy = DeployConfig(async_chunk=async_chunk)
resolution = StageConfigFactory._resolve_legacy_from_registry(
pipeline,
{"forced_aligner": "/models/Qwen3-ForcedAligner-0.6B", "async_chunk": cli_async_chunk},
user_deploy_config=deploy,
)
stages = [stage.to_omegaconf() for stage in resolution.stage_configs]
expected_async = async_chunk if cli_async_chunk is None else cli_async_chunk
assert len(stages) == 3
assert [stage.engine_args.async_chunk for stage in stages] == [expected_async, expected_async, False]
assert stages[2].custom_process_input_func.endswith("code2wav2aligner")
assert stages[2].engine_args.runner == "pooling"
assert len(pipeline.stages) == 2
assert deploy.stages == []
def test_injected_aligner_survives_typed_config_and_runtime_projections():
pipeline, deploy = inject_forced_aligner_stage(
_PIPELINE_REGISTRY["qwen3_tts"],
DeployConfig(),
{"forced_aligner": "/models/Qwen3-ForcedAligner-0.6B"},
)
config = VllmOmniConfig.from_pipeline_config(
pipeline,
user_deploy_config=deploy,
cli_overrides={"model": "/models/Qwen3-TTS"},
)
stage = config.stage_configs[-1]
assert stage.pooling_config.runner == "pooling"
assert stage.pooling_config.pooling_output_decoder == POOLING_OUTPUT_DECODER_PATH
assert isinstance(stage.pooling_config.default_pooling_params, PoolingParams)
assert stage.pooling_config.default_pooling_params.task == deploy.stages[-1].default_pooling_params["task"]
metadata = extract_stage_metadata_from_omni_stage_config(stage)
assert isinstance(metadata.default_sampling_params, PoolingParams)
assert metadata.default_sampling_params.task == deploy.stages[-1].default_pooling_params["task"]
engine_args = build_engine_args_dict_from_omni_stage_config(
stage,
stage.model_config.model or "/models/Qwen3-ForcedAligner-0.6B",
)
assert engine_args["runner"] == "pooling"
assert engine_args["pooling_output_decoder"] == POOLING_OUTPUT_DECODER_PATH
@@ -0,0 +1,60 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import pytest
from tests.helpers.stage_config import get_deploy_config_path
from vllm_omni.config.endpoint_policy import OmniServingCapability
from vllm_omni.config.stage_config import StageExecutionType, load_deploy_config
from vllm_omni.diffusion.registry import _DIFFUSION_MODELS
from vllm_omni.model_executor.models.mammoth_moda2.pipeline import (
MAMMOTH_MODA2_AR_PIPELINE,
MAMMOTH_MODA2_PIPELINE,
)
from vllm_omni.model_executor.models.registry import _OMNI_MODELS
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
def test_mammothmoda2_generation_stage_uses_shared_diffusion_runtime() -> None:
ar_stage, dit_stage = MAMMOTH_MODA2_PIPELINE.stages
assert ar_stage.execution_type is StageExecutionType.LLM_AR
assert dit_stage.execution_type is StageExecutionType.DIFFUSION
assert dit_stage.model_arch == "MammothModa2DiTPipeline"
assert dit_stage.custom_process_input_func.endswith(".ar2diffusion")
assert dit_stage.omni_kv_config == {"need_recv_cache": False}
assert dit_stage.input_sources == (0,)
assert dit_stage.final_output is True
assert dit_stage.final_output_type == "image"
def test_mammothmoda2_dit_is_registered_only_with_diffusion_runtime() -> None:
assert _DIFFUSION_MODELS["MammothModa2DiTPipeline"] == (
"mammoth_moda2",
"pipeline_mammothmoda2_dit",
"MammothModa2DiTPipeline",
)
assert "MammothModa2DiTPipeline" not in _OMNI_MODELS
def test_mammothmoda2_deploy_does_not_shadow_request_sampling_fields() -> None:
deploy = load_deploy_config(get_deploy_config_path("mammoth_moda2.yaml"))
assert deploy.stages[1].default_sampling_params is None
def test_mammothmoda2_rejects_unsupported_image_edits() -> None:
restrictions = {
restriction.capability: restriction.reason for restriction in MAMMOTH_MODA2_PIPELINE.endpoint_restrictions
}
assert set(restrictions) == {OmniServingCapability.IMAGE_EDITS}
assert "img2img" in restrictions[OmniServingCapability.IMAGE_EDITS]
assert MAMMOTH_MODA2_AR_PIPELINE.endpoint_restrictions == ()
def test_mammothmoda2_ar_only_topology_is_unchanged() -> None:
assert len(MAMMOTH_MODA2_AR_PIPELINE.stages) == 1
stage = MAMMOTH_MODA2_AR_PIPELINE.stages[0]
assert stage.execution_type is StageExecutionType.LLM_AR
assert stage.final_output_type == "text"
+505 -63
View File
@@ -4,6 +4,7 @@
from __future__ import annotations
import warnings
from dataclasses import fields
from inspect import Parameter, signature
from multiprocessing.reduction import ForkingPickler
@@ -11,6 +12,7 @@ from pathlib import Path
import msgspec
import pytest
import torch
from pydantic import ValidationError
from pydantic.fields import FieldInfo
from transformers import Qwen3OmniMoeConfig
@@ -23,6 +25,7 @@ from vllm.config import SchedulerConfig as VllmSchedulerConfig
from tests.helpers.stage_config import get_deploy_config_path
from vllm_omni.config import omni_config as omni_config_module
from vllm_omni.config.config_factory import StageConfigFactory
from vllm_omni.config.omni_config import (
BaseVllmOmniStageConfig,
OmniStageCacheConfig,
@@ -47,8 +50,10 @@ from vllm_omni.config.stage_config import (
StageDeployConfig,
StageExecutionType,
StagePipelineConfig,
_apply_platform_overrides,
load_deploy_config,
merge_pipeline_deploy,
resolve_deploy_yaml,
)
from vllm_omni.diffusion.diffusion_kv.config import DiffusionKVCacheMode
from vllm_omni.engine.stage_engine_startup import _serialize_stage_config
@@ -59,6 +64,24 @@ pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
_DEPLOY_DIR = Path(__file__).parents[2] / "vllm_omni" / "deploy"
@pytest.mark.parametrize("async_chunk", [False, True])
def test_native_kv_transfer_requires_completed_ar_stage(async_chunk):
from types import SimpleNamespace
pipeline = SimpleNamespace(stages=(), model_type="test")
deploy = DeployConfig(
async_chunk=async_chunk,
stages=[
StageDeployConfig(stage_id=0, engine_extras={"kv_transfer_config": {"kv_connector": "MooncakeConnector"}})
],
)
if async_chunk:
with pytest.raises(ValueError, match="requires async_chunk=False"):
omni_config_module._validate_async_chunk_support(pipeline, deploy)
else:
omni_config_module._validate_async_chunk_support(pipeline, deploy)
@pytest.fixture(autouse=True)
def _stable_test_platform(monkeypatch):
from vllm_omni import platforms
@@ -94,6 +117,20 @@ def _from_pipeline_key(
)
def test_mammothmoda2_diffusion_stage_projects_native_backend_config() -> None:
config = _from_pipeline_key(
"mammoth_moda2",
cli_overrides={"model": "/models/MammothModa2-Preview"},
)
stage = config.stage_by_id(1)
assert isinstance(stage, VllmOmniDiffusionStageConfig)
assert stage.diffusion_config.model_class_name == "MammothModa2DiTPipeline"
assert stage.diffusion_config.model == "/models/MammothModa2-Preview"
assert stage.diffusion_config.step_execution is False
assert stage.scheduler_config.max_num_seqs == 1
assert stage.connector_config.omni_kv_config == {"need_recv_cache": False}
def test_minimax_h3_text_encoder_tp_targets_only_structured_stage_zero() -> None:
config = _from_pipeline_key(
"minimax_h3_disaggregated",
@@ -123,6 +160,42 @@ def test_non_duplex_deploy_keeps_model_session_capacity_at_one(tmp_path: Path) -
assert [stage.model_config.session_mode for stage in omni_config.stage_configs] == ["turn", "turn"]
def test_nested_stage_override_deep_merges_structured_model_config() -> None:
config = _from_pipeline_key(
"cosmos3_policy",
deploy_config_path=get_deploy_config_path("cosmos3_policy_droid.yaml"),
cli_overrides={"stage_0_model_config": {"guardrails": False}},
)
model_config = config.stage_by_id(0).diffusion_config.model_config
assert model_config["guardrails"] is False
assert model_config["policy_server_config"]["action_space"] == "joint_position"
def _build_single_diffusion_config(
*,
cli_overrides: dict | None = None,
engine_extras: dict | None = None,
) -> VllmOmniConfig:
pipeline = PipelineConfig(
model_type="diffusion-owner-test",
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="diffusion",
execution_type=StageExecutionType.DIFFUSION,
final_output=True,
),
),
)
deploy_stages = [StageDeployConfig(stage_id=0, engine_extras=engine_extras)] if engine_extras is not None else []
return VllmOmniConfig.from_pipeline_config(
pipeline,
user_deploy_config=DeployConfig(async_chunk=False, stages=deploy_stages),
cli_overrides=cli_overrides,
)
@pytest.mark.parametrize("model_type", sorted(OMNI_PIPELINES))
def test_vllm_omni_config_from_pipeline_config_matches_merge_pipeline_deploy(model_type: str):
pipeline = _resolve_pipeline_or_skip(model_type)
@@ -219,7 +292,7 @@ def test_from_pipeline_config_normalizes_stage_engine_extras_without_expanding_s
def test_frontend_log_stats_flag_is_not_an_unowned_stage_argument(disabled):
from vllm_omni.engine.stage_init_utils import build_engine_args_dict_from_omni_stage_config
config = _from_pipeline_key("dots_tts", cli_overrides={"disable_log_stats": disabled})
config = _from_pipeline_key("voxcpm2", cli_overrides={"disable_log_stats": disabled})
assert config.stage_configs
engine_args = build_engine_args_dict_from_omni_stage_config(config.stage_by_id(0), model="test-model")
assert "disable_log_stats" not in engine_args
@@ -242,6 +315,30 @@ def test_from_pipeline_config_applies_cli_overrides_without_stage_config_runtime
assert stage1.runtime_config.num_gpus == stage1.parallel_config.world_size
def test_diffusion_cli_parallel_overrides_beat_nested_deploy_parallel_config():
"""Flat CLI parallel flags override the deploy YAML's nested parallel_config.
Regression for the NPU nightly failure (#7778): hunyuan_image3_dit.yaml's
platform section sets nested parallel_config.tensor_parallel_size=4 while
the perf tests pass --tensor-parallel-size 2. The flat CLI value must win,
mirroring StageConfig.to_omegaconf, or the stage demands more devices than
the machine has (tp=4 x usp=2 = 8 on a 4-card box).
"""
omni_config = VllmOmniConfig.from_pipeline_config(
_resolve_pipeline_or_skip("hunyuan_image3_dit"),
user_deploy_config=DeployConfig(
stages=[StageDeployConfig(stage_id=0, engine_extras={"parallel_config": {"tensor_parallel_size": 4}})]
),
cli_overrides={"tensor_parallel_size": 2, "ulysses_degree": 2},
)
stage = omni_config.stage_by_id(0)
assert stage.parallel_config.tensor_parallel_size == 2
assert stage.parallel_config.ulysses_degree == 2
assert stage.parallel_config.world_size == 4
@pytest.mark.parametrize(
"cli_overrides",
[
@@ -271,6 +368,44 @@ def test_from_pipeline_config_rejects_unowned_deploy_engine_extras(engine_extras
VllmOmniConfig.from_pipeline_config(pipeline, user_deploy_config=deploy)
_MODEL_CLI_FLAGS = {
"served_model_name": "omni",
"allowed_local_media_path": "/data",
"allowed_media_domains": ["example.com"],
"max_logprobs": 7,
"logprobs_mode": "processed_logprobs",
"mm_processor_kwargs": {"max_slice_nums": 1},
"mm_processor_cache_type": "shm",
"hf_token": "hf_test",
"hf_config_path": "/models/config",
"generation_config": "vllm",
"override_generation_config": {"temperature": 0.5},
"enable_prompt_embeds": True,
}
@pytest.mark.parametrize("model_type", ["minicpmo_4_5", "qwen3_tts"])
@pytest.mark.parametrize(("field", "value"), list(_MODEL_CLI_FLAGS.items()), ids=list(_MODEL_CLI_FLAGS))
def test_from_pipeline_config_owns_model_cli_fields(model_type, field, value):
config = _from_pipeline_key(model_type, cli_overrides={field: value})
for stage in config.stage_configs:
assert getattr(stage.model_config, field) == value
def test_model_cli_fields_reach_typed_engine_args(monkeypatch):
from vllm_omni.engine import stage_init_utils
from vllm_omni.engine.stage_init_utils import build_engine_args_dict_from_omni_stage_config
# Worker discovery requires hardware support; this test covers config transport.
monkeypatch.setattr(stage_init_utils, "resolve_worker_cls", lambda engine_args: None)
config = _from_pipeline_key("minicpmo_4_5", cli_overrides=dict(_MODEL_CLI_FLAGS))
engine_args = build_engine_args_dict_from_omni_stage_config(config.stage_by_id(0), model="test-model")
assert {field: engine_args.get(field) for field in _MODEL_CLI_FLAGS} == _MODEL_CLI_FLAGS
@pytest.mark.parametrize("stage_id", [0, 2], ids=["ar", "generation"])
def test_llm_additional_config_roundtrip_and_isolation(stage_id, monkeypatch):
from vllm_omni.engine import stage_init_utils
@@ -386,7 +521,7 @@ def test_from_pipeline_config_normalizes_nested_parallel_config_aliases(field_na
assert "data_parallel_master_ip" in stage.parallel_config._omni_explicit_fields
def test_from_pipeline_config_accepts_diffusion_only_cli_fields_for_diffusion_stage():
def test_from_pipeline_config_keeps_global_kv_cache_dtype_outside_diffusion_stage():
stage = _from_pipeline_key(
"dreamzero",
deploy_config_path="dreamzero_tp1_cfg2",
@@ -394,11 +529,57 @@ def test_from_pipeline_config_accepts_diffusion_only_cli_fields_for_diffusion_st
).stage_by_id(0)
assert isinstance(stage, VllmOmniDiffusionStageConfig)
assert stage.diffusion_config.diffusion_kv_cache_dtype == "fp8"
assert stage.diffusion_config.diffusion_kv_cache_dtype is None
def test_stage_cli_field_selection_defers_ownership_validation_until_sources_are_merged():
assert omni_config_module._stage_cli_overrides(0, {"enable_lora": True}) == {"enable_lora": True}
assert omni_config_module._stage_cli_overrides(
0,
{"enable_lora": True},
) == {"enable_lora": True}
@pytest.mark.parametrize(
("cli_overrides", "expected_dtype"),
[
({}, torch.float32),
({"dtype": None}, torch.float32),
({"dtype": "float16"}, torch.float16),
({"dtype": "auto"}, torch.bfloat16),
({"stage_0_dtype": "bfloat16"}, torch.bfloat16),
],
)
def test_diffusion_deploy_dtype_survives_unset_cli_overrides(cli_overrides, expected_dtype):
stage = _build_single_diffusion_config(
engine_extras={"dtype": "float32", "cache_backend": "tea_cache"},
cli_overrides=cli_overrides,
).stage_by_id(0)
assert stage.diffusion_config.dtype == expected_dtype
assert stage.diffusion_config.cache_backend == "tea_cache"
@pytest.mark.parametrize(
"coordination_kwargs",
[
{"omni_master_address": "127.0.0.1", "omni_master_port": 30000},
{"omni_dp_size_local": 2, "omni_heartbeat_timeout": 60.0, "omni_lb_policy": "random"},
],
)
def test_diffusion_ingress_routes_coordination_fields_away(coordination_kwargs):
normalize = omni_config_module.normalize_and_validate_diffusion_engine_ingress_kwargs
assert normalize({**coordination_kwargs, "enable_sleep_mode": True}, stage_id=0) == {"enable_sleep_mode": True}
with pytest.raises(ValueError, match="omni_master_unknown_field"):
normalize({**coordination_kwargs, "omni_master_unknown_field": "unknown"}, stage_id=0)
def test_diffusion_ingress_defers_defaults(monkeypatch):
monkeypatch.setenv("DIFFUSION_CACHE_BACKEND", "tea_cache")
assert omni_config_module.normalize_and_validate_diffusion_engine_ingress_kwargs({}, stage_id=0) == {}
assert omni_config_module.normalize_and_validate_diffusion_engine_ingress_kwargs(
{"dtype": None, "cache_backend": None}, stage_id=0
) == {"dtype": None, "cache_backend": None}
@pytest.mark.parametrize(
@@ -604,6 +785,67 @@ def test_joyai_code2wav_waits_for_full_payload():
assert code2wav.model_config.requires_full_payload_input is True
@pytest.mark.parametrize("model_runner", ["v1", "v2"])
def test_deploy_model_runner_selection_propagates_to_every_stage(tmp_path: Path, model_runner: str):
deploy_path = tmp_path / "qwen3_tts_runner.yaml"
deploy_path.write_text(
f"""\
pipeline: qwen3_tts
model_runner: {model_runner}
async_chunk: true
stages:
- stage_id: 0
- stage_id: 1
"""
)
deploy = load_deploy_config(deploy_path)
pipeline = _resolve_pipeline_or_skip("qwen3_tts")
legacy_stages = merge_pipeline_deploy(pipeline, deploy)
structured = _from_pipeline_key("qwen3_tts", deploy_config_path=str(deploy_path))
expect_v2 = model_runner == "v2"
assert deploy.model_runner == model_runner
assert all(stage.yaml_engine_args["use_v2_model_runner"] is expect_v2 for stage in legacy_stages)
assert all(stage.model_config.use_v2_model_runner is expect_v2 for stage in structured.stage_configs)
@pytest.mark.parametrize("platform", ["npu", "xpu"])
def test_mrv2_fails_fast_on_platforms_without_native_workers(platform: str):
with pytest.raises(NotImplementedError, match="Model Runner V2"):
_apply_platform_overrides(DeployConfig(model_runner="v2"), platform=platform)
@pytest.mark.parametrize(
("default_name", "mrv2_name"),
[
("qwen3_tts.yaml", "qwen3_tts_mrv2.yaml"),
(
"qwen3_tts_high_concurrency.yaml",
"qwen3_tts_high_concurrency_mrv2.yaml",
),
],
)
def test_qwen3_mrv2_profiles_are_explicit_opt_in(default_name: str, mrv2_name: str):
assert load_deploy_config(_DEPLOY_DIR / default_name).model_runner == "v1"
assert load_deploy_config(_DEPLOY_DIR / mrv2_name).model_runner == "v2"
def test_qwen3_tts_mrv2_retunes_do_not_change_default_mrv1_profile():
default = resolve_deploy_yaml(_DEPLOY_DIR / "qwen3_tts_high_concurrency.yaml")
mrv2 = resolve_deploy_yaml(_DEPLOY_DIR / "qwen3_tts_high_concurrency_mrv2.yaml")
default_extra = default["connectors"]["connector_of_shared_memory"]["extra"]
mrv2_extra = mrv2["connectors"]["connector_of_shared_memory"]["extra"]
# B2 batch stays consistent with the graph buckets; V1 profile untouched.
assert default_extra["decode_batch_max_size"] == 1
assert mrv2_extra["decode_batch_max_size"] == 2
assert mrv2_extra["decode_cudagraph_batch_sizes"] == [1, 2]
assert mrv2_extra["code_predictor_prefix_graphs"] is False
assert mrv2["stages"][1]["enforce_eager"] is False
assert default["stages"][1]["enforce_eager"] is True
def test_vllm_omni_stage_config_public_fields_use_typed_stage_realizations():
assert not hasattr(BaseVllmOmniStageConfig, "from_stage_config")
assert not hasattr(BaseVllmOmniStageConfig, "to_legacy_stage_config")
@@ -616,6 +858,7 @@ def test_vllm_omni_stage_config_public_fields_use_typed_stage_realizations():
"load_config",
"cache_config",
"scheduler_config",
"pooling_config",
"connector_config",
"runtime_config",
"parallel_config",
@@ -699,9 +942,11 @@ def test_sub_config_fields_match_structured_scopes():
"limit_mm_per_prompt",
"interleave_mm_strings",
"media_io_kwargs",
"final_output",
"active_stream_window",
"session_mode",
"duplex_max_sessions",
"use_v2_model_runner",
"enable_sleep_mode",
"default_sampling_params",
"subtalker_sampling_params",
@@ -710,10 +955,12 @@ def test_sub_config_fields_match_structured_scopes():
"custom_voice_dir",
"task_type",
"codec_frame_rate_hz",
"supports_native_mrv2_data_plane",
"enforce_eager",
"max_cudagraph_capture_size",
"enable_flashinfer_autotune",
"enable_multithread_weight_load",
"enable_broadcast_weight_load",
"num_weight_load_threads",
"disable_autocast",
# Per-stage checkpoint resolution for repos whose stages live in
@@ -722,6 +969,18 @@ def test_sub_config_fields_match_structured_scopes():
"model_subdir",
"tokenizer_subdir",
"requires_full_payload_input",
"served_model_name",
"allowed_local_media_path",
"allowed_media_domains",
"max_logprobs",
"logprobs_mode",
"mm_processor_kwargs",
"mm_processor_cache_type",
"hf_token",
"hf_config_path",
"generation_config",
"override_generation_config",
"enable_prompt_embeds",
}
vllm_load_fields = {f.name for f in fields(VllmLoadConfig)}
assert issubclass(OmniStageLoadConfig, VllmLoadConfig)
@@ -746,6 +1005,7 @@ def test_sub_config_fields_match_structured_scopes():
assert {f.name for f in fields(OmniStageConnectorConfig)} == {
"async_chunk",
"omni_kv_config",
"kv_transfer_config",
"stage_connector",
"output_connectors",
"input_connectors",
@@ -838,6 +1098,17 @@ def test_structured_llm_stage_registration_payloads_remain_msgpack_transport_saf
msgspec.msgpack.encode(payload)
def test_structured_diffusion_torch_dtype_is_msgpack_transport_safe():
stage_config = _from_pipeline_key(
"hunyuan_image3_dit",
cli_overrides={"dtype": torch.bfloat16},
).stage_by_id(0)
serialized = _serialize_stage_config(stage_config)
assert serialized["diffusion_config"]["dtype"] == "bfloat16"
msgspec.msgpack.encode(serialized)
def test_diffusion_parallel_config_fields_cover_legacy_surface():
from vllm_omni.diffusion.data import DiffusionParallelConfig
@@ -1301,18 +1572,19 @@ def test_diffusion_config_from_kwargs_reuses_legacy_normalization(monkeypatch):
monkeypatch.setenv("DIFFUSION_CACHE_BACKEND", "TEA_CACHE")
monkeypatch.setattr(current_omni_platform, "is_cuda", lambda: True)
cfg = omni_config_module._DiffusionConfigProjection.from_kwargs(
diffusion_attention_backend="flash_attn",
fa_deterministic=True,
kv_cache_dtype="fp8",
kv_cache_skip_steps="0-1",
kv_cache_skip_layers=[2],
static_lora_scale=0.25,
diffusion_kv_mode="paged_scheduler",
diffusion_kv_max_rows_per_request=2,
diffusers_load_kwargs=None,
diffusers_call_kwargs=None,
)
with pytest.warns(FutureWarning):
cfg = omni_config_module._DiffusionConfigProjection.from_kwargs(
diffusion_attention_backend="flash_attn",
fa_deterministic=True,
kv_cache_dtype="fp8",
kv_cache_skip_steps="0-1",
kv_cache_skip_layers=[2],
static_lora_scale=0.25,
diffusion_kv_mode="paged_scheduler",
diffusion_kv_max_rows_per_request=2,
diffusers_load_kwargs=None,
diffusers_call_kwargs=None,
)
assert cfg.diffusion_attention_config.default.backend == "flash_attn"
assert cfg.fa_deterministic is True
@@ -1349,47 +1621,6 @@ def test_diffusion_config_none_values_preserve_dataclass_defaults():
assert config.enable_sleep_mode is False
@pytest.mark.parametrize(
("canonical_key", "alias_key", "canonical_value", "alias_value"),
[
("lora_scale", "static_lora_scale", 0.75, 0.25),
(
"quantization_config",
"diffusion_quantization_config",
{"method": "canonical"},
{"method": "diffusion-alias"},
),
(
"quantization_config",
"quantization",
{"method": "canonical"},
"legacy-alias",
),
("diffusion_kv_cache_dtype", "kv_cache_dtype", "fp8", "fp16"),
("diffusion_kv_cache_skip_steps", "kv_cache_skip_steps", "0-1", "2-3"),
("diffusion_kv_cache_skip_layers", "kv_cache_skip_layers", "1-2", "3-4"),
("streaming_output", "diffusion_streaming_output", False, True),
],
)
def test_diffusion_alias_conflicts_prefer_canonical_key(
canonical_key,
alias_key,
canonical_value,
alias_value,
):
from vllm_omni.diffusion.data import normalize_omni_diffusion_kwargs
normalized = normalize_omni_diffusion_kwargs(
{
canonical_key: canonical_value,
alias_key: alias_value,
}
)
assert normalized[canonical_key] == canonical_value
assert alias_key not in normalized
def test_from_pipeline_config_normalizes_diffusion_config_aliases_from_engine_args(tmp_path, monkeypatch):
from vllm_omni.platforms import current_omni_platform
@@ -1414,10 +1645,11 @@ def test_from_pipeline_config_normalizes_diffusion_config_aliases_from_engine_ar
)
)
stage = _from_pipeline_key(
"dreamzero",
deploy_config_path=str(deploy_path),
).stage_by_id(0)
with pytest.warns(FutureWarning):
stage = _from_pipeline_key(
"dreamzero",
deploy_config_path=str(deploy_path),
).stage_by_id(0)
assert isinstance(stage, VllmOmniDiffusionStageConfig)
assert stage.diffusion_config.diffusion_attention_config.default.backend == "flash_attn"
@@ -1429,8 +1661,11 @@ def test_from_pipeline_config_normalizes_diffusion_config_aliases_from_engine_ar
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.engine.stage_init_utils import build_engine_args_dict_from_omni_stage_config
engine_args = build_engine_args_dict_from_omni_stage_config(stage, model="test-model")
od_config = OmniDiffusionConfig.from_kwargs(**engine_args)
engine_args = build_engine_args_dict_from_omni_stage_config(stage, model=str(tmp_path))
diffusion_kwargs = omni_config_module.extract_diffusion_stage_config_kwargs(
engine_args, stage_id=stage.stage_id, include_engine_adapter_metadata=True
)
od_config = OmniDiffusionConfig.from_kwargs(**diffusion_kwargs)
assert od_config.kv_transfer_config.engine_id == "dit-engine-1"
@@ -1542,6 +1777,59 @@ def test_diffusion_quantization_mapping_reaches_terminal_config(monkeypatch):
assert cfg.quantization_config.get_name() == "int8"
def test_video_output_transport_mapping_is_normalized() -> None:
from vllm_omni.diffusion.data import VideoOutputTransportConfig
cfg = omni_config_module._DiffusionConfigProjection(
video_output_transport={"enable_device_postprocess": True},
)
assert isinstance(cfg.video_output_transport, VideoOutputTransportConfig)
assert cfg.video_output_transport.enable_device_postprocess is True
def test_omni_diffusion_config_normalizes_video_output_transport_mapping() -> None:
from vllm_omni.diffusion.data import OmniDiffusionConfig, VideoOutputTransportConfig
cfg = OmniDiffusionConfig(
model=None,
video_output_transport={"enable_device_postprocess": True},
)
assert isinstance(cfg.video_output_transport, VideoOutputTransportConfig)
assert cfg.video_output_transport.enable_device_postprocess is True
def test_video_output_transport_rejects_non_boolean_flag() -> None:
from vllm_omni.diffusion.data import VideoOutputTransportConfig
with pytest.raises(TypeError, match="enable_device_postprocess must be a bool"):
VideoOutputTransportConfig(enable_device_postprocess="true") # type: ignore[arg-type]
def test_video_output_transport_survives_stage_override_filtering() -> None:
from vllm_omni.config.stage_config import build_stage_runtime_overrides, deploy_runtime_override_keys
transport = {"enable_device_postprocess": True}
overrides = build_stage_runtime_overrides(0, {"video_output_transport": transport})
assert "video_output_transport" in deploy_runtime_override_keys()
assert overrides["video_output_transport"] == transport
def test_video_output_transport_reaches_default_diffusion_stage() -> None:
transport = {"enable_device_postprocess": True}
stages = StageConfigFactory.create_default_diffusion(
{
"model": "unused",
"model_class_name": "UnknownPipeline",
"video_output_transport": transport,
}
)
assert stages[0]["engine_args"]["video_output_transport"] == transport
def test_compact_offload_config_reaches_terminal_config(monkeypatch):
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.diffusion.offloader.config import OffloadStrategy, resolve_offload_strategy
@@ -1599,3 +1887,157 @@ def test_compact_offload_config_is_validated_during_projection():
"components": ["dit"],
}
)
@pytest.mark.parametrize("pipeline_async", [True, False])
@pytest.mark.parametrize("stage_async", [None, False, True])
def test_stage_async_chunk_opt_out_matches_legacy_config(pipeline_async, stage_async):
pipeline = _resolve_pipeline_or_skip("qwen3_tts")
deploy = DeployConfig(
async_chunk=pipeline_async,
stages=[StageDeployConfig(stage_id=i, async_chunk=stage_async) for i in (0, 1)],
)
config = VllmOmniConfig.from_pipeline_config(pipeline, user_deploy_config=deploy)
legacy = merge_pipeline_deploy(pipeline, deploy)
expected = pipeline_async and stage_async is not False
assert config.stage_by_id(0).connector_config.async_chunk is expected
assert config.stage_by_id(1).connector_config.async_chunk is expected
assert legacy[1].yaml_engine_args["async_chunk"] is expected
assert config.stage_by_id(1).custom_process_input_func == legacy[1].custom_process_input_func
if not expected:
assert config.stage_by_id(1).custom_process_input_func.endswith("talker2code2wav_token_only")
@pytest.mark.parametrize("disabled_stage", [0, 1])
@pytest.mark.parametrize("builder", [merge_pipeline_deploy, VllmOmniConfig.from_pipeline_config])
def test_async_chunk_rejects_mismatched_connector_edge(disabled_stage, builder):
pipeline = _resolve_pipeline_or_skip("qwen3_tts")
deploy = DeployConfig(
async_chunk=True,
stages=[StageDeployConfig(stage_id=disabled_stage, async_chunk=False)],
)
with pytest.raises(ValueError, match="incompatible async_chunk settings on connector edge 0 -> 1"):
if builder is merge_pipeline_deploy:
builder(pipeline, deploy)
else:
builder(pipeline, user_deploy_config=deploy)
@pytest.mark.parametrize("explicit", [False, True])
def test_diffusion_quantization_origin_survives_projection_and_transport(monkeypatch, explicit):
from vllm_omni.diffusion.data import OmniDiffusionConfig, TransformerConfig
from vllm_omni.quantization import build_quant_config
checkpoint = TransformerConfig.from_dict(
{
"quantization_config": {
"quant_method": "mxfp4",
"is_checkpoint_mxfp4_serialized": True,
"w4a8_fallback_steps": [37],
}
}
)
requested = build_quant_config("mxfp4", w4a8_fallback_steps=[]) if explicit else None
cfg = omni_config_module._DiffusionConfigProjection.from_kwargs(
tf_model_config=checkpoint,
quantization_config=requested,
)
assert cfg.quantization_config_is_auto_detected is not explicit
monkeypatch.setattr(OmniDiffusionConfig, "_resolve_master_port", lambda _self: 29500)
monkeypatch.setattr(OmniDiffusionConfig, "enrich_config", lambda self: self.set_tf_model_config(checkpoint))
cfg.enrich_config()
restored = ForkingPickler.loads(ForkingPickler.dumps(cfg))
assert restored.quantization_config_is_auto_detected is not explicit
assert restored.quantization_config.w4a8_fallback_steps == ([] if explicit else [37])
@pytest.mark.parametrize(
"factory",
[
omni_config_module._DiffusionConfigProjection.from_kwargs,
pytest.param(
lambda **kwargs: __import__(
"vllm_omni.diffusion.data",
fromlist=["OmniDiffusionConfig"],
).OmniDiffusionConfig.from_kwargs(**kwargs),
id="runtime-config",
),
],
)
def test_diffusion_config_entrypoints_reject_unknown_none(factory):
with pytest.raises((ValueError, ValidationError), match="enable_sleep_mod"):
factory(enable_sleep_mod=None)
def test_diffusion_config_projection_rejects_unknown_none():
with pytest.raises(ValueError, match="enable_sleep_mod"):
omni_config_module._DiffusionConfigProjection.from_kwargs(enable_sleep_mod=None)
def test_runtime_diffusion_config_rejects_unknown_none():
from vllm_omni.diffusion.data import OmniDiffusionConfig
with pytest.raises(ValueError, match="enable_sleep_mod"):
OmniDiffusionConfig.from_kwargs(enable_sleep_mod=None)
def test_direct_diffusion_aliases_promote_none_and_reject_real_conflicts(monkeypatch):
from vllm_omni.diffusion import data as diffusion_data
from vllm_omni.diffusion.data import OmniDiffusionConfig
monkeypatch.setattr(diffusion_data, "build_quant_config", lambda config: config)
with pytest.warns(FutureWarning) as warnings:
config = OmniDiffusionConfig.from_kwargs(
quantization={"method": "example"},
quantization_config=None,
kv_cache_dtype="fp8",
diffusion_kv_cache_dtype=None,
enable_sleep_mode=False,
request_batch_max_wait_ms=0.0,
)
warning_messages = [str(warning.message) for warning in warnings]
assert any("quantization" in message for message in warning_messages)
assert any("kv_cache_dtype" in message for message in warning_messages)
assert config.quantization_config == {"method": "example"}
assert config.diffusion_kv_cache_dtype == "fp8"
assert config.enable_sleep_mode is False
assert config.request_batch_max_wait_ms == 0.0
with pytest.raises(ValueError, match=r"quantization.*quantization_config"):
OmniDiffusionConfig.from_kwargs(quantization="fp8", quantization_config={"method": "example"})
def test_structured_diffusion_stage_rejects_unknown_engine_extra():
with pytest.raises(ValueError, match=r"stage 0.*enable_sleep_mod"):
_build_single_diffusion_config(engine_extras={"enable_sleep_mod": None})
with pytest.raises(ValueError, match=r"stage 0.*enable_sleep_mod"):
_build_single_diffusion_config(cli_overrides={"enable_sleep_mod": None})
with pytest.raises(ValueError, match=r"stage 0.*enable_sleep_mod"):
_build_single_diffusion_config(cli_overrides={"stage_0_enable_sleep_mod": None})
with pytest.raises(ValueError, match=r"no structured config owner: parallel_config\.unknown_field"):
_build_single_diffusion_config(engine_extras={"parallel_config": {"unknown_field": 1}})
def test_structured_diffusion_stage_keeps_shared_globals_outside_diffusion():
with warnings.catch_warnings(record=True) as caught:
stage = _build_single_diffusion_config(
cli_overrides={"kv_cache_dtype": "fp8", "seed": 7},
).stage_by_id(0)
assert stage.diffusion_config.diffusion_kv_cache_dtype is None
assert not any(issubclass(warning.category, FutureWarning) for warning in caught)
@pytest.mark.parametrize(
("field_name", "config_kwargs"),
[
("seed", {"cli_overrides": {"stage_0_seed": None}}),
("kv_cache_dtype", {"engine_extras": {"kv_cache_dtype": "fp8"}}),
],
)
def test_structured_diffusion_stage_rejects_explicit_shared_engine_field(field_name, config_kwargs):
with pytest.raises(ValueError, match=rf"stage 0.*{field_name}"):
_build_single_diffusion_config(**config_kwargs)
+51
View File
@@ -0,0 +1,51 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Check the sleep/wake E2E topology before loading large BAGEL weights."""
import pytest
from tests.entrypoints.test_omni_sleep_mode import _sleep_deploy_config
from vllm_omni.config.omni_config import (
VllmOmniConfig,
VllmOmniDiffusionStageConfig,
extract_diffusion_stage_config_kwargs,
)
from vllm_omni.config.pipeline_registry import resolve_pipeline_config
from vllm_omni.config.stage_config import load_deploy_config
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.engine.stage_init_utils import build_engine_args_dict_from_omni_stage_config
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@pytest.mark.parametrize("diffusion_only,tp_size", [(False, 1), (False, 2), (True, 2)])
def test_sleep_deploy_resolves_expected_stages(diffusion_only, tp_size):
deploy = load_deploy_config(_sleep_deploy_config(diffusion_only=diffusion_only, tp_size=tp_size))
pipeline = resolve_pipeline_config(deploy.pipeline or "bagel")
config = VllmOmniConfig.from_pipeline_config(pipeline, user_deploy_config=deploy)
assert len(config.stage_configs) == (1 if diffusion_only else 2)
for stage in config.stage_configs:
is_diffusion = diffusion_only or stage.stage_id == 1
assert isinstance(stage, VllmOmniDiffusionStageConfig) == is_diffusion
# Keep BAGEL's batch budget: a single multimodal item needs 8625 tokens.
assert stage.scheduler_config.max_num_batched_tokens == 32768
assert stage.model_config.enable_sleep_mode is True
assert stage.parallel_config.tensor_parallel_size == tp_size
assert stage.runtime_config.devices == ",".join(str(stage.stage_id * tp_size + rank) for rank in range(tp_size))
if not is_diffusion:
assert stage.cache_config.gpu_memory_utilization == 0.8
if is_diffusion:
engine_args = build_engine_args_dict_from_omni_stage_config(stage, "test-bagel")
terminal = OmniDiffusionConfig.from_kwargs(
**extract_diffusion_stage_config_kwargs(
engine_args, stage_id=stage.stage_id, include_engine_adapter_metadata=True
)
)
assert terminal.enable_sleep_mode is True
assert terminal.parallel_config.tensor_parallel_size == tp_size
if not diffusion_only:
assert config.stage_by_id(1).stage_pipeline_config.input_sources == (0,)
assert deploy.stages[1].input_connectors["from_stage_0"] == "shared_memory_connector"
@@ -1,14 +1,22 @@
"""Test that OmniGenerationScheduler restores chunk-waiting requests
even when the OmniNewRequestData rewrapping fails.
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
Regression test: if process_pending_chunks() moves requests into
internal deques but restore_queues() is not called due to an exception,
those requests are permanently orphaned.
"""
"""Chunk-lifecycle coverage for OmniGenerationScheduler: restore on error,
native terminal state, in-flight no-resubmission, slot release on finish,
and single scheduling of a terminal empty-prompt chunk."""
from collections import deque
from types import SimpleNamespace
import pytest
import torch
from vllm import SamplingParams
from vllm.v1.core.sched.interface import PauseState
from vllm.v1.core.sched.request_queue import SchedulingPolicy, create_request_queue
from vllm.v1.request import Request, RequestStatus
from vllm_omni.core.sched.omni_generation_scheduler import OmniGenerationScheduler, _has_async_chunk_payload_to_run
from vllm_omni.engine.serialization import serialize_additional_information
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -20,16 +28,20 @@ class FakeAdapter:
self.waiting_for_chunk_waiting_requests = deque()
self.waiting_for_chunk_running_requests = deque()
self.restore_called = False
self.done_request_ids = set()
def process_pending_chunks(self, waiting, running):
"""Simulate moving requests out of the scheduler queues."""
# Move one request from running into internal deque
def process_pending_chunks(self, waiting, running, scheduler_requests=None):
if running:
req = running.pop()
self.waiting_for_chunk_running_requests.append(req)
def is_done_receiving_chunks(self, request_id):
return request_id in self.done_request_ids
def collect_failed_send_request_ids(self):
return {}
def restore_queues(self, waiting, running, scheduler_requests=None):
"""Put requests back."""
self.restore_called = True
running.extend(self.waiting_for_chunk_running_requests)
self.waiting_for_chunk_running_requests = deque()
@@ -38,6 +50,131 @@ class FakeAdapter:
pass
def _make_generation_scheduler(waiting_request, *, use_v2_model_runner=False):
scheduler = OmniGenerationScheduler.__new__(OmniGenerationScheduler)
scheduler.max_num_scheduled_tokens = 8
scheduler.max_num_running_reqs = 1
scheduler._pause_state = PauseState.UNPAUSED
scheduler.running = []
scheduler.waiting = create_request_queue(SchedulingPolicy.FCFS)
scheduler.waiting.add_request(waiting_request)
scheduler.skipped_waiting = create_request_queue(SchedulingPolicy.FCFS)
scheduler.requests = {waiting_request.request_id: waiting_request}
scheduler.policy = SchedulingPolicy.FCFS
scheduler.chunk_transfer_adapter = FakeAdapter()
scheduler.input_coordinator = None
scheduler.log_stats = False
scheduler.scheduler_config = SimpleNamespace(enable_chunked_prefill=True)
scheduler.num_lookahead_tokens = 0
scheduler.kv_cache_manager = SimpleNamespace(
new_step_starts=lambda: None,
allocate_slots=lambda *args, **kwargs: SimpleNamespace(get_block_ids=lambda: ([1],)),
get_num_common_prefix_blocks=lambda request_id: [0],
take_new_block_ids=lambda: None,
)
scheduler.kv_cache_config = SimpleNamespace(kv_cache_groups=[object()])
scheduler.use_v2_model_runner = use_v2_model_runner
scheduler._retains_state_across_chunks = False
scheduler.needs_kv_cache_zeroing = False
scheduler.finished_req_ids = set()
scheduler.encoder_cache_manager = SimpleNamespace(get_freed_mm_hashes=lambda: [])
scheduler.connector = None
scheduler.ec_connector = None
scheduler.prev_step_scheduled_req_ids = set()
scheduler._pending_finish_reqs = []
scheduler._consume_pending_connector_output = lambda model_mode: None
scheduler._process_pending_input_timeouts = lambda: None
scheduler._make_cached_request_data = lambda **kwargs: SimpleNamespace(
req_ids=[],
resumed_req_ids=[],
new_token_ids=[],
all_token_ids=[],
new_block_ids=[],
num_computed_tokens=[],
num_output_tokens=[],
)
scheduler._update_after_schedule = lambda output: None
scheduler._wrap_omni_scheduler_output = lambda output: output
return scheduler
def _chunk_request(request_id, **kwargs):
defaults = dict(
request_id=request_id,
prompt_token_ids=[1],
num_computed_tokens=0,
num_in_flight_tokens=0,
status=None,
sampling_params=None,
pooling_params=None,
mm_features=None,
lora_request=None,
prompt_is_token_ids=True,
additional_information=None,
external_req_id=request_id,
prefill_stats=None,
record_event=lambda *args, **kwargs: None,
)
defaults.update(kwargs)
return SimpleNamespace(**defaults)
def test_chunk_lifecycle_no_resubmit_and_state_survives_requeue(monkeypatch) -> None:
# Native plane: a completed payload without a new chunk is never executed
# again; requeued requests keep WAITING_FOR_CHUNK and their token counts.
scheduler = _make_generation_scheduler(_chunk_request("unused"))
monkeypatch.setattr("vllm_omni.core.sched.omni_generation_scheduler.create_request_queue", create_request_queue)
scheduler._native_data_plane = True
scheduler.chunk_transfer_adapter = None
scheduler.input_coordinator = SimpleNamespace(finished_requests=set(), restore_queues=lambda *args, **kwargs: None)
scheduler.running = []
scheduler.waiting = create_request_queue(scheduler.policy)
scheduler.skipped_waiting = create_request_queue(scheduler.policy)
completed = Request("completed", [1, 2], SamplingParams(max_tokens=4), pooling_params=None)
completed.status = RequestStatus.RUNNING
completed.num_computed_tokens = 2
scheduler.running = [completed]
scheduler.requests = {"completed": completed}
scheduler.input_coordinator.finished_requests.add("completed") # terminal payload, no new chunk
assert scheduler._is_done_receiving_chunks("completed")
assert not scheduler._is_done_receiving_chunks("unknown")
output = scheduler.schedule()
assert not output.num_scheduled_tokens
assert scheduler._pending_finish_reqs == [completed]
completed.status = RequestStatus.WAITING_FOR_CHUNK
scheduler._pending_finish_reqs = []
scheduler._requeue_completed_native_chunks()
assert completed.status == RequestStatus.WAITING_FOR_CHUNK
assert completed.num_computed_tokens == 2
assert not scheduler.running
def test_generation_scheduler_schedules_terminal_empty_prompt_chunk_once(monkeypatch: pytest.MonkeyPatch) -> None:
waiting = _chunk_request(
"terminal",
prompt_token_ids=[],
num_prompt_tokens=0,
additional_information=serialize_additional_information(
{"codes": {"audio": torch.tensor([[1, 2, 3]], dtype=torch.long)}}
),
)
scheduler = _make_generation_scheduler(waiting)
scheduler.chunk_transfer_adapter.done_request_ids.add("terminal")
scheduler.requests = {"terminal": waiting}
assert _has_async_chunk_payload_to_run(waiting)
# A terminal codec request with an empty prompt is still scheduled exactly once.
monkeypatch.setattr("vllm_omni.core.sched.omni_generation_scheduler.create_request_queue", create_request_queue)
output = OmniGenerationScheduler.schedule(scheduler)
assert output.num_scheduled_tokens == {"terminal": 1}
assert output.scheduled_new_reqs[0].req_id == "terminal"
assert scheduler._pending_finish_reqs == []
class TestRestoreQueuesOnError:
"""Verify that restore_queues is called even when rewrapping raises."""
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Tests for ``OmniARScheduler._drop_aborted_queued_requests``.
``schedule()`` sweeps ``FINISHED_ABORTED`` requests out of the queues before
@@ -68,6 +71,7 @@ def test_schedule_sweeps_skipped_waiting_before_upstream_selection(
aborted = _StubRequest("req-aborted", RequestStatus.FINISHED_ABORTED)
scheduler = _make_scheduler(policy, skipped_waiting=[aborted])
scheduler.chunk_transfer_adapter = None
scheduler.max_num_running_reqs = 8
scheduler.input_coordinator = None
scheduler.num_waiting_for_streaming_input = 0
scheduler._process_pending_omni_inputs = lambda model_mode: None
@@ -7,6 +7,7 @@ window fills with stale entries after K completions.
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
@@ -15,6 +16,7 @@ import pytest
# Request / RequestStatus are bound in this module. Ruff isort would reorder them.
# isort: off
import vllm_omni # noqa: F401 - import for side effects (patch vLLM)
from vllm.v1.request import RequestStatus
from vllm_omni.core.sched.omni_ar_scheduler import OmniARScheduler
# isort: on
@@ -72,3 +74,85 @@ def test_free_request_is_safe_without_a_chunk_transfer_adapter():
sched._free_request(request) # must not raise
sched._free_input_coordinator_request.assert_called_once_with("req-1")
def test_native_mooncake_finish_uses_confirmed_token_boundary() -> None:
sched = _make_scheduler(chunk_transfer_adapter=None)
sched.vllm_config = SimpleNamespace(kv_transfer_config=SimpleNamespace(kv_connector="MooncakeConnector"))
observed = {}
def connector_finished(request):
observed["status"] = request.status
observed["num_computed_tokens"] = request.num_computed_tokens
return True, None
sched._connector_finished = connector_finished
request = _make_finished_request("req-native")
request.client_index = 0
request.status = RequestStatus.FINISHED_STOPPED
request.kv_transfer_params = {
"do_remote_decode": True,
"transfer_id": "xfer-req-native",
}
request.num_computed_tokens = 13
request.num_output_placeholders = 1
request.num_prompt_tokens = 10
kv_params, _ = sched._free_request(request)
assert observed == {
"status": RequestStatus.FINISHED_LENGTH_CAPPED,
"num_computed_tokens": 12,
}
assert request.status == RequestStatus.FINISHED_STOPPED
assert request.num_computed_tokens == 13
assert kv_params == {
"transfer_id": "xfer-req-native",
"num_transfer_tokens": 12,
}
def test_native_mooncake_recycles_ar_pages_in_physical_order() -> None:
sched = OmniARScheduler.__new__(OmniARScheduler)
sched.vllm_config = SimpleNamespace(kv_transfer_config=SimpleNamespace(kv_connector="MooncakeConnector"))
blocks = [SimpleNamespace(block_id=7), SimpleNamespace(block_id=2), SimpleNamespace(block_id=4)]
sched.kv_cache_manager = SimpleNamespace(
enable_caching=False,
pop_blocks_for_free=MagicMock(return_value=blocks),
block_pool=SimpleNamespace(free_blocks=MagicMock()),
)
sched.defer_block_free = False
sched.processed_step_seq = 3
request = SimpleNamespace(last_sched_seq=3)
sched._free_request_blocks(request)
sched.kv_cache_manager.block_pool.free_blocks.assert_called_once()
freed = sched.kv_cache_manager.block_pool.free_blocks.call_args.args[0]
assert [block.block_id for block in freed] == [2, 4, 7]
def test_native_mooncake_deferred_ar_pages_drain_in_physical_order() -> None:
from collections import deque
sched = OmniARScheduler.__new__(OmniARScheduler)
sched.vllm_config = SimpleNamespace(kv_transfer_config=SimpleNamespace(kv_connector="MooncakeConnector"))
blocks = [SimpleNamespace(block_id=7), SimpleNamespace(block_id=2), SimpleNamespace(block_id=4)]
sched.kv_cache_manager = SimpleNamespace(
enable_caching=False,
pop_blocks_for_free=MagicMock(return_value=blocks),
block_pool=SimpleNamespace(free_blocks=MagicMock()),
)
sched.defer_block_free = True
sched.processed_step_seq = 2
sched.sched_step_seq = 3
sched.deferred_frees = deque()
request = SimpleNamespace(last_sched_seq=3)
sched._free_request_blocks(request)
assert [block.block_id for block in sched.deferred_frees[0][1]] == [7, 4, 2]
sched.processed_step_seq = 3
sched._drain_deferred_frees()
freed = list(sched.kv_cache_manager.block_pool.free_blocks.call_args.args[0])
assert [block.block_id for block in freed] == [2, 4, 7]
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Tests for the AR sampled-token logprob contract."""
from __future__ import annotations
@@ -93,6 +96,7 @@ class _Request:
self.num_computed_tokens = 0
self.num_in_flight_tokens = 0
self.num_output_placeholders = 0
self.output_token_ids: list[int] = []
# vLLM 0.27 (a0c092ee72): Request gained num_stale_output_tokens to
# track in-flight outputs discarded at preemption/streaming-stop.
self.num_stale_output_tokens = 0
@@ -145,10 +149,21 @@ def _make_scheduler_stub(requests: list[_Request]) -> SimpleNamespace:
kv_cache_manager=SimpleNamespace(take_events=lambda: None),
kv_event_publisher=SimpleNamespace(publish=lambda _events: None),
recompute_kv_load_failures=False,
_native_data_plane=False,
vllm_config=SimpleNamespace(
model_config=SimpleNamespace(
use_v2_model_runner=False,
async_chunk=False,
final_output=True,
)
),
)
for name in _MIXIN_UPDATE_HELPERS:
setattr(scheduler, name, MethodType(getattr(OmniSchedulerMixin, name), scheduler))
scheduler._cleanup_kv_tracking = MethodType(OmniARScheduler._cleanup_kv_tracking, scheduler)
scheduler._emit_streaming_context_overflow_outputs = MethodType(
OmniARScheduler._emit_streaming_context_overflow_outputs, scheduler
)
scheduler.make_spec_decoding_stats = lambda *args, **kwargs: None
scheduler.make_stats = lambda *args, **kwargs: None
return scheduler
@@ -164,10 +179,15 @@ def _bind_request_lifecycle(
scheduler.requests.pop(request.request_id, None)
scheduler.finished_req_ids.add(request.request_id)
scheduler.finished_req_ids_dict[request.client_index].add(request.request_id)
# vLLM 0.26 contract: (kv_xfer_params, ec_xfer_params)
# Current vLLM contract: (kv_xfer_params, ec_xfer_params)
return None, None
scheduler._update_request_with_output = update_request
def update_with_history(request, token_ids):
accepted, stopped = update_request(request, token_ids)
request.output_token_ids.extend(accepted)
return accepted, stopped
scheduler._update_request_with_output = update_with_history
scheduler._process_kv_transfer_trigger = lambda _request, _tokens: False
scheduler._handle_stopped_request = handle_stopped or (lambda _request: True)
scheduler._free_request = free_request
@@ -216,6 +236,7 @@ def test_mid_step_stop_trims_logprob_rows_with_token_ids() -> None:
(output,) = outputs[0].outputs
assert output.new_token_ids == [7]
assert output.num_generation_tokens == 1
assert output.finish_reason is FinishReason.STOP
token_rows = np.asarray(output.new_logprobs.logprob_token_ids)
value_rows = np.asarray(output.new_logprobs.logprobs)
@@ -0,0 +1,43 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from types import SimpleNamespace
import pytest
from vllm_omni.core.sched.omni_ar_scheduler import _should_emit_engine_output
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@pytest.mark.parametrize(
("async_chunk", "final_output", "use_v2", "stopped", "has_control", "expected"),
[
(True, False, True, False, False, False), # async+v2 suppresses data
(True, False, False, False, False, True), # v1 continues to emit
(True, False, True, True, False, True), # stopped always emits
(True, False, True, False, True, True), # control-only still emits
],
)
def test_async_chunk_intermediate_stage_emits_only_control_outputs(
async_chunk: bool,
final_output: bool,
use_v2: bool,
stopped: bool,
has_control: bool,
expected: bool,
) -> None:
model_config = SimpleNamespace(
async_chunk=async_chunk,
final_output=final_output,
use_v2_model_runner=use_v2,
)
assert (
_should_emit_engine_output(
model_config,
stopped=stopped,
has_control=has_control,
)
is expected
)
@@ -5,6 +5,7 @@
from __future__ import annotations
from collections import defaultdict
from types import SimpleNamespace
from unittest.mock import MagicMock
@@ -16,7 +17,10 @@ import pytest
import vllm_omni # noqa: F401 - import for side effects (patch vLLM)
from vllm.sampling_params import SamplingParams
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.core.sched.scheduler import Scheduler as VLLMScheduler
from vllm.v1.outputs import ModelRunnerOutput
from vllm.v1.engine import FinishReason
from vllm.v1.core.sched.request_queue import SchedulingPolicy, create_request_queue
from vllm.v1.request import Request, RequestStatus, StreamingUpdate
from vllm_omni.core.sched.omni_ar_scheduler import OmniARAsyncScheduler, OmniARScheduler
from vllm_omni.distributed.omni_connectors.transfer_adapter.chunk_transfer_adapter import (
@@ -958,3 +962,347 @@ def test_chunk_segment_cleanup_keeps_explicit_update_stage_parked(
assert session.request_id not in sched.chunk_transfer_adapter.segment_finished_requests
sched.skipped_waiting.remove_requests.assert_not_called()
sched._enqueue_waiting_request.assert_not_called()
def _make_live_session_scheduler(*, max_model_len: int) -> OmniARScheduler:
"""A scheduler whose finish path is real: the queues, ``finish_requests``,
``_free_request`` and the finished-request bookkeeping that wakes an idle
engine all run. Only block freeing and the encoder cache are mocked."""
sched = _make_admission_scheduler(max_model_len=max_model_len)
del sched._free_request # the admission helper mocks it; run the real one
sched._omits_kv_transfer_cache = {}
sched.connector = None
sched.perf_metrics = None
sched.recompute_kv_load_failures = False
sched.finished_req_ids = set()
sched.finished_req_ids_dict = defaultdict(set)
sched.transfer_triggered_requests = set()
sched.active_kv_transfers = set()
sched.waiting_for_transfer_free = set()
sched.pending_stop_after_extraction = set()
sched.requests_needing_kv_transfer = {}
sched._kv_wait_start_ts = {}
sched.kv_cache_manager = SimpleNamespace(take_events=lambda: None, estimate_cached_tokens=lambda _request: 0)
return sched
def _run_idle_step(sched: OmniARScheduler):
"""One ``update_from_output`` with nothing scheduled: the step an idle
engine runs once ``has_finished_requests()`` reports a freed session."""
scheduler_output = SimpleNamespace(
num_scheduled_tokens={},
scheduled_spec_decode_tokens={},
num_invalid_spec_tokens=0,
)
model_runner_output = SimpleNamespace(
sampled_token_ids=[],
logprobs=None,
prompt_logprobs_dict={},
pooler_output=None,
num_nans_in_logits=None,
kv_connector_output=None,
cudagraph_stats=None,
req_id_to_index={},
routed_experts=None,
)
return OmniARScheduler.update_from_output(sched, scheduler_output, model_runner_output)
def _park_session(sched: OmniARScheduler, session: Request) -> None:
"""Put a session where a 1 fps video stream leaves it between appends:
prompt partly computed, waiting for streaming input, in admission."""
sched.requests[session.request_id] = session
session.append_output_token_ids([7, 8, 9])
session.num_computed_tokens = 6
session.num_output_placeholders = 0
session.status = RequestStatus.WAITING_FOR_STREAMING_REQ
sched.skipped_waiting.add_request(session)
sched.num_waiting_for_streaming_input = 1
def test_stage0_streaming_update_that_overflows_max_model_len_finishes_the_session() -> None:
"""A native duplex session grows its prompt on every append; once the
extension cannot fit the model the worker crashes copying the prompt.
The scheduler must drop the update and fail only this session, at once,
through the real finish path: a parked session does not make the engine
schedule, so what wakes the engine is the freed request showing up in
``has_finished_requests()``, and the step that follows must carry one
explicit ERROR rather than the synthesized ABORT."""
sched = _make_live_session_scheduler(max_model_len=8)
session = _make_request()
_park_session(sched, session)
sched._update_request_as_session(session, _make_update([10, 20, 30]))
assert session.prompt_token_ids == [1, 2, 3]
assert session.num_prompt_tokens == 3
assert session.status == RequestStatus.FINISHED_ERROR
assert session.request_id not in sched.requests
assert len(sched.waiting) == 0
assert len(sched.skipped_waiting) == 0
assert sched.num_waiting_for_streaming_input == 0
sched._free_request_blocks.assert_called_once_with(session)
assert sched.finished_req_ids == {session.request_id}
assert sched.has_finished_requests()
client_index, reason = sched._streaming_context_overflow[session.request_id]
assert client_index == session.client_index
assert reason.startswith("context_length_exceeded: ")
assert "9 tokens" in reason and "max_model_len 8" in reason
engine_core_outputs = _run_idle_step(sched)
(output,) = engine_core_outputs[session.client_index].outputs
assert output.request_id == session.request_id
assert output.finish_reason == FinishReason.ERROR
assert output.stop_reason == reason
assert output.new_token_ids == []
assert engine_core_outputs[session.client_index].finished_requests == {session.request_id}
assert sched._streaming_context_overflow == {}
# Nothing is left to report once the error went out.
assert _run_idle_step(sched) == {}
def test_stage0_streaming_update_that_fills_max_model_len_exactly_finishes_the_session() -> None:
"""An exactly full prompt leaves no room for the token every duplex step
samples: upstream's running budget drops to -1, which ``schedule()`` does
not catch, so the exact fill is an overflow too."""
sched = _make_scheduler(stage_id=0)
sched.max_model_len = 8
sched.finish_requests = MagicMock()
session = _make_request()
session.status = RequestStatus.WAITING_FOR_STREAMING_REQ
session.append_output_token_ids([7, 8, 9])
session.num_computed_tokens = 6
session.num_output_placeholders = 0
sched._update_request_as_session(session, _make_update([10, 20]))
assert session.prompt_token_ids == [1, 2, 3]
assert session.num_prompt_tokens == 3
sched.finish_requests.assert_called_once_with((session.request_id,), RequestStatus.FINISHED_ERROR)
_, reason = sched._streaming_context_overflow[session.request_id]
assert "8 tokens" in reason and "max_model_len 8" in reason
def test_stage0_streaming_update_that_leaves_room_to_sample_is_applied() -> None:
sched = _make_scheduler(stage_id=0)
sched.max_model_len = 9
sched.finish_requests = MagicMock()
session = _make_request()
session.status = RequestStatus.WAITING_FOR_STREAMING_REQ
session.append_output_token_ids([7, 8, 9])
session.num_computed_tokens = 6
session.num_output_placeholders = 0
sched._update_request_as_session(session, _make_update([10, 20]))
assert session.prompt_token_ids == [1, 2, 3, 7, 8, 9, 10, 20]
assert session.num_prompt_tokens == 8
assert session.status == RequestStatus.WAITING
sched.finish_requests.assert_not_called()
assert not getattr(sched, "_streaming_context_overflow", {})
def test_stage0_streaming_update_keeps_room_for_every_token_sampled_per_step() -> None:
"""With speculative decoding a step samples more than one token, and the
prompt must leave room for all of them."""
sched = _make_scheduler(stage_id=0)
sched.max_model_len = 9
sched.num_sampled_tokens_per_step = 2
sched.finish_requests = MagicMock()
session = _make_request()
session.status = RequestStatus.WAITING_FOR_STREAMING_REQ
session.append_output_token_ids([7, 8, 9])
session.num_computed_tokens = 6
session.num_output_placeholders = 0
sched._update_request_as_session(session, _make_update([10, 20]))
assert session.prompt_token_ids == [1, 2, 3]
sched.finish_requests.assert_called_once_with((session.request_id,), RequestStatus.FINISHED_ERROR)
assert "8 tokens" in sched._streaming_context_overflow[session.request_id][1]
def test_stage0_streaming_update_overflow_counts_an_uncomputed_prompt() -> None:
"""A preempted session keeps its prompt even though num_computed_tokens
fell behind it; the projection must use the longer of the two."""
sched = _make_scheduler(stage_id=0)
sched.max_model_len = 4
sched.finish_requests = MagicMock()
session = _make_request()
session.status = RequestStatus.WAITING_FOR_STREAMING_REQ
session.num_computed_tokens = 0
sched._update_request_as_session(session, _make_update([10, 20]))
assert session.prompt_token_ids == [1, 2, 3]
sched.finish_requests.assert_called_once()
assert "5 tokens" in sched._streaming_context_overflow[session.request_id][1]
def _make_admission_scheduler(*, max_model_len: int) -> OmniARScheduler:
"""A scheduler with real admission queues, so nothing about the terminal
handling below is mocked away except block freeing."""
sched = _make_scheduler(stage_id=0)
sched.max_model_len = max_model_len
sched.policy = SchedulingPolicy.FCFS
sched.waiting = create_request_queue(sched.policy)
sched.skipped_waiting = create_request_queue(sched.policy)
sched.running = []
sched.requests = {}
sched._free_request = MagicMock() # needs a KV manager; not what this covers
return sched
def _make_queued_stop(session: Request, update: StreamingUpdate) -> None:
"""Put the request in the state upstream hands to _handle_stopped_request:
an append that arrived during generation is queued, and the stop status is
still on the request."""
from collections import deque
session.resumable = True
session.streaming_queue = deque([update])
session.status = RequestStatus.FINISHED_STOPPED
def test_queued_streaming_update_that_overflows_does_not_return_to_admission() -> None:
sched = _make_admission_scheduler(max_model_len=4)
session = _make_request()
sched.requests[session.request_id] = session
session.num_computed_tokens = 3
_make_queued_stop(session, _make_update([10, 20]))
finished = sched._handle_stopped_request(session)
assert finished is True
assert len(sched.waiting) == 0
assert len(sched.skipped_waiting) == 0
assert session.status == RequestStatus.FINISHED_ERROR
assert session.resumable is False
assert "context_length_exceeded: " in sched._streaming_context_overflow[session.request_id][1]
# update_from_output frees every request reported as finished; freeing here
# as well deleted it from self.requests twice (KeyError in _free_blocks).
sched._free_request.assert_not_called()
def test_queued_streaming_update_that_fits_still_resumes_the_session() -> None:
sched = _make_admission_scheduler(max_model_len=64)
session = _make_request()
sched.requests[session.request_id] = session
session.num_computed_tokens = 3
_make_queued_stop(session, _make_update([10, 20]))
finished = sched._handle_stopped_request(session)
assert finished is False
assert len(sched.waiting) == 1
assert session.status == RequestStatus.WAITING
assert not getattr(sched, "_streaming_context_overflow", {})
sched._free_request.assert_not_called()
def test_queued_stop_with_a_recorded_overflow_still_leaves_admission() -> None:
"""The overflow may already be on record when the stop is handled (an
earlier update of the same session). Upstream still re-enqueues the
request, so the override must take it back out either way instead of
leaving a FINISHED_ERROR request for admission to trip over."""
sched = _make_admission_scheduler(max_model_len=64)
session = _make_request()
sched.requests[session.request_id] = session
session.num_computed_tokens = 3
sched._streaming_context_overflow = {session.request_id: (session.client_index, "context_length_exceeded: earlier")}
_make_queued_stop(session, _make_update([10, 20])) # this update itself fits
finished = sched._handle_stopped_request(session)
assert finished is True
assert len(sched.waiting) == 0
assert len(sched.skipped_waiting) == 0
assert session.status == RequestStatus.FINISHED_ERROR
assert session.resumable is False
sched._free_request.assert_not_called()
def test_parked_stop_with_a_recorded_overflow_keeps_the_streaming_counter_balanced() -> None:
"""Same as above with nothing queued: upstream parks the request as
waiting for streaming input and counts it; the dequeue must uncount it."""
from collections import deque
sched = _make_admission_scheduler(max_model_len=64)
session = _make_request()
sched.requests[session.request_id] = session
session.num_computed_tokens = 3
sched._streaming_context_overflow = {session.request_id: (session.client_index, "context_length_exceeded: earlier")}
session.resumable = True
session.streaming_queue = deque()
session.status = RequestStatus.FINISHED_STOPPED
finished = sched._handle_stopped_request(session)
assert finished is True
assert len(sched.skipped_waiting) == 0
assert sched.num_waiting_for_streaming_input == 0
assert session.status == RequestStatus.FINISHED_ERROR
sched._free_request.assert_not_called()
def test_context_overflow_emits_an_error_output_with_the_reason() -> None:
sched = _make_scheduler(stage_id=0)
sched._streaming_context_overflow = {"req-a": (2, "context_length_exceeded: too long")}
outputs: dict[int, list] = {}
sched._emit_streaming_context_overflow_outputs(outputs)
(output,) = outputs[2]
assert output.request_id == "req-a"
assert output.finish_reason == FinishReason.ERROR
assert output.stop_reason == "context_length_exceeded: too long"
assert output.new_token_ids == []
assert sched._streaming_context_overflow == {}
sched._emit_streaming_context_overflow_outputs(outputs)
assert len(outputs[2]) == 1
@pytest.mark.parametrize("native", [True, False])
def test_async_chunk_reserves_parked_slots_during_ar_admission(monkeypatch, native) -> None:
sched = _make_scheduler(stage_id=1)
parked = SimpleNamespace(request_id="parked")
sched.requests = {"parked": parked}
sched.waiting = []
sched.running = []
sched._native_data_plane = native
sched.use_v2_model_runner = native
sched.max_num_running_reqs = 8
sched.input_coordinator = (
SimpleNamespace(_waiting_for_chunk_running=[parked], restore_queues=lambda _w, _r: None) if native else None
)
sched.chunk_transfer_adapter = (
None
if native
else SimpleNamespace(
waiting_for_chunk_running_requests=[parked],
_held_non_active=[],
process_pending_chunks=lambda *_a, **_kw: None,
collect_failed_send_request_ids=lambda: {},
restore_queues=lambda *_a, **_kw: None,
postprocess_scheduler_output=lambda *_a, **_kw: None,
)
)
sched._consume_pending_connector_output = lambda model_mode: None
sched._process_pending_input_timeouts = lambda: None
sched._should_defer_waiting_admission = lambda: False
sched.get_finished_requests_needing_kv_transfer = lambda: {}
sched._wrap_omni_scheduler_output = lambda output, **_kwargs: output
observed_limits: list[int] = []
def fake_schedule(self, _throttle_prefills=False):
observed_limits.append(self.max_num_running_reqs)
return SimpleNamespace(scheduled_new_reqs=[])
monkeypatch.setattr(VLLMScheduler, "schedule", fake_schedule)
sched.schedule()
assert observed_limits == [7 if native else 8]
assert sched.max_num_running_reqs == 8
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from types import SimpleNamespace
@@ -141,6 +144,7 @@ def test_voxcpm2_unified_decode_graph_does_not_defer_without_cuda_graph(monkeypa
def test_unified_decode_graph_deferral_restores_waiting_queue(monkeypatch) -> None:
scheduler = _make_scheduler()
scheduler.max_num_running_reqs = 8
scheduler.running = [_MockRequest("decode")]
original_waiting_req = _MockRequest("waiting", status=RequestStatus.WAITING)
deferred_by_upstream = _MockRequest("deferred-by-upstream", status=RequestStatus.WAITING)
@@ -123,6 +123,9 @@ def _make_fast_path_sched(*, defer_block_free: bool) -> tuple[MagicMock, Request
sched = MagicMock()
sched.max_num_scheduled_tokens = 8
sched.max_num_running_reqs = 8
sched._native_data_plane = False
sched._retains_state_across_chunks = False
sched._pause_state = PauseState.UNPAUSED
sched.requests = {request.request_id: request}
sched.running = [request]
@@ -1,5 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from collections import defaultdict
from types import SimpleNamespace
from typing import Any
import pytest
from vllm.v1.engine import FinishReason
@@ -87,7 +91,7 @@ def test_full_payload_coordinator_matches_legacy_gate(monkeypatch, stage_id, asy
def test_schedule_lifecycle_helpers_process_and_restore_both_input_paths():
calls = []
calls: list[tuple[Any, ...]] = []
scheduler = _Scheduler()
scheduler.waiting = ["waiting"]
scheduler.running = ["running"]
@@ -115,7 +119,7 @@ def test_schedule_lifecycle_helpers_process_and_restore_both_input_paths():
collect_failed_send_request_ids=_collect_failed_sends,
)
scheduler.input_coordinator = SimpleNamespace(
restore_queues=lambda waiting: calls.append(("restore-full", waiting))
restore_queues=lambda waiting, running: calls.append(("restore-full", waiting, running))
)
scheduler._process_pending_omni_inputs("ar")
@@ -130,7 +134,7 @@ def test_schedule_lifecycle_helpers_process_and_restore_both_input_paths():
("chunk-timeouts", omni_scheduler_mixin.DEFAULT_INPUT_WAIT_TIMEOUT_S),
("failed-sends",),
("restore-chunks", scheduler.waiting, scheduler.running, scheduler.requests),
("restore-full", scheduler.waiting),
("restore-full", scheduler.waiting, scheduler.running),
]
@@ -0,0 +1,38 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Drain ready events once, merging live requests and filtering cancellations."""
from types import SimpleNamespace
import pytest
from vllm_omni.core.sched.omni_scheduler_mixin import OmniSchedulerMixin
from vllm_omni.outputs import OmniConnectorOutput
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
def test_ready_inbox_coalesces_live_events_and_drops_cancelled(mocker):
scheduler = OmniSchedulerMixin()
scheduler.requests, scheduler.waiting, scheduler.running = {"r": object()}, [], []
coordinator = SimpleNamespace(
_async_chunk=True, update_request_metadata=mocker.Mock(), process_pending_chunks=mocker.Mock()
)
scheduler.input_coordinator = coordinator
scheduler._init_omni_connector_output_inbox()
scheduler.enqueue_omni_connector_output(OmniConnectorOutput(chunk_ready_req_ids={"r"}))
scheduler.enqueue_omni_connector_output(
OmniConnectorOutput(
chunk_ready_req_ids={"r", "aborted"},
chunk_finished_req_ids={"r", "aborted"},
request_metadata={"r": {"decode_token_end": 2}, "aborted": {"decode_token_end": 99}},
)
)
scheduler._consume_pending_connector_output(model_mode="ar")
coordinator.update_request_metadata.assert_called_once_with(
scheduler.requests, {"r": {"decode_token_end": 2}}, model_mode="ar"
)
coordinator.process_pending_chunks.assert_called_once_with([], [], {"r"}, {"r"})
scheduler._consume_pending_connector_output(model_mode="ar")
assert coordinator.update_request_metadata.call_count == 1
coordinator.process_pending_chunks.assert_called_with([], [], set(), set())
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Tests for the ``num_waiting_for_streaming_input`` resync placed in
``OmniARScheduler.finish_requests`` / ``OmniGenerationScheduler.finish_requests``
and in ``OmniARScheduler.schedule``.
@@ -128,6 +131,7 @@ def test_ar_schedule_resyncs_before_delegating_upstream(monkeypatch: pytest.Monk
scheduler.skipped_waiting = []
scheduler.num_waiting_for_streaming_input = 1 # leaked by the status rewrite
scheduler.policy = "fcfs"
scheduler.max_num_running_reqs = 8
seen: dict[str, int] = {}
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Unit tests for OmniSchedulingCoordinator.
These tests use mock request objects and mock queues. They do not require
@@ -20,7 +20,9 @@ import torch
import vllm_omni.core.sched.omni_scheduling_coordinator as coord_mod
from vllm_omni.core.sched.omni_scheduling_coordinator import (
OmniSchedulingCoordinator,
uses_native_mrv2_data_plane,
)
from vllm_omni.core.sched.output import OmniChunkRecvHandle
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -56,8 +58,10 @@ def _make_request(req_id: str, status: str = "waiting") -> SimpleNamespace:
prompt_token_ids=[],
num_prompt_tokens=0,
num_computed_tokens=0,
num_output_placeholders=0,
_all_token_ids=[],
_output_token_ids=[],
payload_sender_info=None,
)
@@ -82,7 +86,7 @@ class MockQueue:
def prepend_requests(self, requests):
self._items = list(requests) + self._items
def remove(self, request):
def remove_request(self, request):
self._items.remove(request)
def remove_requests(self, requests):
@@ -95,7 +99,47 @@ class MockQueue:
# ------------------------------------------------------------------ #
class TestCoordinatorUpdateRequestMetadata(unittest.TestCase):
class TestNativeMRV2DataPlaneSelection(unittest.TestCase):
def test_native_plane_requires_v2_and_async_chunk_capability(self):
native = SimpleNamespace(async_chunk=True, supports_native_mrv2_data_plane=True)
self.assertTrue(uses_native_mrv2_data_plane(native, use_v2_model_runner=True))
self.assertFalse(uses_native_mrv2_data_plane(native, use_v2_model_runner=False))
self.assertFalse(uses_native_mrv2_data_plane(SimpleNamespace(async_chunk=False), use_v2_model_runner=True))
def test_chunk_registration_ready_and_terminal_lifecycle():
coord = OmniSchedulingCoordinator(scheduler_max_num_seqs=10, stage_id=1, async_chunk=True)
req = _make_request("internal", status=RequestStatus.WAITING)
req.external_req_id = "external"
waiting = MockQueue([req])
coord.process_pending_chunks(waiting, [], set(), set())
assert req.status == RequestStatus.WAITING_FOR_CHUNK
[handle] = coord.pending_chunk_registrations
assert isinstance(handle, OmniChunkRecvHandle)
assert (handle.request_id, handle.external_req_id) == ("internal", "external")
coord.restore_queues(waiting, [])
coord.process_pending_chunks(waiting, [], {"internal"}, set())
assert req.status == RequestStatus.WAITING
assert "internal" in coord.requests_with_ready_chunks
req.status = RequestStatus.WAITING_FOR_CHUNK
coord.process_pending_chunks(waiting, [], set(), {"internal"})
assert "internal" in coord.finished_requests
def test_chunk_waiting_removes_request_from_running_list():
coord = OmniSchedulingCoordinator(scheduler_max_num_seqs=10, stage_id=1, async_chunk=True)
req = _make_request("running", status=RequestStatus.RUNNING)
running = [req]
coord.process_pending_chunks(MockQueue(), running, set(), set())
assert running == []
assert req.status == RequestStatus.WAITING_FOR_CHUNK
assert list(coord._waiting_for_chunk_running) == [req]
class TestChunkCoordinatorUpdateRequestMetadata(unittest.TestCase):
"""Test update_request_metadata applies scheduling metadata to requests."""
def test_ar_mode_no_longer_sets_additional_information(self):
@@ -270,6 +314,19 @@ class TestWaitingForInputTransition(unittest.TestCase):
self.assertEqual(len(coord.pending_input_registrations), 1)
self.assertEqual(coord.pending_input_registrations[0].request_id, "r1")
def test_pending_input_registration_carries_payload_sender_info(self):
coord = OmniSchedulingCoordinator(stage_id=1)
req = _make_request("r1", status=RequestStatus.WAITING_FOR_INPUT)
req.payload_sender_info = {"host": "10.0.0.1", "zmq_port": 50051}
waiting = MockQueue([req])
coord.process_pending_full_payload_inputs(waiting, set())
self.assertEqual(
coord.pending_input_registrations[0].payload_sender_info,
{"host": "10.0.0.1", "zmq_port": 50051},
)
def test_idle_cycles_retain_received_marker_before_request_appears(self):
coord = OmniSchedulingCoordinator(stage_id=1)
coord._full_payload_input_received.add("late")
@@ -368,17 +425,18 @@ class TestTimeoutDetection(unittest.TestCase):
self.assertEqual(result, {"r1"})
self.assertEqual(len(coord._waiting_for_input), 0)
def test_free_finished_request_clears_waiting_since(self):
"""free_finished_request clears coordinator lifecycle markers."""
coord = OmniSchedulingCoordinator(stage_id=1)
coord._waiting_since["r1"] = 0.0
coord._full_payload_input_received.add("r1")
def test_free_finished_request_clears_all_lifecycle_state(self):
"""free_finished_request makes stale connector events harmless."""
coord = OmniSchedulingCoordinator(scheduler_max_num_seqs=10, stage_id=1)
r1, r2 = _make_request("r1"), _make_request("r2")
coord.finished_requests.add("r1")
coord.requests_with_ready_chunks.add("r1")
coord._waiting_for_chunk_running.extend([r1, r2])
coord.pending_chunk_registrations = [OmniChunkRecvHandle(request_id="r1"), OmniChunkRecvHandle(request_id="r2")]
coord.free_finished_request("r1")
self.assertNotIn("r1", coord._waiting_since)
self.assertNotIn("r1", coord._full_payload_input_received)
self.assertNotIn("r1", coord.finished_requests)
if __name__ == "__main__":
unittest.main()
self.assertNotIn("r1", coord.requests_with_ready_chunks)
self.assertEqual([r.request_id for r in coord._waiting_for_chunk_running], ["r2"])
self.assertEqual([h.request_id for h in coord.pending_chunk_registrations], ["r2"])
File diff suppressed because it is too large. Load diff
-119
View File
@@ -1,119 +0,0 @@
import pytest
import torch
from vllm_omni.core.prefix_cache import OmniTensorPrefixCache
# `cpu` is the lane selector, not a hardware claim: the only Buildkite steps that
# reach tests/ select `core_model and cpu`, and they run on GPU hardware (l4_1).
# Marking this `cuda` collects it nowhere. Real hardware need is the skipif below.
pytestmark = [
pytest.mark.core_model,
pytest.mark.cpu,
pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a CUDA device"),
]
NUM_BLOCKS = 10
BLOCK_SIZE = 4
HIDDEN_SIZE = 2
DTYPE = torch.float32
def get_omni_pcache() -> OmniTensorPrefixCache:
"""Build an OmniTensorPrefixCache, but don't init mm tensors."""
return OmniTensorPrefixCache(
num_blocks=NUM_BLOCKS,
block_size=BLOCK_SIZE,
hidden_size=HIDDEN_SIZE,
hs_dtype=DTYPE,
)
def test_drain_ready_async_writes_is_a_noop_before_the_event_is_ready(monkeypatch):
"""drain_ready_async_writes() must not touch the cache while the
scheduled D2H's event has not completed, and must consume it exactly
once after it has.
Real GPU timing (e.g. via torch.cuda._sleep to stall the copy stream)
was tried and found unreliable on this box: cross-stream wait_stream/
wait_event did not reliably delay event.query() from reporting ready
immediately, likely a virtualization/driver quirk of this cloud GPU.
Forcing the event's query() result directly tests the branching logic
in drain_ready_async_writes/_consume_pending_write deterministically,
independent of real CUDA scheduling behavior.
"""
cache = get_omni_pcache()
mm_key = "codes.audio"
cache.maybe_init_missing_mm_cache_keys({mm_key: torch.zeros(4, HIDDEN_SIZE)}, seq_len=4)
num_tokens = 4
slot_mapping_gpu = torch.arange(8, 8 + num_tokens, dtype=torch.int64, device="cuda")
mm_gpu = {
mm_key: torch.arange(num_tokens * HIDDEN_SIZE, dtype=torch.float32, device="cuda").reshape(
num_tokens, HIDDEN_SIZE
)
}
cache.schedule_async_write(
hidden_states_gpu=None,
multimodal_outputs_gpu=mm_gpu,
slot_mapping_gpu=slot_mapping_gpu,
num_tokens_unpadded=num_tokens,
num_tokens_padded=num_tokens,
)
pending_event = cache._pending_write.event
rows = cache.mm_outputs_cache[mm_key].view(-1, HIDDEN_SIZE)
monkeypatch.setattr(pending_event, "query", lambda: False)
assert cache.drain_ready_async_writes() == 0
assert torch.all(rows[8 : 8 + num_tokens] == 0)
assert cache._pending_write is not None
monkeypatch.setattr(pending_event, "query", lambda: True)
assert cache.drain_ready_async_writes() == 1
assert torch.equal(rows[8 : 8 + num_tokens], mm_gpu[mm_key].cpu())
assert cache._pending_write is None
# Nothing pending anymore: a second drain is a no-op, not a re-scatter.
assert cache.drain_ready_async_writes() == 0
def test_schedule_async_write_consumes_previous_pending_write_first():
"""Scheduling step N+1's write must first consume (scatter) step N's
pending write, even if the caller never explicitly called
drain_ready_async_writes() in between -- otherwise step N's data would
be silently dropped when overwritten by step N+1's pending write."""
cache = get_omni_pcache()
mm_key = "codes.audio"
cache.maybe_init_missing_mm_cache_keys({mm_key: torch.zeros(4, HIDDEN_SIZE)}, seq_len=4)
num_tokens = 4
first_slots = torch.arange(8, 8 + num_tokens, dtype=torch.int64, device="cuda")
first_gpu = {mm_key: torch.full((num_tokens, HIDDEN_SIZE), 1.0, device="cuda")}
second_slots = torch.arange(12, 12 + num_tokens, dtype=torch.int64, device="cuda")
second_gpu = {mm_key: torch.full((num_tokens, HIDDEN_SIZE), 2.0, device="cuda")}
cache.schedule_async_write(
hidden_states_gpu=None,
multimodal_outputs_gpu=first_gpu,
slot_mapping_gpu=first_slots,
num_tokens_unpadded=num_tokens,
num_tokens_padded=num_tokens,
)
torch.accelerator.synchronize()
# This call's internal _consume_pending_write() must flush the FIRST
# write before the second one is scheduled; the caller never drained.
cache.schedule_async_write(
hidden_states_gpu=None,
multimodal_outputs_gpu=second_gpu,
slot_mapping_gpu=second_slots,
num_tokens_unpadded=num_tokens,
num_tokens_padded=num_tokens,
)
torch.accelerator.synchronize()
cache.drain_ready_async_writes()
rows = cache.mm_outputs_cache[mm_key].view(-1, HIDDEN_SIZE)
assert torch.all(rows[8:12] == 1.0)
assert torch.all(rows[12:16] == 2.0)
@@ -0,0 +1,182 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""CPU tests for PrefixCacheRunnerMixin: one-shot construction, policy
snapshot identity/isolation, and the shared save/materialize gates.
No vLLM and no GPU required (same shim as test_prefix_cache.py)."""
import sys
from pathlib import Path
from types import ModuleType, SimpleNamespace
from typing import Any
import pytest
import torch
try: # pragma: no cover - shim only matters on vllm-less dev machines
import vllm # noqa: F401
except ModuleNotFoundError:
_root = Path(__file__).resolve().parents[2]
for _pkg in ("vllm_omni", "vllm_omni.core"):
if _pkg not in sys.modules:
_m = ModuleType(_pkg)
_m.__path__ = [str(_root / _pkg.replace(".", "/"))]
sys.modules[_pkg] = _m
import logging
_vllm = ModuleType("vllm")
_vllm_logger = ModuleType("vllm.logger")
setattr(_vllm_logger, "init_logger", logging.getLogger)
setattr(_vllm, "logger", _vllm_logger)
sys.modules["vllm"] = _vllm
sys.modules["vllm.logger"] = _vllm_logger
from vllm_omni.core.prefix_cache.interface import PrefixCacheConfig, StageCacheOutputs
from vllm_omni.core.prefix_cache.runner_mixin import PrefixCacheRunnerMixin
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
BLOCK_SIZE = 4
def _patch_pp(monkeypatch, is_last: bool) -> None:
"""Route the mixin's call-time get_pp_group import to a fake rank."""
mod = ModuleType("vllm.distributed.parallel_state")
setattr(mod, "get_pp_group", lambda: SimpleNamespace(is_last_rank=is_last))
if "vllm.distributed" not in sys.modules:
monkeypatch.setitem(sys.modules, "vllm.distributed", ModuleType("vllm.distributed"))
monkeypatch.setitem(sys.modules, "vllm.distributed.parallel_state", mod)
def _full_attention_groups():
"""A single-group config that passes check_prefix_cache_kv_groups.
Real FullAttentionSpec when vllm is installed; otherwise a stand-in
registered under the import path the check resolves at call time.
"""
try:
from vllm.v1.kv_cache_interface import FullAttentionSpec
except ModuleNotFoundError:
iface = sys.modules.get("vllm.v1.kv_cache_interface")
if iface is None:
iface = ModuleType("vllm.v1.kv_cache_interface")
class _FullAttentionSpecStub:
pass
setattr(iface, "FullAttentionSpec", _FullAttentionSpecStub)
sys.modules["vllm.v1"] = ModuleType("vllm.v1")
sys.modules["vllm.v1.kv_cache_interface"] = iface
FullAttentionSpec = getattr(iface, "FullAttentionSpec")
return [SimpleNamespace(kv_cache_spec=FullAttentionSpec.__new__(FullAttentionSpec))]
class _FakeBlockTables:
"""Group-0 table whose layout attrs pass check_prefix_cache_block_layout."""
def __init__(self):
self.block_tables = [object()]
def __getitem__(self, idx):
return SimpleNamespace()
class _Runner(PrefixCacheRunnerMixin):
def __init__(self, cfg: PrefixCacheConfig | None = None):
# Any: tests swap in _CacheStub for the manager.
self.omni_prefix_cache: Any = None
self._omni_prefix_cache_cfg = cfg
self.input_batch = SimpleNamespace(block_table=_FakeBlockTables(), req_ids=[])
self.kv_cache_config = SimpleNamespace(kv_cache_groups=_full_attention_groups())
self.is_pooling_model = False
def _cfg() -> PrefixCacheConfig:
return PrefixCacheConfig(num_blocks=8, block_size=BLOCK_SIZE)
def _sched():
return SimpleNamespace(scheduled_new_reqs=(), finished_req_ids=set(), num_scheduled_tokens={})
class _CacheStub:
def __init__(self):
self.save_calls = []
self.materialize_calls = []
self.outs = StageCacheOutputs(hidden_states=None, mm_outputs={})
def save_outputs(self, hidden, mm, *, num_tokens_unpadded, num_tokens_padded):
self.save_calls.append((hidden, mm, num_tokens_unpadded, num_tokens_padded))
return 7
def materialize(self, step_id, req_ids):
self.materialize_calls.append((step_id, req_ids))
return self.outs
def test_step_begin_builds_once_and_registers_snapshot_policy(monkeypatch):
_patch_pp(monkeypatch, is_last=True)
r = _Runner(_cfg())
r._snapshot_prefix_cache_model_policy(
SimpleNamespace(requires_full_prefix_cached_hidden_states=True, deferred_prefix_cache_mm_keys=("k",))
)
r._prefix_cache_step_begin(_sched())
mgr = r.omni_prefix_cache
assert mgr is not None and r._omni_prefix_cache_cfg is None
assert mgr._policy is r._omni_cache_policy # the load-time snapshot, same object
r._prefix_cache_step_begin(_sched())
assert r.omni_prefix_cache is mgr # one-shot
def test_default_policy_isolated_per_instance():
a, b = _Runner(), _Runner()
a._snapshot_prefix_cache_model_policy(SimpleNamespace(requires_full_prefix_cached_hidden_states=False))
assert a._omni_cache_policy.needs_full_hidden_states is False
assert a._model_needs_full_prefix_hidden_states() is False
assert b._omni_cache_policy.needs_full_hidden_states is True # class default untouched
assert PrefixCacheRunnerMixin._omni_cache_policy.needs_full_hidden_states is True
def test_non_last_rank_consumes_cfg_without_building(monkeypatch):
_patch_pp(monkeypatch, is_last=False)
r = _Runner(_cfg())
r._prefix_cache_step_begin(_sched())
assert r.omni_prefix_cache is None and r._omni_prefix_cache_cfg is None
def test_disabled_cache_step_begin_is_a_noop():
r = _Runner(cfg=None) # enable_prefix_caching off: nothing staged
r._prefix_cache_step_begin(_sched())
assert r.omni_prefix_cache is None
def test_save_step_gates_and_passthrough(monkeypatch):
r = _Runner()
stub = _CacheStub()
hidden = torch.zeros(2, 2)
def save():
return r._prefix_cache_save_step(hidden, None, num_tokens_unpadded=2, num_tokens_padded=2)
_patch_pp(monkeypatch, is_last=True)
assert save() is None # cache off
r.omni_prefix_cache = stub
r.is_pooling_model = True
assert save() is None # pooling stage never writes
r.is_pooling_model = False
_patch_pp(monkeypatch, is_last=False)
assert save() is None # not the last PP rank
_patch_pp(monkeypatch, is_last=True)
assert save() == 7
assert stub.save_calls == [(hidden, {}, 2, 2)] # empty mm stays {}
def test_materialize_requires_explicit_step_and_snapshot_req_ids():
r = _Runner()
stub = _CacheStub()
r.omni_prefix_cache = stub
assert r._prefix_cache_materialize(None, ["a"]) == (None, None)
assert stub.materialize_calls == [] # step_id None: nothing to consume
hidden = {"a": torch.zeros(1, 2)}
stub.outs = StageCacheOutputs(hidden_states=hidden, mm_outputs={})
assert r._prefix_cache_materialize(7, ["a"]) == (hidden, None) # empty mm -> None
assert stub.materialize_calls == [(7, ["a"])]
@@ -5,7 +5,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 2
}
@@ -63,7 +63,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 2
}
@@ -132,7 +132,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 2
}
@@ -200,7 +200,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 2
}
@@ -5,7 +5,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 1
}
@@ -55,7 +55,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 2
}
@@ -5,7 +5,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 1
}
@@ -54,7 +54,8 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"],
"npu": "A3"
},
"num_cards": 2
}
+1 -1
View File
@@ -5,7 +5,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100",
"cuda": ["H100", "B200"],
"npu": "A3"
},
"num_cards": 1
@@ -5,7 +5,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100",
"cuda": ["H100", "B200"],
"npu": "A3"
},
"num_cards": 1
@@ -43,43 +43,7 @@
"extra_body": {
"save_duplex_request_metrics": true
},
"percentile-metrics": "ttft,tpot,itl,e2el,audio_ttfp,audio_rtf,audio_duration",
"baseline": {
"H100": {
"request_throughput": [
0.3038
],
"mean_ttft_ms": [
139.997
],
"mean_e2el_ms": [
3269.8807
],
"mean_audio_ttfp_ms": [
456.073
],
"mean_audio_rtf": [
0.2254
]
},
"A3": {
"request_throughput": [
0.1594
],
"mean_ttft_ms": [
274.164
],
"mean_e2el_ms": [
6250.7696
],
"mean_audio_ttfp_ms": [
994.422
],
"mean_audio_rtf": [
0.46163
]
}
}
"percentile-metrics": "ttft,tpot,itl,e2el,audio_ttfp,audio_rtf,audio_duration"
}
]
}
@@ -5,7 +5,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 4
}
@@ -76,7 +76,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 4
}
@@ -148,7 +148,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 4
}
@@ -219,7 +219,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 4
}
@@ -5,7 +5,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100",
"cuda": ["H100", "B200"],
"npu": "A3"
},
"num_cards": 2
@@ -242,7 +242,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 2
}
@@ -5,7 +5,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100",
"cuda": ["H100", "B200"],
"npu": "A3"
},
"num_cards": 2
@@ -5,7 +5,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 1
}
@@ -66,7 +66,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 1
}
@@ -150,7 +150,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 4
}
@@ -197,7 +197,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 4
}
+10 -6
View File
@@ -570,6 +570,7 @@ def test_omni_tpot_baseline_accepts_measured_finite_sample():
@pytest.mark.parametrize(
("num_tpot_samples", "mean_tpot_ms", "match"),
[
(None, 10.0, "no measurable TPOT samples"),
(0, float("nan"), "no measurable TPOT samples"),
(1, float("nan"), "mean_tpot_ms is not finite"),
],
@@ -577,14 +578,17 @@ def test_omni_tpot_baseline_accepts_measured_finite_sample():
def test_omni_tpot_baseline_rejects_missing_or_nonfinite_sample(num_tpot_samples, mean_tpot_ms, match):
from tests.dfx.perf.scripts.run_benchmark import assert_result
result = {
"completed": 1,
"Hardware": "H100",
"mean_tpot_ms": mean_tpot_ms,
}
if num_tpot_samples is not None:
result["num_tpot_samples"] = num_tpot_samples
with pytest.raises(AssertionError, match=match):
assert_result(
{
"completed": 1,
"Hardware": "H100",
"num_tpot_samples": num_tpot_samples,
"mean_tpot_ms": mean_tpot_ms,
},
result,
{"baseline": {"H100": {"mean_tpot_ms": 20.0}}},
1,
)
+4 -4
View File
@@ -5,7 +5,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100",
"cuda": ["H100", "B200"],
"npu": "A3"
},
"num_cards": 2
@@ -121,7 +121,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 2
}
@@ -285,7 +285,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 2
}
@@ -416,7 +416,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 1
}
@@ -5,7 +5,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100"
"cuda": ["H100", "B200"]
},
"num_cards": 1
}
@@ -57,7 +57,7 @@
{
"hardware_marks": {
"res": {
"cuda": "H100",
"cuda": ["H100", "B200"],
"npu": "A3"
},
"num_cards": 2
@@ -157,14 +157,8 @@ def test_speech_missing_required_fields(omni_server: OmniServer, online_client:
"ref_audio": None,
"ref_text": None,
},
# NOTE: This is delegating down the TTS adapter, so the message is both specific
# to the Qwen3TTS adapter and dependent on whether or not the model has any speakers
# (as opposed to having valida speakers, but getting an invalid speaker). it would
# be more ideal to validate that this is landing on `.validate()` on the adapter
# and ensuring that the returned message matches what we would get from calling the
# adapter validate directly.
("no speakers configured",),
id="customvoice_invalid_voice",
("Base checkpoint does not support task_type='CustomVoice'",),
id="base_checkpoint_customvoice_task_mismatch",
),
pytest.param(
{"task_type": "InvalidEnum"}, ("task_type", "literal_error", "CustomVoice"), id="task_type_invalid"
@@ -323,12 +323,18 @@ def test_lingbot_like_sink_survives_sliding_window_eviction():
kv = runner.kv_cache
assert kv is not None
for _ in range(8):
state = commit_one_frame(runner, "s1", "main")
sink_block = kv.block_table(state.adapter("main"))[0]
for _ in range(7):
state = commit_one_frame(runner, "s1", "main")
table = kv.block_table(state.adapter("main"))
assert table[0] != kv.null_block_id
assert table[1] == kv.null_block_id
adapter = state.adapter("main")
table = kv.block_table(adapter)
assert len(table) == 6 # one sink + five recent frames
assert table[0] == sink_block
assert kv.null_block_id not in table
assert adapter.absolute_num_computed_tokens == 8 * BLOCK
assert adapter.num_computed_tokens == 6 * BLOCK
ctx = state.get_kv_caches("main", seq_len=BLOCK, commit_current=False)[0].forward_ctx
visible, _ = ctx.video_block_table(torch.device("cpu"))
+103 -1
View File
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Unit tests for the AR-Diffusion KV cache helpers (Phase 1, PR-2).
Covers the request adapter, the chunk-window spec/manager (registration + the
@@ -269,9 +270,14 @@ def test_compiled_paged_write_does_not_clone_the_pool():
# drives the reinplace pass, so a drift here would silently test nothing.
real_schema = torch.ops.vllm_omni.ar_diffusion_paged_write_attn.default._schema
real_mutated = [arg.name for arg in real_schema.arguments if arg.alias_info and arg.alias_info.is_write]
assert real_mutated == ["key_pool", "value_pool"], (
# The staging buffers are mutated too when reuse_history_staging is on, but they are separate
# allocations and not what this test is about; the pools are what must not be cloned.
assert real_mutated[:2] == ["key_pool", "value_pool"], (
f"the real paged-write op now mutates {real_mutated}; this test still models two pools"
)
assert set(real_mutated) - {"key_pool", "value_pool"} <= {"stage_key", "stage_value"}, (
f"unexpected mutated argument in the real paged-write op: {real_mutated}"
)
num_blocks, heads, dim = 8, 4, 16
cache_shape = (num_blocks, BLOCK, heads, dim)
@@ -357,6 +363,7 @@ def _make_tiny_capacity_kv(
available_bytes: int,
gpu_memory_fraction: float = 1.0,
model_owned_state_bytes_per_session: int = 0,
reuse_history_staging: bool = False,
) -> ARDiffusionKVCache:
return ARDiffusionKVCache(
ARDiffusionKVConfig(
@@ -365,6 +372,7 @@ def _make_tiny_capacity_kv(
window_chunks=3,
sink_chunks=3,
gpu_memory_fraction=gpu_memory_fraction,
reuse_history_staging=reuse_history_staging,
),
num_layers=1,
num_kv_heads=1,
@@ -382,6 +390,33 @@ def _make_tiny_capacity_kv(
)
def test_history_staging_is_reserved_in_the_kv_budget(monkeypatch):
"""The per-layer staging pair is worker-wide memory allocated after admission; the budget must hold it."""
monkeypatch.setenv("VLLM_OMNI_AR_DIFFUSION_KV_GATHER", "1")
# Same geometry as the capacity-two test: 192 bytes fits two sessions exactly without staging.
plain = _make_tiny_capacity_kv(requested_capacity=2, available_bytes=192)
assert plain.session_capacity == 2 and plain.history_staging_reserved_bytes == 0
staged = _make_tiny_capacity_kv(requested_capacity=2, available_bytes=192, reuse_history_staging=True)
# 2 (K, V) x 1 layer x (sink 3 + window 3 + one action-capacity block) tokens x 1 head x 1 dim x 4 bytes.
assert staged.history_staging_reserved_bytes == 2 * 1 * 7 * 1 * 1 * 4
# It comes out of the same budget, so the second session no longer fits.
assert staged.session_capacity == 1
assert staged.num_blocks_total * 8 + staged.history_staging_reserved_bytes <= 192
# Boundary: one session fits at 128 bytes without staging; with staging the same budget is rejected
# up front instead of failing on the first forward.
_make_tiny_capacity_kv(requested_capacity=1, available_bytes=128)
with pytest.raises(ValueError, match="cannot fit one session"):
_make_tiny_capacity_kv(requested_capacity=1, available_bytes=128, reuse_history_staging=True)
def test_history_staging_is_not_reserved_when_the_gather_path_is_off(monkeypatch):
monkeypatch.delenv("VLLM_OMNI_AR_DIFFUSION_KV_GATHER", raising=False)
staged = _make_tiny_capacity_kv(requested_capacity=2, available_bytes=192, reuse_history_staging=True)
assert staged.history_staging_reserved_bytes == 0 and staged.session_capacity == 2
def test_capacity_two_retains_both_windows_and_allocates_next_block():
# LingBot-like single-branch geometry: page=8 bytes; capacity=2 requires
# 17 managed + 3 scratch blocks, plus two 16-byte cross-attention
@@ -588,3 +623,70 @@ def test_non_contiguous_branch_indices_rejected():
kv_branches=(ARDiffusionKVBranchSpec("main", 1),),
session_capacity=1,
)
def test_staged_window_reuse_matches_a_full_gather():
"""Reusing the staged history must be byte-identical to re-gathering the whole window.
This is the property the optimisation rests on: the leading blocks were staged by an earlier forward of
the same AR block, so skipping them can only be correct if what is already there equals what a fresh
gather would write. The test stages once, mutates only the current chunk's blocks in the pool (what a
later probe of the same block does), restages the tail alone, and compares against a full gather.
"""
from vllm_omni.experimental.ar_diffusion.kv_cache.paged_attention import _stage_window
torch.manual_seed(0)
num_blocks, block_size, heads, dim = 6, 4, 2, 8
current_blocks = 2
key_cache = torch.randn(num_blocks, block_size, heads, dim)
value_cache = torch.randn(num_blocks, block_size, heads, dim)
block_ids = torch.tensor([5, 4, 3, 2, 1, 0])
stage_key = torch.zeros(num_blocks * block_size, heads, dim)
stage_value = torch.zeros(num_blocks * block_size, heads, dim)
_stage_window(stage_key, stage_value, key_cache, value_cache, block_ids, num_blocks, block_size, first_block=0)
# A later probe rewrites only the current chunk's blocks in the pool.
for slot in block_ids[num_blocks - current_blocks :]:
key_cache[slot] = torch.randn(block_size, heads, dim)
value_cache[slot] = torch.randn(block_size, heads, dim)
_stage_window(
stage_key,
stage_value,
key_cache,
value_cache,
block_ids,
num_blocks,
block_size,
first_block=num_blocks - current_blocks,
)
full_key = torch.zeros_like(stage_key)
full_value = torch.zeros_like(stage_value)
_stage_window(full_key, full_value, key_cache, value_cache, block_ids, num_blocks, block_size, first_block=0)
torch.testing.assert_close(stage_key, full_key, rtol=0, atol=0)
torch.testing.assert_close(stage_value, full_value, rtol=0, atol=0)
def test_staged_window_tail_refresh_leaves_history_untouched():
"""The tail restage must not write the history rows -- that is what makes it cheaper."""
from vllm_omni.experimental.ar_diffusion.kv_cache.paged_attention import _stage_window
torch.manual_seed(1)
num_blocks, block_size, heads, dim = 5, 4, 1, 4
key_cache = torch.randn(num_blocks, block_size, heads, dim)
value_cache = torch.randn(num_blocks, block_size, heads, dim)
block_ids = torch.arange(num_blocks)
stage_key = torch.full((num_blocks * block_size, heads, dim), -1.0)
stage_value = torch.full((num_blocks * block_size, heads, dim), -1.0)
_stage_window(
stage_key, stage_value, key_cache, value_cache, block_ids, num_blocks, block_size, first_block=num_blocks - 1
)
history_rows = (num_blocks - 1) * block_size
assert (stage_key[:history_rows] == -1.0).all(), "history rows were rewritten by a tail restage"
assert (stage_value[:history_rows] == -1.0).all()
torch.testing.assert_close(stage_key[history_rows:], key_cache[-1].reshape(block_size, heads, dim), rtol=0, atol=0)
@@ -6,6 +6,7 @@ import torch
from vllm_omni.experimental.ar_diffusion.capability import ARDiffusionKVBranchSpec
from vllm_omni.experimental.ar_diffusion.kv_cache import ARDiffusionKVCache, ARDiffusionKVConfig
from vllm_omni.experimental.ar_diffusion.kv_cache.state import ARDiffusionKVState
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
DIMS = dict(
@@ -108,3 +109,104 @@ def test_state_close_frees_both_branch_blocks():
state.close()
# All blocks returned — no leak across an evicted session.
assert kv.manager.block_pool.get_num_free_blocks() == free_total
@pytest.mark.parametrize(
"frames_per_call,block_size,max_model_len,num_calls",
[(1, 16, 113, 1000), (3, 16, 113, 1000), (3, 1560, 1 << 20, 241)],
ids=["single-frame", "three-frame", "lingbot-two-minutes"],
)
@pytest.mark.parametrize("sink_chunks,reset_at_boundary", [(0, False), (2, False), (0, True), (2, True)])
def test_rollout_keeps_metadata_bounded(
frames_per_call, block_size, max_model_len, num_calls, sink_chunks, reset_at_boundary
):
"""Long rollouts retain exact global-position K/V with bounded storage indices."""
kv = ARDiffusionKVCache(
ARDiffusionKVConfig(
enable=True,
chunk_size=block_size,
window_chunks=3,
sink_chunks=sink_chunks,
reset_at_boundary=reset_at_boundary,
),
num_layers=1,
num_kv_heads=1,
head_size=4,
dtype=torch.float32,
block_size=block_size,
max_model_len=max_model_len,
available_bytes=1 << 24,
kv_branches=(ARDiffusionKVBranchSpec("main", 0),),
session_capacity=1,
frames_per_block=frames_per_call,
device=torch.device("cpu"),
)
adapter = kv.begin_request("long-rollout")
state = ARDiffusionKVState(kv, "long-rollout", {"main": adapter}, num_layers=1)
free_total = kv.manager.block_pool.get_num_free_blocks()
pool_shape = kv.key_cache(0).shape
retained_frames = sink_chunks + (0 if reset_at_boundary else 3)
for call_index in range(num_calls):
start = call_index * frames_per_call * block_size
stop = start + frames_per_call * block_size
if frames_per_call == 1:
kv.allocate_chunk(adapter)
slots = kv.chunk_write_slots(adapter)
else:
context = state.get_kv_caches("main", seq_len=stop - start, commit_current=True)[0].forward_ctx
context.ensure_video_slots(torch.device("cpu"))
slots = context.current_video_slot_mapping
assert len(kv.block_table(adapter)) <= retained_frames + frames_per_call
values = torch.arange(start, stop, dtype=torch.float32).view(-1, 1, 1).expand(-1, 1, 4)
kv.key_cache(0).flatten(0, 1)[slots] = values
kv.value_cache(0).flatten(0, 1)[slots] = -values
if frames_per_call == 1:
kv.commit_chunk(adapter)
else:
state.commit_paged_context("main")
assert state._committed["main"] == stop
sink_end = min(stop, sink_chunks * block_size)
tail_start = stop if reset_at_boundary else max(sink_end, stop - 3 * block_size)
expected = torch.cat((torch.arange(sink_end), torch.arange(tail_start, stop))).float()
expected = expected.view(-1, 1, 1).expand(-1, 1, 4)
resident = kv.window_block_ids(adapter)
torch.testing.assert_close(kv.key_cache(0)[resident].flatten(0, 1), expected)
torch.testing.assert_close(kv.value_cache(0)[resident].flatten(0, 1), -expected)
assert adapter.completed_chunks * block_size == stop
assert adapter.absolute_num_computed_tokens == stop
assert len(kv.block_table(adapter)) <= retained_frames
assert adapter.num_computed_tokens <= retained_frames * block_size
assert kv.key_cache(0).shape == pool_shape
assert free_total - kv.manager.block_pool.get_num_free_blocks() == min(stop // block_size, retained_frames)
state.reset()
fresh = state.adapter("main")
assert fresh.compacted_tokens == fresh.absolute_num_computed_tokens == fresh.num_computed_tokens == 0
assert kv.block_table(fresh) == []
assert kv.manager.block_pool.get_num_free_blocks() == free_total
kv.allocate_chunk(fresh)
assert len(kv.chunk_write_slots(fresh)) == block_size
state.close()
assert kv.manager.block_pool.get_num_free_blocks() == free_total
def test_compaction_offsets_are_request_local():
kv = make_cache()
free_total = kv.manager.block_pool.get_num_free_blocks()
first, second = kv.begin_request("first"), kv.begin_request("second")
for index in range(8):
kv.allocate_chunk(first)
kv.commit_chunk(first)
if index in (0, 4):
kv.allocate_chunk(second)
kv.commit_chunk(second)
assert first.absolute_num_computed_tokens == 8 * 16
assert first.compacted_tokens == 6 * 16
assert second.absolute_num_computed_tokens == 2 * 16
assert second.compacted_tokens == 0
assert first.num_computed_tokens == second.num_computed_tokens == 2 * 16
assert set(kv.block_table(first)).isdisjoint(kv.block_table(second))
kv.end_request(first)
kv.end_request(second)
group = kv.manager.coordinator.single_type_managers[0]
assert not group.req_to_blocks and not group.num_cached_block
assert kv.manager.block_pool.get_num_free_blocks() == free_total
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Tests for AR-Diffusion paged self-attention contexts."""
from __future__ import annotations
@@ -20,6 +21,8 @@ from vllm_omni.experimental.ar_diffusion.kv_cache import (
ar_diffusion_paged_attention,
paged_write_attn,
)
from vllm_omni.experimental.ar_diffusion.kv_cache import paged_attention as paged_attention_module
from vllm_omni.experimental.ar_diffusion.kv_cache.config import KV_GATHER_ENV
from vllm_omni.experimental.ar_diffusion.kv_cache.state import ARDiffusionKVState
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
@@ -32,8 +35,12 @@ POS = "positive"
NEG = "negative"
def make_state(*, num_layers=1, window_chunks=2, dtype=torch.float32, device=torch.device("cpu")):
cfg = ARDiffusionKVConfig(enable=True, chunk_size=BLOCK, window_chunks=window_chunks)
def make_state(
*, num_layers=1, window_chunks=2, dtype=torch.float32, device=torch.device("cpu"), reuse_history_staging=False
):
cfg = ARDiffusionKVConfig(
enable=True, chunk_size=BLOCK, window_chunks=window_chunks, reuse_history_staging=reuse_history_staging
)
kv = ARDiffusionKVCache(
cfg,
num_layers=num_layers,
@@ -236,6 +243,86 @@ def test_paged_attention_matches_dense_reference_cpu(history_chunks, action_len,
assert st.adapter(POS).completed_chunks == before + (1 if commit_current else 0)
@pytest.mark.parametrize("history_chunks", [0, 1, 2, 3])
def test_staged_reuse_refreshes_the_current_blocks_at_their_live_offset(monkeypatch, history_chunks):
"""A second probe of the same AR block restages its current K/V where the table actually holds it.
The padded table always ends in at least one action-capacity block, and while the window is still
growing in unused window capacity too, so "the last current_blocks entries" is padding. The refresh
has to start right after the visible history: empty (window growing), partial, full, and after a slide.
"""
monkeypatch.setenv(KV_GATHER_ENV, "1")
device = torch.device("cpu")
dtype = torch.float32
kv, st = make_state(dtype=dtype, device=device, window_chunks=2, reuse_history_staging=True)
if history_chunks:
_commit_video_span(kv, st, kv_branch=POS, n_chunks=history_chunks, dtype=dtype, device=device)
ctx = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=False)[0].forward_ctx
ctx.ensure_video_slots(device)
key_cache, value_cache = kv.key_cache(0), kv.value_cache(0)
def probe(step: int):
# Each probe of the block writes new current K/V, then stages.
kv._k_pools[0][ctx.current_video_slot_mapping] = torch.full((BLOCK, N_HEADS, HEAD_DIM), float(step))
kv._v_pools[0][ctx.current_video_slot_mapping] = torch.full((BLOCK, N_HEADS, HEAD_DIM), -float(step))
# Store the metadata on the context the way prepare() does.
(ctx.block_table, ctx.query_start_loc, ctx.seq_lens, ctx.max_query_len, ctx.max_seq_len) = (
ctx.build_block_table(action_len=0, query_len=BLOCK, device=device)
)
block_table, max_seq_len = ctx.block_table, ctx.max_seq_len
ctx._prepare_history_staging(0)
n_blocks = max_seq_len // BLOCK
block_ids = block_table[0, :n_blocks].to(torch.long)
stage_k, stage_v = ctx.history_staging(0)
paged_attention_module._stage_window(
stage_k,
stage_v,
key_cache,
value_cache,
block_ids,
n_blocks,
BLOCK,
first_block=ctx.stage_first_block if ctx.reuse_history else 0,
)
full_k = key_cache.index_select(0, block_ids).reshape(n_blocks * BLOCK, N_HEADS, HEAD_DIM)
full_v = value_cache.index_select(0, block_ids).reshape(n_blocks * BLOCK, N_HEADS, HEAD_DIM)
return stage_k, stage_v, full_k, full_v, n_blocks
stage_k, stage_v, full_k, full_v, n_blocks = probe(1)
assert ctx.reuse_history is False
assert torch.equal(stage_k, full_k) and torch.equal(stage_v, full_v)
stage_k, stage_v, full_k, full_v, n_blocks = probe(2)
assert ctx.reuse_history is True
visible_history_blocks = min(history_chunks, 2 - 1) # window of 2 blocks minus the current one
assert ctx.stage_first_block == visible_history_blocks
# The padded table is wider than the live window, so the end-of-table guess is not the offset.
assert n_blocks - 1 != ctx.stage_first_block
assert torch.equal(stage_k, full_k) and torch.equal(stage_v, full_v)
@pytest.mark.parametrize("gather_enabled", [False, True])
def test_staging_is_only_allocated_for_the_gather_path(monkeypatch, gather_enabled):
if gather_enabled:
monkeypatch.setenv(KV_GATHER_ENV, "1")
else:
monkeypatch.delenv(KV_GATHER_ENV, raising=False)
device = torch.device("cpu")
kv, st = make_state(device=device, reuse_history_staging=True)
# The manager owns the pairs and allocates them only when their consumer is on.
assert bool(kv.history_staging) is gather_enabled
ctx = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=False)[0].forward_ctx
ctx.ensure_video_slots(device)
(ctx.block_table, ctx.query_start_loc, ctx.seq_lens, ctx.max_query_len, ctx.max_seq_len) = ctx.build_block_table(
action_len=0, query_len=BLOCK, device=device
)
ctx._prepare_history_staging(0)
assert ctx.staging_enabled is gather_enabled
stage_k, _ = ctx.history_staging(0)
assert (stage_k is not None) is gather_enabled
@pytest.mark.skipif(not _gpu_flash_attn_usable(), reason="usable GPU FlashAttention is required")
@pytest.mark.parametrize("history_chunks", [1, 3])
@pytest.mark.parametrize("action_len", [0, 3])
@@ -376,13 +463,27 @@ def test_custom_op_registration_idempotent():
assert hasattr(torch.ops.vllm_omni, "ar_diffusion_paged_write_attn")
def test_custom_op_compiles_fullgraph_without_recompile_on_value_change():
def test_custom_op_mutable_arguments_cannot_be_elided_as_defaults():
# Older PyTorch ADInplaceOrView handlers index positional mutable inputs
# directly. Default-valued trailing inputs can disappear before that handler.
schema = torch.ops.vllm_omni.ar_diffusion_paged_write_attn.default._schema
mutable = [arg for arg in schema.arguments if arg.alias_info is not None and arg.alias_info.is_write]
assert {arg.name for arg in mutable} == {"key_pool", "value_pool", "stage_key", "stage_value"}
assert all(not arg.has_default_value() for arg in mutable)
@pytest.mark.parametrize("reuse_history_staging", [False, True])
def test_custom_op_compiles_fullgraph_without_recompile_on_value_change(monkeypatch, reuse_history_staging):
"""The op must trace as one opaque node: fullgraph OK, and changed tensor
VALUES (new slots / block ids) must not trigger recompilation."""
import torch._dynamo
device = torch.device("cpu")
kv, st = make_state(num_layers=2, window_chunks=2)
monkeypatch.setenv(KV_GATHER_ENV, "1")
kv, st = make_state(num_layers=2, window_chunks=2, reuse_history_staging=reuse_history_staging)
if reuse_history_staging:
# Hold the host-side staging offset fixed while table/slot values change.
_commit_video_span(kv, st, kv_branch=POS, n_chunks=2, dtype=torch.float32, device=device)
def run_one_forward(commit):
contexts = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=commit)
@@ -391,9 +492,8 @@ def test_custom_op_compiles_fullgraph_without_recompile_on_value_change():
q = torch.randn(BLOCK, N_HEADS, HEAD_DIM)
k = torch.randn(BLOCK, N_HEADS, HEAD_DIM)
v = torch.randn(BLOCK, N_HEADS, HEAD_DIM)
# Both layers through ONE compiled fn: layer_idx is a tensor, so a
# different layer must NOT recompile (all 40 DiT blocks share the
# block-forward code object in production).
# Both layers use one compiled function; the tensor-valued layer index
# must not specialize it.
for layer_ctx in contexts:
out = compiled(layer_ctx.to_layer_inputs(), q, k, v)
st.commit_paged_context(POS)
@@ -419,3 +519,52 @@ def test_custom_op_compiles_fullgraph_without_recompile_on_value_change():
# Leave a clean dynamo state for later suites in the same pytest process
# (e.g. model_executor transformers models).
torch._dynamo.reset()
@pytest.mark.skipif(not _gpu_flash_attn_usable(), reason="usable GPU FlashAttention is required")
@pytest.mark.parametrize("history_chunks", [0, 1, 3])
@pytest.mark.parametrize("action_len", [0, 3])
def test_contiguous_kv_gather_path_matches_paged_path_gpu(monkeypatch, history_chunks, action_len):
"""VLLM_OMNI_AR_DIFFUSION_KV_GATHER=1 gathers the visible blocks and runs varlen FA3 without a block table.
Covers an empty, partial and full window plus a partially filled action block:
the gather reads the tail-padding null block, so its (zeroed) rows must be masked.
"""
torch.manual_seed(0)
device = torch.device("cuda")
dtype = torch.float16
kv, st = make_state(dtype=dtype, device=device, window_chunks=2)
if history_chunks:
_commit_video_span(kv, st, kv_branch=POS, n_chunks=history_chunks, dtype=dtype, device=device)
layer_ctx = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=False)[0]
ctx = layer_ctx.forward_ctx
current_k = torch.randn(1, BLOCK, N_HEADS, HEAD_DIM, dtype=dtype, device=device)
current_v = torch.randn(1, BLOCK, N_HEADS, HEAD_DIM, dtype=dtype, device=device)
action_k = action_v = None
if action_len:
action_k = torch.randn(1, action_len, N_HEADS, HEAD_DIM, dtype=dtype, device=device)
action_v = torch.randn(1, action_len, N_HEADS, HEAD_DIM, dtype=dtype, device=device)
query = torch.randn(1, BLOCK + action_len, N_HEADS, HEAD_DIM, dtype=dtype, device=device)
ctx.prepare(device=device, action_len=action_len, query_len=query.shape[1])
inputs = layer_ctx.to_layer_inputs()
def run() -> torch.Tensor:
return paged_write_attn(
inputs,
query[0],
current_k[0],
current_v[0],
action_k[0] if action_len else None,
action_v[0] if action_len else None,
HEAD_DIM**-0.5,
).unsqueeze(0)
monkeypatch.delenv(KV_GATHER_ENV, raising=False)
paged = run()
monkeypatch.setenv(KV_GATHER_ENV, "1")
gathered = run()
assert torch.isfinite(gathered).all()
# Same kernel family on the same K/V: only accumulation order differs.
torch.testing.assert_close(gathered, paged, rtol=2e-3, atol=2e-3)
@@ -0,0 +1,361 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Streaming VAE decode against the real Wan autoencoder, on CPU.
The autoencoder is built from a config rather than a checkpoint -- weights are
random, only shapes and the temporal cache protocol matter -- so these run
without a device or a download.
The load-bearing test is equivalence: decoding a session chunk by chunk must
produce exactly what decoding the whole clip produces. Everything else about
streaming is worthless if that does not hold.
"""
from __future__ import annotations
from contextlib import contextmanager
import pytest
import torch
from vllm_omni.experimental.ar_diffusion.streaming_decode import (
StreamingDecodeState,
SupportsStreamingDecode,
WanStreamingDecoder,
)
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
# Small enough to decode on CPU in a test, same architecture as the shipped
# checkpoint: base_dim 96 / dim_mult [1,2,4,4] would be far too slow, so the
# widths are scaled down while the causal structure is unchanged.
VAE_CONFIG = {
"base_dim": 8,
"z_dim": 4,
"dim_mult": [1, 2],
"num_res_blocks": 1,
"temperal_downsample": [True],
"attn_scales": [],
"dropout": 0.0,
}
LATENT_H = LATENT_W = 4
@pytest.fixture(scope="module")
def vae():
diffusers = pytest.importorskip("diffusers")
torch.manual_seed(0)
model = diffusers.AutoencoderKLWan(**VAE_CONFIG).eval()
for parameter in model.parameters():
parameter.requires_grad_(False)
return model
@pytest.fixture(scope="module")
def decoder(vae):
return WanStreamingDecoder(vae)
def _latent(num_frames: int, *, seed: int = 0) -> torch.Tensor:
generator = torch.Generator().manual_seed(seed)
return torch.randn(1, VAE_CONFIG["z_dim"], num_frames, LATENT_H, LATENT_W, generator=generator)
@torch.no_grad()
def _decode_whole(vae, latent: torch.Tensor) -> torch.Tensor:
"""The non-streaming reference: one call, cache cleared at both ends."""
return vae._decode(latent, return_dict=False)[0]
# --------------------------------------------------------------------------
# Equivalence: the property that makes streaming worth doing at all
# --------------------------------------------------------------------------
def _stream(decoder, latent: torch.Tensor, chunk_sizes, *, session_id: str = "s") -> torch.Tensor:
state = decoder.new_decode_state(session_id)
pieces, offset = [], 0
for size in chunk_sizes:
pieces.append(decoder.decode_chunk(latent[:, :, offset : offset + size], state))
offset += size
return torch.cat(pieces, dim=2)
@torch.no_grad()
@pytest.mark.parametrize("chunk_sizes", [(3, 3, 3), (1, 1, 1, 1, 1), (2, 4, 3)])
def test_chunking_is_neutral(vae, decoder, chunk_sizes) -> None:
"""Splitting a session into chunks must change nothing about its output.
This is the property streaming actually introduces, so it is the one
asserted exactly. The control is the same session decoded in a single
call through the same code path -- not ``_decode`` -- because ``_decode``
differs in a way that has nothing to do with chunking; see
``test_distance_from_the_one_shot_path_is_a_post_quant_conv_artifact``.
"""
total = sum(chunk_sizes)
latent = _latent(total)
reference = _stream(decoder, latent, (total,), session_id="ref")
streamed = _stream(decoder, latent, chunk_sizes)
assert streamed.shape == reference.shape
torch.testing.assert_close(streamed, reference, rtol=0, atol=0)
@torch.no_grad()
def test_distance_from_the_one_shot_path_is_a_post_quant_conv_artifact(vae, decoder) -> None:
"""Explain, and bound, the gap against diffusers' ``_decode``.
``_decode`` applies ``post_quant_conv`` to the whole latent at once; the
tiled path in this repo, and this decoder, apply it per frame. It is a
1x1x1 convolution, so the two are mathematically identical -- but they can
select different kernels, and on bf16 CUDA that difference is real and is
amplified by the causal convolutions downstream.
Asserting equality with ``_decode`` would therefore pin a kernel-selection
coincidence rather than a property of streaming. Assert instead that the
gap is entirely explained by where ``post_quant_conv`` runs.
"""
latent = _latent(6)
per_frame_pq = torch.cat([vae.post_quant_conv(latent[:, :, k : k + 1]) for k in range(latent.shape[2])], dim=2)
whole_pq = vae.post_quant_conv(latent)
streamed = _stream(decoder, latent, (3, 3))
one_shot = _decode_whole(vae, latent)
# Same inputs to the decoder => same output, whatever the backend does.
if torch.equal(whole_pq, per_frame_pq):
torch.testing.assert_close(streamed, one_shot, rtol=0, atol=0)
else: # pragma: no cover - backend dependent
pytest.skip("backend batches post_quant_conv differently; the gap is that, not chunking")
@torch.no_grad()
def test_a_restarted_stream_does_not_match_a_continued_one(decoder) -> None:
"""Negative control: the equivalence test above must be discriminating.
Clearing state between chunks -- what the non-streaming path does on every
call -- has to change the pixels, otherwise the temporal cache carries
nothing and the assertion above holds for a write-only cache too.
Restarting also changes the frame count, because a fresh state expands its
opening latent frame to one raw frame. Comparing totals would therefore
pass on the frame count alone and never look at a pixel, so this compares
the tail both runs agree on: the frames from the chunk's later latents,
which are the full temporal factor wide on either side.
"""
latent = _latent(6)
state = decoder.new_decode_state("continued")
decoder.decode_chunk(latent[:, :, :3], state)
continued = decoder.decode_chunk(latent[:, :, 3:], state)
restarted = decoder.decode_chunk(latent[:, :, 3:], decoder.new_decode_state("restarted"))
tail = min(continued.shape[2], restarted.shape[2]) - 1
assert tail > 0, "the comparison needs at least one fully expanded frame on both sides"
continued_tail, restarted_tail = continued[:, :, -tail:], restarted[:, :, -tail:]
assert continued_tail.shape == restarted_tail.shape, "the tails must be comparable for this to mean anything"
assert not torch.equal(continued_tail, restarted_tail), (
"restarting the decoder produced the same pixels as continuing it, so the carried cache is not being read"
)
# --------------------------------------------------------------------------
# Cross-session isolation: the failure that timing metrics cannot see
# --------------------------------------------------------------------------
@torch.no_grad()
@pytest.mark.parametrize("seed_a, seed_b", [(1, 2), (11, 12)])
def test_interleaved_sessions_keep_independent_temporal_context(vae, decoder, seed_a: int, seed_b: int) -> None:
"""Two sessions ticking alternately must each match their solo decode.
A session that reads another's temporal cache produces a perfectly
plausible but wrong video, and every latency metric stays green, so this
has to be asserted against a recorded solo run rather than inferred. The
control is a solo stream rather than ``_decode``, so it differs from the
run under test only in the interleaving.
"""
latent_a = _latent(6, seed=seed_a)
latent_b = _latent(6, seed=seed_b)
solo_a = _stream(decoder, latent_a, (6,), session_id="solo-a")
solo_b = _stream(decoder, latent_b, (6,), session_id="solo-b")
assert not torch.equal(solo_a, solo_b), "negative control: the two sessions must differ"
state_a = decoder.new_decode_state("a")
state_b = decoder.new_decode_state("b")
out_a, out_b = [], []
for start in (0, 3):
window = slice(start, start + 3)
out_a.append(decoder.decode_chunk(latent_a[:, :, window], state_a))
out_b.append(decoder.decode_chunk(latent_b[:, :, window], state_b))
torch.testing.assert_close(torch.cat(out_a, dim=2), solo_a, rtol=0, atol=0)
torch.testing.assert_close(torch.cat(out_b, dim=2), solo_b, rtol=0, atol=0)
@torch.no_grad()
def test_the_module_cache_is_untouched_so_sessions_can_share_one_decoder(vae, decoder) -> None:
vae.clear_cache()
before = [entry for entry in vae._feat_map]
decoder.decode_chunk(_latent(3), decoder.new_decode_state("s"))
assert vae._feat_map == before, "streaming decode must not write the module-owned cache"
# --------------------------------------------------------------------------
# Causal geometry and boundedness
# --------------------------------------------------------------------------
@torch.no_grad()
def test_opening_chunk_is_shorter_and_later_chunks_are_full_length(vae, decoder) -> None:
"""(n - 1) * factor + 1 for the opening chunk, n * factor after it."""
factor = 2 ** sum(VAE_CONFIG["temperal_downsample"])
state = decoder.new_decode_state("s")
first = decoder.decode_chunk(_latent(3), state)
second = decoder.decode_chunk(_latent(3, seed=5), state)
assert first.shape[2] == (3 - 1) * factor + 1
assert second.shape[2] == 3 * factor
assert state.chunks_decoded == 2
assert state.frames_decoded == 6
@torch.no_grad()
def test_resident_state_does_not_grow_with_session_length(vae, decoder) -> None:
"""Each causal convolution retains at most CACHE_T temporal slices."""
state = decoder.new_decode_state("s")
decoder.decode_chunk(_latent(3), state)
baseline = state.nbytes()
assert baseline > 0
for step in range(8):
decoder.decode_chunk(_latent(3, seed=step + 10), state)
assert state.nbytes() == baseline
assert sum(state.nbytes_by_device().values()) == baseline
@torch.no_grad()
def test_release_returns_the_session_to_its_pre_stream_state(vae, decoder) -> None:
state = decoder.new_decode_state("s")
decoder.decode_chunk(_latent(3), state)
assert state.started and state.nbytes() > 0
decoder.release(state)
assert state.nbytes() == 0
assert not state.started
assert state.chunks_decoded == 0
# A released session restarts rather than resumes, so its first chunk is
# short again -- the same semantics reset() has for AR KV.
factor = 2 ** sum(VAE_CONFIG["temperal_downsample"])
assert decoder.decode_chunk(_latent(3), state).shape[2] == (3 - 1) * factor + 1
# --------------------------------------------------------------------------
# Contract
# --------------------------------------------------------------------------
def test_the_vaes_execution_context_is_entered_for_every_frame(vae) -> None:
"""Decode must run inside the autoencoder's own execution context.
Every public compute entry point on ``OmniAutoencoderKLWan`` enters
``_execution_context()``, which is where autocast is established for
fp16/bf16 parameters -- and on NPU the only place it is established at all.
Driving ``post_quant_conv`` and ``decoder`` directly bypasses it unless this
decoder enters it itself, which would compute streamed chunks under a
different numeric context from the whole-clip decode they are compared to.
"""
entered: list[str] = []
class _ContextualVAE:
"""The parts of the contract this decoder uses, plus the hook."""
config = vae.config
dtype = torch.float32
def __init__(self) -> None:
self.decoder = vae.decoder
self.post_quant_conv = vae.post_quant_conv
self._cached_conv_counts = vae._cached_conv_counts
@contextmanager
def _execution_context(self):
entered.append("enter")
try:
yield
finally:
entered.append("exit")
decoder = WanStreamingDecoder(_ContextualVAE())
with torch.no_grad():
decoder.decode_chunk(_latent(3), decoder.new_decode_state("s"))
# One context for the call, not one per frame, and it closes.
assert entered == ["enter", "exit"]
def test_a_plain_diffusers_autoencoder_needs_no_execution_context(decoder) -> None:
"""The hook is optional: a VAE without one still decodes."""
with torch.no_grad():
out = decoder.decode_chunk(_latent(1), decoder.new_decode_state("s"))
assert out.shape[2] == 1
def test_wan_decoder_satisfies_the_protocol(decoder) -> None:
assert isinstance(decoder, SupportsStreamingDecode)
def test_state_from_another_decoder_is_rejected(decoder) -> None:
foreign = StreamingDecodeState(session_id="s", feat_map=[None])
with pytest.raises(ValueError, match="does not belong to this decoder"):
decoder.decode_chunk(_latent(1), foreign)
def test_a_non_wan_module_is_rejected() -> None:
with pytest.raises(TypeError, match="Wan-family autoencoder"):
WanStreamingDecoder(object())
def test_empty_and_malformed_latents_are_rejected(decoder) -> None:
state = decoder.new_decode_state("s")
with pytest.raises(ValueError, match=r"\[B, C, T, H, W\]"):
decoder.decode_chunk(torch.zeros(1, 4, 4, 4), state)
with pytest.raises(ValueError, match="at least one frame"):
decoder.decode_chunk(torch.zeros(1, 4, 0, LATENT_H, LATENT_W), state)
def test_a_batch_is_refused_rather_than_threaded_through_one_cache(decoder) -> None:
"""One state is one session, so a batch has no correct interpretation here.
``AutoencoderKLWan.decode`` handles a batch by decoding each sample with
its own cleared cache (``use_slicing``). This decoder carries exactly one
temporal context, so a batch would mix samples into it and still return
correctly shaped pixels.
"""
state = decoder.new_decode_state("s")
batched = torch.zeros(2, VAE_CONFIG["z_dim"], 3, LATENT_H, LATENT_W)
with pytest.raises(ValueError, match="one sample per session state"):
decoder.decode_chunk(batched, state)
assert state.frames_decoded == 0, "a refused call must not advance the session"
def test_session_id_must_be_meaningful(decoder) -> None:
with pytest.raises(ValueError, match="session_id"):
decoder.new_decode_state(" ")
def test_declared_state_bytes_scales_with_area_and_dtype(vae) -> None:
# A local decoder, not the module-scoped fixture: the measured constant
# belongs to this test, and leaking it would change what a reordered run
# of the default-None case sees. Passing it here is also the constructor
# argument's intended use.
# Measured for the shipped checkpoint: 37832 KiB of fp32 cache at 64x64.
decoder = WanStreamingDecoder(vae, bytes_per_pixel_fp32=37832 * 1024 / (64 * 64))
fp32 = decoder.declared_state_bytes(height=480, width=832, dtype=torch.float32)
bf16 = decoder.declared_state_bytes(height=480, width=832, dtype=torch.bfloat16)
half_area = decoder.declared_state_bytes(height=240, width=832, dtype=torch.float32)
assert bf16 == fp32 // 2
assert half_area == fp32 // 2
assert fp32 / 2**20 == pytest.approx(3602.0, abs=5.0)
@@ -10,6 +10,7 @@ Tests cover:
- AttentionMetadata.extra field
"""
from dataclasses import replace
from types import SimpleNamespace
from unittest.mock import Mock
@@ -17,7 +18,12 @@ import pytest
import torch
import vllm_omni.diffusion.attention.layer as layer_mod
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
import vllm_omni.diffusion.attention.selector as selector_mod
from vllm_omni.diffusion.attention.backends.abstract import (
AttentionMetadata,
PackedPaddingMetadata,
QueryRange,
)
from vllm_omni.diffusion.attention.backends.flash_attn import FlashAttentionBackend
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.config import (
@@ -477,6 +483,7 @@ class TestAttentionInitUsesCurrentDiffusionConfig:
@pytest.mark.parametrize("mindiesd_available", [False, True])
def test_paged_npu_memory_profile_uses_sdpa_only_without_mindiesd(self, monkeypatch, mindiesd_available):
attention = Attention.__new__(Attention)
attention.allow_fp32_fallback = False
attention._scheduler_paged_kv = True
attention.paged_kv_cache_role = "primary"
attention.backend_pref = "FLASH_ATTN"
@@ -519,6 +526,7 @@ class TestAttentionInitUsesCurrentDiffusionConfig:
@pytest.mark.parametrize("fa4_available", [False, True])
def test_paged_cuda_memory_profile_uses_sdpa_without_dense_fa4(self, monkeypatch, fa4_available):
attention = Attention.__new__(Attention)
attention.allow_fp32_fallback = False
attention._scheduler_paged_kv = True
attention.paged_kv_cache_role = "primary"
attention.backend_pref = "FLASH_ATTN"
@@ -561,6 +569,7 @@ class TestAttentionInitUsesCurrentDiffusionConfig:
def test_dense_flash_import_error_is_not_reclassified(self, monkeypatch):
attention = Attention.__new__(Attention)
attention.allow_fp32_fallback = False
attention._scheduler_paged_kv = False
attention.paged_kv_cache_role = "primary"
attention.backend_pref = "FLASH_ATTN"
@@ -900,6 +909,7 @@ class TestAttentionInitUsesCurrentDiffusionConfig:
return sentinel
fake_attention = SimpleNamespace(
allow_fp32_fallback=False,
attention=SimpleNamespace(
forward=_selected_forward,
),
@@ -938,6 +948,164 @@ class TestAttentionInitUsesCurrentDiffusionConfig:
Attention._run_ring_attention(fake_attention, query, query, query, metadata)
class TestOptInFloat32Fallback:
@staticmethod
def _make_attention(monkeypatch, *, backend=None, allow=True, kv_cache_dtype=None):
events, state = [], {}
context = object()
class _SelectedImpl:
def __init__(self, **kwargs):
self.kwargs = kwargs
@staticmethod
def supports_kv_cache_dtype(*args):
return True
def forward(self, query, key, value, metadata):
events.append("selected")
state["kernel_call"] = (query, key, value, metadata)
state["kernel_output"] = query + 4
return state["kernel_output"]
class _FallbackImpl(_SelectedImpl):
def forward(self, query, key, value, metadata):
output = super().forward(query, key, value, metadata)
events[-1] = "fallback"
return output
class _FlashBackend(FlashAttentionBackend):
@staticmethod
def get_impl_cls():
return _SelectedImpl
class _SDPABackend(layer_mod.SDPABackend):
@staticmethod
def get_impl_cls():
return _SelectedImpl
class _Strategy:
def pre_attention(self, query, key, value, metadata):
events.append("pre")
state["prepared"] = (
query + 1,
key + 2,
value + 3,
replace(metadata) if metadata is not None else None,
)
return (*state["prepared"], context)
def post_attention(self, output, ctx):
events.append("post")
assert output is state["kernel_output"]
assert ctx is context
return output + 7
# Keep real role/config resolution and construction; replace hardware
# lookup and kernels. These are CPU dispatch tests, not SP collectives.
monkeypatch.setattr(
selector_mod,
"_cached_get_backend_cls",
lambda name, *args, **kwargs: _SDPABackend if name == "TORCH_SDPA" else _FlashBackend,
)
monkeypatch.setattr(layer_mod.SDPABackend, "get_impl_cls", staticmethod(lambda: _FallbackImpl))
monkeypatch.setattr(layer_mod, "build_parallel_attention_strategy", lambda **kwargs: _Strategy())
monkeypatch.setattr(layer_mod, "is_forward_context_available", lambda: False)
config = OmniDiffusionConfig(
diffusion_attention_config={"default": backend} if backend else {},
diffusion_kv_cache_dtype=kv_cache_dtype,
)
with set_current_diffusion_config(config):
attention = Attention(
num_heads=4,
num_kv_heads=2,
head_size=8,
causal=False,
softmax_scale=0.25,
**({"allow_fp32_fallback": True} if allow else {}),
)
return attention, events, state
@pytest.mark.parametrize(
"backend,allow,dtype,is_cuda,expected",
[
pytest.param(None, True, torch.float32, True, "fallback", id="auto-fp32"),
pytest.param(None, False, torch.float32, True, "selected", id="default-opt-out"),
pytest.param("FLASH_ATTN", True, torch.float32, True, "selected", id="explicit-flash"),
pytest.param("TORCH_SDPA", True, torch.float32, True, "selected", id="explicit-sdpa"),
pytest.param(None, True, torch.bfloat16, True, "selected", id="bf16"),
pytest.param(None, True, torch.float32, False, "selected", id="cpu-fp32"),
],
)
def test_public_forward_preserves_strategy_and_backend_choice(
self, monkeypatch, backend, allow, dtype, is_cuda, expected
):
attention, events, state = self._make_attention(monkeypatch, backend=backend, allow=allow)
# Only the dispatch predicate is simulated; every tensor stays on CPU.
monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: is_cuda))
query = torch.ones(1, 2, 4, 8, dtype=dtype)
key = torch.full((1, 2, 2, 8), 2, dtype=dtype)
value = torch.full_like(key, 3)
metadata = AttentionMetadata(attn_mask=torch.tensor([[True, False]]))
output = attention(query, key, value, metadata)
assert events == ["pre", expected, "post"]
assert all(got is prepared for got, prepared in zip(state["kernel_call"], state["prepared"]))
assert state["kernel_call"][3] is not metadata
assert state["kernel_call"][3].attn_mask is metadata.attn_mask
torch.testing.assert_close(output, query + 12)
assert attention.backend_explicit is (backend is not None)
impl = attention.sdpa_fallback if expected == "fallback" else attention.attention
assert impl.kwargs["num_kv_heads"] == 2
assert impl.kwargs["softmax_scale"] == 0.25
def test_explicit_backend_failure_is_not_retried_with_sdpa(self, monkeypatch):
attention, events, _ = self._make_attention(monkeypatch, backend="FLASH_ATTN")
monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
selected = Mock(side_effect=RuntimeError("selected backend rejects this dtype"))
monkeypatch.setattr(attention.attention, "forward", selected)
query = torch.ones(1, 2, 4, 8)
with pytest.raises(RuntimeError, match="selected backend rejects this dtype"):
attention(query, query, query)
selected.assert_called_once()
assert events == ["pre"]
@pytest.mark.parametrize("contract", ["packed", "packed-padding", "piecewise", "quantized-kv"])
def test_backend_metadata_is_not_silently_sent_to_dense_sdpa(self, monkeypatch, contract):
quant_dtype = "fp8" if contract == "quantized-kv" else None
attention, events, state = self._make_attention(monkeypatch, kv_cache_dtype=quant_dtype)
monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
lengths = torch.tensor([0, 1, 2], dtype=torch.int32)
metadata = AttentionMetadata()
if contract == "packed":
metadata.extra = {
"cu_seqlens_q": lengths,
"cu_seqlens_k": lengths,
"max_seqlen_q": 1,
"max_seqlen_k": 1,
}
elif contract == "packed-padding":
metadata.packed_padding = PackedPaddingMetadata(1, 1, lengths[:2], lengths[:2])
elif contract == "piecewise":
metadata.full_attn_spans = [[(0, 1)]]
metadata.query_ranges = (QueryRange(0, 2, 0),)
query = torch.ones(1, 2, 4, 8)
attention(query, query, query, metadata)
assert events == ["pre", "selected", "post"]
forwarded = state["kernel_call"][3]
if quant_dtype:
# Quantization is injected by the public forward from config.
assert forwarded.extra == {"kv_cache_dtype": "fp8"}
assert metadata.extra == {}
else:
assert forwarded is state["prepared"][3]
class TestDiffusionKvCacheQuantization:
@staticmethod
def _install_attention_init_stubs(monkeypatch, *, supports_kv_cache_dtype=True):
@@ -0,0 +1,126 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import sys
import types
import pytest
import torch
from torch._subclasses.fake_tensor import FakeTensorMode
from vllm_omni.diffusion.attention.ops.block_sparse import (
build_prefix_dense_block_map,
fastvideo_block_sparse_attn_bshd,
mean_pool_tiles,
)
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
@pytest.mark.parametrize("prefix_blocks,topk", [(0, 1), (2, 0), (2, 1), (2, 3), (2, 5)])
def test_block_map_keeps_prefix_dense_and_selects_non_prefix_keys(prefix_blocks, topk):
sparse_blocks = 3
blocks = prefix_blocks + sparse_blocks
scores = torch.arange(2 * blocks * blocks, dtype=torch.float32).reshape(1, 2, blocks, blocks)
block_map = build_prefix_dense_block_map(scores, prefix_blocks, sparse_blocks, topk)
expected = torch.zeros_like(scores, dtype=torch.bool)
# Scores increase with key index, so top-k always selects the last keys.
for query_block in range(blocks):
for key_block in range(blocks):
if (
query_block < prefix_blocks
or key_block < prefix_blocks
or key_block >= blocks - min(topk, sparse_blocks)
):
expected[..., query_block, key_block] = True
assert torch.equal(block_map, expected)
@pytest.mark.parametrize("block_size", [4, 32, 64])
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
def test_pooling_uses_valid_tile_sizes_and_fp32_accumulation(block_size, dtype):
sizes = torch.tensor([block_size, block_size - 1, 0], dtype=torch.int32)
tiles = torch.arange(2 * 3 * block_size * 2 * 3).reshape(2, 3, block_size, 2, 3).to(dtype)
tiles[:, 1, -1] = 0
tiles[:, 2] = 0
expected = torch.stack(
[tiles[:, 0].float().mean(dim=1), tiles[:, 1, :-1].float().mean(dim=1), torch.zeros(2, 2, 3)], dim=2
)
result = mean_pool_tiles(tiles.flatten(1, 2), sizes, block_size)
assert result.dtype == torch.float32
torch.testing.assert_close(result, expected, rtol=0, atol=0)
def test_provider_wrapper_restores_transport_rows_and_bshd_layout(monkeypatch):
monkeypatch.delenv("FASTVIDEO_VSA_SM100A", raising=False)
calls = []
def block_sparse_attn(q, k, v, block_map, sizes):
calls.append((q.shape, block_map.shape, sizes.tolist()))
assert q.is_contiguous() and k.is_contiguous() and v.is_contiguous()
assert sizes.dtype == torch.int32
return q + k + v, None
module = types.ModuleType("fastvideo_kernel.block_sparse_attn")
setattr(module, "block_sparse_attn", block_sparse_attn)
monkeypatch.setitem(sys.modules, "fastvideo_kernel", types.ModuleType("fastvideo_kernel"))
monkeypatch.setitem(sys.modules, "fastvideo_kernel.block_sparse_attn", module)
query = torch.randn(1, 4 * 64, 2, 8)
block_map = torch.ones(1, 2, 4, 4, dtype=torch.bool)
sizes = torch.tensor([64, 17, 64, 0])
output = fastvideo_block_sparse_attn_bshd(query, query, query, block_map, sizes, 3)
expected = torch.zeros_like(query)
expected[:, : 3 * 64] = query[:, : 3 * 64] * 3
torch.testing.assert_close(output, expected)
assert calls == [(torch.Size([1, 2, 3 * 64, 8]), torch.Size([1, 2, 3, 3]), [64, 17, 64])]
def test_custom_op_fake_preserves_metadata_without_loading_provider(monkeypatch):
monkeypatch.setitem(sys.modules, "fastvideo_kernel", None)
with FakeTensorMode():
query = torch.empty(1, 4 * 64, 2, 8, dtype=torch.bfloat16)
block_map = torch.empty(1, 2, 4, 4, dtype=torch.bool)
sizes = torch.empty(4, dtype=torch.int32)
output = fastvideo_block_sparse_attn_bshd(query, query, query, block_map, sizes, 3)
assert output.shape == query.shape
assert output.dtype == query.dtype
assert output.device == query.device
@pytest.mark.parametrize("error_type", [ImportError, RuntimeError, torch.AcceleratorError])
def test_native_provider_failure_only_recovers_without_accelerator_fault(monkeypatch, mocker, error_type):
monkeypatch.setenv("FASTVIDEO_VSA_SM100A", "1")
error = error_type("native provider failure")
native = mocker.Mock()
native.is_supported.return_value = True
native.block_sparse_attn_sm100a.side_effect = error
provider = types.ModuleType("fastvideo_kernel")
setattr(provider, "block_sparse_attn_sm100a", native)
index = types.ModuleType("fastvideo_kernel.triton_kernels.index")
setattr(
index,
"map_to_index",
mocker.Mock(return_value=(torch.zeros(1, dtype=torch.int32), torch.ones(1, dtype=torch.int32))),
)
triton = types.ModuleType("fastvideo_kernel.block_sparse_attn")
fallback = mocker.Mock(side_effect=lambda q, *args: (q.clone(), None))
setattr(triton, "block_sparse_attn", fallback)
monkeypatch.setitem(sys.modules, "fastvideo_kernel", provider)
monkeypatch.setitem(
sys.modules, "fastvideo_kernel.triton_kernels", types.ModuleType("fastvideo_kernel.triton_kernels")
)
monkeypatch.setitem(sys.modules, "fastvideo_kernel.triton_kernels.index", index)
monkeypatch.setitem(sys.modules, "fastvideo_kernel.block_sparse_attn", triton)
query = torch.arange(128 * 2 * 8, dtype=torch.float32).reshape(1, 128, 2, 8)
block_map = torch.ones(1, 2, 2, 2, dtype=torch.bool)
sizes = torch.tensor([64, 64], dtype=torch.int32)
if error_type is torch.AcceleratorError:
with pytest.raises(torch.AcceleratorError, match="native provider failure") as raised:
fastvideo_block_sparse_attn_bshd(query, query, query, block_map, sizes, 2)
assert raised.value is error
fallback.assert_not_called()
else:
output = fastvideo_block_sparse_attn_bshd(query, query, query, block_map, sizes, 2)
torch.testing.assert_close(output, query, rtol=0, atol=0)
fallback.assert_called_once()
+3 -161
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import math
import sys
import types
from typing import Any
@@ -12,14 +11,10 @@ import torch
from vllm_omni.diffusion.attention.backends.abstract import (
AttentionMetadata,
PackedPaddingMetadata,
VideoTokenLayout,
VideoTokenSpan,
)
from vllm_omni.diffusion.attention.backends.fastvideo_vsa import (
FastVideoVSABackend,
FastVideoVSAImpl,
_build_h3_block_map,
_get_h3_tile_metadata,
)
from vllm_omni.diffusion.attention.backends.registry import (
DiffusionAttentionBackendEnum,
@@ -218,144 +213,8 @@ def test_fastvideo_vsa_allows_topk_equal_to_num_blocks():
assert too_many._fallback_reason(query, query, query, metadata) == "topk 3 > num_blocks 2"
def _h3_metadata(prefix_segments, video_shape, *, gate=None, packed_padding=None):
extra: dict[str, Any] = {
"vsa_h3_prefix_segments": prefix_segments,
}
if gate is not None:
extra["gate_compress"] = gate
return AttentionMetadata(
packed_padding=packed_padding,
video_layout=VideoTokenLayout(
used_len=sum(prefix_segments) + math.prod(video_shape),
video_spans=(VideoTokenSpan(start=sum(prefix_segments), latent_grid=video_shape, role="target"),),
),
extra=extra,
)
def _fake_block_sparse_kernel(monkeypatch, calls):
"""Stand in for fastvideo_kernel.block_sparse_attn with a mask-obeying SDPA."""
def block_sparse_attn(q, k, v, block_map, variable_block_sizes):
calls["block_map"] = block_map.clone()
calls["variable_block_sizes"] = variable_block_sizes.tolist()
calls["q_shape"] = tuple(q.shape)
blocks = block_map.shape[-1]
assert blocks * 64 == q.shape[2]
# Expand the per-block map to a per-token mask so the stand-in honours
# the sparsity contract the real kernel implements, and drop the rows
# each partial block pads with, which the real kernel skips through
# variable_block_sizes.
token_mask = block_map.repeat_interleave(64, dim=-1).repeat_interleave(64, dim=-2)
within = torch.arange(64, device=q.device)[None, :] < variable_block_sizes[:, None]
token_mask = token_mask & within.reshape(1, 1, 1, -1)
out = torch.nn.functional.scaled_dot_product_attention(q.float(), k.float(), v.float(), attn_mask=token_mask)
return out.to(q.dtype), None
module = types.ModuleType("fastvideo_kernel.block_sparse_attn")
setattr(module, "block_sparse_attn", block_sparse_attn)
monkeypatch.setitem(sys.modules, "fastvideo_kernel", types.ModuleType("fastvideo_kernel"))
monkeypatch.setitem(sys.modules, "fastvideo_kernel.block_sparse_attn", module)
def _h3_impl(**backend_kwargs):
kwargs = {"topk": 1, "min_seq_len": 1, "disable_when_sp_active": False}
kwargs.update(backend_kwargs)
return FastVideoVSAImpl(num_heads=2, head_size=8, softmax_scale=8**-0.5, backend_kwargs=kwargs)
def test_h3_forward_tiles_untiles_and_restores_the_original_row_order(monkeypatch):
calls: dict[str, Any] = {}
_fake_block_sparse_kernel(monkeypatch, calls)
impl = _h3_impl(topk=64)
prefix_segments, video_shape = (5, 70), (2, 4, 4)
seq_len = sum(prefix_segments) + 2 * 4 * 4
torch.manual_seed(0)
query = torch.randn(1, seq_len, 2, 8, dtype=torch.bfloat16)
output = impl.forward_cuda(query, query, query, _h3_metadata(prefix_segments, video_shape))
assert output.shape == query.shape
# topk covers every video block, so the block map is dense and the tiled
# kernel must reproduce plain attention over the same rows.
reference = torch.nn.functional.scaled_dot_product_attention(
*(x.float().transpose(1, 2) for x in (query, query, query))
).transpose(1, 2)
torch.testing.assert_close(output.float(), reference, atol=2e-2, rtol=2e-2)
# 5 + 70 splits into segment-pure 5 | 64 | 6, then one (2, 4, 4) video tile.
assert calls["variable_block_sizes"] == [5, 64, 6, 32]
def test_h3_forward_keeps_prefix_dense_and_selects_top_k_video_tiles(monkeypatch):
calls: dict[str, Any] = {}
_fake_block_sparse_kernel(monkeypatch, calls)
impl = _h3_impl(topk=1)
prefix_segments, video_shape = (5,), (8, 4, 4)
seq_len = 5 + 8 * 4 * 4
torch.manual_seed(0)
query = torch.randn(1, seq_len, 2, 8, dtype=torch.bfloat16)
impl.forward_cuda(query, query, query, _h3_metadata(prefix_segments, video_shape))
# 1 prefix block + 2 video blocks. The odd count is padded to an even one
# for the paired-CTA kernel contract, and the Triton route slices that
# transport-only partner off again before launching.
block_map = calls["block_map"]
assert block_map.shape[-1] == 3
assert calls["variable_block_sizes"] == [5, 64, 64]
assert block_map[:, :, :1, :].all(), "prefix queries stay dense"
assert block_map[..., :1].all(), "prefix keys are exempt from selection"
assert (block_map[:, :, 1:, 1:].sum(dim=-1) == 1).all(), "one video tile per video query"
# The same odd geometry must still untile back onto the original rows.
dense = _h3_impl(topk=64).forward_cuda(query, query, query, _h3_metadata(prefix_segments, video_shape))
reference = torch.nn.functional.scaled_dot_product_attention(
*(x.float().transpose(1, 2) for x in (query, query, query))
).transpose(1, 2)
torch.testing.assert_close(dense.float(), reference, atol=2e-2, rtol=2e-2)
def test_h3_forward_applies_the_learned_compression_gate(monkeypatch):
_fake_block_sparse_kernel(monkeypatch, {})
impl = _h3_impl(topk=64)
prefix_segments, video_shape = (5,), (2, 4, 4)
seq_len = 5 + 2 * 4 * 4
torch.manual_seed(0)
query = torch.randn(1, seq_len, 2, 8, dtype=torch.bfloat16)
without_gate = impl.forward_cuda(query, query, query, _h3_metadata(prefix_segments, video_shape))
zero_gate = torch.zeros_like(query)
with_zero_gate = impl.forward_cuda(query, query, query, _h3_metadata(prefix_segments, video_shape, gate=zero_gate))
live_gate = torch.full_like(query, 0.5)
with_live_gate = impl.forward_cuda(query, query, query, _h3_metadata(prefix_segments, video_shape, gate=live_gate))
torch.testing.assert_close(with_zero_gate.float(), without_gate.float())
assert not torch.allclose(with_live_gate.float(), without_gate.float())
def test_h3_forward_restores_rows_the_packed_padding_excludes(monkeypatch):
_fake_block_sparse_kernel(monkeypatch, {})
impl = _h3_impl(topk=64)
prefix_segments, video_shape = (5,), (2, 4, 4)
valid = 5 + 2 * 4 * 4
torch.manual_seed(0)
query = torch.randn(1, valid + 24, 2, 8, dtype=torch.bfloat16)
padding = PackedPaddingMetadata(
q_length=valid,
kv_length=valid,
cu_seqlens_q=torch.tensor([0, valid], dtype=torch.int32),
cu_seqlens_k=torch.tensor([0, valid], dtype=torch.int32),
)
output = impl.forward_cuda(query, query, query, _h3_metadata(prefix_segments, video_shape, packed_padding=padding))
assert output.shape == query.shape
assert torch.count_nonzero(output[:, valid:]) == 0
def test_sdpa_fallback_never_attends_the_structural_padding(monkeypatch):
# The backend advertises supports_packed_mask_free, so MiniMax-H3 skips
# The backend advertises supports_packed_mask_free, so a model may skip
# building the padding mask. Every fallback out of the VSA path must honour
# that contract itself; SDPA reads attn_mask and nothing else.
impl = FastVideoVSAImpl(
@@ -374,6 +233,8 @@ def test_sdpa_fallback_never_attends_the_structural_padding(monkeypatch):
cu_seqlens_k=torch.tensor([0, valid], dtype=torch.int32),
)
monkeypatch.setattr(impl.sdpa_fallback, "forward", impl.sdpa_fallback.forward_cuda)
baseline = impl.forward_cuda(query, query, query, AttentionMetadata(packed_padding=padding, extra={}))
perturbed_input = query.clone()
perturbed_input[:, valid:] += 100.0
@@ -384,22 +245,3 @@ def test_sdpa_fallback_never_attends_the_structural_padding(monkeypatch):
assert baseline.shape == query.shape
torch.testing.assert_close(baseline[:, :valid], perturbed[:, :valid])
assert torch.count_nonzero(baseline[:, valid:]) == 0
def test_h3_geometry_keeps_prefix_segments_pure_and_tiles_video_3d():
partition, sizes, non_pad, untile, prefix_blocks, video_blocks = _get_h3_tile_metadata(
(5, 70, 9), (5, 6, 6), torch.device("cpu")
)
assert sizes[:4].tolist() == [5, 64, 6, 9]
assert prefix_blocks == 4
assert video_blocks == 8
assert int(sizes.sum()) == 5 + 70 + 9 + 5 * 6 * 6
assert partition.numel() == non_pad.numel() == untile.numel() == int(sizes.sum())
def test_h3_block_map_makes_prefix_queries_dense_and_prefix_keys_exempt():
scores = torch.arange(1 * 2 * 5 * 5, dtype=torch.float32).reshape(1, 2, 5, 5)
block_map = _build_h3_block_map(scores, num_prefix_blocks=2, num_video_blocks=3, topk=1)
assert block_map[:, :, :2].all()
assert block_map[..., :2].all()
assert (block_map[:, :, 2:, 2:].sum(dim=-1) == 1).all()
+144 -9
View File
@@ -16,13 +16,14 @@ from unittest.mock import Mock
import pytest
import torch
from tests.helpers.mark import hardware_test
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.backends.flash_attn import FlashAttentionImpl
from vllm_omni.diffusion.attention.backends.sdpa import SDPAImpl
from vllm_omni.diffusion.attention.backends.utils import fa # noqa: E402
from vllm_omni.platforms import current_omni_platform
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion]
is_gpu = current_omni_platform.is_cuda_alike() or current_omni_platform.is_xpu()
HAS_FLASH_ATTN = fa.HAS_FLASH_ATTN
@@ -42,10 +43,12 @@ flash_attn_func = fa.flash_attn_func # noqa: N813
(9, "4", frozenset((2, 3, 4)), 4),
],
)
@pytest.mark.cpu
def test_versioned_flash_attention_selection(device_major, requested, supported, expected):
assert fa._choose_vllm_flash_attn_version(device_major, requested, supported) == expected
@pytest.mark.cpu
def test_versioned_flash_attention_selection_rejects_invalid_or_unavailable_version():
with pytest.raises(ValueError, match="must be 2, 3, or 4"):
fa._choose_vllm_flash_attn_version(9, "5", frozenset((2, 3, 4)))
@@ -92,7 +95,8 @@ def pad_tensor(tensor: torch.Tensor, target_seq_len: int, pad_value: float = 0.0
return torch.cat([tensor, padding], dim=1)
@pytest.mark.skipif(not is_gpu, reason="FlashAttention requires CUDA or XPU")
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
@pytest.mark.skipif(not is_gpu, reason="FlashAttention requires an accelerator")
def test_padding_equivalence():
"""
Case 1: Test that padded and unpadded inputs produce similar outputs.
@@ -185,7 +189,8 @@ def test_padding_equivalence():
print("✓ Case 1 PASSED: Padded and unpadded outputs are very close!")
@pytest.mark.skipif(not is_gpu, reason="FlashAttention requires CUDA or XPU")
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
@pytest.mark.skipif(not is_gpu, reason="FlashAttention requires an accelerator")
def test_fa_vs_sdpa():
"""
Case 2: Compare FlashAttention and SDPA backends with padding.
@@ -302,7 +307,8 @@ def test_fa_vs_sdpa():
print("✓ Case 2 PASSED: FA and SDPA outputs are very close!")
@pytest.mark.skipif(not is_gpu, reason="FlashAttention requires CUDA or XPU")
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
@pytest.mark.skipif(not is_gpu, reason="FlashAttention requires an accelerator")
def test_flash_attn_func_preferred_over_varlen():
"""Test flash_attn_func availability and basic forward call."""
if not HAS_FLASH_ATTN:
@@ -332,7 +338,8 @@ def test_flash_attn_func_preferred_over_varlen():
print("✓ flash_attn_func forward works correctly!")
@pytest.mark.skipif(not is_gpu, reason="FlashAttention requires CUDA or XPU")
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
@pytest.mark.skipif(not is_gpu, reason="FlashAttention requires an accelerator")
@pytest.mark.parametrize("k_len", [40, 256])
def test_cross_attn_key_padding_vs_sdpa(k_len):
"""
@@ -390,6 +397,7 @@ def test_cross_attn_key_padding_vs_sdpa(k_len):
print("✓ Case 3 PASSED: FA and SDPA cross-attention outputs are very close!")
@pytest.mark.cpu
def test_varlen_masked_routing_by_role(monkeypatch):
"""The unpad route is picked by role, not Q/K length equality; runs without a GPU."""
calls = []
@@ -424,6 +432,7 @@ def test_varlen_masked_routing_by_role(monkeypatch):
assert cu_seqlens_k.tolist() == [0, 2, 5]
@pytest.mark.cpu
def test_piecewise_flash_attn_uses_varlen_fallback(monkeypatch):
calls = []
@@ -454,6 +463,7 @@ def test_piecewise_flash_attn_uses_varlen_fallback(monkeypatch):
assert calls[0]["softmax_scale"] == 0.5
@pytest.mark.cpu
def test_packed_varlen_metadata_bypasses_mask_unpadding(monkeypatch):
calls = []
@@ -486,6 +496,7 @@ def test_packed_varlen_metadata_bypasses_mask_unpadding(monkeypatch):
assert calls[0][3]["max_seqlen_q"] == 6
@pytest.mark.cpu
def test_packed_varlen_metadata_must_be_complete(monkeypatch):
monkeypatch.setattr(fa, "HAS_FLASH_ATTN", True)
impl = FlashAttentionImpl(num_heads=2, head_size=4, softmax_scale=0.5, causal=False)
@@ -503,11 +514,12 @@ def test_packed_varlen_metadata_must_be_complete(monkeypatch):
# - boundary resolution in ``_resolve_packed_seq_npu`` (pure Python, no device
# sync, no MindIE-SD import);
# - env dispatch in ``forward_fa_npu`` (which op a packed forward takes);
# - native torch_npu dispatch for right-down causal attention;
# - the laser input pre-scaling math in ``_forward_prefix_kv_slice_npu``.
#
# They run on CPU without a real NPU by injecting a fake ``mindiesd`` module
# into ``sys.modules`` (same pattern as ``test_paged_attention`` /
# ``benchmarks/conftest``). No production code is exercised for real kernels.
# They run on CPU without a real NPU by injecting fake ``mindiesd`` and
# ``torch_npu`` modules into ``sys.modules`` (same pattern as
# ``test_paged_attention`` / ``benchmarks/conftest``). No real kernel runs.
def _npu_impl(causal: bool = False) -> FlashAttentionImpl:
@@ -529,9 +541,19 @@ def _fake_mindiesd(monkeypatch, *, attention_forward=None, attention_forward_var
return fake
def _fake_torch_npu(monkeypatch, *, npu_fusion_attention=None):
"""Install the minimal torch_npu surface used by causal NPU attention."""
fake = SimpleNamespace(
npu_fusion_attention=npu_fusion_attention or Mock(return_value=(torch.zeros(1), None, None, None, 0, 0, 0)),
)
monkeypatch.setitem(sys.modules, "torch_npu", fake)
return fake
# --- Test group A: boundary resolution (_resolve_packed_seq_npu) -------------
@pytest.mark.cpu
def test_resolve_packed_seq_accepts_real_plus_pad_contract():
impl = _npu_impl()
q = torch.randn(1, 8, 2, 4)
@@ -541,6 +563,7 @@ def test_resolve_packed_seq_accepts_real_plus_pad_contract():
assert impl._resolve_packed_seq_npu(q, q, extra) == ([5, 8], [5, 8])
@pytest.mark.cpu
def test_resolve_packed_seq_single_document_no_padding():
impl = _npu_impl()
q = torch.randn(1, 8, 2, 4)
@@ -564,6 +587,7 @@ def test_resolve_packed_seq_single_document_no_padding():
"pad_longer_than_real",
],
)
@pytest.mark.cpu
def test_resolve_packed_seq_rejects_malformed_metadata(case):
"""Any metadata outside the exact [real, pad] contract returns None so the
caller falls back to the masked path."""
@@ -620,6 +644,7 @@ def _npu_impl_with_mocked_paths() -> tuple[FlashAttentionImpl, torch.Tensor]:
return impl, sentinel
@pytest.mark.cpu
def test_npu_env_unset_uses_varlen(monkeypatch):
monkeypatch.delenv("MINDIE_SD_FA_TYPE", raising=False)
_fake_mindiesd(monkeypatch)
@@ -632,6 +657,7 @@ def test_npu_env_unset_uses_varlen(monkeypatch):
impl._forward_prefix_kv_slice_npu.assert_not_called()
@pytest.mark.cpu
def test_npu_env_laser_uses_slice(monkeypatch):
monkeypatch.setenv("MINDIE_SD_FA_TYPE", "ascend_laser_attention")
_fake_mindiesd(monkeypatch)
@@ -645,6 +671,7 @@ def test_npu_env_laser_uses_slice(monkeypatch):
@pytest.mark.parametrize("fa_type", ["prompt_flash_attn", "fused_attn_score", "ascend_laser_attenton", "garbage"])
@pytest.mark.cpu
def test_npu_env_non_laser_value_falls_back_to_varlen(monkeypatch, fa_type):
"""Locks in the CURRENT dispatch behavior (PR #5891).
@@ -665,6 +692,7 @@ def test_npu_env_non_laser_value_falls_back_to_varlen(monkeypatch, fa_type):
impl._forward_prefix_kv_slice_npu.assert_not_called()
@pytest.mark.cpu
def test_npu_varlen_opt_in_unset_takes_mask_path(monkeypatch):
"""Models that do not set ``npu_attn_varlen`` (e.g. Wan/Cosmos) keep using
the existing masked attention_forward path; the new branches are skipped."""
@@ -685,9 +713,115 @@ def test_npu_varlen_opt_in_unset_takes_mask_path(monkeypatch):
assert out is fake_forward.return_value
# --- Test group C: laser input pre-scaling in _forward_prefix_kv_slice_npu --
# --- Test group C: native NPU causal attention dispatch ----------------------
@pytest.mark.parametrize(
("query_length", "key_length", "expected_inner_precise"),
[(4, 4, 0), (2, 4, 0), (4, 2, 2)],
)
@pytest.mark.cpu
def test_npu_causal_uses_native_right_down_mode(
monkeypatch,
query_length,
key_length,
expected_inner_precise,
):
expected_out = torch.randn(1, query_length, 2, 4)
fusion_attention = Mock(return_value=(expected_out, None, None, None, 0, 0, 0))
fake_torch_npu = _fake_torch_npu(monkeypatch, npu_fusion_attention=fusion_attention)
impl = FlashAttentionImpl(num_heads=8, head_size=4, softmax_scale=0.5, causal=True)
query = torch.randn(1, query_length, 2, 4)
key = torch.randn(1, key_length, 2, 4)
out = impl.forward_fa_npu(query, key, key)
fake_torch_npu.npu_fusion_attention.assert_called_once()
args, kwargs = fake_torch_npu.npu_fusion_attention.call_args
assert torch.equal(args[0], query)
assert torch.equal(args[1], key)
assert torch.equal(args[2], key)
assert all(tensor.is_contiguous() for tensor in args[:3])
assert kwargs["head_num"] == query.shape[2]
assert kwargs["input_layout"] == "BSND"
assert kwargs["scale"] == 0.5
assert kwargs["keep_prob"] == 1.0
assert kwargs["sparse_mode"] == 3
assert kwargs["inner_precise"] == expected_inner_precise
block_mask = kwargs["atten_mask"]
assert block_mask.shape == (2048, 2048)
assert block_mask.dtype == torch.bool
assert block_mask.is_contiguous()
expected_corner = torch.tensor(
[
[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
[False, False, False, False],
]
)
assert torch.equal(block_mask[:4, :4], expected_corner)
assert out is expected_out
@pytest.mark.cpu
def test_npu_causal_composes_explicit_keep_mask(monkeypatch):
expected_out = torch.randn(1, 4, 2, 4)
fusion_attention = Mock(return_value=(expected_out, None, None, None, 0, 0, 0))
fake_torch_npu = _fake_torch_npu(monkeypatch, npu_fusion_attention=fusion_attention)
impl = FlashAttentionImpl(num_heads=2, head_size=4, softmax_scale=0.5, causal=True)
query = torch.randn(1, 4, 2, 4)
key_keep_mask = torch.tensor([[True, False, True, True]])
out = impl.forward_fa_npu(
query,
query,
query,
AttentionMetadata(attn_mask=key_keep_mask),
)
fake_torch_npu.npu_fusion_attention.assert_called_once()
kwargs = fake_torch_npu.npu_fusion_attention.call_args.kwargs
assert kwargs["sparse_mode"] == 1
assert kwargs["inner_precise"] == 2
expected_block_mask = torch.tensor(
[
[
[
[False, True, True, True],
[False, True, True, True],
[False, True, False, True],
[False, True, False, False],
]
]
]
)
assert torch.equal(kwargs["atten_mask"], expected_block_mask)
assert kwargs["atten_mask"].is_contiguous()
assert out is expected_out
@pytest.mark.cpu
def test_npu_noncausal_without_explicit_mask_stays_unmasked(monkeypatch):
captured: dict = {}
def fake_attention_forward(query, key, value, **kwargs):
captured.update(kwargs)
return torch.zeros_like(query)
_fake_mindiesd(monkeypatch, attention_forward=fake_attention_forward)
query = torch.randn(1, 4, 2, 4)
_npu_impl(causal=False).forward_fa_npu(query, query, query)
assert captured["attn_mask"] is None
# --- Test group D: laser input pre-scaling in _forward_prefix_kv_slice_npu --
@pytest.mark.cpu
def test_prefix_kv_slice_applies_laser_input_scaling(monkeypatch):
monkeypatch.setenv("MINDIE_SD_FA_TYPE", "ascend_laser_attention")
captured: dict = {}
@@ -726,6 +860,7 @@ def test_prefix_kv_slice_applies_laser_input_scaling(monkeypatch):
torch.testing.assert_close(out, torch.ones(1, 8, 2, 4) * 256.0)
@pytest.mark.cpu
def test_prefix_kv_slice_no_scaling_without_factor(monkeypatch):
monkeypatch.setenv("MINDIE_SD_FA_TYPE", "ascend_laser_attention")
captured: dict = {}
@@ -0,0 +1,118 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import pytest
import torch
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.backends.flash_attn import FlashAttentionImpl
from vllm_omni.platforms import current_omni_platform
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.npu]
def _bottom_right_causal_reference(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
scale: float,
key_keep_mask: torch.Tensor | None = None,
) -> torch.Tensor:
scores = torch.einsum("bqhd,bkhd->bhqk", query.float(), key.float()) * scale
query_positions = torch.arange(query.shape[1]).unsqueeze(1)
key_positions = torch.arange(key.shape[1]).unsqueeze(0)
keep_mask = key_positions <= query_positions + (key.shape[1] - query.shape[1])
if key_keep_mask is not None:
assert query.shape[0] == 1
keep_mask = keep_mask & key_keep_mask[0].bool().unsqueeze(0)
valid_rows = keep_mask.any(dim=-1)
output = torch.zeros(
query.shape[0],
query.shape[1],
query.shape[2],
value.shape[-1],
dtype=torch.float32,
)
valid_scores = scores[:, :, valid_rows].masked_fill(~keep_mask[valid_rows], float("-inf"))
probabilities = torch.softmax(valid_scores, dim=-1)
output[:, valid_rows] = torch.einsum("bhqk,bkhd->bqhd", probabilities, value.float())
return output
@pytest.mark.skipif(not current_omni_platform.is_npu(), reason="Native causal attention requires Ascend NPU")
def test_npu_bottom_right_causal_fully_masked_rows_are_zero():
torch.manual_seed(0)
batch_size, query_length, key_length = 1, 4, 2
num_heads, head_size = 2, 64
scale = head_size**-0.5
query_cpu = torch.randn(batch_size, query_length, num_heads, head_size).to(torch.bfloat16)
key_cpu = torch.randn(batch_size, key_length, num_heads, head_size).to(torch.bfloat16)
value_cpu = torch.randn(batch_size, key_length, num_heads, head_size).to(torch.bfloat16)
expected = _bottom_right_causal_reference(query_cpu, key_cpu, value_cpu, scale)
device = torch.device(current_omni_platform.device_type)
query = query_cpu.to(device)
key = key_cpu.to(device)
value = value_cpu.to(device)
impl = FlashAttentionImpl(
num_heads=num_heads,
head_size=head_size,
softmax_scale=scale,
causal=True,
)
output = impl.forward_fa_npu(query, key, value)
output_cpu = output.float().cpu()
assert torch.isfinite(output_cpu).all()
assert torch.equal(output_cpu[:, : query_length - key_length], torch.zeros_like(output_cpu[:, :2]))
torch.testing.assert_close(
output_cpu[:, query_length - key_length :],
expected[:, query_length - key_length :],
rtol=2e-2,
atol=2e-2,
)
@pytest.mark.skipif(not current_omni_platform.is_npu(), reason="Native causal attention requires Ascend NPU")
def test_npu_bottom_right_causal_composes_explicit_keep_mask():
torch.manual_seed(1)
batch_size, sequence_length = 1, 4
num_heads, head_size = 2, 64
scale = head_size**-0.5
key_keep_mask_cpu = torch.tensor([[True, False, True, True]])
query_cpu = torch.randn(batch_size, sequence_length, num_heads, head_size).to(torch.bfloat16)
key_cpu = torch.randn(batch_size, sequence_length, num_heads, head_size).to(torch.bfloat16)
value_cpu = torch.randn(batch_size, sequence_length, num_heads, head_size).to(torch.bfloat16)
expected = _bottom_right_causal_reference(
query_cpu,
key_cpu,
value_cpu,
scale,
key_keep_mask_cpu,
)
device = torch.device(current_omni_platform.device_type)
query = query_cpu.to(device)
key = key_cpu.to(device)
value = value_cpu.to(device)
impl = FlashAttentionImpl(
num_heads=num_heads,
head_size=head_size,
softmax_scale=scale,
causal=True,
)
output = impl.forward_fa_npu(
query,
key,
value,
AttentionMetadata(attn_mask=key_keep_mask_cpu.to(device)),
)
output_cpu = output.float().cpu()
assert torch.isfinite(output_cpu).all()
torch.testing.assert_close(output_cpu, expected, rtol=2e-2, atol=2e-2)
@@ -0,0 +1,136 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import pytest
from vllm_omni.diffusion.attention import layer
from vllm_omni.diffusion.attention.backends.fastvideo_vsa import FastVideoVSABackend, FastVideoVSAImpl
from vllm_omni.diffusion.attention.backends.sdpa import SDPABackend
from vllm_omni.diffusion.attention.parallel.base import NoParallelAttention
from vllm_omni.diffusion.data import AttentionSpec
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
class _SpecializedImpl(FastVideoVSAImpl):
pass
@pytest.fixture
def local_attention(monkeypatch):
monkeypatch.setattr(layer, "get_current_diffusion_config_or_none", lambda: None)
monkeypatch.setattr(layer, "build_parallel_attention_strategy", lambda **kwargs: NoParallelAttention())
@pytest.mark.parametrize("explicit", [False, True])
@pytest.mark.parametrize("override", [False, True])
def test_specialization_preserves_selected_backend_and_options(mocker, local_attention, explicit, override):
spec = AttentionSpec(backend="FASTVIDEO_VSA", fastvideo_vsa_topk=7) if explicit else None
select = mocker.patch.object(layer, "get_attn_backend_for_role", return_value=(FastVideoVSABackend, spec))
attention = layer.Attention(
num_heads=2,
head_size=8,
softmax_scale=8**-0.5,
causal=False,
role="video.self",
role_category="self",
qkv_layout="BSND",
impl_overrides={"FASTVIDEO_VSA": _SpecializedImpl} if override else None,
)
assert attention.attn_backend is FastVideoVSABackend
assert type(attention.attention) is (_SpecializedImpl if override else FastVideoVSAImpl)
assert attention.attention.topk == (7 if explicit else 64)
assert attention.attention.qkv_layout == "BSND"
assert attention.backend_pref == "FASTVIDEO_VSA"
assert attention.backend_explicit is explicit
assert attention.attn_spec is spec
assert isinstance(attention.parallel_strategy, NoParallelAttention)
select.assert_called_once_with(
role="video.self", head_size=8, attention_config=None, role_category="self", allow_trtllm_default=False
)
def test_unselected_specialization_does_not_replace_dense_backend(mocker, local_attention):
mocker.patch.object(layer, "get_attn_backend_for_role", return_value=(SDPABackend, None))
attention = layer.Attention(
num_heads=2,
head_size=8,
softmax_scale=8**-0.5,
causal=False,
impl_overrides={"FASTVIDEO_VSA": _SpecializedImpl},
)
assert attention.attn_backend is SDPABackend
assert type(attention.attention) is SDPABackend.get_impl_cls()
def test_specialization_does_not_bypass_selection_errors(mocker, local_attention):
mocker.patch.object(layer, "get_attn_backend_for_role", side_effect=ImportError("optional kernel unavailable"))
with pytest.raises(ImportError, match="optional kernel unavailable"):
layer.Attention(
num_heads=2,
head_size=8,
softmax_scale=8**-0.5,
causal=False,
impl_overrides={"FASTVIDEO_VSA": _SpecializedImpl},
)
def test_specialization_must_extend_selected_implementation(mocker, local_attention):
mocker.patch.object(layer, "get_attn_backend_for_role", return_value=(FastVideoVSABackend, None))
with pytest.raises(TypeError, match="must subclass the selected implementation"):
layer.Attention(
num_heads=2,
head_size=8,
softmax_scale=8**-0.5,
causal=False,
impl_overrides={"FASTVIDEO_VSA": SDPABackend.get_impl_cls()},
)
def test_platform_backend_capabilities_survive_model_specialization(mocker, local_attention):
from vllm_omni.diffusion.models.minimax_h3.attention.fastvideo_h3 import MiniMaxH3VSAImpl
class PlatformBackend(FastVideoVSABackend):
@classmethod
def supports_packed_mask_free(cls):
return False
@staticmethod
def get_supported_head_sizes():
return [128]
# A registry/platform may refine capabilities without changing the
# implementation. The model must not replace those capability decisions.
mocker.patch.object(layer, "get_attn_backend_for_role", return_value=(PlatformBackend, None))
attention = layer.Attention(
num_heads=2,
head_size=128,
softmax_scale=128**-0.5,
causal=False,
impl_overrides={"FASTVIDEO_VSA": MiniMaxH3VSAImpl},
)
assert attention.attn_backend is PlatformBackend
assert not attention.attn_backend.supports_packed_mask_free()
assert attention.attn_backend.get_supported_head_sizes() == [128]
assert type(attention.attention) is MiniMaxH3VSAImpl
def test_incompatible_platform_implementation_is_not_discarded(mocker, local_attention):
class PlatformImpl(FastVideoVSAImpl):
pass
class PlatformBackend(FastVideoVSABackend):
@staticmethod
def get_impl_cls():
return PlatformImpl
mocker.patch.object(layer, "get_attn_backend_for_role", return_value=(PlatformBackend, None))
with pytest.raises(TypeError, match="selected implementation .*PlatformImpl"):
layer.Attention(
num_heads=2,
head_size=8,
softmax_scale=8**-0.5,
causal=False,
impl_overrides={"FASTVIDEO_VSA": _SpecializedImpl},
)
@@ -0,0 +1,160 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Cross-repository CPU dispatch contracts, requiring the matching MindIE-SD source.
Only native operators are replaced. Public adapters, rotations, layouts, padding,
scale preparation, sequence metadata and output cropping execute their real code.
Operator substitutes carry floating tensors; these are not numerical quantization tests.
"""
import importlib
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
import torch
from vllm_omni.diffusion.attention.backends import flash_attn, rainfusion_attn
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.platforms.npu.quant.kv_quant_npu import get_quant_attention_rotation
mindiesd = pytest.importorskip("mindiesd")
torch_npu = importlib.import_module("torch_npu")
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
@pytest.mark.parametrize(
"precision,batch,q_len,kv_len,q_heads",
[
("fp8", 1, 130, 130, 2),
("mxfp8", 1, 130, 130, 2),
("mxfp4", 1, 130, 130, 2),
("mxfp8", 2, 17, 8, 4),
("mxfp8", 2, 8, 17, 4),
],
)
@pytest.mark.parametrize("layout", ["BSND", "BNSD"])
def test_omni_calls_real_dense_public_api(monkeypatch, precision, layout, batch, q_len, kv_len, q_heads):
assert callable(getattr(mindiesd, "quant_attention", None)), "MindIE-SD must export quant_attention"
monkeypatch.setattr(flash_attn, "current_omni_platform", SimpleNamespace(is_npu=lambda: True, device_name="npu"))
monkeypatch.setattr(flash_attn, "get_current_diffusion_config_or_none", lambda: None)
quantized_inputs = []
def dynamic_quant(tensor, **kwargs):
quantized_inputs.append((tensor.clone(), kwargs))
shape = list(tensor.shape)
axis = kwargs.get("axis", -1)
shape[axis] = max(1, shape[axis] // 32)
return tensor, torch.ones(shape, dtype=torch.uint8)
monkeypatch.setattr(torch_npu, "npu_dynamic_block_quant", dynamic_quant, raising=False)
monkeypatch.setattr(torch_npu, "npu_dynamic_mx_quant", dynamic_quant, raising=False)
execute = Mock(side_effect=lambda query, *args, **kwargs: (query, None))
metadata = Mock(return_value=torch.zeros(1, dtype=torch.int32))
if precision == "fp8":
monkeypatch.setattr(torch.ops.mindiesd, "fused_infer_attention_score_v2", execute, raising=False)
elif precision == "mxfp8":
monkeypatch.setattr(torch_npu, "npu_fused_infer_attention_score_v2", execute, raising=False)
else:
monkeypatch.setattr(torch.ops.mindiesd, "quant_flash_attn", execute, raising=False)
monkeypatch.setattr(torch.ops.mindiesd, "quant_flash_attn_metadata", metadata, raising=False)
query = torch.randn(batch, q_len, q_heads, 64, dtype=torch.bfloat16)
key = torch.randn(batch, kv_len, 2, 64, dtype=torch.bfloat16)
value = torch.randn_like(key)
if layout == "BNSD":
query, key, value = (tensor.transpose(1, 2) for tensor in (query, key, value))
impl = flash_attn.FlashAttentionImpl(
num_heads=q_heads,
head_size=64,
softmax_scale=0.37,
qkv_layout=layout,
)
output = impl.forward_npu(query, key, value, AttentionMetadata(extra={"kv_cache_dtype": precision}))
rotation = get_quant_attention_rotation(query.device, query.dtype, 64)
expected = query @ rotation
torch.testing.assert_close(output, expected)
assert output.shape == query.shape and len(quantized_inputs) == 3
execute.assert_called_once()
kwargs = execute.call_args.kwargs
assert kwargs["softmax_scale"] == 0.37
if precision == "fp8":
assert kwargs["input_layout"] == "BNSD"
assert quantized_inputs[0][0].shape == (2, 130, 64)
assert quantized_inputs[0][1]["row_block_size"] == 128
elif precision == "mxfp8":
args = execute.call_args.args
assert args[0].shape == (batch * q_len, q_heads, 64)
assert args[1].shape == args[2].shape == (batch * kv_len, 2, 64)
assert kwargs["input_layout"] == "TND"
assert kwargs["num_query_heads"] == q_heads and kwargs["num_key_value_heads"] == 2
assert kwargs["actual_seq_qlen"] == [q_len * (i + 1) for i in range(batch)]
assert kwargs["actual_seq_kvlen"] == [kv_len * (i + 1) for i in range(batch)]
assert [entry[1]["axis"] for entry in quantized_inputs] == [-1, -1, 0]
else:
seq_axis = 1 if layout == "BSND" else 2
assert quantized_inputs[0][0].shape[seq_axis] == 512
assert kwargs["seqused_q"].tolist() == kwargs["seqused_kv"].tolist() == [512]
assert kwargs["layout_q"] == kwargs["layout_out"] == layout
assert kwargs["q_dtype"] == torch_npu.float4_e2m1fn_x2
assert kwargs["q_descale_dtype"] == torch_npu.float8_e8m0fnu
assert execute.call_args.args[3].shape[:2] == (1, 2)
assert [entry[1]["axis"] for entry in quantized_inputs] == [-1, -1, seq_axis]
assert kwargs["metadata"] is metadata.return_value
metadata.assert_called_once()
@pytest.mark.parametrize("precision", ["fp8", "mxfp4"])
@pytest.mark.parametrize("length", [65, 600])
def test_omni_calls_real_sparse_public_api(monkeypatch, precision, length):
rf = importlib.import_module("mindiesd.layers.flash_attn.sparse_flash_attn_rf_v3")
monkeypatch.setattr(flash_attn, "current_omni_platform", SimpleNamespace(is_npu=lambda: True, device_name="npu"))
for module in (flash_attn, rainfusion_attn):
monkeypatch.setattr(module, "get_current_diffusion_config_or_none", lambda: None)
rainfusion_attn._mindiesd_supports_precision.cache_clear()
monkeypatch.setattr(rf, "do_tensor_rearrange_only", lambda q, k, v, *a, **kw: (q, k, v))
monkeypatch.setattr(rf, "avgpool", lambda *a, **kw: torch.ones(1))
monkeypatch.setattr(rf, "_generate_mask_direct", lambda *a, **kw: torch.ones(1, 2, 8, 8))
monkeypatch.setattr(rf, "_bsa_inv_rearrange", lambda out, *a: out)
def quantize(tensor, **kwargs):
shape = list(tensor.shape)
axis = kwargs.get("axis", -1)
shape[axis] = max(1, shape[axis] // 32)
return tensor, torch.ones(shape, dtype=torch.uint8)
monkeypatch.setattr(torch_npu, "npu_dynamic_mx_quant", quantize, raising=False)
monkeypatch.setattr(torch_npu, "npu_dynamic_block_quant", quantize, raising=False)
execute = Mock(side_effect=lambda **kw: (torch.ones_like(kw["query"]), None))
monkeypatch.setattr(torch.ops.mindiesd, "block_sparse_attention", execute, raising=False)
query = torch.randn(1, length, 2, 64, dtype=torch.bfloat16)
impl = rainfusion_attn.RainFusionAttentionImpl(
num_heads=2,
head_size=64,
softmax_scale=0.37,
qkv_layout="BSND",
backend_kwargs={"sparsity": 0.8},
)
plan = rainfusion_attn.RainFusionPlan(used_len=length, prefix_len=0, latent_shape=(1, 1, length))
try:
output = impl._forward_sparse_npu(
query,
query,
query,
plan,
AttentionMetadata(extra={"kv_cache_dtype": precision}),
)
finally:
rainfusion_attn._mindiesd_supports_precision.cache_clear()
torch.testing.assert_close(output, torch.ones_like(query))
execute.assert_called_once()
kwargs = execute.call_args.kwargs
assert kwargs["actual_seq_lengths"] == kwargs["actual_seq_lengths_kv"] == [length]
assert kwargs["q_input_layout"] == "BNSD"
assert kwargs["block_sparse_mask"] is not None
if precision == "mxfp4":
assert kwargs["query"].shape[2] == (length + 63) // 64 * 64
assert kwargs["quant_mode"] == 2
assert kwargs["q_dtype"] == torch_npu.float4_e2m1fn_x2
assert kwargs["v_scale_dtype"] == torch_npu.float8_e8m0fnu
@@ -0,0 +1,323 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""CPU contract tests for MindIE adapters; no NPU kernels are mocked in production."""
import sys
from types import ModuleType, SimpleNamespace
from unittest.mock import Mock
import pytest
import torch
from vllm_omni.diffusion.attention import layer as layer_mod
from vllm_omni.diffusion.attention.backends import flash_attn, rainfusion_attn
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata, VideoTokenLayout
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
_DEFAULT_SKIP_STEPS = frozenset({0, 1, 38, 39})
@pytest.fixture
def runtime(monkeypatch):
mod = ModuleType("mindiesd")
def execute(q, k, v, *, precision, layout, scale, q_rot=None, k_rot=None):
return q
setattr(mod, "quant_attention", Mock(side_effect=execute))
monkeypatch.setitem(sys.modules, mod.__name__, mod)
for module in (flash_attn, layer_mod):
monkeypatch.setattr(module, "current_omni_platform", SimpleNamespace(is_npu=lambda: True, device_name="npu"))
monkeypatch.setattr(flash_attn, "get_current_diffusion_config_or_none", lambda: None)
monkeypatch.setattr(rainfusion_attn, "get_current_diffusion_config_or_none", lambda: None)
monkeypatch.setattr(rainfusion_attn, "is_forward_context_available", lambda: False)
supports_precision = rainfusion_attn._mindiesd_supports_precision
supports_precision.cache_clear()
yield mod
supports_precision.cache_clear()
def flash(layout="BSND"):
return flash_attn.FlashAttentionImpl(
num_heads=2,
head_size=64,
softmax_scale=0.37,
qkv_layout=layout,
)
def sparse(**kwargs):
return rainfusion_attn.RainFusionAttentionImpl(
num_heads=2,
head_size=64,
softmax_scale=0.37,
qkv_layout="BSND",
backend_kwargs={"sparsity": 0.8, **kwargs},
)
def video_metadata(**extra):
return AttentionMetadata(
video_layout=VideoTokenLayout(prefix_len=0, latent_grid=(4, 32, 32), used_len=4096),
extra={"max_seqlen_q": 4096, **extra},
)
@pytest.mark.parametrize("method", ["fp8", "mxfp8", "mxfp4"])
@pytest.mark.parametrize("layout", [None, "BSND", "BNSD"])
def test_exact_runtime_layout_scale_and_rotation(runtime, method, layout):
q = torch.randn(1, 128, 2, 64, dtype=torch.bfloat16)
if layout == "BNSD":
q = q.transpose(1, 2)
impl = flash(layout=layout)
metadata = AttentionMetadata(extra={"kv_cache_dtype": method})
assert impl.forward_npu(q, q, q, metadata) is q
args, kwargs = runtime.quant_attention.call_args
assert args[0] is q # no unconditional transpose or extra quantization
assert kwargs["layout"] == (layout or "BSND") and kwargs["scale"] == 0.37 and kwargs["precision"] == method
assert "attn_mask" not in kwargs
from vllm_omni.platforms.npu.quant.kv_quant_npu import get_quant_attention_rotation
assert kwargs["q_rot"] is kwargs["k_rot"]
torch.testing.assert_close(kwargs["q_rot"], get_quant_attention_rotation(q.device, q.dtype, 64))
def test_missing_runtime_requires_config_change(runtime):
q = torch.randn(1, 128, 2, 64, dtype=torch.bfloat16)
del runtime.quant_attention
with pytest.raises(ImportError, match="diffusion_kv_cache_dtype"):
flash().forward_npu(q, q, q, AttentionMetadata(extra={"kv_cache_dtype": "mxfp4"}))
def test_operator_failure_never_falls_back(runtime):
q = torch.randn(1, 128, 2, 64, dtype=torch.bfloat16)
runtime.quant_attention.side_effect = RuntimeError("operator failure")
with pytest.raises(RuntimeError, match="operator failure"):
flash().forward_npu(q, q, q, AttentionMetadata(extra={"kv_cache_dtype": "mxfp4"}))
runtime.quant_attention.assert_called_once()
@pytest.mark.parametrize("method", ["fp8", "mxfp8", "mxfp4"])
def test_unsupported_shape_requires_config_change(runtime, method):
q = torch.randn(1, 128, 2, 96, dtype=torch.bfloat16)
with pytest.raises(ValueError, match="diffusion_kv_cache_dtype"):
flash().forward_npu(q, q, q, AttentionMetadata(extra={"kv_cache_dtype": method}))
runtime.quant_attention.assert_not_called()
def test_packed_metadata_never_reaches_quant_runtime(runtime):
q = torch.randn(1, 128, 2, 64, dtype=torch.bfloat16)
metadata = AttentionMetadata(extra={"kv_cache_dtype": "mxfp8", "cu_seqlens_q": torch.tensor([0, 64, 128])})
with pytest.raises(ValueError, match="packed/varlen"):
flash().forward_npu(q, q, q, metadata)
runtime.quant_attention.assert_not_called()
def make_layer(runtime, monkeypatch, method="mxfp8", skip_steps=_DEFAULT_SKIP_STEPS):
layer = object.__new__(layer_mod.Attention)
torch.nn.Module.__init__(layer)
layer.attention = flash()
layer.attn_backend = flash_attn.FlashAttentionBackend
layer._disable_kv_quant = False
layer.layer_idx = 3
cfg = SimpleNamespace(
diffusion_kv_cache_dtype=method,
diffusion_kv_cache_skip_step_indices=skip_steps,
diffusion_kv_cache_skip_layer_indices=None,
parallel_config=SimpleNamespace(ring_degree=1),
)
layer._init_kv_cache_quantization(cfg)
return layer
@pytest.mark.parametrize("method", ["fp8", "mxfp8", "mxfp4"])
def test_global_quant_method_is_published_per_forward(runtime, monkeypatch, method):
layer = make_layer(runtime, monkeypatch, method=method, skip_steps=None)
assert layer._with_kv_cache_dtype(None).extra["kv_cache_dtype"] == method
@pytest.mark.parametrize("method", [None, "auto", "float"])
def test_optout_without_quant_policy_keeps_metadata_unchanged(runtime, monkeypatch, method):
layer = make_layer(runtime, monkeypatch)
layer._disable_kv_quant = True
layer._init_kv_cache_quantization(
SimpleNamespace(
diffusion_kv_cache_dtype=method,
diffusion_kv_cache_skip_step_indices=None,
diffusion_kv_cache_skip_layer_indices=None,
parallel_config=SimpleNamespace(ring_degree=1),
)
)
source = video_metadata()
assert layer._with_kv_cache_dtype(source) is source
def test_step_skip_is_request_local_and_cross_optout(runtime, monkeypatch):
layer = make_layer(runtime, monkeypatch)
ctx = SimpleNamespace(denoise_step_idx=0)
monkeypatch.setattr(layer_mod, "is_forward_context_available", lambda: True)
monkeypatch.setattr(layer_mod, "get_forward_context", lambda: ctx)
source = video_metadata()
for step in list(range(40)) * 2:
ctx.denoise_step_idx = step
resolved = layer._with_kv_cache_dtype(source)
assert resolved.extra["kv_cache_dtype"] == ("float" if step in (0, 1, 38, 39) else "mxfp8")
assert resolved.video_layout is source.video_layout
assert source.extra == {"max_seqlen_q": 4096}
layer._disable_kv_quant = True
assert layer._with_kv_cache_dtype(source).extra["kv_cache_dtype"] == "float"
def test_ring_attention_is_rejected(runtime, monkeypatch):
layer = make_layer(runtime, monkeypatch)
cfg = SimpleNamespace(diffusion_kv_cache_dtype="mxfp8", parallel_config=SimpleNamespace(ring_degree=2))
with pytest.raises(ValueError, match="ring"):
layer._init_kv_cache_quantization(cfg)
def test_sparse_tail_steps_and_dense_quant_dispatch(runtime, monkeypatch):
ctx = SimpleNamespace(denoise_step_idx=49, total_denoise_steps=50)
monkeypatch.setattr(rainfusion_attn, "is_forward_context_available", lambda: True)
monkeypatch.setattr(rainfusion_attn, "get_forward_context", lambda: ctx)
impl = sparse(start_step=2, end_step=2)
metadata = video_metadata(kv_cache_dtype="fp8")
assert impl._resolve_plan(metadata) is None
q = torch.randn(1, 4096, 2, 64, dtype=torch.bfloat16)
impl.forward_npu(q, q, q, metadata)
assert runtime.quant_attention.call_args.kwargs["precision"] == "fp8"
@pytest.mark.parametrize("method", ["fp8", "mxfp4"])
def test_sparse_quant_uses_public_runtime(runtime, monkeypatch, method):
runtime.sparse_attention = Mock(side_effect=lambda q, k, v, **kwargs: q)
monkeypatch.setattr(rainfusion_attn, "_mindiesd_supports_precision", lambda: True)
q = torch.randn(1, 4224, 2, 64, dtype=torch.bfloat16)
out = sparse().forward_npu(q, q, q, video_metadata(kv_cache_dtype=method))
# The sparse path reuses the query tail as the output padding instead of
# zero-filling a fresh buffer; rows past the 4096-row valid prefix are
# never read back downstream (the model unpads by cu_seqlens), so pin the
# passthrough rather than requiring zeros.
assert out.shape == q.shape and torch.equal(out[:, 4096:], q[:, 4096:])
kwargs = runtime.sparse_attention.call_args.kwargs
assert (kwargs["precision"], kwargs["sparse_type"], kwargs["inner_precise"]) == (method, "rf_v3", 4)
runtime.quant_attention.assert_not_called()
def test_sparse_custom_mask_stays_dense(runtime):
metadata = AttentionMetadata(
attn_mask=torch.ones(1, 4096, dtype=torch.bool),
video_layout=VideoTokenLayout(prefix_len=0, latent_grid=(4, 32, 32)),
extra={"max_seqlen_q": 4096},
)
assert sparse()._resolve_plan(metadata) is None
def test_sparse_model_padding_mask_is_equivalent_to_trimming(runtime):
metadata = video_metadata()
metadata.attn_mask = torch.arange(4224)[None] < 4096
assert sparse()._resolve_plan(metadata).used_len == 4096
def test_bsa_operator_failure_never_retries(runtime, monkeypatch):
runtime.sparse_attention = Mock(side_effect=RuntimeError("BSA operator failure"))
monkeypatch.setattr(rainfusion_attn, "_mindiesd_supports_precision", lambda: True)
q = torch.randn(1, 4096, 2, 64, dtype=torch.bfloat16)
with pytest.raises(RuntimeError, match="BSA operator failure"):
sparse().forward_npu(q, q, q, video_metadata(kv_cache_dtype="mxfp4"))
runtime.sparse_attention.assert_called_once()
@pytest.mark.parametrize(
"method,shape,supports_precision,error",
[
("mxfp8", (1, 4096, 2, 64), True, "sparse mxfp8 is not supported"),
("mxfp4", (1, 4096, 2, 64), False, "explicitly support precision"),
("fp8", (2, 4096, 2, 64), True, "batch size 1"),
("fp8", (1, 4096, 2, 32), True, "power-of-two head dimension"),
("mxfp4", (1, 4096, 2, 96), True, "power-of-two head dimension"),
],
)
def test_invalid_sparse_quant_requires_config_change(runtime, monkeypatch, method, shape, supports_precision, error):
runtime.sparse_attention = Mock(side_effect=lambda q, k, v, **kwargs: q)
monkeypatch.setattr(rainfusion_attn, "_mindiesd_supports_precision", lambda: supports_precision)
q = torch.randn(shape, dtype=torch.bfloat16)
with pytest.raises(ValueError, match=error):
sparse().forward_npu(q, q, q, video_metadata(kv_cache_dtype=method))
runtime.sparse_attention.assert_not_called()
def test_layer_selector_requires_index_except_cross_optout(runtime, monkeypatch):
layer = make_layer(runtime, monkeypatch)
layer.layer_idx = None
config = SimpleNamespace(
diffusion_kv_cache_dtype="mxfp8",
diffusion_kv_cache_skip_step_indices=None,
diffusion_kv_cache_skip_layer_indices={0, 3},
parallel_config=SimpleNamespace(ring_degree=1),
)
with pytest.raises(ValueError, match="parseable transformer block index"):
layer._init_kv_cache_quantization(config)
layer._disable_kv_quant = True
layer._init_kv_cache_quantization(config)
assert layer._with_kv_cache_dtype(None).extra["kv_cache_dtype"] == "float"
@pytest.mark.parametrize("prefix", ["transformer.blocks.3.attn1", "transformer_2.blocks.3.attn1"])
@pytest.mark.parametrize("method", ["fp8", "mxfp4"])
def test_expert_layer_and_step_skip_remain_sparse(runtime, monkeypatch, prefix, method):
def execute(q, k, v, *, precision="bf16", **kwargs):
return q
runtime.sparse_attention = Mock(wraps=execute)
monkeypatch.setattr(rainfusion_attn, "_mindiesd_supports_precision", lambda: True)
layer = make_layer(runtime, monkeypatch)
layer.layer_idx = rainfusion_attn._try_extract_layer_index(prefix)
assert layer.layer_idx == 3
config = SimpleNamespace(
diffusion_kv_cache_dtype=method,
diffusion_kv_cache_skip_step_indices={0, 1, 38, 39},
diffusion_kv_cache_skip_layer_indices={3},
parallel_config=SimpleNamespace(ring_degree=1),
)
impl = sparse()
layer.attention = impl
layer.attn_backend = rainfusion_attn.RainFusionAttentionBackend
layer._init_kv_cache_quantization(config)
ctx = SimpleNamespace(denoise_step_idx=0)
monkeypatch.setattr(layer_mod, "is_forward_context_available", lambda: True)
monkeypatch.setattr(layer_mod, "get_forward_context", lambda: ctx)
source = video_metadata(kv_cache_dtype="mxfp8")
q = torch.randn(1, 4096, 2, 64, dtype=torch.bfloat16)
for layer_idx, step in ((3, 0), (3, 2), (4, 0), (4, 1), (4, 2), (4, 37), (4, 38), (4, 39), (4, 0)):
expected = "bf16" if layer_idx == 3 or step in (0, 1, 38, 39) else method
layer.layer_idx = layer_idx
ctx.denoise_step_idx = step
metadata = layer._with_kv_cache_dtype(source)
impl.forward_npu(q, q, q, metadata)
assert runtime.sparse_attention.call_args.kwargs["precision"] == expected
runtime.quant_attention.assert_not_called()
assert source.extra["kv_cache_dtype"] == "mxfp8"
def test_custom_attention_initialization_keeps_upstream_optout(monkeypatch):
monkeypatch.setattr(layer_mod, "get_current_diffusion_config_or_none", lambda: None)
monkeypatch.setattr(layer_mod, "build_parallel_attention_strategy", lambda **kw: object())
monkeypatch.setattr(layer_mod, "NoParallelAttention", lambda: object())
custom = torch.nn.Identity()
layer = layer_mod.Attention(
num_heads=2,
head_size=64,
softmax_scale=0.125,
causal=False,
custom_attention=custom,
skip_sequence_parallel=True,
)
assert layer.attention is custom and layer._kv_cache_dtype is None
def test_legacy_global_fp8_uses_implicit_bsnd(runtime):
q = torch.randn(1, 17, 2, 64, dtype=torch.bfloat16)
impl = flash(layout=None)
assert impl.forward_npu(q, q, q, AttentionMetadata(extra={"kv_cache_dtype": "fp8"})) is q
assert runtime.quant_attention.call_args.kwargs["layout"] == "BSND"
assert runtime.quant_attention.call_args.kwargs["precision"] == "fp8"
@@ -133,18 +133,17 @@ def test_invalid_ref2va_video_spans_fall_back_to_dense():
assert make_impl()._resolve_plan(AttentionMetadata(extra={"max_seqlen_q": 12000}, video_layout=layout)) is None
def test_validate_available_rejects_legacy_mindiesd(monkeypatch):
def test_validate_available_accepts_single_video_mindiesd(monkeypatch):
mindiesd = types.ModuleType("mindiesd")
def sparse_attention(query, key, value, **kwargs):
return query
mindiesd.sparse_attention = sparse_attention
monkeypatch.setattr(mindiesd, "sparse_attention", sparse_attention, raising=False)
monkeypatch.setitem(sys.modules, "mindiesd", mindiesd)
monkeypatch.setattr("importlib.util.find_spec", lambda _: object())
with pytest.raises(ValueError, match="video_spans"):
RainFusionAttentionBackend.validate_available()
RainFusionAttentionBackend.validate_available()
def test_validate_available_accepts_new_mindiesd(monkeypatch):
@@ -153,13 +152,25 @@ def test_validate_available_accepts_new_mindiesd(monkeypatch):
def sparse_attention(query, key, value, *, video_spans=None, **kwargs):
return query
mindiesd.sparse_attention = sparse_attention
monkeypatch.setattr(mindiesd, "sparse_attention", sparse_attention, raising=False)
monkeypatch.setitem(sys.modules, "mindiesd", mindiesd)
monkeypatch.setattr("importlib.util.find_spec", lambda _: object())
RainFusionAttentionBackend.validate_available()
def test_prefix_kv_slicing_contract_is_pinned():
# Regression pin for the #5543 packed-padding crash: reverting the flag
# would pass CI while reintroducing the ValueError for non-64-aligned
# requests. Both halves of the contract must hold together — the impl
# trims [real, pad] packed tensors to the valid prefix itself (so it may
# advertise prefix slicing) and it never reads attn_mask (so it must keep
# refusing one), which is what lets the model skip materializing the
# padding mask that _assert_metadata_compatible would reject.
assert RainFusionAttentionBackend.supports_prefix_kv_slicing is True
assert RainFusionAttentionBackend.supports_attention_mask() is False
@pytest.mark.parametrize("grid", [(4, 24, 40), (1, 24, 40)])
def test_short_video_stays_dense(grid):
assert make_impl()._resolve_plan(make_metadata(grid)) is None
@@ -300,22 +311,21 @@ def _fake_mindiesd_module():
import types
fake = types.ModuleType("mindiesd")
fake.sparse_attention = lambda *args, **kwargs: None
setattr(fake, "sparse_attention", lambda *args, **kwargs: None)
return fake
def test_precision_non_bf16_requires_mindiesd_support():
"""precision != bf16 against a mindiesd lacking the kwarg must raise RuntimeError."""
"""Unsupported sparse precision must fail before any operator executes."""
import sys
impl = make_impl(precision="mix")
sys.modules["mindiesd"] = _fake_mindiesd_module()
try:
with mock.patch.dict(sys.modules, {"mindiesd": _fake_mindiesd_module()}):
with mock.patch.object(rainfusion_attn, "_mindiesd_supports_precision", return_value=False):
with pytest.raises(RuntimeError, match="requires MindIE-SD"):
impl._forward_sparse_npu(None, None, None, None)
finally:
sys.modules.pop("mindiesd", None)
with pytest.raises(ValueError, match="explicitly support precision"):
impl._forward_sparse_npu(
None, None, None, RainFusionPlan(prefix_len=0, used_len=8, latent_shape=[2, 2, 2])
)
def test_precision_non_bf16_passes_gate_when_supported():
@@ -323,8 +333,7 @@ def test_precision_non_bf16_passes_gate_when_supported():
import sys
impl = make_impl(precision="mix")
sys.modules["mindiesd"] = _fake_mindiesd_module()
try:
with mock.patch.dict(sys.modules, {"mindiesd": _fake_mindiesd_module()}):
with mock.patch.object(rainfusion_attn, "_mindiesd_supports_precision", return_value=True):
# q/k/v shapes: [B, S, N, D]; plan geometry must match S.
q = torch.randn(1, 8, 4, 128)
@@ -332,5 +341,3 @@ def test_precision_non_bf16_passes_gate_when_supported():
# The gate must pass; the fake mindiesd returns None so no crash.
out = impl._forward_sparse_npu(q, q, q, plan)
assert out is None
finally:
sys.modules.pop("mindiesd", None)
@@ -0,0 +1,221 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from dataclasses import dataclass
from typing import Any
import pytest
import torch
from vllm_omni.diffusion.attention.backends import ring_flash_attn, ring_pytorch_attn
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.backends.ring.ring_selector import AttnType
from vllm_omni.diffusion.attention.backends.ring.ring_utils import ring_kv_block_valid_length
from vllm_omni.diffusion.attention.parallel import ring as ring_parallel
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
class _SingleRankComm:
rank = 0
world_size = 1
@dataclass(frozen=True)
class _FakeSequenceParallelGroup:
ring_group: object
def _fake_attention_result(q, _k, _v, **_kwargs):
return torch.zeros_like(q), torch.zeros(q.shape[0], q.shape[2], q.shape[1])
@pytest.mark.parametrize(("block_rank", "expected"), [(0, 4), (1, 1), (2, 0)])
def test_global_prefix_is_partitioned_across_ring_blocks(block_rank, expected):
assert ring_kv_block_valid_length(5, 4, block_rank, 3) == expected
def test_absent_prefix_length_keeps_the_full_ring_block():
assert ring_kv_block_valid_length(None, 4, 2, 3) == 4
def test_pytorch_ring_trims_padding_from_each_kv_block(monkeypatch):
captured: dict[str, Any] = {}
def fake_attention(q, k, v, **kwargs):
captured.update(k=k, v=v, **kwargs)
return _fake_attention_result(q, k, v, **kwargs)
monkeypatch.setattr(ring_pytorch_attn, "RingComm", lambda _group: _SingleRankComm())
monkeypatch.setattr(ring_pytorch_attn, "pytorch_attn_forward", fake_attention)
qkv = torch.randn(1, 4, 2, 8)
output = ring_pytorch_attn.ring_pytorch_attn_func(
qkv,
qkv,
qkv,
group=object(),
valid_kv_length=3,
)
assert output.shape == qkv.shape
assert captured["k"].shape[1] == 3
assert captured["v"].shape[1] == 3
def test_pytorch_ring_trims_circulated_blocks_by_source_rank(monkeypatch):
observed_lengths = []
# Each ring step sends K and V separately.
blocks = [torch.randn(1, 4, 2, 8) for _ in range(4)]
class FakeRingComm:
rank = 2
world_size = 3
def __init__(self, _group):
self._next_block = 0
def send_recv(self, _tensor):
block = blocks[self._next_block]
self._next_block += 1
return block
def commit(self):
pass
def wait(self):
pass
def fake_attention(q, k, v, **kwargs):
observed_lengths.append(k.shape[1])
return _fake_attention_result(q, k, v, **kwargs)
monkeypatch.setattr(ring_pytorch_attn, "RingComm", FakeRingComm)
monkeypatch.setattr(ring_pytorch_attn, "pytorch_attn_forward", fake_attention)
qkv = torch.randn(1, 4, 2, 8)
ring_pytorch_attn.ring_pytorch_attn_func(
qkv,
qkv,
qkv,
group=object(),
valid_kv_length=5,
)
# Rank 2 starts with global block 2, then receives blocks 1 and 0.
# The first block is empty and therefore does not launch attention.
assert observed_lengths == [1, 4]
def test_flash_ring_trims_padding_from_each_kv_block(monkeypatch):
captured: dict[str, Any] = {}
def fake_attention(q, k, v, **kwargs):
captured.update(k=k, v=v, **kwargs)
return _fake_attention_result(q, k, v, **kwargs)
monkeypatch.setattr(ring_flash_attn, "RingComm", lambda _group: _SingleRankComm())
monkeypatch.setattr(ring_flash_attn, "select_flash_attn_impl", lambda *_args, **_kwargs: fake_attention)
qkv = torch.randn(1, 4, 2, 8)
output, _ = ring_flash_attn.ring_flash_attn_forward(
object(),
qkv,
qkv,
qkv,
softmax_scale=0.25,
causal=False,
attn_type=AttnType.FA,
valid_kv_length=3,
)
assert output.shape == qkv.shape
assert captured["k"].shape[1] == 3
assert captured["v"].shape[1] == 3
def test_ring_dispatch_forwards_global_valid_kv_length(monkeypatch):
captured: dict[str, Any] = {}
def fake_ring_attention(*_args, **kwargs):
captured.update(kwargs)
return "output"
monkeypatch.setattr(ring_pytorch_attn, "ring_pytorch_attn_func", fake_ring_attention)
strategy = ring_parallel.RingParallelAttention(
_FakeSequenceParallelGroup(ring_group=object()),
attn_backend_pref="sdpa",
)
metadata = AttentionMetadata(extra={"valid_kv_length": 3})
query = torch.randn(1, 4, 2, 8)
assert strategy.run_attention(query, query, query, metadata) == "output"
assert captured["valid_kv_length"] == 3
def test_pytorch_ring_rejects_causal_with_a_valid_prefix(monkeypatch):
"""Trimming a K/V block under causal=True would silently shift the diagonal.
The query block keeps the full padded length while the circulated K/V block
is trimmed, and a causal mask over a rectangular tile is bottom-right
aligned, so the combination must be refused rather than computed.
"""
monkeypatch.setattr(ring_pytorch_attn, "RingComm", lambda _group: _SingleRankComm())
monkeypatch.setattr(ring_pytorch_attn, "pytorch_attn_forward", _fake_attention_result)
qkv = torch.randn(1, 4, 2, 8)
with pytest.raises(ValueError, match="valid_kv_length is not supported with causal=True"):
ring_pytorch_attn.ring_pytorch_attn_func(
qkv,
qkv,
qkv,
causal=True,
group=object(),
valid_kv_length=3,
)
def test_flash_ring_rejects_causal_with_a_valid_prefix(monkeypatch):
"""Same refusal on the Flash-Attention ring path."""
monkeypatch.setattr(ring_flash_attn, "RingComm", lambda _group: _SingleRankComm())
monkeypatch.setattr(
ring_flash_attn,
"select_flash_attn_impl",
lambda *_args, **_kwargs: _fake_attention_result,
)
qkv = torch.randn(1, 4, 2, 8)
with pytest.raises(ValueError, match="valid_kv_length is not supported with causal=True"):
ring_flash_attn.ring_flash_attn_forward(
object(),
qkv,
qkv,
qkv,
softmax_scale=0.25,
causal=True,
attn_type=AttnType.FA,
valid_kv_length=3,
)
def test_ring_paths_still_accept_causal_without_a_valid_prefix(monkeypatch):
"""The guard is scoped to the padded case: plain causal Ring is unchanged."""
monkeypatch.setattr(ring_flash_attn, "RingComm", lambda _group: _SingleRankComm())
monkeypatch.setattr(
ring_flash_attn,
"select_flash_attn_impl",
lambda *_args, **_kwargs: _fake_attention_result,
)
qkv = torch.randn(1, 4, 2, 8)
output, _ = ring_flash_attn.ring_flash_attn_forward(
object(),
qkv,
qkv,
qkv,
softmax_scale=0.25,
causal=True,
attn_type=AttnType.FA,
)
assert output.shape == qkv.shape
+635
View File
@@ -0,0 +1,635 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import datetime
from contextlib import nullcontext
from types import SimpleNamespace
import pytest
import torch
from tests.helpers.runtime import get_distributed_init_method
from vllm_omni.diffusion.cache.seacache import (
SeaCacheBackend,
SeaCacheConfig,
SeaCacheRootHook,
apply_sea_cache_hook,
)
from vllm_omni.diffusion.cache.seacache.sea_filter import (
apply_sea_filter,
extrapolate_residual,
indicator_distance,
)
from vllm_omni.diffusion.cache.selector import get_cache_backend
from vllm_omni.diffusion.cache.teacache.extractors import EXTRACTOR_REGISTRY, CacheContext, get_extractor
from vllm_omni.diffusion.data import DiffusionCacheConfig
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
class TinyCosmos3Transformer(torch.nn.Module):
"""Small model that exposes a cache-neutral execution boundary."""
def _run_gen_layers(self, hidden_gen: torch.Tensor) -> torch.Tensor:
return hidden_gen * 2
def forward(
self,
hidden_states: torch.Tensor,
timestep: torch.Tensor,
text_ids: torch.Tensor | None = None,
text_mask: torch.Tensor | None = None,
video_shape: tuple[int, int, int] | None = None,
noisy_frame_mask: torch.Tensor | None = None,
control_latents: list[torch.Tensor] | torch.Tensor | None = None,
**kwargs,
) -> torch.Tensor:
del timestep, text_ids, text_mask, video_shape, noisy_frame_mask
if kwargs:
raise TypeError(f"Unexpected tiny transformer kwargs: {sorted(kwargs)}")
controls = (
[]
if control_latents is None
else [control_latents]
if isinstance(control_latents, torch.Tensor)
else list(control_latents)
)
inputs = [*controls, hidden_states]
gen_input = torch.cat(
[value.movedim(1, -1).flatten(1, 3) for value in inputs],
dim=1,
)
return self._run_gen_layers(gen_input)
def _extract_tiny_cosmos3_context(
module: TinyCosmos3Transformer,
hidden_states: torch.Tensor,
timestep: torch.Tensor,
text_ids: torch.Tensor | None = None,
text_mask: torch.Tensor | None = None,
video_shape: tuple[int, int, int] | None = None,
noisy_frame_mask: torch.Tensor | None = None,
control_latents: list[torch.Tensor] | torch.Tensor | None = None,
**kwargs,
) -> CacheContext:
del timestep, text_ids, text_mask, video_shape
if kwargs:
raise TypeError(f"Unexpected tiny transformer kwargs: {sorted(kwargs)}")
controls = (
[]
if control_latents is None
else [control_latents]
if isinstance(control_latents, torch.Tensor)
else list(control_latents)
)
vision_items = [*controls, hidden_states]
gen_input = torch.cat(
[value.movedim(1, -1).flatten(1, 3) for value in vision_items],
dim=1,
)
return CacheContext(
modulated_input=gen_input,
hidden_states=gen_input,
encoder_hidden_states=None,
temb=torch.zeros_like(gen_input[:, 0]),
run_transformer_blocks=lambda: (module._run_gen_layers(gen_input),),
postprocess=lambda output: output,
extra_states={
"sea_cache_latents": vision_items,
"sea_cache_noisy_frame_mask": noisy_frame_mask,
},
)
class Cosmos3OmniDiffusersPipeline:
def __init__(self) -> None:
self.transformer = TinyCosmos3Transformer()
self._current_step_index: int | None = None
self._current_sigma: float | None = None
self._num_timesteps: int | None = None
@property
def current_step_index(self) -> int | None:
return self._current_step_index
@property
def current_sigma(self) -> float | None:
return self._current_sigma
@property
def num_timesteps(self) -> int | None:
return self._num_timesteps
def _latent(value: float) -> torch.Tensor:
return torch.full((1, 2, 2, 2, 2), value)
def _run_step(
transformer: TinyCosmos3Transformer,
timestep: int,
value: float,
*,
hook: SeaCacheRootHook | None = None,
context: str = "cond",
control: float | None = None,
noisy_frame_mask: torch.Tensor | None = None,
) -> torch.Tensor:
controls = None if control is None else [_latent(control)]
cache_context = hook.cache_context(context) if hook is not None else nullcontext()
with torch.inference_mode(), cache_context:
return transformer(
hidden_states=_latent(value),
timestep=torch.tensor([timestep]),
noisy_frame_mask=noisy_frame_mask,
control_latents=controls,
)
def _apply_test_hook(
transformer: TinyCosmos3Transformer,
metadata: SimpleNamespace,
config: SeaCacheConfig | None = None,
) -> SeaCacheRootHook:
return apply_sea_cache_hook(
transformer,
config or SeaCacheConfig(threshold=100.0),
current_step_callback=lambda: metadata.step,
current_sigma_callback=lambda: metadata.sigma,
num_inference_steps_callback=lambda: metadata.num_steps,
extractor_fn=_extract_tiny_cosmos3_context,
)
def test_config_validation() -> None:
assert SeaCacheConfig().threshold == 0.25
with pytest.raises(ValueError, match="residual_order"):
SeaCacheConfig(residual_order=-1)
with pytest.raises(ValueError, match="max_consecutive_cached"):
SeaCacheConfig(max_consecutive_cached=-1)
def test_sea_filter_matches_reference_equation() -> None:
hidden = torch.randn(3, 4, 5, 2, dtype=torch.float32)
sigma = 0.4
power_exp = 3.0
spectrum = torch.fft.fftn(hidden, dim=(0, 1, 2))
gain = None
for axis in (0, 1, 2):
frequencies = torch.fft.fftfreq(hidden.shape[axis], dtype=torch.float32)
clean_power = 1.0 / (frequencies.abs().pow(power_exp) + 1e-16)
axis_gain = (1.0 - sigma) * clean_power / ((1.0 - sigma) ** 2 * clean_power + sigma**2 + 1e-16)
shape = [1] * hidden.ndim
shape[axis] = hidden.shape[axis]
gain = axis_gain.reshape(shape) if gain is None else gain * axis_gain.reshape(shape)
assert gain is not None
gain = gain / gain.mean()
expected = torch.fft.ifftn(spectrum * gain, dim=(0, 1, 2)).real
torch.testing.assert_close(
apply_sea_filter(hidden, sigma=sigma, power_exp=power_exp),
expected,
)
def test_indicator_distance_and_linear_extrapolation() -> None:
previous = [torch.ones(2, 2)]
current = [torch.full((2, 2), 1.5)]
assert indicator_distance(current, previous) == pytest.approx(0.5)
assert indicator_distance([torch.ones(3)], previous) == float("inf")
history = [
(0, torch.full((2, 2), 2.0)),
(2, torch.full((2, 2), 6.0)),
]
torch.testing.assert_close(
extrapolate_residual(history, step=3, order=1),
torch.full((2, 2), 8.0),
)
torch.testing.assert_close(
extrapolate_residual(history, step=3, order=0),
torch.full((2, 2), 6.0),
)
quadratic_history = [
(0, torch.zeros(2, 2)),
(1, torch.ones(2, 2)),
(2, torch.full((2, 2), 4.0)),
]
torch.testing.assert_close(
extrapolate_residual(quadratic_history, step=3, order=2),
torch.full((2, 2), 9.0),
)
def test_hook_skips_middle_steps_and_forces_endpoints() -> None:
transformer = TinyCosmos3Transformer()
metadata = SimpleNamespace(step=0, sigma=1.0, num_steps=4)
hook = _apply_test_hook(
transformer,
metadata,
SeaCacheConfig(threshold=100.0, max_consecutive_cached=2),
)
hook.refresh(transformer)
for step, timestep in enumerate((1000, 750, 500, 250)):
metadata.step = step
metadata.sigma = timestep / 1000
_run_step(transformer, timestep, 1.0 - step * 0.01, hook=hook)
assert hook.full_count == 2
assert hook.skip_count == 2
assert [step for step, _ in hook.state_manager._states["cond"].history] == [0, 3]
def test_parameter_sharded_hook_skips_when_all_shard_ranks_agree(monkeypatch: pytest.MonkeyPatch) -> None:
from vllm_omni.diffusion.distributed import parallel_state
transformer = TinyCosmos3Transformer()
metadata = SimpleNamespace(step=0, sigma=1.0, num_steps=3)
hook = _apply_test_hook(transformer, metadata)
hook._parameter_sharded = True
fs_group = object()
reduced_groups: list[object] = []
monkeypatch.setattr(torch.distributed, "is_available", lambda: True)
monkeypatch.setattr(torch.distributed, "is_initialized", lambda: True)
monkeypatch.setattr(
parallel_state,
"get_fs_group",
lambda: SimpleNamespace(world_size=2, device_group=fs_group),
)
monkeypatch.setattr(parallel_state, "get_sequence_parallel_world_size", lambda: 1)
def all_reduce(decision, *, op, group):
assert op == torch.distributed.ReduceOp.MAX
reduced_groups.append(group)
monkeypatch.setattr(torch.distributed, "all_reduce", all_reduce)
_run_step(transformer, 1000, 1.0, hook=hook)
metadata.step = 1
metadata.sigma = 0.5
_run_step(transformer, 500, 0.99, hook=hook)
assert hook.full_count == 1
assert hook.skip_count == 1
assert reduced_groups == [fs_group, fs_group]
def test_parameter_sharded_peer_forces_full_compute(monkeypatch: pytest.MonkeyPatch) -> None:
from vllm_omni.diffusion.distributed import parallel_state
transformer = TinyCosmos3Transformer()
metadata = SimpleNamespace(step=0, sigma=1.0, num_steps=3)
hook = _apply_test_hook(transformer, metadata)
hook._parameter_sharded = True
monkeypatch.setattr(torch.distributed, "is_available", lambda: True)
monkeypatch.setattr(torch.distributed, "is_initialized", lambda: True)
monkeypatch.setattr(
parallel_state,
"get_fs_group",
lambda: SimpleNamespace(world_size=2, device_group=object()),
)
monkeypatch.setattr(parallel_state, "get_sequence_parallel_world_size", lambda: 1)
reduce_count = 0
def all_reduce(decision, *, op, group):
nonlocal reduce_count
del op, group
reduce_count += 1
if reduce_count == 2:
decision.fill_(1)
monkeypatch.setattr(torch.distributed, "all_reduce", all_reduce)
_run_step(transformer, 1000, 1.0, hook=hook)
metadata.step = 1
metadata.sigma = 0.5
_run_step(transformer, 500, 0.99, hook=hook)
assert hook.full_count == 2
assert hook.skip_count == 0
assert hook.state_manager._states["cond"].accumulated_distance == 0.0
def _uneven_cfg_sharded_worker(
rank: int,
init_method: str,
result_queue: torch.multiprocessing.Queue,
) -> None:
from vllm_omni.diffusion.distributed import parallel_state
torch.distributed.init_process_group(
"gloo",
init_method=init_method,
rank=rank,
world_size=4,
timeout=datetime.timedelta(seconds=10),
)
try:
fs_groups = [
(ranks, torch.distributed.new_group(ranks, timeout=datetime.timedelta(seconds=10)))
for ranks in ([0, 1], [2, 3])
]
sp_groups = [
(ranks, torch.distributed.new_group(ranks, timeout=datetime.timedelta(seconds=10)))
for ranks in ([0, 1], [2, 3])
]
cfg_groups = [
(ranks, torch.distributed.new_group(ranks, timeout=datetime.timedelta(seconds=10)))
for ranks in ([0, 2], [1, 3])
]
fs_group = next(group for ranks, group in fs_groups if rank in ranks)
sp_group = next(group for ranks, group in sp_groups if rank in ranks)
cfg_group = next(group for ranks, group in cfg_groups if rank in ranks)
parallel_state._FS = SimpleNamespace(world_size=2, device_group=fs_group)
parallel_state._SP = SimpleNamespace(world_size=2, device_group=sp_group)
hook = SeaCacheRootHook(SeaCacheConfig())
hook._parameter_sharded = True
hook._synchronize_compute(False, torch.device("cpu"))
if rank in (0, 1):
hook._synchronize_compute(False, torch.device("cpu"))
gathered = [torch.zeros(1) for _ in range(2)]
torch.distributed.all_gather(
gathered,
torch.tensor([rank], dtype=torch.float32),
group=cfg_group,
)
result_queue.put((rank, [int(value.item()) for value in gathered]))
finally:
parallel_state._FS = None
parallel_state._SP = None
torch.distributed.destroy_process_group()
def test_parameter_sharded_hook_handles_uneven_cfg_branch_dispatch() -> None:
mp_context = torch.multiprocessing.get_context("spawn")
manager = mp_context.Manager()
result_queue = manager.Queue()
torch.multiprocessing.spawn(
_uneven_cfg_sharded_worker,
args=(get_distributed_init_method("seacache_uneven_cfg_"), result_queue),
nprocs=4,
)
results = sorted(result_queue.get(timeout=2) for _ in range(4))
assert results == [
(0, [0, 2]),
(1, [1, 3]),
(2, [0, 2]),
(3, [1, 3]),
]
def _hybrid_sp_worker(
rank: int,
init_method: str,
result_queue: torch.multiprocessing.Queue,
) -> None:
from vllm_omni.diffusion.distributed import parallel_state
torch.distributed.init_process_group(
"gloo",
init_method=init_method,
rank=rank,
world_size=4,
timeout=datetime.timedelta(seconds=10),
)
try:
fs_groups = [
(ranks, torch.distributed.new_group(ranks, timeout=datetime.timedelta(seconds=10)))
for ranks in ([0, 1], [2, 3])
]
ulysses_groups = [
(ranks, torch.distributed.new_group(ranks, timeout=datetime.timedelta(seconds=10)))
for ranks in ([0, 1], [2, 3])
]
ring_groups = [
(ranks, torch.distributed.new_group(ranks, timeout=datetime.timedelta(seconds=10)))
for ranks in ([0, 2], [1, 3])
]
sp_group = torch.distributed.new_group(
[0, 1, 2, 3],
timeout=datetime.timedelta(seconds=10),
)
fs_group = next(group for ranks, group in fs_groups if rank in ranks)
ulysses_group = next(group for ranks, group in ulysses_groups if rank in ranks)
ring_group = next(group for ranks, group in ring_groups if rank in ranks)
parallel_state._FS = SimpleNamespace(world_size=2, device_group=fs_group)
parallel_state._SP = SimpleNamespace(
world_size=4,
device_group=sp_group,
ulysses_world_size=2,
ulysses_group=ulysses_group,
ring_world_size=2,
ring_group=ring_group,
)
compute = rank == 3
non_sharded_hook = SeaCacheRootHook(SeaCacheConfig())
non_sharded_result = non_sharded_hook._synchronize_compute(compute, torch.device("cpu"))
sharded_hook = SeaCacheRootHook(SeaCacheConfig())
sharded_hook._parameter_sharded = True
sharded_result = sharded_hook._synchronize_compute(compute, torch.device("cpu"))
result_queue.put((rank, non_sharded_result, sharded_result))
finally:
parallel_state._FS = None
parallel_state._SP = None
torch.distributed.destroy_process_group()
def test_hook_synchronizes_full_hybrid_sequence_parallel_group() -> None:
mp_context = torch.multiprocessing.get_context("spawn")
manager = mp_context.Manager()
result_queue = manager.Queue()
torch.multiprocessing.spawn(
_hybrid_sp_worker,
args=(get_distributed_init_method("seacache_hybrid_sp_"), result_queue),
nprocs=4,
)
results = sorted(result_queue.get(timeout=2) for _ in range(4))
assert results == [
(0, True, True),
(1, True, True),
(2, True, True),
(3, True, True),
]
def test_parameter_sharded_hook_fails_open_without_distributed_state(
monkeypatch: pytest.MonkeyPatch,
) -> None:
hook = SeaCacheRootHook(SeaCacheConfig())
hook._parameter_sharded = True
monkeypatch.setattr(torch.distributed, "is_available", lambda: True)
monkeypatch.setattr(torch.distributed, "is_initialized", lambda: False)
assert hook._synchronize_compute(False, torch.device("cpu")) is True
def test_hook_keeps_three_transfer_branches_separate() -> None:
transformer = TinyCosmos3Transformer()
metadata = SimpleNamespace(step=0, sigma=1.0, num_steps=3)
hook = _apply_test_hook(transformer, metadata)
hook.refresh(transformer)
contexts = ("cond", "cond_no_control", "uncond")
for step, (timestep, value) in enumerate(((1000, 1.0), (500, 0.9))):
metadata.step = step
metadata.sigma = timestep / 1000
_run_step(transformer, timestep, value, hook=hook, context=contexts[0], control=0.5)
_run_step(transformer, timestep, value, hook=hook, context=contexts[1])
_run_step(transformer, timestep, value, hook=hook, context=contexts[2], control=0.5)
assert set(hook.state_manager._states) == set(contexts)
assert hook.full_count == 3
assert hook.skip_count == 3
assert len(hook.state_manager._states["cond"].previous_indicator) == 2
assert len(hook.state_manager._states["cond_no_control"].previous_indicator) == 1
def test_hook_fails_open_without_noisy_vision() -> None:
transformer = TinyCosmos3Transformer()
metadata = SimpleNamespace(step=0, sigma=1.0, num_steps=3)
hook = _apply_test_hook(transformer, metadata)
hook.refresh(transformer)
all_clean = torch.zeros(1, 1, 2, 1, 1)
_run_step(transformer, 1000, 1.0, hook=hook, noisy_frame_mask=all_clean)
metadata.step = 1
metadata.sigma = 0.5
_run_step(transformer, 500, 0.9, hook=hook, noisy_frame_mask=all_clean)
assert hook.full_count == 0
assert hook.skip_count == 0
def test_conditioning_only_model_failure_runs_forward_once(monkeypatch: pytest.MonkeyPatch) -> None:
transformer = TinyCosmos3Transformer()
metadata = SimpleNamespace(step=0, sigma=1.0, num_steps=3)
hook = _apply_test_hook(transformer, metadata)
hook.refresh(transformer)
forward_calls = 0
def fail_forward(hidden_gen: torch.Tensor) -> torch.Tensor:
nonlocal forward_calls
forward_calls += 1
raise RuntimeError("model forward failed")
monkeypatch.setattr(transformer, "_run_gen_layers", fail_forward)
all_clean = torch.zeros(1, 1, 2, 1, 1)
with pytest.raises(RuntimeError, match="model forward failed"):
_run_step(transformer, 1000, 1.0, hook=hook, noisy_frame_mask=all_clean)
assert forward_calls == 1
def test_hook_fails_open_without_explicit_context() -> None:
transformer = TinyCosmos3Transformer()
metadata = SimpleNamespace(step=0, sigma=1.0, num_steps=2)
hook = _apply_test_hook(transformer, metadata)
hook.refresh(transformer)
_run_step(transformer, 1000, 1.0)
assert hook.full_count == 0
assert hook.skip_count == 0
assert hook.state_manager._states == {}
def test_hook_uses_exact_sigma_callback(monkeypatch: pytest.MonkeyPatch) -> None:
from vllm_omni.diffusion.cache.seacache import hook as hook_module
transformer = TinyCosmos3Transformer()
metadata = SimpleNamespace(step=0, sigma=0.37, num_steps=2)
observed_sigmas: list[float] = []
original_filter = hook_module.apply_sea_filter
def recording_filter(hidden_states: torch.Tensor, sigma: float, power_exp: float) -> torch.Tensor:
observed_sigmas.append(sigma)
return original_filter(hidden_states, sigma, power_exp)
monkeypatch.setattr(hook_module, "apply_sea_filter", recording_filter)
hook = _apply_test_hook(transformer, metadata)
hook.refresh(transformer)
_run_step(transformer, timestep=999, value=1.0, hook=hook)
assert observed_sigmas
assert all(sigma == pytest.approx(0.37) for sigma in observed_sigmas)
def test_backend_selector_and_refresh(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setitem(EXTRACTOR_REGISTRY, "TinyCosmos3Transformer", _extract_tiny_cosmos3_context)
class FSDPTinyCosmos3Transformer(TinyCosmos3Transformer):
pass
assert get_extractor(FSDPTinyCosmos3Transformer) is _extract_tiny_cosmos3_context
backend = get_cache_backend(
"sea_cache",
{
"sea_threshold": 0.4,
"sea_residual_order": 0,
},
)
assert isinstance(backend, SeaCacheBackend)
assert backend.config.sea_threshold == 0.4
pipeline = Cosmos3OmniDiffusersPipeline()
backend.enable(pipeline)
hook = pipeline.transformer._hook_registry.get_hook(SeaCacheRootHook._HOOK_NAME)
assert isinstance(hook, SeaCacheRootHook)
assert callable(getattr(pipeline, "_cache_context_factory", None))
for name in ("_seacache_skip", "_seacache_record", "_seacache_residual", "_seacache_last_residual"):
assert not hasattr(pipeline.transformer, name)
pipeline._current_step_index = 0
pipeline._current_sigma = 1.0
pipeline._num_timesteps = 7
_run_step(pipeline.transformer, 1000, 1.0, hook=hook)
assert hook.full_count == 1
backend.refresh(pipeline, num_inference_steps=7)
assert hook.full_count == 0
assert hook.skip_count == 0
assert hook.state_manager._states == {}
def test_backend_uses_resolved_pipeline_metadata_not_refresh_argument(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setitem(EXTRACTOR_REGISTRY, "TinyCosmos3Transformer", _extract_tiny_cosmos3_context)
pipeline = Cosmos3OmniDiffusersPipeline()
backend = SeaCacheBackend(DiffusionCacheConfig())
backend.enable(pipeline)
hook = pipeline.transformer._hook_registry.get_hook(SeaCacheRootHook._HOOK_NAME)
assert isinstance(hook, SeaCacheRootHook)
backend.refresh(pipeline, num_inference_steps=35)
pipeline._num_timesteps = 50
pipeline._current_step_index = 0
pipeline._current_sigma = 1.0
_run_step(pipeline.transformer, 1000, 1.0, hook=hook)
assert hook.full_count == 1
assert hook.num_inference_steps_callback is not None
assert hook.num_inference_steps_callback() == 50
pipeline._current_step_index = 1
pipeline._current_sigma = 0.98
_run_step(pipeline.transformer, 980, 0.99, hook=hook)
assert hook.full_count == 1
assert hook.skip_count == 1
def test_shared_config_defaults() -> None:
config = DiffusionCacheConfig()
assert config.sea_threshold == 0.25
assert config.sea_residual_order == 1
assert config.sea_max_consecutive_cached == 2
assert config.sea_power_exp == 3.0
+5 -5
View File
@@ -68,12 +68,12 @@ class BaseExtractorTest(ABC):
pass
@abstractmethod
def get_module(self):
def get_module(self, module, /):
"""Return model module instance."""
pass
@abstractmethod
def get_sample_inputs(self):
def get_sample_inputs(self, sample_inputs, /):
"""Return sample inputs for model."""
pass
@@ -737,10 +737,10 @@ class TestMiniMaxH3Extractor(BaseExtractorTest):
monkeypatch,
):
"""Strict SP must not mix local TeaCache state with gathered block rows."""
from vllm_omni.diffusion.attention.ops import minimax_h3_modulation
from vllm_omni.diffusion.cache.teacache.config import TeaCacheConfig
from vllm_omni.diffusion.cache.teacache.hook import TeaCacheHook
from vllm_omni.diffusion.distributed import parallel_state
from vllm_omni.diffusion.layers import indexed_modulation
seq_len = sample_inputs["x"].shape[1]
local_len = seq_len // 2
@@ -844,13 +844,13 @@ class TestMiniMaxH3Extractor(BaseExtractorTest):
)
monkeypatch.setattr(parallel_state, "get_sp_group", lambda: sp_group)
original_indexed_scale_shift = minimax_h3_modulation.indexed_scale_shift_
original_indexed_scale_shift = indexed_modulation.indexed_scale_shift_
def capture_indexed_scale_shift(hidden, shift, scale, indices):
captured_modulation_indices.append(indices.clone())
return original_indexed_scale_shift(hidden, shift, scale, indices)
monkeypatch.setattr(minimax_h3_modulation, "indexed_scale_shift_", capture_indexed_scale_shift)
monkeypatch.setattr(indexed_modulation, "indexed_scale_shift_", capture_indexed_scale_shift)
local_img_pos = torch.tensor([0, 1])
local_audio_pos = torch.tensor([2, 3])
@@ -325,7 +325,7 @@ def _runner(
model_config=SimpleNamespace(max_model_len=max_len),
scheduler_config=SimpleNamespace(
max_num_batched_tokens=max_num_batched_tokens,
max_num_seqs=max_num_seqs,
max_num_seqs=max_num_seqs * max_rows_per_request,
),
parallel_config=SimpleNamespace(
decode_context_parallel_size=cp_size,
@@ -403,7 +403,7 @@ def test_initialize_failure_does_not_publish_partial_cache_state(
successful_init_cache = model_runner_backend_module.init_kv_cache
vllm_config = SimpleNamespace(
model_config=SimpleNamespace(max_model_len=16),
scheduler_config=SimpleNamespace(max_num_batched_tokens=32, max_num_seqs=1),
scheduler_config=SimpleNamespace(max_num_batched_tokens=32, max_num_seqs=2),
parallel_config=SimpleNamespace(
decode_context_parallel_size=1,
cp_kv_cache_interleave_size=1,
@@ -445,7 +445,7 @@ def test_initialize_failure_does_not_publish_partial_cache_state(
assert backend.block_tables is None
assert backend.paged_attention_adapter is None
assert backend._kv_cache_layer_adapters["layer-0"].kv_cache == "placeholder-0"
assert backend.vllm_config.scheduler_config.max_num_seqs == 1
assert backend.vllm_config.scheduler_config.max_num_seqs == 2
monkeypatch.setattr(model_runner_backend_module, "init_kv_cache", successful_init_cache)
backend.initialize_kv_cache(config)
@@ -58,6 +58,7 @@ def _od_config(**overrides):
gpu_memory_utilization=0.9,
kv_cache_memory_bytes=None,
max_num_seqs=1,
diffusion_kv_max_rows_per_request=1,
max_num_batched_tokens=64,
num_gpus=1,
)
@@ -1,16 +1,23 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from contextlib import nullcontext
from types import SimpleNamespace
from unittest import mock
import pytest
import torch
from vllm.config import KVTransferConfig
from vllm.v1.core.kv_cache_manager import KVCacheBlocks
from vllm.v1.outputs import KVConnectorOutput
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.diffusion.diffusion_kv.kv_connector import (
KVTransferRegistrationError,
commit_kv_load,
parse_kv_transfer_config,
shutdown_kv_connector,
wait_for_kv_load,
)
from vllm_omni.diffusion.sched.base_scheduler import BaseScheduler
from vllm_omni.diffusion.vllm_config import create_diffusion_vllm_config
@@ -138,3 +145,205 @@ def test_shutdown_kv_connector_is_idempotent() -> None:
assert ensure_shutdown.call_count == 2
scheduler_connector.shutdown.assert_called_once()
def test_commit_aligns_cfg_transport_pages_without_extending_computed_prefix() -> None:
requests = tuple(
SimpleNamespace(
request_id=f"req/{sequence_id}",
kv_transfer_params={"num_transfer_tokens": 9},
num_tokens=16,
num_computed_tokens=0,
)
for sequence_id in range(2)
)
manager = SimpleNamespace(
get_blocks=lambda _request_id: KVCacheBlocks(([0, 1, 2, 3],)),
kv_cache_config=SimpleNamespace(kv_cache_groups=[SimpleNamespace(kv_cache_spec=SimpleNamespace(block_size=4))]),
)
connector = mock.Mock()
expected = commit_kv_load(connector, manager, requests, [7, 5])
assert expected == {"req/0", "req/1"}
calls = connector.update_state_after_alloc.call_args_list
assert [len(call.args[1].blocks[0]) for call in calls] == [3, 3]
assert [call.args[2] for call in calls] == [7, 5]
assert [request.num_computed_tokens for request in requests] == [7, 5]
def test_wait_without_pending_load_uses_vllm_post_forward_once() -> None:
connector = mock.Mock()
output = mock.Mock(invalid_block_ids=set())
active_connector = mock.Mock(kv_connector=connector)
active_connector.post_forward.return_value = output
scheduler_output = SimpleNamespace(
kv_transfer_request_ids=set(),
finished_req_ids={"finished"},
kv_finished_request_ids={"finished/diffusion-kv/0", "finished/diffusion-kv/1"},
)
result = wait_for_kv_load(active_connector, scheduler_output, timeout=1.0)
assert result is output
active_connector.pre_forward.assert_called_once_with(scheduler_output)
active_connector.post_forward.assert_called_once_with({"finished/diffusion-kv/0", "finished/diffusion-kv/1"})
connector.get_finished.assert_not_called()
def test_timeout_returns_partial_completion_without_releasing_pages():
active = mock.Mock()
active.kv_connector.get_finished.return_value = (set(), {"cfg0"})
active.kv_connector.get_block_ids_with_load_errors.return_value = set()
active.post_forward.return_value = KVConnectorOutput()
scheduled = SimpleNamespace(kv_transfer_request_ids={"cfg0", "cfg1"}, kv_finished_request_ids=set())
output = wait_for_kv_load(active, scheduled, timeout=0)
assert output.finished_recving == {"cfg0"}
active.kv_connector.request_finished.assert_not_called()
active.post_forward.assert_called_once_with(set())
@pytest.fixture
def cfg_registration():
requests = tuple(
SimpleNamespace(
request_id=f"cfg{i}",
status=None,
num_tokens=8,
kv_transfer_params={"num_transfer_tokens": 4, "transfer_id": "ticket", "do_remote_prefill": True},
)
for i in range(2)
)
manager = SimpleNamespace(
get_blocks=lambda _: KVCacheBlocks(([0, 1],)),
kv_cache_config=SimpleNamespace(kv_cache_groups=[SimpleNamespace(kv_cache_spec=SimpleNamespace(block_size=4))]),
)
return requests, manager
def test_cfg_validation_is_atomic_before_connector_registration(cfg_registration):
requests, manager = cfg_registration
requests[1].kv_transfer_params["num_transfer_tokens"] = 9
connector = mock.Mock()
with pytest.raises(KVTransferRegistrationError, match="boundary"):
commit_kv_load(connector, manager, requests, [4, 4])
connector.update_state_after_alloc.assert_not_called()
@pytest.mark.parametrize("fail_init", [False, True])
def test_sp_connector_init_snapshots_topology_and_restores_model_tp(monkeypatch, fail_init):
import vllm.distributed.parallel_state as parallel_state
import vllm_omni.diffusion.diffusion_kv.kv_connector as module
import vllm_omni.diffusion.distributed.parallel_state as omni_parallel
tp = SimpleNamespace(world_size=1, rank_in_group=0)
sp = SimpleNamespace(world_size=2, rank_in_group=1)
monkeypatch.setattr(parallel_state, "_TP", tp)
monkeypatch.setattr(omni_parallel, "get_sp_group", lambda: sp)
snapshot: dict[str, int] = {}
def initialize(*args):
snapshot.update(
rank=parallel_state.get_tensor_model_parallel_rank(),
size=parallel_state.get_tensor_model_parallel_world_size(),
)
if fail_init:
raise RuntimeError("initialization failed")
monkeypatch.setattr(module, "ensure_kv_transfer_initialized", initialize)
config = SimpleNamespace(
kv_transfer_config=SimpleNamespace(kv_connector="MooncakeConnector", engine_id="dit"),
parallel_config=SimpleNamespace(prefill_context_parallel_size=2),
)
with pytest.raises(RuntimeError, match="initialization failed") if fail_init else nullcontext():
module.init_worker_kv_connector(config, object())
assert parallel_state._TP is tp
assert snapshot == {"rank": 1, "size": 2}
def test_partial_mooncake_registration_is_replaced_by_empty_notifications(cfg_registration):
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_connector import (
MooncakeConnector,
MooncakeConnectorScheduler,
)
scheduler = object.__new__(MooncakeConnectorScheduler)
scheduler.is_kv_producer = False
scheduler.is_kv_consumer = True
scheduler._reqs_need_recv = {}
connector = object.__new__(MooncakeConnector)
connector.connector_scheduler = scheduler
requests, manager = cfg_registration
for request in requests:
request.kv_transfer_params.update(remote_engine_id="ar", remote_bootstrap_addr="http://localhost:8998")
def register(request, blocks, count):
scheduler._reqs_need_recv[request.request_id] = (request, blocks)
request.kv_transfer_params["do_remote_prefill"] = False
if request.request_id == "cfg1":
raise RuntimeError("partial registration")
connector.update_state_after_alloc = register
with pytest.raises(KVTransferRegistrationError, match="partial registration"):
commit_kv_load(connector, manager, requests, [4, 4])
assert set(scheduler._reqs_need_recv) == {"cfg0", "cfg1"}
assert all(blocks == [] for _, blocks in scheduler._reqs_need_recv.values())
metadata = scheduler.build_connector_meta(None)
# Even partial registration failure sends every row in one per-rank batch,
# preserving the producer's complete fan-out count for the shared ticket.
assert set(metadata.reqs_to_recv["ar"]) == {"cfg0", "cfg1"}
assert all(
meta.transfer_id == "ticket" and meta.local_block_ids == [] for meta in metadata.reqs_to_recv["ar"].values()
)
@pytest.mark.parametrize("timeout", [0, -1, float("inf"), "60"])
def test_native_transfer_timeout_must_be_positive_finite(timeout):
with pytest.raises(ValueError, match="transfer_timeout"):
parse_kv_transfer_config(
{
**KV_TRANSFER_CONFIG,
"kv_connector_extra_config": {"transfer_timeout": timeout},
}
)
def test_receive_completion_requires_all_ranks_across_polls():
from vllm_omni.diffusion.executor.abstract import DiffusionExecutor
from vllm_omni.diffusion.sched.interface import CachedRequestData, DiffusionSchedulerOutput
executor = SimpleNamespace(od_config=SimpleNamespace(num_gpus=2))
executor.collective_rpc = mock.Mock(
side_effect=[
[KVConnectorOutput(finished_recving={"cfg0", "cfg1"}), KVConnectorOutput(finished_recving={"cfg0"})],
[KVConnectorOutput(), KVConnectorOutput(finished_recving={"cfg1"})],
]
)
scheduled = DiffusionSchedulerOutput(
step_id=0,
scheduled_new_reqs=[],
scheduled_cached_reqs=CachedRequestData.make_empty(),
finished_req_ids=set(),
num_running_reqs=0,
num_waiting_reqs=0,
kv_connector_metadata=object(),
kv_transfer_request_ids={"cfg0", "cfg1"},
)
result = DiffusionExecutor.prepare_kv_for_forward(executor, scheduled)
assert result.finished_recving == {"cfg0"}
scheduled.kv_transfer_request_ids = set()
result = DiffusionExecutor.prepare_kv_for_forward(executor, scheduled)
assert result.finished_recving == {"cfg1"}
assert not executor._kv_receive_completed_ranks
def test_native_transfer_rejects_sleep_without_changing_legacy_sleep():
with pytest.raises(ValueError, match="registered pages must remain mapped"):
OmniDiffusionConfig.from_kwargs(
diffusion_kv_mode="paged_scheduler",
diffusion_kv_max_rows_per_request=2,
kv_transfer_config=dict(KV_TRANSFER_CONFIG),
enable_sleep_mode=True,
)
assert OmniDiffusionConfig.from_kwargs(enable_sleep_mode=True).enable_sleep_mode
@@ -61,13 +61,14 @@ class _MetadataScheduler(BaseScheduler):
def test_scheduler_copies_opaque_params_to_sequence_requests() -> None:
params = {"transfer_id": "xfer-req-0", "do_remote_prefill": True}
params = {"transfer_id": "xfer-req-0", "do_remote_prefill": True, "num_transfer_tokens": 3}
sequence = DiffusionKVRequest(
"req-0/diffusion-kv/0",
sequence_id=0,
prefix_len=4,
target_len=2,
seq_len=6,
prompt_token_ids=[10, 11, 12, 13],
)
request = OmniDiffusionRequest(
prompt="prompt",
@@ -83,6 +84,9 @@ def test_scheduler_copies_opaque_params_to_sequence_requests() -> None:
assert state.diffusion_kv_requests[0].kv_transfer_params == params
assert state.diffusion_kv_requests[0].kv_transfer_params is not params
assert sequence.prompt_token_ids == [10, 11, 12]
assert sequence.num_prompt_tokens == 3
assert sequence.seq_len == 6
def test_diffusion_kv_metadata_uses_native_cache_group_block_ids() -> None:
@@ -0,0 +1,204 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Exercise upstream Mooncake completion accounting without device/network I/O."""
import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
import msgspec
import pytest
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake import mooncake_connector as mc
from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.outputs import KVConnectorOutput
from vllm_omni.diffusion.diffusion_kv.kv_connector import install_mooncake_cfg_fanout
from vllm_omni.worker.mixins import OmniWorkerMixin
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
@pytest.fixture
def producer(monkeypatch):
worker = object.__new__(mc.MooncakeConnectorWorker)
worker.shutdown = Mock() # No hardware constructor, sockets or listener thread.
worker.is_kv_consumer = False
worker.tp_rank, worker.tp_size = 0, 1
worker.transfer_topo = SimpleNamespace(handshake_target_ranks=lambda size: list(range(size)))
worker.reqs_need_send, worker.finished_sending_reqs = {}, set()
for name in (
"kv_caches_base_addr",
"block_len_per_layer",
"kv_block_len_per_layer",
"registered_layer_names",
"registered_layer_indices",
"registered_group_indices",
):
setattr(worker, name, [])
worker._get_transfer_regions = Mock(return_value=[])
worker._producer_cache_is_replicated = Mock(return_value=False)
worker._encoder = msgspec.msgpack.Encoder()
worker._sender_executor = None
worker._send_blocks = Mock(return_value=0)
worker.xfer_stats = Mock()
worker._build_transfer_params = AsyncMock(return_value=([1], [2], [16], [], None))
monkeypatch.setattr(mc, "_align_transfer_regions", lambda *_: ([], [], None))
monkeypatch.setattr(mc, "_validate_asymmetric_region_lengths", lambda **_: None)
monkeypatch.setattr(mc.envs, "VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", 0.05)
connector = object.__new__(mc.MooncakeConnector)
connector.connector_worker = worker
return connector
async def register(worker, ticket):
worker.sender_loop = asyncio.get_running_loop()
for blocks in ([], [[10]]):
meta = mc.MooncakeConnectorMetadata()
meta.add_new_req(ticket, blocks, {"transfer_id": ticket}, load_remote_cache=False)
await worker.record_send_reqs(meta)
return worker.reqs_need_send[ticket]
def packet(rank, ranks, tickets, empty=False):
return mc.MooncakeXferMetadata(
remote_hostname="localhost",
remote_port=1234 + rank,
remote_tp_size=ranks,
remote_tp_rank=rank,
req_blocks={
f"{ticket}/{row}": (ticket, [] if empty else [[100 + rank * 10 + row]])
for ticket, rows in tickets.items()
for row in range(rows)
},
kv_caches_base_addr=[],
block_lens=[],
kv_block_lens=[],
)
async def send(worker, rank, ranks, tickets, empty=False):
sock = SimpleNamespace(send_multipart=AsyncMock())
await worker.send_kv_to_decode(str(rank).encode(), sock, packet(rank, ranks, tickets, empty))
return [
msgspec.msgpack.decode(c.args[0][1], type=mc.MooncakeXferResponse) for c in sock.send_multipart.call_args_list
]
@pytest.mark.asyncio
@pytest.mark.parametrize("rows", [1, 2])
@pytest.mark.parametrize("ranks", [2, 4])
@pytest.mark.parametrize("in_flight", [False, True])
async def test_source_pages_wait_for_every_rank_and_row(producer, rows, ranks, in_flight):
worker = producer.connector_worker
entered, release = asyncio.Event(), asyncio.Event()
original = worker._build_transfer_params
async def plan(ready, meta, *regions):
if in_flight and meta.remote_tp_rank == ranks - 1:
entered.set()
await release.wait()
return await original(ready, meta, *regions)
worker._build_transfer_params = plan
install_mooncake_cfg_fanout(producer)
adapted = worker._build_transfer_params
install_mooncake_cfg_fanout(producer)
assert worker._build_transfer_params is adapted # Do not multiply twice.
ticket = await register(worker, "request")
pending = asyncio.create_task(send(worker, ranks - 1, ranks, {"request": rows})) if in_flight else None
try:
if pending is not None:
await asyncio.wait_for(entered.wait(), 2)
for rank in range(ranks - 1):
await send(worker, rank, ranks, {"request": rows})
assert ticket.need_send == ranks * rows
assert ticket.sent == (rank + 1) * rows
assert worker.reqs_need_send["request"] is ticket
finished = await worker.fetch_finished_sending_reqs()
scheduler = SimpleNamespace(connector=None, requests={"request": object()}, _free_blocks=Mock())
Scheduler._update_from_kv_xfer_finished(scheduler, KVConnectorOutput(finished_sending=finished))
scheduler._free_blocks.assert_not_called()
release.set()
responses = (
await asyncio.wait_for(pending, 2) if pending else await send(worker, ranks - 1, ranks, {"request": rows})
)
assert sum(len(response.ok_reqs or []) for response in responses) == rows
assert all(not response.err_reqs for response in responses)
assert "request" not in worker.reqs_need_send
finished = await worker.fetch_finished_sending_reqs()
assert finished == {"request"}
Scheduler._update_from_kv_xfer_finished(scheduler, KVConnectorOutput(finished_sending=finished))
scheduler._free_blocks.assert_called_once()
assert not await worker.fetch_finished_sending_reqs()
finally:
release.set()
if pending is not None:
await asyncio.gather(pending, return_exceptions=True)
@pytest.mark.asyncio
@pytest.mark.parametrize("empty", [False, True])
@pytest.mark.parametrize("ranks", [1, 2])
async def test_mixed_tickets_and_empty_block_notifications(producer, empty, ranks):
worker = producer.connector_worker
if empty:
worker._build_transfer_params.return_value = ([], [], [], [], None)
install_mooncake_cfg_fanout(producer)
single, cfg = await register(worker, "single"), await register(worker, "cfg")
await asyncio.gather(*(send(worker, rank, ranks, {"single": 1, "cfg": 2}, empty) for rank in range(ranks)))
assert (single.need_send, single.sent) == (ranks, ranks)
assert (cfg.need_send, cfg.sent) == (2 * ranks, 2 * ranks)
assert await worker.fetch_finished_sending_reqs() == {"single", "cfg"}
assert not worker.reqs_need_send
@pytest.mark.asyncio
@pytest.mark.parametrize("failure", ["row_count", "transport"])
async def test_failed_rank_does_not_report_source_complete(producer, failure):
worker = producer.connector_worker
install_mooncake_cfg_fanout(producer)
ticket = await register(worker, "request")
await send(worker, 0, 2, {"request": 2})
if failure == "transport":
worker._send_blocks.return_value = -1
responses = await send(worker, 1, 2, {"request": 1 if failure == "row_count" else 2})
assert any(response.err_reqs for response in responses)
assert ticket.sent == 2 and ticket.need_send == 4 and ticket.sending == 0
assert worker.reqs_need_send["request"] is ticket
assert not await worker.fetch_finished_sending_reqs()
# Preserve upstream timeout cleanup after all in-flight writes have stopped.
ticket.expire_time = 0
assert await worker.fetch_finished_sending_reqs() == {"request"}
assert not worker.reqs_need_send
def test_worker_installs_adapter_after_native_initialization(producer, monkeypatch):
import vllm.distributed.kv_transfer as kv_transfer
worker = producer.connector_worker
original = worker._build_transfer_params
class UpstreamWorker:
def initialize_from_config(self, config):
assert config == "config"
assert worker._build_transfer_params is original
class OmniWorker(OmniWorkerMixin, UpstreamWorker):
pass
monkeypatch.setattr(kv_transfer, "has_kv_transfer_group", lambda: True)
monkeypatch.setattr(kv_transfer, "get_kv_transfer_group", lambda: producer)
object.__new__(OmniWorker).initialize_from_config("config")
assert worker._build_transfer_params is not original
@pytest.mark.parametrize("role", ["other_connector", "scheduler", "consumer"])
def test_adapter_leaves_other_roles_untouched(producer, role):
worker = producer.connector_worker
original = worker._build_transfer_params
if role == "scheduler":
producer.connector_worker = None
elif role == "consumer":
worker.is_kv_consumer = True
install_mooncake_cfg_fanout(object() if role == "other_connector" else producer)
assert worker._build_transfer_params is original
@@ -94,7 +94,7 @@ class _FakeAttentionGroup:
return self.builder
@dataclass(frozen=True, slots=True)
@dataclass(slots=True)
class _FakeNativeMetadata:
build_id: int
causal: bool
@@ -102,6 +102,7 @@ class _FakeNativeMetadata:
query_start_loc_cpu: torch.Tensor
positions: torch.Tensor
slot_mappings: torch.Tensor
max_num_splits: int = 0
class _FakeLayer:
@@ -288,6 +289,8 @@ def test_omni_paged_backend_consumes_context_and_restores_diffusion_shape(
assert output.shape == query.shape
assert torch.equal(output, query)
assert layer.calls[0][0].shape == (5, 2, 4)
assert layer.calls[0][1] is None
assert layer.calls[0][2] is None
assert layer.native_events == ["update", "forward"]
assert layer.calls[0][3] is events[0][2]
@@ -440,9 +443,7 @@ def test_platform_prewrite_updates_once_then_piecewise_reads_cache(monkeypatch:
def test_omni_paged_backend_runs_hunyuan_piecewise_segments(monkeypatch: pytest.MonkeyPatch) -> None:
adapter, _, layer, events = _make_adapter(monkeypatch)
# Exercise the Ascend-only homogeneous batch path. CUDA keeps its native
# output-buffer contract and is covered by the GPU adapter tests.
monkeypatch.setattr(adapter_module.current_omni_platform, "is_npu", lambda: True)
layer.impl.vllm_flash_attn_version = 2
batch = adapter.prepare_batch(
[
DiffusionPagedAttentionRow(
@@ -499,10 +500,10 @@ def test_omni_paged_backend_runs_hunyuan_piecewise_segments(monkeypatch: pytest.
assert torch.equal(layer.updates[0][0], key.reshape(12, 2, 4))
assert torch.equal(layer.updates[0][1], value.reshape(12, 2, 4))
assert [call[0].shape[0] for call in layer.calls] == [4, 6, 2]
assert [call[1].shape[0] for call in layer.calls] == [4, 6, 2]
assert [call[2].shape[0] for call in layer.calls] == [4, 6, 2]
assert all(call[1] is None and call[2] is None for call in layer.calls)
assert all(call[3] is event[2] for call, event in zip(layer.calls, events[1:], strict=True))
assert [metadata.build_id for metadata in context.piecewise_native_metadata] == [1, 2, 3]
assert [metadata.max_num_splits for metadata in context.piecewise_native_metadata] == [1, 1, 1]
# The first metadata build is the normal whole-query path. Piecewise calls
# then use causal [3, 5), full [5, 8), and causal [8, 9) segments.
@@ -539,6 +540,51 @@ def test_omni_paged_backend_runs_hunyuan_piecewise_segments(monkeypatch: pytest.
]
def test_homogeneous_piecewise_packs_strided_query_only_per_segment(
monkeypatch: pytest.MonkeyPatch,
) -> None:
adapter, _, _, _ = _make_adapter(monkeypatch)
batch = adapter.prepare_batch(
[
DiffusionPagedAttentionRow(
request_id="req-0",
sequence_id=0,
query_len=6,
seq_len=9,
kv_start_pos=3,
),
DiffusionPagedAttentionRow(
request_id="req-1",
sequence_id=1,
query_len=6,
seq_len=9,
kv_start_pos=3,
),
]
)
packed_qkv = torch.randn(2, 6, 3, 2, 4)
query, key, value = packed_qkv.unbind(dim=2)
assert not query.is_contiguous()
metadata = SimpleNamespace(
attn_mask=None,
full_attn_spans=[[(5, 8)], [(5, 8)]],
query_ranges=None,
extra={},
)
with adapter.activate(batch):
context = adapter.prepare_layer_context(
"layer-0",
query,
key,
value,
omni_attn_metadata=metadata,
)
assert not context.query.is_contiguous()
assert context.query.data_ptr() == query.data_ptr()
def test_piecewise_metadata_snapshots_reused_native_scheduler_buffer(monkeypatch: pytest.MonkeyPatch) -> None:
adapter, _, _, _ = _make_adapter(monkeypatch)
shared_scheduler_metadata = torch.zeros(1, dtype=torch.int32)
@@ -1232,7 +1278,7 @@ def test_layer_adapter_accepts_platform_native_backend_and_uses_rank_local_heads
ulysses_degree=2,
)
assert selected_backends == [(adapter_module.AttentionBackendEnum.FLASH_ATTN, {}, 2)]
assert selected_backends == [(adapter_module.AttentionBackendEnum.FLASH_ATTN, {}, 1)]
assert specialized_backends == [(native_backend, 2)]
assert config.attention_config.backend is None
assert config.attention_config.backend_per_kind is original_backend_per_kind
@@ -43,8 +43,7 @@ class _SmokeDiffusionAttention(nn.Module):
self.softmax_scale = _HEAD_SIZE**-0.5
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required for native paged attention")
def test_adapter_executes_native_paged_attention_on_non_contiguous_blocks() -> None:
def _native_adapter(num_rows: int = 1):
device = torch.device("cuda", torch.accelerator.current_device_index())
vllm_config = VllmConfig(
cache_config=CacheConfig(
@@ -89,8 +88,8 @@ def test_adapter_executes_native_paged_attention_on_non_contiguous_blocks() -> N
canonical_spec = native_layer.spec
kv_cache_config = KVCacheConfig(
num_blocks=4,
kv_cache_tensors=[build_kv_cache_tensor(canonical_spec, 4, [_LAYER_NAME])],
num_blocks=4 * num_rows,
kv_cache_tensors=[build_kv_cache_tensor(canonical_spec, 4 * num_rows, [_LAYER_NAME])],
kv_cache_groups=[
KVCacheGroupSpec(
layer_names=[_LAYER_NAME],
@@ -120,14 +119,15 @@ def test_adapter_executes_native_paged_attention_on_non_contiguous_blocks() -> N
)
block_tables = BlockTables(
block_sizes=[_BLOCK_SIZE],
max_num_reqs=1,
max_num_batched_tokens=32,
max_num_reqs=num_rows,
max_num_batched_tokens=32 * num_rows,
max_num_blocks_per_group=[2],
device=device,
kernel_block_sizes=kernel_block_sizes,
)
block_tables.append_block_ids(0, ([3, 1],), overwrite=True)
for row in range(num_rows):
block_tables.append_block_ids(row, ([4 * row + 3, 4 * row + 1],), overwrite=True)
block_tables.apply_staged_writes()
adapter = DiffusionPagedAttentionAdapter(
vllm_config=vllm_config,
@@ -136,11 +136,17 @@ def test_adapter_executes_native_paged_attention_on_non_contiguous_blocks() -> N
block_tables=block_tables,
attn_groups=attn_groups,
layers={_LAYER_NAME: native_layer},
resolve_row=lambda _request_id, _sequence_id, _context_id: DiffusionPagedAttentionRowBinding(
row_index=0,
resolve_row=lambda _request_id, sequence_id, _context_id: DiffusionPagedAttentionRowBinding(
row_index=sequence_id,
max_seq_len=19,
),
)
return adapter, diffusion_layer, device
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required for native paged attention")
def test_adapter_executes_native_paged_attention_on_non_contiguous_blocks() -> None:
adapter, diffusion_layer, device = _native_adapter()
prefix_batch = adapter.prepare_batch(
[
DiffusionPagedAttentionRow(
@@ -258,3 +264,48 @@ def test_adapter_executes_native_paged_attention_on_non_contiguous_blocks() -> N
torch.testing.assert_close(prefix_output, prefix_reference, rtol=2e-2, atol=2e-2)
torch.testing.assert_close(suffix_output, suffix_reference, rtol=2e-2, atol=2e-2)
torch.testing.assert_close(piecewise_output, piecewise_reference, rtol=2e-2, atol=2e-2)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required for native paged attention")
def test_hunyuan_homogeneous_cfg_paged_attention_graph_replay() -> None:
"""Real paged kernels, strided QKV, mixed image spans and changed replay inputs."""
adapter, layer, device = _native_adapter(num_rows=2)
packed = torch.randn(2, 19, 3, _NUM_HEADS, _HEAD_SIZE, device=device, dtype=torch.float16)
query, key, value = packed.unbind(dim=2)
backend = FlashAttentionImpl(
num_heads=_NUM_HEADS, head_size=_HEAD_SIZE, softmax_scale=layer.softmax_scale, num_kv_heads=_NUM_HEADS
)
batch = adapter.prepare_batch(
[DiffusionPagedAttentionRow(request_id="cfg", sequence_id=i, query_len=19, seq_len=19) for i in range(2)]
)
metadata = AttentionMetadata(full_attn_spans=[[(5, 10)], [(5, 10)]])
with adapter.activate(batch):
context = adapter.prepare_layer_context(_LAYER_NAME, query, key, value, omni_attn_metadata=metadata)
assert context.piecewise_plan.homogeneous_batch_shape == (2, 19)
warmup = torch.cuda.Stream()
warmup.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(warmup):
for _ in range(3):
backend.forward_paged(context)
torch.cuda.current_stream().wait_stream(warmup)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
captured = backend.forward_paged(context)
output_ptr = captured.data_ptr()
mask = torch.ones(19, 19, device=device, dtype=torch.bool).tril()
mask[5:10, 5:10] = True
for _ in range(2):
packed.copy_(torch.randn_like(packed))
graph.replay()
actual = captured.clone()
eager = backend.forward_paged(context)
reference = F.scaled_dot_product_attention(
query.transpose(1, 2),
key.transpose(1, 2),
value.transpose(1, 2),
attn_mask=mask,
scale=layer.softmax_scale,
).transpose(1, 2)
torch.testing.assert_close(actual.reshape_as(reference), reference, rtol=2e-2, atol=2e-2)
torch.testing.assert_close(actual, eager, rtol=2e-2, atol=2e-2)
assert captured.data_ptr() == output_ptr
@@ -176,10 +176,11 @@ def test_worker_honors_explicit_kv_memory_budget(monkeypatch) -> None:
profile_request = object()
assert worker.determine_available_kv_memory(profile_request) == [4096]
worker.model_runner.profile_run.assert_called_once_with(profile_request)
worker.model_runner.profile_run.assert_not_called()
def test_worker_treats_zero_kv_memory_budget_as_profiled_auto_sizing(monkeypatch) -> None:
monkeypatch.setattr(diffusion_worker_module, "current_omni_platform", SimpleNamespace(empty_cache=Mock()))
worker = object.__new__(DiffusionWorker)
worker.rank = 0
worker.init_snapshot = SimpleNamespace(free_memory=900)
@@ -209,6 +210,7 @@ def test_worker_treats_zero_kv_memory_budget_as_profiled_auto_sizing(monkeypatch
@pytest.mark.parametrize("non_kv_cache_memory", [750, 800])
def test_worker_rejects_non_positive_profiled_kv_memory(monkeypatch, non_kv_cache_memory: int) -> None:
monkeypatch.setattr(diffusion_worker_module, "current_omni_platform", SimpleNamespace(empty_cache=Mock()))
worker = object.__new__(DiffusionWorker)
worker.rank = 0
worker.init_snapshot = SimpleNamespace(free_memory=900)
@@ -245,6 +247,7 @@ def test_worker_rejects_non_positive_profiled_kv_memory(monkeypatch, non_kv_cach
def test_worker_profiles_activation_headroom_instead_of_current_residency(monkeypatch) -> None:
monkeypatch.setattr(diffusion_worker_module, "current_omni_platform", SimpleNamespace(empty_cache=Mock()))
worker = object.__new__(DiffusionWorker)
worker.rank = 0
worker.init_snapshot = SimpleNamespace(free_memory=1200)
@@ -310,3 +313,31 @@ def test_rank_probe_gathers_local_failure_before_raising(monkeypatch) -> None:
)
assert gathered == [(False, "ValueError: local failure")]
def test_hunyuan_native_layer_identity_matches_ar_spec(monkeypatch):
import vllm_omni.diffusion.models.hunyuan_image3.hunyuan_image3_transformer as hy3
monkeypatch.setattr(hy3, "get_tensor_model_parallel_world_size", lambda: 1)
monkeypatch.setattr(hy3, "get_sequence_parallel_world_size", lambda: 1)
monkeypatch.setattr(hy3, "get_allgather_parallel_world_size", lambda: 1)
monkeypatch.setattr(hy3, "get_sequence_parallel_rank", lambda: 0)
monkeypatch.setattr(hy3, "QKVParallelLinear", lambda **_: nn.Identity())
monkeypatch.setattr(hy3, "RowParallelLinear", lambda **_: nn.Identity())
monkeypatch.setattr(hy3, "get_rope", lambda **_: nn.Identity())
# Only backend construction is fake; execute both HY3 constructors and the
# real runner spec-discovery path, including the actual Attention prefix.
def attention(**kwargs):
return _attention(enabled=kwargs.get("paged_kv_cache_role") is not None, prefix=kwargs["prefix"])
monkeypatch.setattr(hy3, "Attention", attention)
model = hy3.HunYuanAttention(
config=SimpleNamespace(num_key_value_heads=2, attention_head_dim=8),
hidden_size=16,
num_heads=2,
num_kv_heads=2,
prefix="layers.3.self_attn",
)
runner = _runner(model.image_attn.attn)
assert set(runner.get_kv_cache_spec()) == {"model.layers.3.self_attn.attn"}
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Tests for CFG (Classifier-Free Guidance) parallel functionality.
CPU tests mock the CFG process group and validate mixin logic without GPUs.
@@ -32,8 +32,8 @@ from vllm_omni.diffusion.distributed.parallel_state import (
)
from vllm_omni.platforms import current_omni_platform
_L4_TWO_GPU = hardware_marks(res={"cuda": "L4"}, num_cards=2)
_L4_THREE_GPU = hardware_marks(res={"cuda": "L4"}, num_cards=3)
_L4_TWO_GPU = hardware_marks(res={"cuda": ["L4", "B200"]}, num_cards=2)
_L4_THREE_GPU = hardware_marks(res={"cuda": ["L4", "B200"]}, num_cards=3)
def _set_random_seeds(seed: int) -> None:
@@ -1009,7 +1009,7 @@ def _run_multi_branch_gpu_parity(
@pytest.mark.full_model
@pytest.mark.diffusion
@pytest.mark.parallel
@hardware_test(res={"cuda": "L4"}, num_cards=2)
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=2)
@pytest.mark.parametrize("batch_size", [2])
@pytest.mark.parametrize("cfg_normalize", [False, True])
@pytest.mark.parametrize("extra_kwargs", [None, {"step_i": 1}])
+46 -3
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Tests for SeqAllToAll4D, SeqAllToAll5D, and RingComm communication primitives.
CPU tests use gloo on CPU tensors (no GPU). Nightly parity tests run the same
@@ -24,8 +24,8 @@ from vllm_omni.diffusion.distributed.parallel_state import (
)
from vllm_omni.platforms import current_omni_platform
_L4_TWO_GPU = hardware_marks(res={"cuda": "L4"}, num_cards=2)
_L4_FOUR_GPU = hardware_marks(res={"cuda": "L4"}, num_cards=4)
_L4_TWO_GPU = hardware_marks(res={"cuda": ["L4", "B200"]}, num_cards=2)
_L4_FOUR_GPU = hardware_marks(res={"cuda": ["L4", "B200"]}, num_cards=4)
DeviceKind = Literal["cpu", "cuda"]
@@ -461,3 +461,46 @@ def test_ring_p2p_parity(world_size: int, dtype: torch.dtype):
device_kind="cuda",
master_port=29501,
)
def _run_fused_qkv_matches_three_4d(
local_rank: int,
world_size: int,
device_kind: DeviceKind,
master_port: int,
) -> None:
"""LingBot's fused (B, S/N, 3, H, D) exchange must equal three per-tensor 4D exchanges."""
from vllm_omni.diffusion.distributed.comm import all_to_all_5D
device = _worker_device(local_rank, device_kind)
if device_kind == "cuda":
current_omni_platform.set_device(device)
_init_worker(local_rank, world_size, master_port, device_kind)
initialize_model_parallel(ulysses_degree=world_size)
sp_group = get_sp_group().ulysses_group
try:
batch, seq_per_rank, heads, head_size = 1, 6, 4 * world_size, 8
# Distinguishable values: rank, q/k/v index, position, head, feature.
base = torch.arange(seq_per_rank * heads * head_size, dtype=torch.float32, device=device).reshape(
batch, seq_per_rank, heads, head_size
)
tensors = [base + 1000.0 * local_rank + 100000.0 * which for which in range(3)]
separate = [SeqAllToAll4D.apply(sp_group, t, 2, 1, False) for t in tensors]
fused = all_to_all_5D(torch.stack(tensors, dim=2), scatter_idx=3, gather_idx=1, group=sp_group)
assert fused.shape == (batch, seq_per_rank * world_size, 3, heads // world_size, head_size)
for which, expected in enumerate(separate):
assert torch.equal(fused.unbind(2)[which], expected), f"q/k/v index {which} differs on rank {local_rank}"
finally:
destroy_distributed_env()
@pytest.mark.core_model
@pytest.mark.diffusion
@pytest.mark.cpu
@pytest.mark.parametrize("world_size", [2, 4])
def test_fused_qkv_all_to_all_matches_three_4d_exchanges_cpu(world_size: int) -> None:
torch.multiprocessing.spawn(
_run_fused_qkv_matches_three_4d,
args=(world_size, "cpu", 29613),
nprocs=world_size,
)
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""
System test for Expert Parallel (EP).
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""FLUX.2-dev VAE patch-parallel correctness tests.
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for SP subgroup construction in parallel_state.py."""
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Unit tests for SP subgroup construction for diffusion parallel state."""
from __future__ import annotations
@@ -8,12 +8,55 @@ from types import SimpleNamespace
import pytest
import torch
import vllm.distributed.parallel_state as vllm_parallel_state
from tests.helpers.runtime import get_distributed_init_method
from vllm_omni.diffusion.distributed import parallel_state as omni_parallel_state
from vllm_omni.diffusion.distributed.parallel_state import RankGenerator, set_seq_parallel_pg
pytestmark = [pytest.mark.diffusion, pytest.mark.parallel, pytest.mark.core_model, pytest.mark.cpu]
def ensure_parallel_state_initialized():
"""Ensure torch distributed is initialized and that all world / count vars are set."""
assert torch.distributed.is_initialized()
assert omni_parallel_state._WORLD is not None
assert vllm_parallel_state._WORLD is not None
assert vllm_parallel_state._NODE_COUNT is not None
def ensure_parallel_state_not_initialized():
"""Ensure torch distributed is not initialized and that all world / count vars are unset."""
assert not torch.distributed.is_initialized()
assert omni_parallel_state._WORLD is None
assert vllm_parallel_state._WORLD is None
assert vllm_parallel_state._NODE_COUNT is None
def test_omni_manages_vllm_distributed_state(monkeypatch):
"""Verify Omni initializes and tears down vLLM's distributed state properly.
This is a regression test for ensuring vLLM Omni also sets up vLLM's vars correctly
to avoid potential misalignment in cases where Omni uses vLLM's native coordinator,
e.g., MoE + diffusion.
"""
ensure_parallel_state_not_initialized()
monkeypatch.setattr(omni_parallel_state.current_omni_platform, "get_device_count", lambda: 1)
monkeypatch.setattr(omni_parallel_state.current_omni_platform, "set_device", lambda _device: None)
omni_parallel_state.init_distributed_environment(
world_size=1,
rank=0,
local_rank=0,
distributed_init_method=get_distributed_init_method(),
backend="gloo",
)
try:
ensure_parallel_state_initialized()
finally:
omni_parallel_state.destroy_distributed_env()
ensure_parallel_state_not_initialized()
def _fake_new_group_factory(created_groups: list[SimpleNamespace]):
def _fake_new_group(ranks, *args, **kwargs):
group = SimpleNamespace(ranks=list(ranks))
@@ -31,9 +31,9 @@ from vllm_omni.diffusion.distributed.parallel_state import (
from vllm_omni.diffusion.distributed.pipeline_parallel import AsyncLatents, PipelineParallelMixin
from vllm_omni.platforms import current_omni_platform
_L4_TWO_GPU = hardware_marks(res={"cuda": "L4"}, num_cards=2)
_L4_THREE_GPU = hardware_marks(res={"cuda": "L4"}, num_cards=3)
_L4_FOUR_GPU = hardware_marks(res={"cuda": "L4"}, num_cards=4)
_L4_TWO_GPU = hardware_marks(res={"cuda": ["L4", "B200"]}, num_cards=2)
_L4_THREE_GPU = hardware_marks(res={"cuda": ["L4", "B200"]}, num_cards=3)
_L4_FOUR_GPU = hardware_marks(res={"cuda": ["L4", "B200"]}, num_cards=4)
DeviceKind = Literal["cpu", "cuda"]
_UNIT_MARKS = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Real multi-process numeric equivalence gate for SANA-Video sequence parallel.
Runs the native transformer directly (no pipeline, no topology validation) with
@@ -273,7 +273,7 @@ def _baseline_worker(
@pytest.mark.full_model
@pytest.mark.diffusion
@pytest.mark.parallel
@hardware_test(res={"cuda": "L4"}, num_cards=2)
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=2)
@pytest.mark.parametrize("task", ["t2v", "i2v"])
@pytest.mark.parametrize("num_frames", [21, 5])
def test_sp2_matches_sp1_fp32(task: str, num_frames: int) -> None:
@@ -290,7 +290,7 @@ def test_sp2_matches_sp1_fp32(task: str, num_frames: int) -> None:
@pytest.mark.full_model
@pytest.mark.diffusion
@pytest.mark.parallel
@hardware_test(res={"cuda": "L4"}, num_cards=4)
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=4)
@pytest.mark.parametrize("task", ["t2v", "i2v"])
@pytest.mark.parametrize("num_frames", [21, 5])
def test_sp4_matches_sp1_fp32(task: str, num_frames: int) -> None:
@@ -307,7 +307,7 @@ def test_sp4_matches_sp1_fp32(task: str, num_frames: int) -> None:
@pytest.mark.full_model
@pytest.mark.diffusion
@pytest.mark.parallel
@hardware_test(res={"cuda": "L4"}, num_cards=4)
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=4)
def test_sp2_cfg2_matches_sp1_fp32() -> None:
"""Four processes: CFG branches with distinct inputs each run their own SP
group; catches CFG/SP group crossover and deadlocks."""
@@ -324,7 +324,7 @@ def test_sp2_cfg2_matches_sp1_fp32() -> None:
@pytest.mark.full_model
@pytest.mark.diffusion
@pytest.mark.parallel
@hardware_test(res={"cuda": "L4"}, num_cards=4)
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=4)
def test_tp2_sp2_matches_sp1_fp32() -> None:
"""Four processes: TP shards heads and channels while SP shards frames; the
combined mesh must still reproduce the serial output."""
@@ -342,7 +342,7 @@ def test_tp2_sp2_matches_sp1_fp32() -> None:
@pytest.mark.full_model
@pytest.mark.diffusion
@pytest.mark.parallel
@hardware_test(res={"cuda": "L4"}, num_cards=2)
@hardware_test(res={"cuda": ["L4", "B200"]}, num_cards=2)
def test_sp2_bf16_drift_informational() -> None:
"""Records the bf16 reduction-reorder drift magnitude; the load-bearing
numeric gate is the fp32 suite above."""
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""
System test for Sequence Parallel (SP) backends: Ulysses and Ring attention.
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""VAE patch-parallel decode parity tests for diffusion models.
@@ -145,7 +145,7 @@ def _run_generate(
@pytest.mark.full_model
@pytest.mark.diffusion
@pytest.mark.parallel
@hardware_test(res={"cuda": "H100"}, num_cards={"cuda": 4})
@hardware_test(res={"cuda": ["H100", "B200"]}, num_cards={"cuda": 4})
@pytest.mark.parametrize("model_case", MODEL_CASES)
def test_vae_patch_parallel_tp2(model_case: dict[str, Any], tmp_path: Path):
if current_omni_platform.is_npu():
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import os
from types import SimpleNamespace
@@ -353,6 +356,94 @@ def test_attention_wrapper_rejects_spatial_extent_change(monkeypatch: pytest.Mon
wan_spatial_shard._SPATIAL_SHARD_CONTEXT.reset(token)
def _reference_conv_input(conv, x, cache_x):
"""The conv input the previous implementation built: cat, F.pad, then halo_exchange."""
padding = list(conv._padding)
if cache_x is not None and padding[4] > 0:
x = torch.cat([cache_x, x], dim=2)
padding[4] -= cache_x.shape[2]
x = torch.nn.functional.pad(x, padding)
x_padded, _, _ = wan_spatial_shard.halo_exchange(
x, group=object(), halo_size=conv.halo_size, split_dim=conv.split_dim
)
return x_padded, x.shape[conv.split_tensor_dim]
def _dist_conv(split_dim, kernel=(3, 3, 3), padding=(1, 1, 1)):
from diffusers.models.autoencoders.autoencoder_kl_wan import WanCausalConv3d
torch.manual_seed(0)
source = WanCausalConv3d(3, 4, kernel, padding=padding)
return source, wan_spatial_shard.WanDistCausalConv3d(source, object(), split_dim=split_dim)
@pytest.mark.core_model
@pytest.mark.cpu
@pytest.mark.parametrize("split_dim", ["width", "height"])
@pytest.mark.parametrize("with_cache", [False, True])
def test_single_pass_conv_input_matches_cat_pad_halo_on_one_rank(monkeypatch, split_dim, with_cache):
"""One rank, halo-bearing kernel: same bytes as the previous cat -> F.pad -> halo_exchange path."""
monkeypatch.setattr(wan_spatial_shard, "_rank_world", lambda group: (0, 1))
_, conv = _dist_conv(split_dim)
x = torch.randn(1, 3, 2, 6, 8)
cache_x = torch.randn(1, 3, 2, 6, 8) if with_cache else None
expected, expected_extent = _reference_conv_input(conv, x, cache_x)
got, got_extent = conv._assemble_input(x, cache_x)
assert got.shape == expected.shape and got_extent == expected_extent
assert torch.equal(got, expected)
@pytest.mark.core_model
@pytest.mark.cpu
def test_single_pass_conv_rejects_cache_longer_than_causal_padding():
_, conv = _dist_conv("width")
with pytest.raises(AssertionError, match="temporal cache exceeds"):
conv._assemble_input(torch.randn(1, 3, 2, 6, 8), torch.randn(1, 3, 3, 6, 8))
@pytest.mark.core_model
@pytest.mark.cpu
@pytest.mark.parametrize("split_dim", ["width", "height"])
def test_single_pass_conv_without_a_halo_matches_the_stock_causal_conv(monkeypatch, split_dim):
"""A kernel with no spatial extent along the split (the temporal conv) needs no halo and equals the stock conv."""
monkeypatch.setattr(wan_spatial_shard, "_rank_world", lambda group: (0, 1))
source, conv = _dist_conv(split_dim, kernel=(3, 1, 1), padding=(1, 0, 0))
x = torch.randn(1, 3, 2, 6, 8)
cache_x = torch.randn(1, 3, 2, 6, 8)
assert torch.equal(conv(x, cache_x), source(x, cache_x))
assert torch.equal(conv(x, None), source(x, None))
@pytest.mark.core_model
@pytest.mark.cpu
@pytest.mark.parametrize("split_dim", ["width", "height"])
@pytest.mark.parametrize("rank", [0, 1])
@pytest.mark.parametrize("kernel,padding", [((3, 3, 3), (1, 1, 1)), ((3, 1, 1), (0, 0, 0))])
def test_single_pass_conv_input_matches_cat_pad_halo_on_two_ranks(monkeypatch, split_dim, rank, kernel, padding):
"""Same bytes as cat -> F.pad -> halo_exchange, halos included, on either rank of a pair."""
monkeypatch.setattr(wan_spatial_shard, "_rank_world", lambda group: (rank, 2))
def fake_p2p(*, rank, world_size, group, top_row_ref, bottom_row_ref, recv_top_buf, recv_bottom_buf):
# A neighbour's halo is whatever it sent; stand in with a marker derived from our own edge so
# both the reference and the single-pass path see the same exchange. Global edges stay zero.
recv_top_buf.copy_(top_row_ref * 0 + 7.0) if rank > 0 else recv_top_buf.zero_()
recv_bottom_buf.copy_(bottom_row_ref * 0 + 9.0) if rank < world_size - 1 else recv_bottom_buf.zero_()
monkeypatch.setattr(wan_spatial_shard, "_halo_exchange_p2p", fake_p2p)
_, conv = _dist_conv(split_dim, kernel=kernel, padding=padding)
x = torch.randn(1, 3, 1, 6, 8)
cache_x = torch.randn(1, 3, 2, 6, 8)
expected, expected_extent = _reference_conv_input(conv, x, cache_x)
got, got_extent = conv._assemble_input(x, cache_x)
assert got.shape == expected.shape and got_extent == expected_extent
assert torch.equal(got, expected)
@pytest.mark.core_model
@pytest.mark.cpu
def test_halo_exchange_single_rank_noop(monkeypatch: pytest.MonkeyPatch):
@@ -538,7 +629,7 @@ def _spatial_shard_decode_worker(rank: int, split_dim: str, return_dict, master_
@pytest.mark.full_model
@pytest.mark.diffusion
@pytest.mark.parallel
@hardware_test(res={"cuda": "H100"}, num_cards=_SPATIAL_SHARD_WORLD_SIZE)
@hardware_test(res={"cuda": ["H100", "B200"]}, num_cards=_SPATIAL_SHARD_WORLD_SIZE)
@pytest.mark.parametrize("split_dim", ["height", "width"])
def test_spatial_shard_decode_matches_reference(split_dim: str):
manager = mp.get_context("spawn").Manager()
@@ -41,13 +41,13 @@ from vllm_omni.diffusion.distributed.parallel_state import (
initialize_model_parallel,
model_parallel_is_initialized,
)
from vllm_omni.diffusion.layers.mot.mot_qkv_parallel_linear import (
from vllm_omni.diffusion.models.bagel.mot.mot_qkv_parallel_linear import (
MoTQKVParallelLinear,
)
from vllm_omni.diffusion.layers.mot.mot_row_parallel_linear import (
from vllm_omni.diffusion.models.bagel.mot.mot_row_parallel_linear import (
MoTRowParallelLinear,
)
from vllm_omni.diffusion.layers.mot.ops.mot_gemm import (
from vllm_omni.diffusion.models.bagel.mot.ops.mot_gemm import (
get_best_mot_config,
)
+4 -1
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# ruff: noqa: N803, E741
"""Layer-level correctness & performance test for MoTRMSNorm.
@@ -20,7 +23,7 @@ import torch
from vllm import ir
from vllm.config import VllmConfig, set_current_vllm_config
from vllm_omni.diffusion.layers.mot.mot_layernorm import MoTRMSNorm
from vllm_omni.diffusion.models.bagel.mot.mot_layernorm import MoTRMSNorm
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.gpu]
@@ -1,8 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import pytest
import torch
import vllm_omni.diffusion.layers.custom_op as custom_op
from vllm_omni.diffusion.layers.mot.mot_layernorm import MoTRMSNorm
from vllm_omni.diffusion.models.bagel.mot.mot_layernorm import MoTRMSNorm
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
+2 -2
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Unit tests for the CustomOp platform-dispatch base class."""
import pytest
@@ -39,7 +39,7 @@ def test_forward_cuda_still_requires_an_implementation():
def test_mot_rmsnorm_dispatches_on_xpu_without_an_override():
"""MoTRMSNorm relies on the inherited fallback (regression test)."""
from vllm_omni.diffusion.layers.mot.mot_layernorm import MoTRMSNorm
from vllm_omni.diffusion.models.bagel.mot.mot_layernorm import MoTRMSNorm
assert "forward_xpu" not in MoTRMSNorm.__dict__
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import pytest
import torch
@@ -80,3 +80,113 @@ def test_fused_qk_norm_rope_matches_bf16_reference(seq_len):
torch.testing.assert_close(actual_q, expected_q, atol=0.0625, rtol=0.02)
torch.testing.assert_close(actual_k, expected_k, atol=0.0625, rtol=0.02)
# ---------------------------------------------------------------------------
# General geometry (any even head_dim, here Boogu-Image's 120) in both
# pairing modes, against the module's own eager reference at the same
# tolerance as the MiniMax-H3 test above.
# ---------------------------------------------------------------------------
_BOOGU_HEAD_DIM = 120
def _boogu_inputs(strided: bool):
torch.manual_seed(11)
if strided:
# Slices of a wider head axis: the op must honour q/k strides
# (merged-QKV projections hand the op such views).
q = torch.randn(4139, 35, _BOOGU_HEAD_DIM, device="cuda", dtype=torch.bfloat16)[:, :28]
k = torch.randn(4139, 35, _BOOGU_HEAD_DIM, device="cuda", dtype=torch.bfloat16)[:, :7]
else:
q = torch.randn(4139, 28, _BOOGU_HEAD_DIM, device="cuda", dtype=torch.bfloat16)
k = torch.randn(4139, 7, _BOOGU_HEAD_DIM, device="cuda", dtype=torch.bfloat16)
q_weight = torch.randn(_BOOGU_HEAD_DIM, device="cuda", dtype=torch.bfloat16)
k_weight = torch.randn(_BOOGU_HEAD_DIM, device="cuda", dtype=torch.bfloat16)
freqs = torch.randn(4139, _BOOGU_HEAD_DIM // 2, device="cuda", dtype=torch.float32)
rope_table = torch.cat((torch.cos(freqs), torch.sin(freqs)), dim=-1)
return q, k, q_weight, k_weight, rope_table
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.skipif(not HAS_TRITON, reason="Triton required")
@pytest.mark.parametrize("strided", [False, True])
def test_fused_qk_norm_rope_interleaved(strided):
from vllm_omni.diffusion.layers.fused_qk_norm_rope import (
_eager_qk_norm_rope,
_launch_fused_qk_norm_rope,
fused_qk_norm_rope,
)
q, k, q_weight, k_weight, rope_table = _boogu_inputs(strided)
expected = _eager_qk_norm_rope(q, k, q_weight, k_weight, rope_table, _EPS, _BOOGU_HEAD_DIM, _BOOGU_HEAD_DIM, True)
# Check the public op AND the launcher directly: the latter cannot fall
# back to eager, so a silent dispatch regression cannot go green here.
for actual in (
fused_qk_norm_rope(q, k, q_weight, k_weight, rope_table, _EPS, interleaved=True),
_launch_fused_qk_norm_rope(q, k, q_weight, k_weight, rope_table, _EPS, interleaved=True),
):
torch.testing.assert_close(actual[0], expected[0], atol=0.0625, rtol=0.02)
torch.testing.assert_close(actual[1], expected[1], atol=0.0625, rtol=0.02)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.skipif(not HAS_TRITON, reason="Triton required")
def test_fused_qk_norm_rope_half_split_general_dim():
"""head_dim=120 off the MiniMax-H3 128 pin, half-split pairing.
Exercises the generalised combined kernel's half-split mode via the
launcher. It is not routed in production (half-split traffic keeps the
untouched pre-existing per-tensor kernel and its 128/96 contract, so the
public op falls back to eager at this geometry), pending the
maintainers' call.
"""
from vllm_omni.diffusion.layers.fused_qk_norm_rope import (
_eager_qk_norm_rope,
_launch_fused_qk_norm_rope,
)
q, k, q_weight, k_weight, rope_table = _boogu_inputs(strided=False)
expected = _eager_qk_norm_rope(q, k, q_weight, k_weight, rope_table, _EPS, _BOOGU_HEAD_DIM, _BOOGU_HEAD_DIM)
actual = _launch_fused_qk_norm_rope(q, k, q_weight, k_weight, rope_table, _EPS, interleaved=False)
torch.testing.assert_close(actual[0], expected[0], atol=0.0625, rtol=0.02)
torch.testing.assert_close(actual[1], expected[1], atol=0.0625, rtol=0.02)
def test_fused_qk_norm_rope_min_tokens_resolution(monkeypatch):
"""The op-level token-gate override: unset or blank -> caller's default; a
non-negative integer string overrides it (``0`` = always fuse); anything
else is rejected naming the variable."""
from vllm_omni.diffusion.layers.fused_qk_norm_rope import fused_qk_norm_rope_min_tokens
env = "VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS"
monkeypatch.delenv(env, raising=False)
assert fused_qk_norm_rope_min_tokens(2048) == 2048
for blank in ("", " "):
monkeypatch.setenv(env, blank)
assert fused_qk_norm_rope_min_tokens(2048) == 2048
monkeypatch.setenv(env, "0")
assert fused_qk_norm_rope_min_tokens(2048) == 0
monkeypatch.setenv(env, "4096")
assert fused_qk_norm_rope_min_tokens(2048) == 4096
for bad in ("-1", "abc"):
monkeypatch.setenv(env, bad)
with pytest.raises(ValueError, match=env):
fused_qk_norm_rope_min_tokens(2048)
@pytest.mark.skipif(not torch.cuda.is_available() or not HAS_TRITON, reason="CUDA and Triton required")
@pytest.mark.parametrize("interleaved", [False, True])
def test_fused_qk_norm_rope_large_storage_offsets(interleaved):
"""Only three tokens, but the last row lies beyond signed 32-bit indexing."""
from vllm_omni.diffusion.layers.fused_qk_norm_rope import fused_qk_norm_rope
# 4 GiB of backing storage; initialize only the three small visible rows.
q = torch.empty_strided((3, 1, 128), (2**30, 128, 1), device="cuda", dtype=torch.bfloat16)
q.fill_(1)
weight = torch.ones(128, device="cuda", dtype=torch.bfloat16)
table = torch.zeros(3, 96, device="cuda", dtype=torch.bfloat16)
table[:, :48] = 1
actual = fused_qk_norm_rope(q, q, weight, weight, table, _EPS, interleaved=interleaved)
for value in actual:
torch.testing.assert_close(value, torch.ones_like(value))
@@ -0,0 +1,125 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import pytest
import torch
from diffusers.models.embeddings import apply_rotary_emb
from vllm.triton_utils import HAS_TRITON
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion]
def test_fused_qk_rope_fake_and_cpu_eligibility():
from vllm_omni.diffusion.layers.fused_qk_rope import (
_fused_qk_rope_fake,
fused_qk_rope,
fused_qk_rope_supported,
)
q = torch.randn(2, 3, 4, 8, dtype=torch.bfloat16)
k = torch.randn_like(q)
cos = torch.randn(3, 8)
sin = torch.randn_like(cos)
fake_q, fake_k = _fused_qk_rope_fake(q, k, cos, sin)
assert fake_q.shape == q.shape and fake_q.dtype == q.dtype
assert fake_k.shape == k.shape and fake_k.dtype == k.dtype
assert not fused_qk_rope_supported(q, k, cos, sin)
with pytest.raises(ValueError, match="contiguous CUDA BF16"):
fused_qk_rope(q, k, cos, sin)
def _cuda_inputs(batch: int, sequence: int, heads: int = 24, head_dim: int = 128):
q = torch.randn(batch, sequence, heads, head_dim, device="cuda", dtype=torch.bfloat16)
k = torch.randn_like(q)
# Deliberately do not repeat adjacent table columns. Diffusers consumes
# full-width tables, so even and odd outputs may use different values.
cos = torch.randn(sequence, head_dim, device="cuda", dtype=torch.float32)
sin = torch.randn_like(cos)
return q, k, cos, sin
def _reference(q, k, cos, sin):
rotary_emb = (cos, sin)
return (
apply_rotary_emb(q, rotary_emb, sequence_dim=1),
apply_rotary_emb(k, rotary_emb, sequence_dim=1),
)
@pytest.mark.cuda
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.skipif(not HAS_TRITON, reason="Triton required")
@pytest.mark.parametrize("sequence", [512, 4096, 4608])
def test_fused_qk_rope_is_bit_exact_at_longcat_production_shapes(sequence):
from vllm_omni.diffusion.layers.fused_qk_rope import _launch_fused_qk_rope, fused_qk_rope
torch.manual_seed(sequence)
with torch.inference_mode():
q, k, cos, sin = _cuda_inputs(1, sequence)
expected = _reference(q, k, cos, sin)
for actual in (
_launch_fused_qk_rope(q, k, cos, sin),
fused_qk_rope(q, k, cos, sin),
):
assert torch.equal(actual[0], expected[0])
assert torch.equal(actual[1], expected[1])
@pytest.mark.cuda
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.skipif(not HAS_TRITON, reason="Triton required")
def test_fused_qk_rope_is_bit_exact_for_batch_and_full_width_odd_even_tables():
from vllm_omni.diffusion.layers.fused_qk_rope import fused_qk_rope
torch.manual_seed(11)
with torch.inference_mode():
q, k, cos, sin = _cuda_inputs(2, 17, heads=3)
assert not torch.equal(cos[:, ::2], cos[:, 1::2])
assert not torch.equal(sin[:, ::2], sin[:, 1::2])
expected = _reference(q, k, cos, sin)
actual = fused_qk_rope(q, k, cos, sin)
assert torch.equal(actual[0], expected[0])
assert torch.equal(actual[1], expected[1])
@pytest.mark.cuda
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.skipif(not HAS_TRITON, reason="Triton required")
def test_fused_qk_rope_rejects_noncontiguous_and_non_fp32_tables():
from vllm_omni.diffusion.layers.fused_qk_rope import fused_qk_rope_supported
q, k, cos, sin = _cuda_inputs(1, 8, heads=2)
q_noncontiguous = torch.randn(1, 8, 2, 256, device="cuda", dtype=torch.bfloat16)[..., ::2]
k_noncontiguous = torch.randn_like(q_noncontiguous)
cos_noncontiguous = torch.randn(8, 256, device="cuda")[:, ::2]
sin_noncontiguous = torch.randn(8, 256, device="cuda")[:, ::2]
with torch.inference_mode():
assert fused_qk_rope_supported(q, k, cos, sin)
assert not fused_qk_rope_supported(q_noncontiguous, k_noncontiguous, cos, sin)
assert not fused_qk_rope_supported(q, k, cos_noncontiguous, sin_noncontiguous)
assert not fused_qk_rope_supported(q, k, cos.to(torch.bfloat16), sin.to(torch.bfloat16))
q_wide = torch.randn(1, 8, 2, 256, device="cuda", dtype=torch.bfloat16)
k_wide = torch.randn_like(q_wide)
cos_wide = torch.randn(8, 256, device="cuda")
sin_wide = torch.randn_like(cos_wide)
assert not fused_qk_rope_supported(q_wide, k_wide, cos_wide, sin_wide)
@pytest.mark.cuda
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.skipif(not HAS_TRITON, reason="Triton required")
def test_fused_qk_rope_custom_op_has_fullgraph_fake():
from vllm_omni.diffusion.layers.fused_qk_rope import fused_qk_rope
torch.manual_seed(29)
with torch.inference_mode():
q, k, cos, sin = _cuda_inputs(1, 19, heads=3)
expected = _reference(q, k, cos, sin)
compiled = torch.compile(fused_qk_rope, dynamic=True, fullgraph=True)
actual = compiled(q, k, cos, sin)
assert torch.equal(actual[0], expected[0])
assert torch.equal(actual[1], expected[1])
@@ -0,0 +1,299 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import pytest
import torch
import torch.nn.functional as F
from vllm_omni.diffusion.layers import qwen_select01_modulation
from vllm_omni.diffusion.layers.qwen_select01_modulation import (
can_use_qwen_select01_triton,
fused_layernorm_select01,
fused_residual_layernorm_select01,
select01_modulation_native,
)
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion]
@pytest.mark.cpu
@pytest.mark.parametrize(
("platform_is_cuda", "tensor_is_cuda", "has_triton", "expected"),
[
(True, True, True, True),
(False, True, True, False),
(True, False, True, False),
(True, True, False, False),
],
)
def test_qwen_select01_triton_requires_cuda_platform(
monkeypatch,
platform_is_cuda: bool,
tensor_is_cuda: bool,
has_triton: bool,
expected: bool,
):
class FakePlatform:
@staticmethod
def is_cuda() -> bool:
return platform_is_cuda
class FakeTensor:
is_cuda = tensor_is_cuda
monkeypatch.setattr(qwen_select01_modulation, "current_platform", FakePlatform())
monkeypatch.setattr(qwen_select01_modulation, "HAS_TRITON", has_triton)
assert can_use_qwen_select01_triton(FakeTensor()) is expected
def _make_inputs(
batch_size: int,
seq_len: int,
hidden_size: int,
dtype: torch.dtype,
device: torch.device,
) -> tuple[torch.Tensor, ...]:
generator = torch.Generator(device=device)
generator.manual_seed(202817)
x = torch.randn(batch_size, seq_len, hidden_size, dtype=dtype, device=device, generator=generator)
residual = torch.randn(batch_size, seq_len, hidden_size, dtype=dtype, device=device, generator=generator)
residual_gate = torch.randn(batch_size, 1, hidden_size, dtype=dtype, device=device, generator=generator)
mod_params = torch.randn(batch_size * 2, hidden_size * 3, dtype=dtype, device=device, generator=generator)
index = torch.randint(0, 2, (batch_size, seq_len), dtype=torch.int64, device=device, generator=generator)
return x, residual, residual_gate, mod_params, index
def _reference_layernorm_select01(
x: torch.Tensor,
mod_params: torch.Tensor,
index: torch.Tensor,
eps: float,
) -> tuple[torch.Tensor, torch.Tensor]:
scale, shift, gate = select01_modulation_native(mod_params, index)
out = F.layer_norm(x.float(), (x.shape[-1],), eps=eps).to(x.dtype)
return out * (1 + scale) + shift, gate
def _reference_residual_layernorm_select01(
x: torch.Tensor,
residual: torch.Tensor,
residual_gate: torch.Tensor,
mod_params: torch.Tensor,
index: torch.Tensor,
eps: float,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
scale, shift, gate = select01_modulation_native(mod_params, index)
residual_out = residual + residual_gate * x
out = F.layer_norm(residual_out.float(), (residual_out.shape[-1],), eps=eps).to(residual_out.dtype)
return out * (1 + scale) + shift, residual_out, gate
@pytest.mark.cpu
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
@pytest.mark.parametrize("broadcast_index", [False, True])
def test_qwen_select01_native_fallback_matches_reference(dtype: torch.dtype, broadcast_index: bool):
device = torch.device("cpu")
x, residual, residual_gate, mod_params, index = _make_inputs(2, 17, 64, dtype, device)
if broadcast_index:
index = index[:1]
eps = 1e-6
actual_norm, actual_gate = fused_layernorm_select01(x, mod_params, index, eps)
ref_norm, ref_gate = _reference_layernorm_select01(x, mod_params, index, eps)
torch.testing.assert_close(actual_norm, ref_norm, atol=1e-5, rtol=1e-5)
torch.testing.assert_close(actual_gate, ref_gate, atol=0, rtol=0)
actual_norm, actual_residual, actual_gate = fused_residual_layernorm_select01(
x,
residual,
residual_gate,
mod_params,
index,
eps,
)
ref_norm, ref_residual, ref_gate = _reference_residual_layernorm_select01(
x,
residual,
residual_gate,
mod_params,
index,
eps,
)
torch.testing.assert_close(actual_norm, ref_norm, atol=1e-5, rtol=1e-5)
torch.testing.assert_close(actual_residual, ref_residual, atol=1e-5, rtol=1e-5)
torch.testing.assert_close(actual_gate, ref_gate, atol=0, rtol=0)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.parametrize(
("dtype", "atol", "rtol"),
[
(torch.float32, 1e-5, 1e-5),
(torch.bfloat16, 5e-2, 5e-2),
],
)
@pytest.mark.parametrize("seq_len", [1, 7, 128, 1024])
def test_qwen_select01_triton_matches_reference(dtype: torch.dtype, atol: float, rtol: float, seq_len: int):
device = torch.device("cuda:0")
x, residual, residual_gate, mod_params, index = _make_inputs(2, seq_len, 256, dtype, device)
eps = 1e-6
actual_norm, actual_gate = fused_layernorm_select01(x, mod_params, index, eps)
ref_norm, ref_gate = _reference_layernorm_select01(x, mod_params, index, eps)
torch.testing.assert_close(actual_norm, ref_norm, atol=atol, rtol=rtol)
torch.testing.assert_close(actual_gate, ref_gate, atol=0, rtol=0)
actual_norm, actual_residual, actual_gate = fused_residual_layernorm_select01(
x,
residual,
residual_gate.expand_as(residual),
mod_params,
index,
eps,
)
ref_norm, ref_residual, ref_gate = _reference_residual_layernorm_select01(
x,
residual,
residual_gate.expand_as(residual),
mod_params,
index,
eps,
)
torch.testing.assert_close(actual_norm, ref_norm, atol=atol, rtol=rtol)
torch.testing.assert_close(actual_residual, ref_residual, atol=atol, rtol=rtol)
torch.testing.assert_close(actual_gate, ref_gate, atol=0, rtol=0)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.parametrize(
("dtype", "atol", "rtol"),
[
(torch.float32, 1e-5, 1e-5),
(torch.bfloat16, 5e-2, 5e-2),
],
)
def test_qwen_select01_triton_matches_reference_for_structured_multi_batch_index(
dtype: torch.dtype,
atol: float,
rtol: float,
):
device = torch.device("cuda:0")
x, residual, residual_gate, mod_params, _ = _make_inputs(3, 16, 256, dtype, device)
index = torch.tensor(
[
[0] * 16,
[1] * 16,
[0, 1] * 8,
],
dtype=torch.int64,
device=device,
)
eps = 1e-6
actual_norm, actual_gate = fused_layernorm_select01(x, mod_params, index, eps)
ref_norm, ref_gate = _reference_layernorm_select01(x, mod_params, index, eps)
torch.testing.assert_close(actual_norm, ref_norm, atol=atol, rtol=rtol)
torch.testing.assert_close(actual_gate, ref_gate, atol=0, rtol=0)
actual_norm, actual_residual, actual_gate = fused_residual_layernorm_select01(
x,
residual,
residual_gate.expand_as(residual),
mod_params,
index,
eps,
)
ref_norm, ref_residual, ref_gate = _reference_residual_layernorm_select01(
x,
residual,
residual_gate.expand_as(residual),
mod_params,
index,
eps,
)
torch.testing.assert_close(actual_norm, ref_norm, atol=atol, rtol=rtol)
torch.testing.assert_close(actual_residual, ref_residual, atol=atol, rtol=rtol)
torch.testing.assert_close(actual_gate, ref_gate, atol=0, rtol=0)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
@pytest.mark.parametrize(
("dtype", "atol", "rtol"),
[
(torch.float32, 1e-5, 1e-5),
(torch.bfloat16, 5e-2, 5e-2),
],
)
def test_qwen_select01_triton_broadcasts_single_index_batch(dtype: torch.dtype, atol: float, rtol: float):
device = torch.device("cuda:0")
x, residual, residual_gate, mod_params, index = _make_inputs(2, 17, 256, dtype, device)
index = index[:1]
eps = 1e-6
actual_norm, actual_gate = fused_layernorm_select01(x, mod_params, index, eps)
ref_norm, ref_gate = _reference_layernorm_select01(x, mod_params, index, eps)
torch.testing.assert_close(actual_norm, ref_norm, atol=atol, rtol=rtol)
torch.testing.assert_close(actual_gate, ref_gate, atol=0, rtol=0)
actual_norm, actual_residual, actual_gate = fused_residual_layernorm_select01(
x,
residual,
residual_gate.expand_as(residual),
mod_params,
index,
eps,
)
ref_norm, ref_residual, ref_gate = _reference_residual_layernorm_select01(
x,
residual,
residual_gate.expand_as(residual),
mod_params,
index,
eps,
)
torch.testing.assert_close(actual_norm, ref_norm, atol=atol, rtol=rtol)
torch.testing.assert_close(actual_residual, ref_residual, atol=atol, rtol=rtol)
torch.testing.assert_close(actual_gate, ref_gate, atol=0, rtol=0)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
def test_qwen_select01_cuda_falls_back_without_triton(monkeypatch):
device = torch.device("cuda:0")
x, residual, residual_gate, mod_params, index = _make_inputs(2, 7, 256, torch.bfloat16, device)
residual_gate = residual_gate.expand_as(residual)
eps = 1e-6
def fail_if_launched(*args, **kwargs):
pytest.fail("Triton launcher must not run when HAS_TRITON is false")
monkeypatch.setattr(qwen_select01_modulation, "HAS_TRITON", False)
monkeypatch.setattr(qwen_select01_modulation, "_launch_layernorm_select01", fail_if_launched)
monkeypatch.setattr(qwen_select01_modulation, "_launch_residual_layernorm_select01", fail_if_launched)
actual_norm, actual_gate = fused_layernorm_select01(x, mod_params, index, eps)
ref_norm, ref_gate = _reference_layernorm_select01(x, mod_params, index, eps)
torch.testing.assert_close(actual_norm, ref_norm, atol=0, rtol=0)
torch.testing.assert_close(actual_gate, ref_gate, atol=0, rtol=0)
actual_norm, actual_residual, actual_gate = fused_residual_layernorm_select01(
x,
residual,
residual_gate,
mod_params,
index,
eps,
)
ref_norm, ref_residual, ref_gate = _reference_residual_layernorm_select01(
x,
residual,
residual_gate,
mod_params,
index,
eps,
)
torch.testing.assert_close(actual_norm, ref_norm, atol=0, rtol=0)
torch.testing.assert_close(actual_residual, ref_residual, atol=0, rtol=0)
torch.testing.assert_close(actual_gate, ref_gate, atol=0, rtol=0)
+91
View File
@@ -18,6 +18,7 @@ from vllm_omni.diffusion.lora.loader import (
WanLoraLoaderMixin,
_prepare_lora_delta,
_remap_state_dict_keys,
_resolve_lora_compute_device,
)
HEAD_DIM = 24
@@ -509,3 +510,93 @@ def test_lora_loader_mixin_lora_is_fused_property(mocker: MockerFixture):
assert pipeline2.lora_is_fused is False
pipeline2.lora_is_fused = True
assert pipeline2.lora_is_fused is True
def test_prepare_lora_delta_with_compute_device():
base_key = "blocks.0.attn.to_q"
state_dict = {
f"{base_key}.lora_A.weight": torch.ones(RANK, HEAD_DIM),
f"{base_key}.lora_B.weight": torch.ones(HEAD_DIM, RANK),
}
delta, used_keys = _prepare_lora_delta(state_dict, base_key, compute_device=torch.device("cpu"))
assert delta is not None
assert delta.shape == (HEAD_DIM, HEAD_DIM)
assert len(used_keys) == 2
def test_resolve_lora_compute_device_probes_unusable_accelerator(mocker: MockerFixture):
"""cuda:N/npu:N may be reported without a physical device; the probe must reject it."""
mocker.patch(
"vllm_omni.diffusion.lora.loader.get_local_device",
return_value=torch.device("cuda:999"),
)
assert _resolve_lora_compute_device() is None
def test_load_lora_into_module_cpu_weights_match_cpu_reference(mocker: MockerFixture):
"""Regression test: params on CPU used to force compute_device=None and skip the
#7005 accelerator path. With an unusable accelerator, fusion must fall back to
CPU and still produce base + lora_B @ lora_A."""
pipeline = DummyPipeline(NUM_LAYERS, HEAD_DIM)
original_params = {name: param.clone() for name, param in pipeline.transformer.named_parameters()}
lora_state_dict = make_lora_state_dict_for_module(pipeline.transformer)
lora_state_dict = _remap_state_dict_keys(lora_state_dict, [(".to_out.0.", ".to_out.")])
mocker.patch(
"vllm_omni.diffusion.lora.loader.get_local_device",
return_value=torch.device("cuda:999"),
)
used_keys = pipeline.load_lora_into_module(lora_state_dict, pipeline.transformer)
assert len(used_keys) > 0
assert not (set(lora_state_dict.keys()) - used_keys)
for name, param in pipeline.transformer.named_parameters():
if not name.endswith(".weight"):
continue
base_key = name[: -len(".weight")]
key_a = f"{base_key}.lora_A.weight"
key_b = f"{base_key}.lora_B.weight"
if key_a in lora_state_dict and key_b in lora_state_dict:
expected = original_params[name] + (
lora_state_dict[key_b].to(param.dtype) @ lora_state_dict[key_a].to(param.dtype)
)
assert_close(param, expected)
def test_load_lora_into_module_forwards_usable_accel_device(mocker: MockerFixture):
"""A usable accelerator must be forwarded as compute_device for CPU params.
A spy forces the actual math back onto CPU so the test runs without a device."""
fake_dev = torch.device("cuda:0")
mocker.patch(
"vllm_omni.diffusion.lora.loader._resolve_lora_compute_device",
return_value=fake_dev,
)
seen_devices = []
original = _prepare_lora_delta
def spy(state_dict, base_key, *args, **kwargs):
seen_devices.append(kwargs.get("compute_device"))
kwargs["compute_device"] = None
return original(state_dict, base_key, *args, **kwargs)
mocker.patch(
"vllm_omni.diffusion.lora.loader._prepare_lora_delta",
side_effect=spy,
)
pipeline = DummyPipeline(NUM_LAYERS, HEAD_DIM)
original_params = {name: param.clone() for name, param in pipeline.transformer.named_parameters()}
lora_state_dict = make_lora_state_dict_for_module(pipeline.transformer)
lora_state_dict = _remap_state_dict_keys(lora_state_dict, [(".to_out.0.", ".to_out.")])
used_keys = pipeline.load_lora_into_module(lora_state_dict, pipeline.transformer)
# Every CPU param with a LoRA delta must have received the accelerator device.
assert seen_devices
assert all(d == fake_dev for d in seen_devices)
assert not (set(lora_state_dict.keys()) - used_keys)
assert_params_not_equal(pipeline.transformer, original_params)
Loaded 100 of 1332 files, more files were not shown because too many files have changed in this diff. Show more