[CI] Restructure vLLM-Omni Test Layout, Fixture Scope, and Support Modules (#2620)

Signed-off-by: wangyu <410167048@qq.com>
This commit is contained in:
wangyu authored and GitHub committed 2026-04-20 14:23:42 +08:00
1 parent 0393c58533
commit 8a9add1c81
130 files changed
+4549 -5306

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
"""Shared, importable test helper utilities.
Submodules (``assertions``, ``env``, ``media``, ``runtime``, …) are imported
explicitly by callers. Avoid star-importing everything here: that ran before
refactor only inside the old monolithic ``conftest``; a greedy ``__init__``
changes import order and can affect in-process Omni (``OmniRunner`` / offline
e2e) vs subprocess-based ``OmniServer`` tests.
"""
+506
View File
@@ -0,0 +1,506 @@
"""Assertion and response validation helpers for tests."""
import io
import tempfile
import threading
from io import BytesIO
from pathlib import Path
from typing import Any
import numpy as np
import soundfile as sf
from PIL import Image
from tests.helpers.media import cosine_similarity_text
_GENDER_PIPELINE = None
_GENDER_PIPELINE_LOCK = threading.Lock()
_PCM_SPEECH_SAMPLE_RATE_HZ = 24_000
_MIN_PCM_SPEECH_HNR_DB = 1.0
_PRESET_VOICE_GENDER_MAP: dict[str, str] = {
"serena": "female",
"uncle_fu": "male",
"chelsie": "female",
"clone": "female",
"ethan": "male",
}
def assert_image_diffusion_response(
response,
request_config: dict[str, Any],
run_level: str = None,
) -> None:
"""
Validate image diffusion response.
Expected request_config schema:
{
"request_type": "image",
"extra_body": {
"num_outputs_per_prompt": 1,
"width": ...,
"height": ...,
...
}
}
"""
assert response.images is not None, "Image response is None"
assert len(response.images) > 0, "No images in response"
extra_body = request_config.get("extra_body") or {}
num_outputs_per_prompt = extra_body.get("num_outputs_per_prompt")
if num_outputs_per_prompt is not None:
assert len(response.images) == num_outputs_per_prompt, (
f"Expected {num_outputs_per_prompt} images, got {len(response.images)}"
)
if run_level == "advanced_model":
width = extra_body.get("width")
height = extra_body.get("height")
if width is not None or height is not None:
for img in response.images:
assert_image_valid(img, width=width, height=height)
def assert_video_diffusion_response(
response,
request_config: dict[str, Any],
run_level: str = None,
) -> None:
"""
Validate video diffusion response.
Expected request_config schema:
{
"request_type": "video",
"form_data": {
"prompt": "...",
"num_frames": ...,
"width": ...,
"height": ...,
"fps": ...,
...
}
}
"""
form_data = request_config.get("form_data", {})
assert response.videos is not None, "Video response is None"
assert len(response.videos) > 0, "No videos in response"
expected_frames = _maybe_int(form_data.get("num_frames"))
expected_width = _maybe_int(form_data.get("width"))
expected_height = _maybe_int(form_data.get("height"))
expected_fps = _maybe_int(form_data.get("fps"))
for vid_bytes in response.videos:
assert_video_valid(
vid_bytes,
num_frames=expected_frames,
width=expected_width,
height=expected_height,
fps=expected_fps,
)
def assert_audio_diffusion_response(
response,
request_config: dict[str, Any],
run_level: str = None,
) -> None:
"""
Validate audio diffusion response.
"""
raise NotImplementedError("Audio validation is not implemented yet")
def _maybe_int(value: Any) -> int | None:
if value is None:
return None
return int(value)
def assert_image_valid(image: Path | Image.Image, *, width: int | None = None, height: int | None = None):
"""Assert the file is a loadable image with optional exact dimensions."""
if isinstance(image, Path):
assert image.exists(), f"Image not found: {image}"
image = Image.open(image)
image.load()
assert image.width > 0 and image.height > 0
if width is not None:
assert image.width == width, f"Expected width={width}, got {image.width}"
if height is not None:
assert image.height == height, f"Expected height={height}, got {image.height}"
return image
def assert_video_valid(
video: Path | bytes | BytesIO,
*,
num_frames: int | None = None,
width: int | None = None,
height: int | None = None,
fps: float | None = None,
) -> dict[str, int | float]:
"""Assert the MP4 has the expected resolution and frame count.
For several diffusion backends, encoded MP4 frame count follows a codec-aligned
convention (e.g. request `num_frames=8` can produce 9 encoded frames). Keep
this compatibility behavior to avoid false negatives in online-serving tests.
"""
temp_path = None
cap = None
try:
import cv2
if isinstance(video, Path):
if not video.exists():
raise AssertionError(f"Video file not found: {video}")
video_path = str(video)
else:
suffix = ".mp4"
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix, mode="wb") as tmp:
if isinstance(video, bytes):
tmp.write(video)
elif isinstance(video, BytesIO):
tmp.write(video.getvalue())
else:
raise TypeError(f"Unsupported video type: {type(video)}")
temp_path = Path(tmp.name)
video_path = str(temp_path)
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise AssertionError("Failed to open video capture")
actual_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
actual_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
actual_fps = float(cap.get(cv2.CAP_PROP_FPS))
actual_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if width is not None:
assert actual_width == width, f"Expected width={width}, got {actual_width}"
if height is not None:
assert actual_height == height, f"Expected height={height}, got {actual_height}"
if fps is not None and actual_fps:
assert abs(actual_fps - float(fps)) < 1.0, f"Expected fps~={fps}, got {actual_fps}"
if num_frames is not None:
expected_frames = (int(num_frames) // 4) * 4 + 1
assert actual_frames == expected_frames, f"Expected frames={expected_frames}, got {actual_frames}"
return {
"width": actual_width,
"height": actual_height,
"fps": actual_fps,
"num_frames": actual_frames,
}
except Exception as e:
print(f"ERROR: {type(e).__name__}: {e}", flush=True)
raise
finally:
if cap is not None:
cap.release()
if temp_path and temp_path.exists():
try:
temp_path.unlink()
except OSError:
pass
def assert_audio_valid(
audio_or_path: Path | np.ndarray,
*,
sample_rate: int,
channels: int,
duration_s: float,
) -> None:
"""Assert WAV file or (batch, channels, samples) ndarray matches expected audio format."""
expected_samples = int(duration_s * sample_rate)
if isinstance(audio_or_path, np.ndarray):
audio = audio_or_path
assert audio.ndim == 3, f"Expected audio ndim=3 (batch, channels, samples), got shape {audio.shape}"
assert audio.shape[0] == 1, f"Expected batch size 1, got {audio.shape[0]}"
assert audio.shape[1] == channels, f"Expected {channels} channels, got {audio.shape[1]}"
assert audio.shape[2] == expected_samples, (
f"Expected {expected_samples} samples ({duration_s}s @ {sample_rate} Hz), got {audio.shape[2]}"
)
return
path = audio_or_path
assert path.exists(), f"Audio not found: {path}"
info = sf.info(str(path))
assert info.samplerate == sample_rate, f"Expected sample_rate={sample_rate}, got {info.samplerate}"
assert info.channels == channels, f"Expected {channels} channel(s), got {info.channels}"
assert info.frames == expected_samples, (
f"Expected {expected_samples} frames ({duration_s}s @ {sample_rate} Hz), got {info.frames}"
)
def _load_gender_pipeline():
global _GENDER_PIPELINE
if _GENDER_PIPELINE is not None:
return _GENDER_PIPELINE
model_name = "7wolf/wav2vec2-base-gender-classification"
try:
from transformers import pipeline
_GENDER_PIPELINE = pipeline(task="audio-classification", model=model_name, device=-1)
return _GENDER_PIPELINE
except Exception as exc: # pragma: no cover
print(f"Warning: failed to create gender pipeline '{model_name}': {exc}")
_GENDER_PIPELINE = None
return None
def _median_pitch_hz_from_autocorr(mono: np.ndarray, sr: int) -> float | None:
x = np.asarray(mono, dtype=np.float64)
x = x - np.mean(x)
if x.size < int(0.15 * sr):
return None
frame_len = int(0.04 * sr)
hop = max(frame_len // 2, 1)
f0_min_hz, f0_max_hz = 70.0, 400.0
lag_min = max(1, int(sr / f0_max_hz))
lag_max = min(frame_len - 2, int(sr / f0_min_hz))
if lag_max <= lag_min:
return None
win = np.hamming(frame_len)
pitches: list[float] = []
for start in range(0, int(x.shape[0]) - frame_len, hop):
frame = x[start : start + frame_len] * win
frame = frame - np.mean(frame)
if float(np.sqrt(np.mean(frame**2))) < 1e-4:
continue
ac = np.correlate(frame, frame, mode="full")[frame_len - 1 :]
ac = ac / (float(ac[0]) + 1e-12)
region = ac[lag_min : lag_max + 1]
peak_rel = int(np.argmax(region))
peak_lag = peak_rel + lag_min
if peak_lag <= 0:
continue
f0 = float(sr) / float(peak_lag)
if f0_min_hz <= f0 <= f0_max_hz:
pitches.append(f0)
if len(pitches) < 4:
return None
return float(np.median(np.asarray(pitches, dtype=np.float64)))
def _estimate_voice_gender_from_audio(audio_bytes: bytes) -> str:
data, sr = sf.read(io.BytesIO(audio_bytes), dtype="float32", always_2d=True)
if data.size == 0:
raise ValueError("Empty audio")
mono = np.mean(data, axis=1)
try:
target_sr = 16000
if int(sr) != target_sr and mono.size > 1:
src_len = int(mono.shape[0])
dst_len = max(1, int(round(src_len * float(target_sr) / float(sr))))
src_idx = np.arange(src_len, dtype=np.float32)
dst_idx = np.linspace(0, src_len - 1, dst_len, dtype=np.float32)
mono = np.interp(dst_idx, src_idx, mono.astype(np.float32, copy=False)).astype(np.float32)
sr = target_sr
median_f0 = _median_pitch_hz_from_autocorr(mono, sr)
clf = _load_gender_pipeline()
if clf is None:
print("gender model not available, returning 'unknown'")
return "unknown"
with _GENDER_PIPELINE_LOCK:
outputs = clf(mono, sampling_rate=sr)
if not outputs:
return "unknown"
top = outputs[0]
label = str(top.get("label", "")).lower()
conf = float(top.get("score", 0.0))
if conf < 0.5:
gender = "unknown"
elif ("female" in label) or ("жен" in label):
gender = "female"
elif ("male" in label) or ("муж" in label):
gender = "male"
else:
gender = "unknown"
if gender == "female" and median_f0 is not None and median_f0 < 165.0 and conf < 0.88:
print(f"gender pitch assist: reclassifying female->male (median_f0={median_f0:.1f} Hz, conf={conf:.3f})")
gender = "male"
elif gender == "male" and median_f0 is not None and median_f0 > 230.0 and conf < 0.88:
print(f"gender pitch assist: reclassifying male->female (median_f0={median_f0:.1f} Hz, conf={conf:.3f})")
gender = "female"
print(
f"gender classifier: label={label}, conf={conf:.3f}, gender={gender}"
+ (f", median_f0={median_f0:.1f}Hz" if median_f0 is not None else "")
)
return gender
except Exception as exc: # pragma: no cover
print(f"Warning: gender classification failed, returning 'unknown': {exc}")
return "unknown"
def _assert_preset_voice_gender_from_audio(audio_bytes: bytes | None, voice_name: str | None) -> None:
"""If ``voice_name`` matches a known preset, assert classifier gender matches (skip when unknown)."""
if not voice_name or not audio_bytes:
return
key = str(voice_name).lower()
expected_gender = _PRESET_VOICE_GENDER_MAP.get(key)
if expected_gender is None:
return
estimated_gender = _estimate_voice_gender_from_audio(audio_bytes)
print(f"Preset voice gender check: preset={key!r}, estimated={estimated_gender!r}, expected={expected_gender!r}")
if estimated_gender != "unknown":
assert estimated_gender == expected_gender, (
f"{voice_name!r} is expected {expected_gender}, but estimated gender is {estimated_gender!r}"
)
def _compute_pcm_hnr_db(pcm_samples: np.ndarray, sr: int = _PCM_SPEECH_SAMPLE_RATE_HZ) -> float:
frame_len = int(0.03 * sr)
hop = frame_len // 2
hnr_values: list[float] = []
for start in range(0, len(pcm_samples) - frame_len, hop):
frame = pcm_samples[start : start + frame_len].astype(np.float32, copy=False)
frame = frame - np.mean(frame)
if np.max(np.abs(frame)) < 0.01:
continue
ac = np.correlate(frame, frame, mode="full")[len(frame) - 1 :]
ac = ac / (ac[0] + 1e-10)
min_lag = int(sr / 400)
max_lag = min(int(sr / 80), len(ac))
if min_lag >= max_lag:
continue
peak = float(np.max(ac[min_lag:max_lag]))
if 0 < peak < 1:
hnr_values.append(10 * np.log10(peak / (1 - peak + 1e-10)))
return float(np.mean(hnr_values)) if hnr_values else 0.0
def _assert_pcm_int16_speech_hnr(audio_bytes: bytes) -> None:
assert audio_bytes is not None and len(audio_bytes) >= 2, "missing PCM bytes"
assert len(audio_bytes) % 2 == 0, "PCM byte length must be aligned to int16"
pcm_samples = np.frombuffer(audio_bytes, dtype=np.int16).astype(np.float32) / 32768.0
hnr = _compute_pcm_hnr_db(pcm_samples)
print(f"PCM speech HNR: {hnr:.2f} dB (threshold: {_MIN_PCM_SPEECH_HNR_DB} dB)")
assert hnr >= _MIN_PCM_SPEECH_HNR_DB, (
f"Audio distortion detected: HNR={hnr:.2f} dB < {_MIN_PCM_SPEECH_HNR_DB} dB. "
"Voice clone decoder may be losing ref_code speaker context on later chunks."
)
def assert_omni_response(response: Any, request_config: dict[str, Any], run_level):
"""
Validate response results.
Args:
response: OmniResponse object
Raises:
AssertionError: When the response does not meet validation criteria
"""
assert response.success, "The request failed."
e2e_latency = response.e2e_latency
if e2e_latency is not None:
print(f"the e2e latency is: {e2e_latency}")
modalities = request_config.get("modalities", ["text", "audio"])
if run_level == "advanced_model":
if "audio" in modalities:
assert response.audio_content is not None, "No audio output is generated"
print(f"audio content is: {response.audio_content}")
speaker = request_config.get("speaker")
if speaker:
_assert_preset_voice_gender_from_audio(
response.audio_bytes,
speaker,
)
if "text" in modalities:
assert response.text_content is not None, "No text output is generated"
print(f"text content is: {response.text_content}")
# Verify image description
word_types = ["text", "image", "audio", "video"]
keywords_dict = request_config.get("key_words", {})
for word_type in word_types:
keywords = keywords_dict.get(word_type)
if "text" in modalities:
if keywords:
text_lower = response.text_content.lower()
assert any(str(kw).lower() in text_lower for kw in keywords), (
"The output does not contain any of the keywords."
)
else:
if keywords:
audio_lower = response.audio_content.lower()
assert any(str(kw).lower() in audio_lower for kw in keywords), (
"The output does not contain any of the keywords."
)
# Verify similarity (Whisper transcript vs streamed/detokenized text)
if "text" in modalities and "audio" in modalities:
assert response.similarity is not None and response.similarity > 0.9, (
"The audio content is not same as the text"
)
print(f"similarity is: {response.similarity}")
def assert_audio_speech_response(response: Any, request_config: dict[str, Any], run_level: str) -> None:
assert response.success, "The request failed."
e2e_latency = getattr(response, "e2e_latency", None)
if e2e_latency is not None:
print(f"the avg e2e latency is: {e2e_latency}")
req_fmt = request_config.get("response_format")
if req_fmt == "pcm" and response.audio_bytes:
_assert_pcm_int16_speech_hnr(response.audio_bytes)
if response.audio_format:
assert "pcm" in response.audio_format.lower(), (
f"Expected audio/pcm content-type, got {response.audio_format!r}"
)
elif req_fmt == "wav" and response.audio_format:
assert req_fmt in response.audio_format
if run_level == "advanced_model" and req_fmt != "pcm":
expected_text = request_config.get("input")
if expected_text:
transcript = (response.audio_content or "").strip()
print(f"audio content is: {transcript}")
print(f"input text is: {expected_text}")
similarity = cosine_similarity_text(transcript.lower(), expected_text.lower())
print(f"Cosine similarity: {similarity:.3f}")
assert similarity > 0.9, (
f"Transcript doesn't match input: similarity={similarity:.2f}, transcript='{transcript}'"
)
_assert_preset_voice_gender_from_audio(response.audio_bytes, request_config.get("voice"))
def assert_diffusion_response(response: Any, request_config: dict[str, Any], run_level: str = None):
assert response.success, "The request failed."
e2e_latency = getattr(response, "e2e_latency", None)
if e2e_latency is not None:
print(f"the avg e2e is: {e2e_latency}")
has_any_content = any(content is not None for content in (response.images, response.videos, response.audios))
assert has_any_content, "Response contains no images, videos, or audios"
if response.images is not None:
assert_image_diffusion_response(response=response, request_config=request_config, run_level=run_level)
if response.videos is not None:
assert_video_diffusion_response(response=response, request_config=request_config, run_level=run_level)
if response.audios is not None:
assert_audio_diffusion_response(response=response, request_config=request_config, run_level=run_level)
__all__ = [
"assert_audio_diffusion_response",
"assert_audio_speech_response",
"assert_diffusion_response",
"assert_image_diffusion_response",
"assert_image_valid",
"assert_omni_response",
"assert_video_diffusion_response",
"assert_video_valid",
"assert_audio_valid",
]
+280
View File
@@ -0,0 +1,280 @@
"""Test environment / lifecycle helpers (GPU cleanup hooks and memory monitoring for tests).
``vllm.platforms`` / ``vllm_omni.platforms`` are imported only inside functions that need them
so importing this module at pytest plugin load does not run before session autouse fixtures
"""
from __future__ import annotations
import gc
import os
import subprocess
import threading
import time
from contextlib import contextmanager
import torch
def run_forced_gpu_cleanup_round() -> None:
run_pre_test_cleanup(enable_force=True)
run_post_test_cleanup(enable_force=True)
def get_physical_device_indices(devices):
visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
if visible_devices is None:
return devices
visible_indices = [int(x) for x in visible_devices.split(",")]
index_mapping = {i: physical for i, physical in enumerate(visible_indices)}
return [index_mapping[i] for i in devices if i in index_mapping]
def wait_for_gpu_memory_to_clear(
*,
devices: list[int],
threshold_bytes: int | None = None,
threshold_ratio: float | None = None,
timeout_s: float = 120,
) -> None:
from vllm.platforms import current_platform
assert threshold_bytes is not None or threshold_ratio is not None
devices = get_physical_device_indices(devices)
start_time = time.time()
device_list = ", ".join(str(d) for d in devices)
if threshold_bytes is not None:
threshold_str = f"{threshold_bytes / 2**30:.2f} GiB"
condition_str = f"Memory usage ≤ {threshold_str}"
else:
threshold_percent = threshold_ratio * 100
threshold_str = f"{threshold_percent:.1f}%"
condition_str = f"Memory usage ratio ≤ {threshold_str}"
print(f"[GPU Memory Monitor] Waiting for GPU {device_list} to free memory, Condition: {condition_str}")
if threshold_bytes is not None:
def is_free(used, total):
return used <= threshold_bytes / 2**30
else:
def is_free(used, total):
return used / total <= threshold_ratio
@contextmanager
def nvml_scope():
if current_platform.is_rocm():
from amdsmi import amdsmi_init, amdsmi_shut_down
amdsmi_init()
try:
yield
finally:
amdsmi_shut_down()
elif current_platform.is_cuda():
from vllm.third_party.pynvml import nvmlInit, nvmlShutdown
nvmlInit()
try:
yield
finally:
nvmlShutdown()
else:
yield
is_rocm = current_platform.is_rocm()
with nvml_scope():
if is_rocm:
from amdsmi import amdsmi_get_gpu_vram_usage, amdsmi_get_processor_handles
elif current_platform.is_cuda():
from vllm.third_party.pynvml import nvmlDeviceGetHandleByIndex, nvmlDeviceGetMemoryInfo
while True:
output: dict[int, str] = {}
output_raw: dict[int, tuple[float, float]] = {}
for device in devices:
if is_rocm:
dev_handle = amdsmi_get_processor_handles()[device]
mem_info = amdsmi_get_gpu_vram_usage(dev_handle)
gb_used = mem_info["vram_used"] / 2**10
gb_total = mem_info["vram_total"] / 2**10
else:
dev_handle = nvmlDeviceGetHandleByIndex(device)
mem_info = nvmlDeviceGetMemoryInfo(dev_handle)
gb_used = mem_info.used / 2**30
gb_total = mem_info.total / 2**30
output_raw[device] = (gb_used, gb_total)
usage_percent = (gb_used / gb_total) * 100 if gb_total > 0 else 0
output[device] = f"{gb_used:.1f}GiB/{gb_total:.1f}GiB ({usage_percent:.1f}%)"
print("[GPU Memory Status] Current usage:")
for device_id, mem_info in output.items():
print(f" GPU {device_id}: {mem_info}")
dur_s = time.time() - start_time
elapsed_minutes = dur_s / 60
if all(is_free(used, total) for used, total in output_raw.values()):
print(f"[GPU Memory Freed] Devices {device_list} meet memory condition")
print(f" Condition: {condition_str}")
print(f" Wait time: {dur_s:.1f} seconds ({elapsed_minutes:.1f} minutes)")
break
if dur_s >= timeout_s:
raise ValueError(
f"[GPU Memory Timeout] Devices {device_list} still don't meet memory condition after {dur_s:.1f} seconds\n"
f"Condition: {condition_str}\n"
f"Current status:\n" + "\n".join(f" GPU {device}: {output[device]}" for device in devices)
)
gc.collect()
torch.cuda.empty_cache()
time.sleep(5)
def _print_gpu_processes() -> None:
"""Print GPU information including nvidia-smi and system processes."""
print("\n" + "=" * 80)
print("NVIDIA GPU Information (nvidia-smi)")
print("=" * 80)
try:
nvidia_result = subprocess.run(
["nvidia-smi"],
capture_output=True,
text=True,
timeout=5,
)
if nvidia_result.returncode == 0:
lines = nvidia_result.stdout.strip().split("\n")
for line in lines[:20]:
print(line)
if len(lines) > 20:
print(f"... (showing first 20 of {len(lines)} lines)")
else:
print("nvidia-smi command failed")
except (subprocess.TimeoutExpired, FileNotFoundError):
print("nvidia-smi not available or timed out")
except Exception as e:
print(f"Error running nvidia-smi: {e}")
print("\n" + "=" * 80)
print("Detailed GPU Processes (nvidia-smi pmon)")
print("=" * 80)
try:
pmon_result = subprocess.run(
["nvidia-smi", "pmon", "-c", "1"],
capture_output=True,
text=True,
timeout=3,
)
if pmon_result.returncode == 0 and pmon_result.stdout.strip():
print(pmon_result.stdout)
else:
print("No active GPU processes found via nvidia-smi pmon")
except Exception:
print("nvidia-smi pmon not available")
print("\n" + "=" * 80)
print("System Processes with GPU keywords")
print("=" * 80)
_SKIPPED_GPU_CLEANUP_MSG = (
"\nSkipping GPU memory cleanup check (typically: instance already up; no check needed between tests)\n"
)
def run_pre_test_cleanup(enable_force: bool = False) -> None:
if os.getenv("VLLM_TEST_CLEAN_GPU_MEMORY", "0") != "1" and not enable_force:
print(_SKIPPED_GPU_CLEANUP_MSG)
return
print("Pre-test GPU status:")
num_gpus = torch.cuda.device_count()
if num_gpus > 0:
try:
wait_for_gpu_memory_to_clear(
devices=list(range(num_gpus)),
threshold_ratio=0.05,
)
except Exception as e:
print(f"Pre-test cleanup note: {e}")
def run_post_test_cleanup(enable_force: bool = False) -> None:
if os.getenv("VLLM_TEST_CLEAN_GPU_MEMORY", "0") != "1" and not enable_force:
print(_SKIPPED_GPU_CLEANUP_MSG)
return
if torch.cuda.is_available():
gc.collect()
torch.cuda.empty_cache()
print("Post-test GPU status:")
_print_gpu_processes()
class DeviceMemoryMonitor:
"""Poll global device memory usage."""
def __init__(self, device_index: int, interval: float = 0.05):
self.device_index = device_index
self.interval = interval
self._peak_used_mb = 0.0
self._stop_event = threading.Event()
self._thread: threading.Thread | None = None
def start(self) -> None:
from vllm_omni.platforms import current_omni_platform
def monitor_loop() -> None:
while not self._stop_event.is_set():
try:
with current_omni_platform.device(self.device_index):
free_bytes, total_bytes = current_omni_platform.mem_get_info()
used_mb = (total_bytes - free_bytes) / (1024**2)
self._peak_used_mb = max(self._peak_used_mb, used_mb)
except Exception:
pass
time.sleep(self.interval)
self._thread = threading.Thread(target=monitor_loop, daemon=False)
self._thread.start()
def stop(self) -> None:
if self._thread is None:
return
self._stop_event.set()
self._thread.join(timeout=2.0)
@property
def peak_used_mb(self) -> float:
from vllm_omni.platforms import current_omni_platform
fallback_alloc = current_omni_platform.max_memory_allocated(device=self.device_index) / (1024**2)
fallback_reserved = current_omni_platform.max_memory_reserved(device=self.device_index) / (1024**2)
return max(self._peak_used_mb, fallback_alloc, fallback_reserved)
def __del__(self):
self.stop()
__all__ = [
"DeviceMemoryMonitor",
"get_physical_device_indices",
"run_post_test_cleanup",
"run_pre_test_cleanup",
"run_forced_gpu_cleanup_round",
"wait_for_gpu_memory_to_clear",
]
+1
View File
@@ -0,0 +1 @@
"""Pytest fixture modules under tests.helpers."""
+59
View File
@@ -0,0 +1,59 @@
import os
import pytest
import torch
@pytest.fixture(scope="session", autouse=True)
def default_env():
# Keep behavior but avoid import-time side effects (RFC #2299).
keys = ("VLLM_WORKER_MULTIPROC_METHOD", "VLLM_TARGET_DEVICE")
previous = {key: os.environ.get(key) for key in keys}
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = previous["VLLM_WORKER_MULTIPROC_METHOD"] or "spawn"
os.environ["VLLM_TARGET_DEVICE"] = previous["VLLM_TARGET_DEVICE"] or (
"cuda" if torch.cuda.is_available() and torch.cuda.device_count() > 0 else "cpu"
)
yield
for key, value in previous.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
@pytest.fixture(scope="session")
def model_prefix() -> str:
prefix = os.environ.get("MODEL_PREFIX", "")
return f"{prefix.rstrip('/')}/" if prefix else ""
@pytest.fixture(autouse=True)
def clean_gpu_memory_between_tests():
# Import here so ``tests.helpers.env`` (and vLLM platform modules) load only
# after session autouse fixtures like ``default_env`` have run (RFC #2299).
from tests.helpers.env import run_post_test_cleanup, run_pre_test_cleanup
print("\n=== PRE-TEST GPU CLEANUP ===")
run_pre_test_cleanup()
yield
run_post_test_cleanup()
@pytest.fixture(scope="session", autouse=True)
def default_vllm_config():
"""Set a default VllmConfig for the whole test session.
Session scope ensures module-scoped fixtures (e.g. ``omni_runner``) and
deferred imports of ``tests.helpers.runtime`` both see the same context.
Function-scoped autouse ran too late for ``OmniRunner`` setup and could
desynchronize vLLM init vs request preprocessing (e.g. renderer state).
"""
from vllm.config import DeviceConfig, VllmConfig, set_current_vllm_config
# Use CPU device if no GPU is available (e.g., in CI environments)
has_gpu = torch.cuda.is_available() and torch.cuda.device_count() > 0
device = "cuda" if has_gpu else "cpu"
device_config = DeviceConfig(device=device)
with set_current_vllm_config(VllmConfig(device_config=device_config)):
yield
+7
View File
@@ -0,0 +1,7 @@
import pytest
@pytest.fixture(autouse=True)
def log_test_name_before_test(request: pytest.FixtureRequest):
print(f"--- Running test: {request.node.name}")
yield
+17
View File
@@ -0,0 +1,17 @@
import pytest
def pytest_addoption(parser):
parser.addoption(
"--run-level",
action="store",
default="core_model",
choices=["core_model", "advanced_model"],
help="Test level to run: L2, L3",
)
@pytest.fixture(scope="session")
def run_level(request) -> str:
"""Session test level from ``--run-level`` (see CI five-level docs)."""
return request.config.getoption("--run-level")
+137
View File
@@ -0,0 +1,137 @@
"""Runtime fixtures (OmniRunner / OmniServer). Imports are deferred to fixture time.
Loading ``tests.helpers.runtime`` at plugin import time (before session fixtures)
pulls in vLLM/vllm_omni too early and breaks initialization order vs the legacy
monolithic conftest. Defer imports until fixtures run so ``default_env`` /
``default_vllm_config`` run first.
"""
from __future__ import annotations
import threading
from collections.abc import Generator
from typing import Any
import pytest
import yaml
from tests.helpers.runtime import OmniServer
from tests.helpers.stage_config import modify_stage_config
omni_fixture_lock = threading.Lock()
@pytest.fixture(scope="module")
def omni_server(request: pytest.FixtureRequest, run_level: str, model_prefix: str) -> Generator[OmniServer, Any, None]:
"""Start vLLM-Omni through the standard or stage-CLI launcher.
The fixture stays module-scoped because multi-stage initialization is costly.
The ``use_stage_cli`` flag on ``OmniServerParams`` routes the setup through the
stage-CLI harness while still reusing the same fixture grouping semantics.
"""
with omni_fixture_lock:
from tests.helpers.runtime import OmniServer, OmniServerParams, OmniServerStageCli
params: OmniServerParams = request.param
model = model_prefix + params.model
port = params.port
stage_config_path = params.stage_config_path
if run_level == "advanced_model" and stage_config_path is not None:
with open(stage_config_path, encoding="utf-8") as f:
cfg = yaml.safe_load(f) or {}
# Strip ``load_format: dummy`` (CI overlay default) so advanced_model
# tests use real weights. New schema (``stages:``) writes the field
# flat at stage level; legacy schema (``stage_args:``) nests it as
# ``engine_args.load_format``. Handle both.
new_schema_stages = cfg.get("stages")
stage_key = "stages" if new_schema_stages is not None else "stage_args"
delete_path = "load_format" if new_schema_stages is not None else "engine_args.load_format"
stage_entries = cfg.get(stage_key, [])
stage_ids = [stage["stage_id"] for stage in stage_entries if "stage_id" in stage]
stage_config_path = modify_stage_config(
stage_config_path,
deletes={stage_key: {stage_id: [delete_path] for stage_id in stage_ids}},
)
server_args = params.server_args or []
if params.use_omni and params.stage_init_timeout is not None:
server_args = [*server_args, "--stage-init-timeout", str(params.stage_init_timeout)]
else:
server_args = [*server_args, "--stage-init-timeout", "600"]
if params.init_timeout is not None:
server_args = [*server_args, "--init-timeout", str(params.init_timeout)]
else:
server_args = [*server_args, "--init-timeout", "900"]
if params.use_stage_cli:
if not params.use_omni:
raise ValueError("omni_server with use_stage_cli=True requires use_omni=True")
if stage_config_path is None:
raise ValueError("omni_server with use_stage_cli=True requires a stage_config_path")
server_args += ["--stage-configs-path", stage_config_path]
with OmniServerStageCli(
model,
stage_config_path,
server_args,
port=port,
env_dict=params.env_dict,
) as server:
print("OmniServer started successfully")
yield server
print("OmniServer stopping...")
else:
if stage_config_path is not None:
server_args += ["--stage-configs-path", stage_config_path]
with (
OmniServer(
model,
server_args,
port=port,
env_dict=params.env_dict,
use_omni=params.use_omni,
)
if port
else OmniServer(
model,
server_args,
env_dict=params.env_dict,
use_omni=params.use_omni,
)
) as server:
print("OmniServer started successfully")
yield server
print("OmniServer stopping...")
print("OmniServer stopped")
@pytest.fixture
def openai_client(request: pytest.FixtureRequest, run_level: str):
"""Resolve ``omni_server`` lazily so parametrized server fixtures work like upstream."""
from tests.helpers.runtime import OpenAIClientHandler
server = request.getfixturevalue("omni_server")
return OpenAIClientHandler(host=server.host, port=server.port, api_key="EMPTY", run_level=run_level)
@pytest.fixture(scope="module")
def omni_runner(request: pytest.FixtureRequest, model_prefix: str):
from tests.helpers.runtime import OmniRunner
with omni_fixture_lock:
model, stage_config_path = request.param
model = model_prefix + model
with OmniRunner(model, seed=42, stage_configs_path=stage_config_path) as runner:
print("OmniRunner started successfully")
yield runner
print("OmniRunner stopping...")
print("OmniRunner stopped")
@pytest.fixture
def omni_runner_handler(omni_runner: Any):
from tests.helpers.runtime import OmniRunnerHandler
return OmniRunnerHandler(omni_runner)
+135
View File
@@ -0,0 +1,135 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Pytest marks and decorators for hardware / resource selection (CUDA, ROCm, …)."""
import pytest
from vllm.utils.torch_utils import cuda_device_count_stateless
# Re-exported from tests.helpers.env (GPU wait + DeviceMemoryMonitor).
def cuda_marks(*, res: str, num_cards: int):
test_platform_detail = pytest.mark.cuda
if res == "L4":
test_resource = pytest.mark.L4
elif res == "H100":
test_resource = pytest.mark.H100
else:
raise ValueError(f"Invalid CUDA resource type: {res}. Supported: L4, H100")
marks = [test_resource, test_platform_detail]
if num_cards == 1:
return marks
test_distributed = pytest.mark.distributed_cuda(num_cards=num_cards)
test_skipif = pytest.mark.skipif_cuda(
cuda_device_count_stateless() < num_cards,
reason=f"Need at least {num_cards} CUDA GPUs to run the test.",
)
return marks + [test_distributed, test_skipif]
def rocm_marks(*, res: str, num_cards: int):
test_platform_detail = pytest.mark.rocm
if res == "MI325":
test_resource = pytest.mark.MI325
else:
raise ValueError(f"Invalid ROCm resource type: {res}. Supported: MI325")
marks = [test_resource, test_platform_detail]
if num_cards == 1:
return marks
test_distributed = pytest.mark.distributed_rocm(num_cards=num_cards)
return marks + [test_distributed]
def xpu_marks(*, res: str, num_cards: int):
test_platform_detail = pytest.mark.xpu
if res == "B60":
test_resource = pytest.mark.B60
else:
raise ValueError(f"Invalid XPU resource type: {res}. Supported: B60")
marks = [test_resource, test_platform_detail]
if num_cards == 1:
return marks
test_distributed = pytest.mark.distributed_rocm(num_cards=num_cards)
return marks + [test_distributed]
def musa_marks(*, res: str, num_cards: int):
test_platform_detail = pytest.mark.musa
if res == "S5000":
test_resource = pytest.mark.S5000
else:
raise ValueError(f"Invalid MUSA resource type: {res}. Supported: S5000")
marks = [test_resource, test_platform_detail]
if num_cards == 1:
return marks
test_distributed = pytest.mark.distributed_musa(num_cards=num_cards)
return marks + [test_distributed]
def gpu_marks(*, res: str, num_cards: int):
test_platform = pytest.mark.gpu
if res in ("L4", "H100"):
return [test_platform] + cuda_marks(res=res, num_cards=num_cards)
if res == "MI325":
return [test_platform] + rocm_marks(res=res, num_cards=num_cards)
if res == "B60":
return [test_platform] + xpu_marks(res=res, num_cards=num_cards)
if res == "S5000":
return [test_platform] + musa_marks(res=res, num_cards=num_cards)
raise ValueError(f"Invalid resource type: {res}. Supported: L4, H100, MI325, B60, S5000")
def npu_marks(*, res: str, num_cards: int):
test_platform = pytest.mark.npu
if res == "A2":
test_resource = pytest.mark.A2
elif res == "A3":
test_resource = pytest.mark.A3
else:
test_resource = None
if num_cards == 1:
return [mark for mark in [test_platform, test_resource] if mark is not None]
test_distributed = pytest.mark.distributed_npu(num_cards=num_cards)
return [mark for mark in [test_platform, test_resource, test_distributed] if mark is not None]
def hardware_marks(*, res: dict[str, str], num_cards: int | dict[str, int] = 1):
for platform, _ in res.items():
if platform not in ("cuda", "rocm", "xpu", "npu", "musa"):
raise ValueError(f"Unsupported platform: {platform}")
if isinstance(num_cards, int):
num_cards_dict = {platform: num_cards for platform in res.keys()}
else:
num_cards_dict = num_cards
for platform in num_cards_dict.keys():
if platform not in res:
raise ValueError(f"Platform '{platform}' in num_cards but not in res.")
for platform in res.keys():
if platform not in num_cards_dict:
num_cards_dict[platform] = 1
all_marks: list[pytest.MarkDecorator] = []
for platform, resource in res.items():
cards = num_cards_dict[platform]
if platform in ("cuda", "rocm", "xpu"):
marks = gpu_marks(res=resource, num_cards=cards)
elif platform == "musa":
marks = musa_marks(res=resource, num_cards=cards)
elif platform == "npu":
marks = npu_marks(res=resource, num_cards=cards)
else:
raise ValueError(f"Unsupported platform: {platform}")
all_marks.extend(marks)
return all_marks
def hardware_test(*, res: dict[str, str], num_cards: int | dict[str, int] = 1):
all_marks = hardware_marks(res=res, num_cards=num_cards)
def wrapper(f):
func = f
for mark in reversed(all_marks):
func = mark(func)
return func
return wrapper
+643
View File
@@ -0,0 +1,643 @@
"""Synthetic media generation and media/text utilities for tests."""
import base64
import concurrent.futures
import gc
import io
import logging
import math
import multiprocessing
import os
import random
import re
import subprocess
import tempfile
import time
import uuid
from contextlib import contextmanager
from pathlib import Path
from typing import Any
import numpy as np
import soundfile as sf
from PIL import Image
logger = logging.getLogger(__name__)
def _resolve_synthetic_media_cache_dir(cache_dir: Path | str | None) -> Path:
if cache_dir is not None:
return Path(cache_dir).expanduser().resolve()
return Path(tempfile.gettempdir()) / "vllm_omni_test_synthetic_media"
def _np_array_from_mp4_bytes(video_bytes: bytes) -> np.ndarray:
"""Decode MP4 bytes to a (T, H, W, 3) uint8 RGB stack (matches in-memory synthetic frames)."""
import cv2
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp:
tmp.write(video_bytes)
path = tmp.name
cap = None
try:
cap = cv2.VideoCapture(path)
if not cap.isOpened():
raise RuntimeError("Failed to open cached synthetic video for decode")
frames: list[np.ndarray] = []
while True:
ok, frame_bgr = cap.read()
if not ok:
break
frames.append(cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB))
if not frames:
raise RuntimeError("Cached synthetic video has no decodable frames")
return np.stack(frames, axis=0)
finally:
if cap is not None:
cap.release()
try:
os.unlink(path)
except OSError:
pass
def generate_synthetic_audio(
duration: int,
num_channels: int,
sample_rate: int = 48000,
*,
force_regenerate: bool = False,
cache_dir: Path | str | None = None,
) -> dict[str, Any]:
"""
Generate TTS speech with pyttsx3 and return base64 string.
Caches the WAV under ``cache_dir`` when given, else under the default temp
subdirectory. Reuses the file when the same
``duration`` / ``num_channels`` / ``sample_rate`` are requested unless
``force_regenerate`` is true.
"""
root = _resolve_synthetic_media_cache_dir(cache_dir)
root.mkdir(parents=True, exist_ok=True)
cache_path = root / f"synth_audio_d{duration}_ch{num_channels}_sr{sample_rate}.wav"
if not force_regenerate and cache_path.is_file():
data, _sr = sf.read(str(cache_path), dtype="float32", always_2d=True)
audio_bytes = cache_path.read_bytes()
return {
"np_array": np.asarray(data, dtype=np.float32),
"base64": base64.b64encode(audio_bytes).decode("utf-8"),
"file_path": str(cache_path.resolve()),
}
import pyttsx3
def _pick_voice(engine: pyttsx3.Engine) -> str | None:
voices = engine.getProperty("voices")
if not voices:
return None
preferred_tokens = (
"natural",
"jenny",
"sonia",
"susan",
"zira",
"aria",
"hazel",
"samantha",
"ava",
"allison",
"female",
"woman",
"english-us",
"en-us",
"english",
)
discouraged_tokens = (
"espeak",
"robot",
"mbrola",
"microsoft david",
"male",
"man",
)
best_voice = voices[0]
best_score = float("-inf")
for voice in voices:
voice_text = f"{getattr(voice, 'id', '')} {getattr(voice, 'name', '')}".lower()
voice_languages = " ".join(
lang.decode(errors="ignore") if isinstance(lang, bytes) else str(lang)
for lang in getattr(voice, "languages", [])
).lower()
combined_text = f"{voice_text} {voice_languages}"
score = 0
for idx, token in enumerate(preferred_tokens):
if token in combined_text:
score += 20 - idx
for token in discouraged_tokens:
if token in combined_text:
score -= 10
if "english" in combined_text or "en_" in combined_text or "en-" in combined_text:
score += 4
if "en-us" in combined_text or "english-us" in combined_text:
score += 4
if score > best_score:
best_score = score
best_voice = voice
return best_voice.id
def _resample_audio(audio: np.ndarray, src_sr: int, dst_sr: int) -> np.ndarray:
if src_sr == dst_sr or len(audio) == 0:
return audio.astype(np.float32)
src_len = audio.shape[0]
dst_len = max(1, int(round(src_len * float(dst_sr) / float(src_sr))))
src_idx = np.arange(src_len, dtype=np.float32)
dst_idx = np.linspace(0, src_len - 1, dst_len, dtype=np.float32)
resampled_channels: list[np.ndarray] = []
for ch in range(audio.shape[1]):
resampled_channels.append(np.interp(dst_idx, src_idx, audio[:, ch]).astype(np.float32))
return np.stack(resampled_channels, axis=1)
def _match_channels(audio: np.ndarray, target_channels: int) -> np.ndarray:
current_channels = audio.shape[1]
if current_channels == target_channels:
return audio.astype(np.float32)
if target_channels == 1:
return np.mean(audio, axis=1, keepdims=True, dtype=np.float32)
if current_channels == 1:
return np.repeat(audio, target_channels, axis=1).astype(np.float32)
collapsed = np.mean(audio, axis=1, keepdims=True, dtype=np.float32)
return np.repeat(collapsed, target_channels, axis=1).astype(np.float32)
def _trim_silence(audio: np.ndarray, threshold: float = 0.01) -> np.ndarray:
if len(audio) == 0:
return audio
energy = np.max(np.abs(audio), axis=1)
voiced = np.where(energy > threshold)[0]
if len(voiced) == 0:
return audio
start = max(0, int(voiced[0]) - int(sample_rate * 0.02))
end = min(len(audio), int(voiced[-1]) + int(sample_rate * 0.04) + 1)
return audio[start:end]
def _enhance_speech(audio: np.ndarray) -> np.ndarray:
if len(audio) == 0:
return audio.astype(np.float32)
enhanced = audio.astype(np.float32).copy()
enhanced -= np.mean(enhanced, axis=0, keepdims=True, dtype=np.float32)
if len(enhanced) > 1:
preemphasis = enhanced.copy()
preemphasis[1:] = enhanced[1:] - 0.94 * enhanced[:-1]
enhanced = 0.7 * enhanced + 0.3 * preemphasis
enhanced = np.sign(enhanced) * np.sqrt(np.abs(enhanced))
fade = min(len(enhanced) // 4, max(1, int(sample_rate * 0.01)))
if fade > 1:
ramp_in = np.linspace(0.0, 1.0, fade, dtype=np.float32)
ramp_out = np.linspace(1.0, 0.0, fade, dtype=np.float32)
enhanced[:fade] *= ramp_in[:, None]
enhanced[-fade:] *= ramp_out[:, None]
peak = float(np.max(np.abs(enhanced)))
if peak > 1e-8:
enhanced = enhanced / peak * 0.95
return enhanced.astype(np.float32)
phrase_text = "test"
num_samples = int(sample_rate * max(1, duration))
audio_data = np.zeros((num_samples, num_channels), dtype=np.float32)
engine = pyttsx3.init()
engine.setProperty("rate", 112)
engine.setProperty("volume", 1.0)
selected_voice = _pick_voice(engine)
if selected_voice is not None:
engine.setProperty("voice", selected_voice)
temp_wav = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
temp_wav.close()
try:
engine.save_to_file(phrase_text, temp_wav.name)
engine.runAndWait()
engine.stop()
ready = False
for _ in range(50):
if os.path.exists(temp_wav.name) and os.path.getsize(temp_wav.name) > 44:
ready = True
break
time.sleep(0.1)
if not ready:
raise RuntimeError("pyttsx3 did not produce a WAV file in time.")
tts_audio, tts_sr = sf.read(temp_wav.name, dtype="float32", always_2d=True)
finally:
if os.path.exists(temp_wav.name):
os.unlink(temp_wav.name)
if len(tts_audio) == 0:
raise RuntimeError("pyttsx3 produced an empty WAV file.")
tts_audio = _resample_audio(tts_audio, tts_sr, sample_rate)
tts_audio = _match_channels(tts_audio, num_channels)
tts_audio = _trim_silence(tts_audio, threshold=0.012)
tts_audio = _enhance_speech(tts_audio)
lead_silence = min(int(sample_rate * 0.02), num_samples // 8)
pause_samples = int(sample_rate * 0.18)
start = lead_silence
phrase_len = tts_audio.shape[0]
while start < num_samples:
take = min(phrase_len, num_samples - start)
audio_data[start : start + take] = tts_audio[:take]
start += phrase_len + pause_samples
max_amp = float(np.max(np.abs(audio_data)))
if max_amp > 0:
audio_data = audio_data / max_amp * 0.95
sf.write(str(cache_path), audio_data, sample_rate, format="WAV", subtype="PCM_16")
audio_bytes = cache_path.read_bytes()
return {
"np_array": audio_data.copy(),
"base64": base64.b64encode(audio_bytes).decode("utf-8"),
"file_path": str(cache_path.resolve()),
}
def _mux_mp4_bytes_with_synthetic_audio(
video_mp4_bytes: bytes,
*,
num_frames: int,
fps: float = 30.0,
sample_rate: int = 48000,
) -> bytes:
duration_sec = num_frames / fps if fps > 0 else 0.0
duration_int = max(1, int(math.ceil(duration_sec)))
try:
audio_result = generate_synthetic_audio(
duration=duration_int,
num_channels=1,
sample_rate=sample_rate,
)
audio_pcm = audio_result["np_array"]
except Exception as e:
logger.warning("Synthetic video: generate_synthetic_audio failed (%s); using video-only MP4.", e)
return video_mp4_bytes
try:
import imageio_ffmpeg
ffmpeg_exe = imageio_ffmpeg.get_ffmpeg_exe()
except Exception:
ffmpeg_exe = "ffmpeg"
try:
with tempfile.TemporaryDirectory(prefix="syn_vid_mux_") as tmp:
vid_path = os.path.join(tmp, "video.mp4")
wav_path = os.path.join(tmp, "audio.wav")
out_path = os.path.join(tmp, "out.mp4")
with open(vid_path, "wb") as f:
f.write(video_mp4_bytes)
sf.write(wav_path, audio_pcm, sample_rate, format="WAV", subtype="PCM_16")
cmd = [
ffmpeg_exe,
"-y",
"-nostdin",
"-hide_banner",
"-loglevel",
"error",
"-i",
vid_path,
"-i",
wav_path,
"-c:v",
"copy",
"-c:a",
"aac",
"-b:a",
"128k",
"-shortest",
"-movflags",
"+faststart",
out_path,
]
subprocess.run(cmd, check=True, stdin=subprocess.DEVNULL, timeout=300)
with open(out_path, "rb") as f:
return f.read()
except (
FileNotFoundError,
subprocess.CalledProcessError,
subprocess.TimeoutExpired,
OSError,
) as e:
logger.warning("Synthetic video: audio mux failed (%s); using video-only MP4.", e)
return video_mp4_bytes
def generate_synthetic_video(
width: int,
height: int,
num_frames: int,
*,
embed_audio: bool = False,
force_regenerate: bool = False,
cache_dir: Path | str | None = None,
) -> dict[str, Any]:
"""
Generate synthetic MP4 (optional AAC audio). Caches final bytes by
``width`` / ``height`` / ``num_frames`` / ``embed_audio`` unless
``force_regenerate`` is true. Cache root: ``cache_dir`` if given, else the
default temp subdirectory.
"""
root = _resolve_synthetic_media_cache_dir(cache_dir)
root.mkdir(parents=True, exist_ok=True)
cache_path = root / f"synth_video_w{width}_h{height}_nf{num_frames}_ea{int(embed_audio)}.mp4"
if not force_regenerate and cache_path.is_file():
video_bytes = cache_path.read_bytes()
return {
"np_array": _np_array_from_mp4_bytes(video_bytes),
"base64": base64.b64encode(video_bytes).decode("utf-8"),
"file_path": str(cache_path.resolve()),
}
import cv2
import imageio
num_balls = random.randint(3, 8)
balls = []
for _ in range(num_balls):
radius = min(width, height) // 8
if radius < 1:
raise ValueError(f"Video dimensions ({width}x{height}) too small")
x = random.randint(radius, width - radius)
y = random.randint(radius, height - radius)
speed = random.uniform(3.0, 8.0)
angle = random.uniform(0, 2 * math.pi)
vx = speed * math.cos(angle)
vy = speed * math.sin(angle)
color_bgr = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
balls.append({"x": x, "y": y, "vx": vx, "vy": vy, "radius": radius, "color_bgr": color_bgr})
video_frames = []
for _ in range(num_frames):
frame_bgr = np.zeros((height, width, 3), dtype=np.uint8)
for ball in balls:
ball["x"] += ball["vx"]
ball["y"] += ball["vy"]
if ball["x"] - ball["radius"] <= 0 or ball["x"] + ball["radius"] >= width:
ball["vx"] = -ball["vx"]
ball["x"] = max(ball["radius"], min(width - ball["radius"], ball["x"]))
if ball["y"] - ball["radius"] <= 0 or ball["y"] + ball["radius"] >= height:
ball["vy"] = -ball["vy"]
ball["y"] = max(ball["radius"], min(height - ball["radius"], ball["y"]))
x, y = int(ball["x"]), int(ball["y"])
radius = int(ball["radius"])
cv2.circle(frame_bgr, (x, y), radius, ball["color_bgr"], -1)
frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
video_frames.append(frame_rgb)
fps = 30
buffer = io.BytesIO()
writer_kwargs = {
"format": "mp4",
"fps": fps,
"codec": "libx264",
"quality": 7,
"pixelformat": "yuv420p",
"macro_block_size": 16,
"ffmpeg_params": ["-preset", "medium", "-crf", "23", "-movflags", "+faststart", "-pix_fmt", "yuv420p"],
}
try:
with imageio.get_writer(buffer, **writer_kwargs) as writer:
for frame in video_frames:
writer.append_data(frame)
buffer.seek(0)
video_only_bytes = buffer.read()
except Exception as e:
print(f"Warning: Failed to encode synthetic video: {e}")
raise
video_bytes = (
_mux_mp4_bytes_with_synthetic_audio(video_only_bytes, num_frames=num_frames, fps=float(fps))
if embed_audio
else video_only_bytes
)
cache_path.write_bytes(video_bytes)
return {
"np_array": np.array(video_frames),
"base64": base64.b64encode(video_bytes).decode("utf-8"),
"file_path": str(cache_path.resolve()),
}
def generate_synthetic_image(
width: int,
height: int,
*,
force_regenerate: bool = False,
cache_dir: Path | str | None = None,
) -> dict[str, Any]:
"""
Random colored squares on white background. Caches JPEG by ``width`` /
``height`` unless ``force_regenerate`` is true. Cache root: ``cache_dir``
if given, else the default temp subdirectory.
"""
root = _resolve_synthetic_media_cache_dir(cache_dir)
root.mkdir(parents=True, exist_ok=True)
cache_path = root / f"synth_image_w{width}_h{height}.jpg"
if not force_regenerate and cache_path.is_file():
from PIL import Image as PILImage
image = PILImage.open(cache_path)
image.load()
image_bytes = cache_path.read_bytes()
return {
"np_array": np.array(image).copy(),
"base64": base64.b64encode(image_bytes).decode("utf-8"),
"file_path": str(cache_path.resolve()),
}
from PIL import ImageDraw
image = Image.new("RGB", (width, height), (255, 255, 255))
draw = ImageDraw.Draw(image)
num_squares = random.randint(3, 8)
for _ in range(num_squares):
square_size = random.randint(max(1, min(width, height) // 8), max(2, min(width, height) // 4))
x = random.randint(0, max(0, width - square_size - 1))
y = random.randint(0, max(0, height - square_size - 1))
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
border_width = random.randint(1, 5)
draw.rectangle([x, y, x + square_size, y + square_size], fill=color, outline=(0, 0, 0), width=border_width)
image.save(str(cache_path), format="JPEG", quality=85, optimize=True)
image_bytes = cache_path.read_bytes()
return {
"np_array": np.array(image).copy(),
"base64": base64.b64encode(image_bytes).decode("utf-8"),
"file_path": str(cache_path.resolve()),
}
def decode_b64_image(b64: str):
img = Image.open(io.BytesIO(base64.b64decode(b64)))
img.load()
return img
def preprocess_text(text):
import opencc
word_to_num = {
"zero": "0",
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
"ten": "10",
}
for word, num in word_to_num.items():
pattern = r"\b" + re.escape(word) + r"\b"
text = re.sub(pattern, num, text, flags=re.IGNORECASE)
text = re.sub(r"[^\w\s]", "", text)
text = re.sub(r"\s+", " ", text)
cc = opencc.OpenCC("t2s")
text = cc.convert(text)
text = re.sub(r"(?<=[\u4e00-\u9fff])\s+(?=[\u4e00-\u9fff])", "", text)
return text.lower().strip()
def cosine_similarity_text(text1, text2, n: int = 3):
from collections import Counter
if not text1 or not text2:
return 0.0
text1 = preprocess_text(text1)
text2 = preprocess_text(text2)
print(f"cosine similarity text1 is: {text1}, text2 is: {text2}")
ngrams1 = [text1[i : i + n] for i in range(len(text1) - n + 1)]
ngrams2 = [text2[i : i + n] for i in range(len(text2) - n + 1)]
counter1 = Counter(ngrams1)
counter2 = Counter(ngrams2)
all_ngrams = set(counter1.keys()) | set(counter2.keys())
vec1 = [counter1.get(ng, 0) for ng in all_ngrams]
vec2 = [counter2.get(ng, 0) for ng in all_ngrams]
dot_product = sum(a * b for a, b in zip(vec1, vec2))
norm1 = sum(a * a for a in vec1) ** 0.5
norm2 = sum(b * b for b in vec2) ** 0.5
if norm1 == 0 or norm2 == 0:
return 0.0
return dot_product / (norm1 * norm2)
def _merge_base64_audio_to_segment(base64_list: list[str]):
from pydub import AudioSegment
merged = None
for b64 in base64_list:
raw = base64.b64decode(b64.split(",", 1)[-1])
seg = AudioSegment.from_file(io.BytesIO(raw))
merged = seg if merged is None else merged + seg
return merged
@contextmanager
def _serialize_whisper_small_model_download():
"""Serialize Whisper ``small`` cache writes across processes (Linux/Unix)."""
import fcntl
lock_path = Path.home() / ".cache" / "whisper" / ".small_model_download.lock"
lock_path.parent.mkdir(parents=True, exist_ok=True)
f = open(lock_path, "a+b")
try:
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
yield
finally:
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
f.close()
def _whisper_transcribe_in_current_process(output_path: str) -> str:
import whisper
device_index = None
from vllm_omni.platforms import current_omni_platform
if current_omni_platform.is_available():
n = current_omni_platform.get_device_count()
if n == 1:
device_index = 0
elif n > 1:
device_index = n - 1
if device_index is not None:
torch_device = current_omni_platform.get_torch_device(device_index)
current_omni_platform.set_device(torch_device)
device = str(torch_device)
use_accelerator = True
else:
use_accelerator = False
device = "cpu"
with _serialize_whisper_small_model_download():
model = whisper.load_model("small", device=device)
try:
text = model.transcribe(
output_path,
temperature=0.0,
word_timestamps=True,
condition_on_previous_text=False,
)["text"]
finally:
del model
gc.collect()
if use_accelerator:
current_omni_platform.synchronize()
current_omni_platform.empty_cache()
return text or ""
def convert_audio_file_to_text(output_path: str) -> str:
"""Convert an audio file to text in an isolated subprocess."""
ctx = multiprocessing.get_context("spawn")
with concurrent.futures.ProcessPoolExecutor(max_workers=1, mp_context=ctx) as executor:
future = executor.submit(_whisper_transcribe_in_current_process, output_path)
return future.result()
def convert_audio_bytes_to_text(raw_bytes: bytes) -> str:
output_path = f"./test_{uuid.uuid4().hex}.wav"
data, samplerate = sf.read(io.BytesIO(raw_bytes))
sf.write(output_path, data, samplerate, format="WAV", subtype="PCM_16")
print(f"audio data is saved: {output_path}")
return convert_audio_file_to_text(output_path)
__all__ = [
"_merge_base64_audio_to_segment",
"convert_audio_bytes_to_text",
"convert_audio_file_to_text",
"cosine_similarity_text",
"decode_b64_image",
"generate_synthetic_audio",
"generate_synthetic_image",
"generate_synthetic_video",
"preprocess_text",
]
+134
View File
@@ -0,0 +1,134 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import functools
import os
import signal
import subprocess
import sys
import tempfile
from collections.abc import Callable
from contextlib import ExitStack, suppress
from typing import Any, Literal
import cloudpickle
from typing_extensions import ParamSpec
from vllm.platforms import current_platform
_P = ParamSpec("_P")
def fork_new_process_for_each_test(func: Callable[_P, None]) -> Callable[_P, None]:
"""Decorator to fork a new process for each test function."""
@functools.wraps(func)
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> None:
os.setpgrp()
from _pytest.outcomes import Skipped
with (
tempfile.NamedTemporaryFile(
delete=False, mode="w+b", prefix=f"vllm_test_{func.__name__}_{os.getpid()}_", suffix=".exc"
) as exc_file,
ExitStack() as delete_after,
):
exc_file_path = exc_file.name
delete_after.callback(os.remove, exc_file_path)
pid = os.fork()
if pid == 0:
delete_after.pop_all()
try:
func(*args, **kwargs)
except Skipped as e:
print(str(e))
os._exit(0)
except Exception as e:
import traceback
tb_string = traceback.format_exc()
exc_to_serialize: dict[str, Any]
try:
exc_to_serialize = {"pickled_exception": e}
cloudpickle.dumps(exc_to_serialize)
except (Exception, KeyboardInterrupt):
exc_to_serialize = {
"exception_type": type(e).__name__,
"exception_msg": str(e),
"traceback": tb_string,
}
try:
with open(exc_file_path, "wb") as f:
cloudpickle.dump(exc_to_serialize, f)
except Exception:
print(tb_string)
os._exit(1)
else:
os._exit(0)
else:
pgid = os.getpgid(pid)
_pid, _exitcode = os.waitpid(pid, 0)
old_signal_handler = signal.signal(signal.SIGTERM, signal.SIG_IGN)
os.killpg(pgid, signal.SIGTERM)
signal.signal(signal.SIGTERM, old_signal_handler)
if _exitcode != 0:
exc_info = {}
if os.path.exists(exc_file_path):
with suppress(Exception), open(exc_file_path, "rb") as f:
exc_info = cloudpickle.load(f)
if (original_exception := exc_info.get("pickled_exception")) is not None:
assert isinstance(original_exception, Exception)
raise original_exception
if (original_tb := exc_info.get("traceback")) is not None:
raise AssertionError(
f"Test {func.__name__} failed when called with args {args} and kwargs {kwargs}"
f" (exit code: {_exitcode}):\n{original_tb}"
) from None
raise AssertionError(
f"function {func.__name__} failed when called with args {args} and kwargs {kwargs}"
f" (exit code: {_exitcode})"
) from None
return wrapper
def spawn_new_process_for_each_test(f: Callable[_P, None]) -> Callable[_P, None]:
"""Decorator to spawn a new process for each test function."""
@functools.wraps(f)
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> None:
if os.environ.get("RUNNING_IN_SUBPROCESS") == "1":
return f(*args, **kwargs)
import torch.multiprocessing as mp
with suppress(RuntimeError):
mp.set_start_method("spawn")
module_name = f.__module__
env = os.environ.copy()
env["RUNNING_IN_SUBPROCESS"] = "1"
with tempfile.TemporaryDirectory() as tempdir:
output_filepath = os.path.join(tempdir, "new_process.tmp")
input_bytes = cloudpickle.dumps((f, output_filepath))
cmd = [sys.executable, "-m", f"{module_name}"]
returned = subprocess.run(cmd, input=input_bytes, capture_output=True, env=env)
try:
returned.check_returncode()
except Exception as e:
raise RuntimeError(f"Error raised in subprocess:\n{returned.stderr.decode()}") from e
return wrapper
def create_new_process_for_each_test(
method: Literal["spawn", "fork"] | None = None,
) -> Callable[[Callable[_P, None]], Callable[_P, None]]:
"""Creates a decorator that runs each test function in a new process."""
if method is None:
use_spawn = current_platform.is_xpu()
method = "spawn" if use_spawn else "fork"
assert method in ["spawn", "fork"], "Method must be either 'spawn' or 'fork'"
if method == "fork":
return fork_new_process_for_each_test
return spawn_new_process_for_each_test
File diff suppressed because it is too large. Load diff
+475
View File
@@ -0,0 +1,475 @@
"""Config/message construction helpers used by tests."""
import atexit
import os
import tempfile
from pathlib import Path
from typing import Any
import yaml
def modify_stage_config(
yaml_path: str,
updates: dict[str, Any] = None,
deletes: dict[str, Any] = None,
) -> str:
"""
Modify configurations in a YAML file, supporting both top-level and stage-specific modifications,
including addition, modification, and deletion of configurations.
Args:
yaml_path: Path to the YAML configuration file.
updates: Dictionary containing both top-level and stage-specific modifications to add or update.
Format: {
'async_chunk': True,
'stage_args': {
0: {'engine_args.max_model_len': 5800},
1: {'engine_args.max_num_seqs': 2}
}
}
deletes: Dictionary containing configurations to delete.
Format: {
'old_config': None, # Delete entire key
'stage_args': {
0: ['engine_args.old_param'],
1: ['runtime.unused_setting']
}
}
Returns:
str: Path to the newly created modified YAML file with timestamp suffix.
"""
path = Path(yaml_path)
if not path.exists():
raise FileNotFoundError(f"yaml does not exist: {path}")
try:
with open(yaml_path, encoding="utf-8") as f:
config = yaml.safe_load(f) or {}
except Exception as e:
raise ValueError(f"Cannot parse YAML file: {e}")
# Helper function to apply update
def apply_update(config_dict: dict, key_path: str, value: Any) -> None:
"""Apply update to dictionary using dot-separated path."""
# Handle direct list assignment (e.g., engine_input_source: [1, 2])
if "." not in key_path:
# Simple key, set directly
config_dict[key_path] = value
return
current = config_dict
keys = key_path.split(".")
for i in range(len(keys) - 1):
key = keys[i]
# Handle list indices
if key.isdigit() and isinstance(current, list):
index = int(key)
if index < 0:
raise ValueError(f"Negative list index not allowed: {index}")
if index >= len(current):
# Expand list if needed
while len(current) <= index:
# If we need to go deeper (more keys after this), create a dict
# Otherwise, create None placeholder
current.append({} if i < len(keys) - 2 else None)
current = current[index]
elif isinstance(current, dict):
# Handle dictionary keys
if key not in current:
# If there are more keys after this, create appropriate structure
if i < len(keys) - 1:
# Check if next key is a digit (list index) or string (dict key)
if keys[i + 1].isdigit():
current[key] = []
else:
current[key] = {}
else:
# This is the last key, create based on value type
current[key] = [] if isinstance(value, list) else {}
elif not isinstance(current[key], (dict, list)) and i < len(keys) - 1:
# If current value is not dict/list but we need to go deeper, replace it
if keys[i + 1].isdigit():
current[key] = []
else:
current[key] = {}
current = current[key]
else:
# Current is not a dict or list, cannot traverse further
raise TypeError(
f"Cannot access {'.'.join(keys[: i + 1])} as a dict/list. It's a {type(current).__name__}"
)
# Set the final value
last_key = keys[-1]
if isinstance(current, list) and last_key.isdigit():
# Setting a value in a list by index
index = int(last_key)
if index < 0:
raise ValueError(f"Negative list index not allowed: {index}")
if index >= len(current):
# Expand list if needed
while len(current) <= index:
current.append(None)
current[index] = value
elif isinstance(current, dict):
# Special case: if the value is a list and we're setting a top-level key
# Example: updating engine_input_source with [1, 2]
current[last_key] = value
else:
# Current is not a dict, cannot set key
raise TypeError(f"Cannot set value at {key_path}. Current type is {type(current).__name__}, expected dict.")
# Helper function to delete by path
def delete_by_path(config_dict: dict, path: str) -> None:
"""Delete configuration by dot-separated path."""
if not path:
return
current = config_dict
keys = path.split(".")
# Traverse to the parent
for i in range(len(keys) - 1):
key = keys[i]
# Handle list indices
if key.isdigit() and isinstance(current, list):
index = int(key)
if index < 0 or index >= len(current):
raise KeyError(f"List index {index} out of bounds")
current = current[index]
elif isinstance(current, dict):
if key not in current:
raise KeyError(f"Path {'.'.join(keys[: i + 1])} does not exist")
current = current[key]
else:
raise TypeError(
f"Cannot access {'.'.join(keys[: i + 1])} as a dict/list. It's a {type(current).__name__}"
)
# Delete the item
last_key = keys[-1]
if isinstance(current, list) and last_key.isdigit():
index = int(last_key)
if index < 0 or index >= len(current):
raise KeyError(f"List index {index} out of bounds")
del current[index]
elif isinstance(current, dict) and last_key in current:
del current[last_key]
else:
print(f"Path {path} does not exist")
_stage_key = "stages" if "stages" in config else "stage_args"
# Apply deletions first
if deletes:
for key, value in deletes.items():
if key in ("stage_args", "stages"):
if value and isinstance(value, dict):
stage_args = config.get(_stage_key, [])
if not stage_args:
raise ValueError("stage_args does not exist in config")
for stage_id, delete_paths in value.items():
if not delete_paths:
continue
# Find stage by ID
target_stage = None
for stage in stage_args:
if stage.get("stage_id") == int(stage_id):
target_stage = stage
break
if target_stage is None:
continue
# Delete specified paths in this stage
# Avoid shadowing the original YAML Path used for the output filename below.
for delete_path in delete_paths:
if delete_path: # Skip empty paths
delete_by_path(target_stage, delete_path)
elif "." in key:
# Delete using dot-separated path
delete_by_path(config, key)
elif value is None and key in config:
# Delete entire key
del config[key]
# Apply updates
if updates:
for key, value in updates.items():
if key in ("stage_args", "stages"):
if value and isinstance(value, dict):
stage_args = config.get(_stage_key, [])
if not stage_args:
raise ValueError("stage_args does not exist in config")
for stage_id, stage_updates in value.items():
# Find stage by ID
target_stage = None
for stage in stage_args:
if stage.get("stage_id") == int(stage_id):
target_stage = stage
break
if target_stage is None:
available_ids = [s.get("stage_id") for s in stage_args if "stage_id" in s]
raise KeyError(f"Stage ID {stage_id} not found, available: {available_ids}")
# Apply updates to this stage
for update_path, val in stage_updates.items():
# Check if this is a simple key (not dot-separated)
# Example: 'engine_input_source' vs 'engine_args.max_model_len'
if "." not in update_path:
# Direct key assignment (e.g., updating a list value)
target_stage[update_path] = val
else:
# Dot-separated path (e.g., nested dict access)
apply_update(target_stage, update_path, val)
elif "." in key:
# Apply using dot-separated path
apply_update(config, key, value)
else:
# Direct top-level key
config[key] = value
# Unique suffix: multiple modify_stage_config calls in one process often run
# within the same second (e.g. test_qwen3_omni_expansion imports both
# get_chunk_config and get_batch_token_config). int(time.time()) would collide
# and the later write would overwrite the earlier YAML on disk.
# Keep generated configs outside the repo and delete them when pytest exits.
output_fd, output_path = tempfile.mkstemp(prefix=f"{path.stem}_", suffix=".yaml")
atexit.register(Path(output_path).unlink, missing_ok=True)
with os.fdopen(output_fd, "w", encoding="utf-8") as f:
yaml.dump(config, f, default_flow_style=None, sort_keys=False, allow_unicode=True, indent=2)
return str(output_path)
# ``stage_config.py`` lives under ``tests/helpers/``; repo root is three parents up.
_REPO_ROOT = Path(__file__).resolve().parent.parent.parent
_DEPLOY_DIR = _REPO_ROOT / "vllm_omni" / "deploy"
_CI_GENERATED_DIR = _REPO_ROOT / "tests" / ".ci_generated"
# CI overlays as Python dicts (LSP-friendly). Materialized on demand to
# tests/.ci_generated/<model>.yaml via get_deploy_config_path("ci/<name>.yaml").
_CI_OVERLAYS: dict[str, dict[str, Any]] = {
"qwen2_5_omni": {
"base_config": "qwen2_5_omni.yaml",
"async_chunk": False,
"stages": [
{
"stage_id": 0,
"max_model_len": 16384,
"max_num_batched_tokens": 16384,
"max_num_seqs": 1,
"gpu_memory_utilization": 0.9,
"skip_mm_profiling": True,
"load_format": "dummy",
"default_sampling_params": {"max_tokens": 128},
},
{
"stage_id": 1,
"max_model_len": 16384,
"max_num_batched_tokens": 16384,
"max_num_seqs": 1,
"gpu_memory_utilization": 0.4,
"skip_mm_profiling": True,
"load_format": "dummy",
"default_sampling_params": {"max_tokens": 4096},
},
{
"stage_id": 2,
"max_num_seqs": 1,
"gpu_memory_utilization": 0.5,
"max_num_batched_tokens": 8192,
"max_model_len": 8192,
"load_format": "dummy",
"devices": "2",
"default_sampling_params": {"max_tokens": 8192},
},
],
"platforms": {
"rocm": {
"stages": [
{"stage_id": 0, "gpu_memory_utilization": 0.9},
{"stage_id": 1, "gpu_memory_utilization": 0.4},
{"stage_id": 2, "gpu_memory_utilization": 0.5, "devices": "2"},
],
},
"xpu": {
"stages": [
{
"stage_id": 0,
"gpu_memory_utilization": 0.9,
"max_num_batched_tokens": 16384,
"max_model_len": 16384,
},
{"stage_id": 1, "gpu_memory_utilization": 0.5},
{
"stage_id": 2,
"gpu_memory_utilization": 0.3,
"max_num_batched_tokens": 4096,
"max_model_len": 4096,
"devices": "2",
},
],
},
},
},
"qwen3_omni_moe": {
"base_config": "qwen3_omni_moe.yaml",
"async_chunk": False,
"stages": [
{
"stage_id": 0,
"max_num_seqs": 5,
"max_model_len": 32768,
"mm_processor_cache_gb": 0,
"load_format": "dummy",
"default_sampling_params": {"max_tokens": 150, "ignore_eos": False},
},
{
"stage_id": 1,
"gpu_memory_utilization": 0.5,
"max_num_seqs": 5,
"max_model_len": 32768,
"load_format": "dummy",
"default_sampling_params": {"max_tokens": 1000},
},
{
"stage_id": 2,
"max_num_seqs": 5,
"max_num_batched_tokens": 100000,
"load_format": "dummy",
"default_sampling_params": {"max_tokens": 2000},
},
],
"platforms": {
"rocm": {
"stages": [
{"stage_id": 0, "max_num_seqs": 1, "default_sampling_params": {"max_tokens": 100}},
{
"stage_id": 1,
"max_num_seqs": 1,
"enforce_eager": True,
"default_sampling_params": {"max_tokens": 100},
},
{
"stage_id": 2,
"max_num_seqs": 1,
"max_num_batched_tokens": 1000000,
"default_sampling_params": {"max_tokens": 200},
},
],
},
"xpu": {
"stages": [
{
"stage_id": 0,
"gpu_memory_utilization": 0.85,
"max_num_seqs": 1,
"tensor_parallel_size": 4,
"enforce_eager": True,
"max_num_batched_tokens": 4096,
"max_model_len": 4096,
"max_cudagraph_capture_size": 0,
"skip_mm_profiling": True,
"devices": "0,1,2,3",
"default_sampling_params": {"max_tokens": 100, "ignore_eos": False},
},
{
"stage_id": 1,
"gpu_memory_utilization": 0.6,
"max_num_seqs": 1,
"enforce_eager": True,
"max_num_batched_tokens": 4096,
"max_model_len": 4096,
"max_cudagraph_capture_size": 0,
"skip_mm_profiling": True,
"devices": "4",
},
{
"stage_id": 2,
"gpu_memory_utilization": 0.3,
"max_num_seqs": 1,
"max_num_batched_tokens": 100000,
"max_cudagraph_capture_size": 0,
"skip_mm_profiling": True,
"devices": "5",
"default_sampling_params": {"max_tokens": 2000},
},
],
},
},
},
# Single-stage thinker-only topology for the abort test.
"qwen2_5_omni_thinker_only": {
"async_chunk": False,
"pipeline": "qwen2_5_omni_thinker_only",
"stages": [
{
"stage_id": 0,
"max_num_seqs": 1,
"gpu_memory_utilization": 0.9,
"enforce_eager": True,
"max_num_batched_tokens": 16384,
"max_model_len": 16384,
"skip_mm_profiling": True,
"mm_processor_cache_gb": 0,
"load_format": "dummy",
"devices": "0",
"default_sampling_params": {
"temperature": 0.0,
"top_p": 1.0,
"top_k": -1,
"max_tokens": 128,
"seed": 42,
"repetition_penalty": 1.1,
},
},
],
},
}
def _materialize_ci_overlay(model_type: str) -> Path:
import yaml
if model_type not in _CI_OVERLAYS:
raise KeyError(f"No CI overlay registered for {model_type!r}. Available: {sorted(_CI_OVERLAYS)}")
_CI_GENERATED_DIR.mkdir(parents=True, exist_ok=True)
out = _CI_GENERATED_DIR / f"{model_type}.yaml"
overlay = {**_CI_OVERLAYS[model_type]}
base = overlay.get("base_config")
if base:
overlay["base_config"] = str(_DEPLOY_DIR / base)
with open(out, "w", encoding="utf-8") as f:
yaml.safe_dump(overlay, f, sort_keys=False)
return out
def get_deploy_config_path(rel_path: str) -> str:
"""Resolve a deploy yaml; ``ci/<model>.yaml`` materializes from ``_CI_OVERLAYS``."""
if rel_path.startswith("ci/") and rel_path.endswith(".yaml"):
model_type = rel_path[len("ci/") : -len(".yaml")]
if model_type in _CI_OVERLAYS:
return str(_materialize_ci_overlay(model_type))
return str(_DEPLOY_DIR / rel_path)
__all__ = [
"modify_stage_config",
"get_deploy_config_path",
]