Merge remote-tracking branch 'remotes/origin/main' into dev/rebase-v0169

This commit is contained in:
tzhouam committed 2026-03-05 02:29:14 +00:00
commit 395eab8984
59 files changed
+11285 -22

No files matched your search

@@ -0,0 +1,215 @@
"""
End-to-end test for MammothModa2 text-to-image generation.
Verifies that the AR->DiT pipeline produces an image tensor whose pixel values
match a golden reference.
Model weights: env var ``MAMMOTHMODA2_MODEL_PATH``
(default: <repo_root>/MammothModa2-Preview)
Stage config: env var ``MAMMOTHMODA2_T2I_STAGE_CONFIG``
(default: vllm_omni/model_executor/stage_configs/mammoth_moda2.yaml)
Golden pixel file: ``tests/e2e/offline_inference/fixtures/mammoth_moda2_t2i_golden.json``
Regenerate with: ``UPDATE_GOLDEN=1 pytest tests/e2e/offline_inference/test_mammoth_moda2.py``
"""
from __future__ import annotations
import json
import os
from pathlib import Path
import pytest
import torch
from vllm.sampling_params import SamplingParams
from tests.utils import hardware_test
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "1"
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
_IMAGE_TOKEN_ID = 151655 # "<|image_pad|>"
_VIDEO_TOKEN_ID = 151656 # "<|video_pad|>"
_VISION_START_TOKEN_ID = 151652 # "<|vision_start|>"
_VISION_END_TOKEN_ID = 151653 # "<|vision_end|>"
_AR_PATCH_SIZE = 16
_STAGE_CONFIGS_DIR = Path(__file__).resolve().parents[3] / "vllm_omni" / "model_executor" / "stage_configs"
MODEL_PATH = os.environ.get(
"MAMMOTHMODA2_MODEL_PATH",
str(Path(__file__).resolve().parents[3] / "MammothModa2-Preview"),
)
T2I_STAGE_CONFIG = os.environ.get(
"MAMMOTHMODA2_T2I_STAGE_CONFIG",
str(_STAGE_CONFIGS_DIR / "mammoth_moda2.yaml"),
)
# Golden pixel reference file. Set UPDATE_GOLDEN=1 to regenerate.
_GOLDEN_T2I_PATH = Path(__file__).parent / "fixtures" / "mammoth_moda2_t2i_golden.json"
# Fixed sampling coordinates: (channel, row_fraction, col_fraction)
# Covers corners, centre, and mid-edges across all 3 channels.
_PIXEL_SAMPLE_COORDS = [
(0, 0.0, 0.0),
(0, 0.5, 0.5),
(0, 1.0, 1.0),
(0, 0.25, 0.75),
(1, 0.0, 1.0),
(1, 0.5, 0.0),
(1, 0.75, 0.25),
(1, 1.0, 0.5),
(2, 0.0, 0.5),
(2, 0.5, 1.0),
(2, 0.75, 0.75),
(2, 1.0, 0.0),
]
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _load_t2i_gen_config(model_dir: str) -> dict:
cfg_path = Path(model_dir) / "t2i_generation_config.json"
if not cfg_path.exists():
pytest.skip(f"t2i_generation_config.json not found at {cfg_path}")
with cfg_path.open() as f:
return json.load(f)
def _format_t2i_prompt(user_prompt: str, ar_width: int, ar_height: int) -> str:
return (
"<|im_start|>system\nYou are a helpful image generator.<|im_end|>\n"
f"<|im_start|>user\n{user_prompt}<|im_end|>\n"
"<|im_start|>assistant\n"
f"<|image start|>{ar_width}*{ar_height}<|image token|>"
)
def _sample_pixels(img_tensor: torch.Tensor) -> list[float]:
"""Sample pixel values at fixed fractional coordinates from a (C, H, W) tensor."""
t = img_tensor.float().clamp(0.0, 1.0)
if t.ndim == 4:
t = t[0] # unbatch
C, H, W = t.shape
values = []
for c, rh, rw in _PIXEL_SAMPLE_COORDS:
ri = min(int(rh * (H - 1)), H - 1)
ci = min(int(rw * (W - 1)), W - 1)
values.append(round(float(t[c, ri, ci]), 6))
return values
# ---------------------------------------------------------------------------
# End-to-end test
# ---------------------------------------------------------------------------
@pytest.mark.core_model
@pytest.mark.diffusion
@hardware_test(res={"cuda": "L4"})
def test_mammothmoda2_t2i_e2e():
"""
End-to-end text-to-image generation with MammothModa2 (AR -> DiT).
Verifies:
- Omni pipeline initialises with the two-stage YAML config.
- DiT stage outputs an image tensor with the correct shape.
- A fixed set of pixel values matches a golden reference
(regenerate with ``UPDATE_GOLDEN=1``).
"""
from vllm_omni import Omni
if not Path(MODEL_PATH).exists():
pytest.skip(f"Model weights not found at {MODEL_PATH}")
if not Path(T2I_STAGE_CONFIG).exists():
pytest.skip(f"Stage config not found at {T2I_STAGE_CONFIG}")
gen_cfg = _load_t2i_gen_config(MODEL_PATH)
eol_token_id = int(gen_cfg["eol_token_id"])
visual_start = int(gen_cfg["visual_token_start_id"])
visual_end = int(gen_cfg["visual_token_end_id"])
height, width = 256, 256 # small for CI speed
ar_height, ar_width = height // _AR_PATCH_SIZE, width // _AR_PATCH_SIZE
expected_grid_tokens = ar_height * (ar_width + 1)
prompt_text = "A cat sitting on a laptop keyboard"
formatted_prompt = _format_t2i_prompt(prompt_text, ar_width, ar_height)
omni = Omni(model=MODEL_PATH, stage_configs_path=T2I_STAGE_CONFIG, trust_remote_code=True)
try:
# Greedy / deterministic sampling so pixel values are reproducible.
ar_sampling = SamplingParams(
temperature=0.0,
top_k=1,
max_tokens=max(1, expected_grid_tokens + 1),
detokenize=False,
)
dit_sampling = SamplingParams(temperature=0.0, max_tokens=1, detokenize=False)
outputs = list(
omni.generate(
[
{
"prompt": formatted_prompt,
"additional_information": {
"omni_task": ["t2i"],
"ar_width": [ar_width],
"ar_height": [ar_height],
"eol_token_id": [eol_token_id],
"visual_token_start_id": [visual_start],
"visual_token_end_id": [visual_end],
"image_height": [height],
"image_width": [width],
"num_inference_steps": [2],
"text_guidance_scale": [1.0],
"cfg_range": [0.0, 1.0],
"visual_ids": [
_IMAGE_TOKEN_ID,
_VIDEO_TOKEN_ID,
_VISION_START_TOKEN_ID,
_VISION_END_TOKEN_ID,
],
},
}
],
[ar_sampling, dit_sampling],
)
)
assert len(outputs) > 0, "Pipeline produced no outputs"
# Find the image tensor produced by the DiT stage and compare pixels.
found_image = False
for out in outputs:
ro_list = getattr(out, "request_output", out)
if not isinstance(ro_list, list):
ro_list = [ro_list]
for ro in ro_list:
completion_outputs = getattr(ro, "outputs", None)
if not isinstance(completion_outputs, list):
continue
for completion in completion_outputs:
mm = getattr(completion, "multimodal_output", None)
if not (isinstance(mm, dict) and "image" in mm):
continue
img_list = mm["image"] if isinstance(mm["image"], list) else [mm["image"]]
for img_tensor in img_list:
assert isinstance(img_tensor, torch.Tensor), f"Expected image tensor, got {type(img_tensor)}"
assert img_tensor.ndim in (3, 4), f"Expected 3D or 4D image tensor, got {img_tensor.ndim}D"
sampled = _sample_pixels(img_tensor)
if os.environ.get("UPDATE_GOLDEN"):
_GOLDEN_T2I_PATH.parent.mkdir(parents=True, exist_ok=True)
_GOLDEN_T2I_PATH.write_text(json.dumps({"pixels": sampled}, indent=2))
print(f"\nGolden file written to {_GOLDEN_T2I_PATH}")
elif _GOLDEN_T2I_PATH.exists():
golden = json.loads(_GOLDEN_T2I_PATH.read_text())["pixels"]
for i, (got, exp) in enumerate(zip(sampled, golden)):
assert abs(got - exp) < 1e-4, f"Pixel {i} mismatch: got {got}, expected {exp}"
found_image = True
assert found_image, "No image tensor found in pipeline output"
finally:
omni.close()
+89
View File
@@ -4,6 +4,7 @@ from queue import Empty, Queue
from typing import Any
import pytest
import torch
from pytest_mock import MockerFixture
from vllm_omni.entrypoints.stage_utils import SHUTDOWN_TASK
@@ -1340,3 +1341,91 @@ def test_close_sends_shutdown_signal(monkeypatch: pytest.MonkeyPatch, mocker: Mo
# Verify stop_stage_worker was called (process should be set)
assert omni.stage_list[0]._proc is not None
# Tests below are for diffusion dtype normalization fix from the following:
# https://github.com/vllm-project/vllm-omni/pull/1391
# In the future we should ensure dtypes are parsed in less hacky way and make
# these tests more atomic.
@pytest.mark.parametrize("dtype", ["float16", torch.float16])
def test_dtype_normalization_valid_types(
monkeypatch, dtype: str | torch.dtype, mocker: MockerFixture, fake_stage_config
):
"""Ensure Diffusion Config builder coerces valid types correctly."""
def _fake_loader(model: str, base_engine_args=None):
# Return not stage configs to fall back to the diffusion cfg builder
return []
import sys
for module_name in [
"vllm_omni.entrypoints.utils",
"vllm_omni.entrypoints.omni",
"vllm_omni.entrypoints.omni_stage",
]:
if module_name in sys.modules:
del sys.modules[module_name]
_setup_engine_mocks(monkeypatch, mocker)
_setup_multiprocessing_mocks(monkeypatch, mocker)
_setup_ipc_mocks(monkeypatch)
_setup_log_mocks(monkeypatch)
from vllm_omni.entrypoints.omni import Omni
monkeypatch.setattr(
"vllm_omni.entrypoints.utils.load_stage_configs_from_model",
_fake_loader,
raising=False,
)
omni = Omni(model="any", init_timeout=1, dtype=dtype)
# Dtype parsing being checked is on the diffusion path
assert len(omni.stage_configs) == 1
assert omni.stage_configs[0]["stage_type"] == "diffusion"
# Regardless of whether a str / dtype is passed, it resolves correctly
engine_args = omni.stage_configs[0]["engine_args"]
assert "dtype" in engine_args
assert isinstance(engine_args["dtype"], str)
assert engine_args["dtype"] == "float16"
def test_dtype_normalization_invalid_types(monkeypatch, mocker: MockerFixture, fake_stage_config):
"""Ensure Diffusion Config builder correctly handles bad dtype overrides."""
def _fake_loader(model: str, base_engine_args=None):
# Return not stage configs to fall back to the diffusion cfg builder
return []
class NotATorchDtype:
pass
import sys
for module_name in [
"vllm_omni.entrypoints.utils",
"vllm_omni.entrypoints.omni",
"vllm_omni.entrypoints.omni_stage",
]:
if module_name in sys.modules:
del sys.modules[module_name]
_setup_engine_mocks(monkeypatch, mocker)
_setup_multiprocessing_mocks(monkeypatch, mocker)
_setup_ipc_mocks(monkeypatch)
_setup_log_mocks(monkeypatch)
from vllm_omni.entrypoints.omni import Omni
monkeypatch.setattr(
"vllm_omni.entrypoints.utils.load_stage_configs_from_model",
_fake_loader,
raising=False,
)
# Raise TypeError if we get an unrecognized type
with pytest.raises(TypeError):
Omni(model="any", init_timeout=1, dtype=NotATorchDtype)
@@ -0,0 +1,249 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for CosyVoice3 components."""
import pytest
import torch
import torch.nn as nn
class TestPreLookaheadLayer:
"""Tests for PreLookaheadLayer."""
@pytest.fixture
def layer(self):
from vllm_omni.model_executor.models.cosyvoice3.code2wav_core.layers import PreLookaheadLayer
return PreLookaheadLayer(in_channels=512, channels=512, pre_lookahead_len=3)
def test_forward_shape(self, layer):
"""Test that output shape matches input shape."""
batch, seq_len, channels = 2, 10, 512
x = torch.randn(batch, seq_len, channels)
out = layer(x)
assert out.shape == x.shape
def test_forward_with_context(self, layer):
"""Test forward with context for streaming."""
batch, seq_len, channels = 1, 10, 512
x = torch.randn(batch, seq_len, channels)
context = torch.randn(batch, 3, channels) # pre_lookahead_len=3
layer.eval()
out = layer(x, context=context)
assert out.shape == x.shape
def test_residual_connection(self, layer):
"""Test that residual connection is applied."""
batch, seq_len, channels = 1, 5, 512
x = torch.zeros(batch, seq_len, channels)
# With zero input, output should also be close to zero due to residual
out = layer(x)
# Output should be close to input (residual) plus conv output
assert out.shape == x.shape
class TestDiTAttention:
"""Tests for DiTAttention with diffusion backend."""
@pytest.fixture
def attention(self):
from vllm_omni.diffusion.models.cosyvoice3_audio.cosyvoice3_dit import DiTAttention
return DiTAttention(dim=512, heads=8, dim_head=64, dropout=0.0)
def test_forward_shape(self, attention):
"""Test attention output shape."""
batch, seq_len, dim = 2, 16, 512
x = torch.randn(batch, seq_len, dim)
out = attention(x)
assert out.shape == x.shape
def test_forward_with_mask(self, attention):
"""Test attention with mask."""
batch, seq_len, dim = 2, 16, 512
x = torch.randn(batch, seq_len, dim)
mask = torch.ones(batch, seq_len, dtype=torch.bool)
mask[:, -3:] = False # Mask last 3 positions
out = attention(x, mask=mask)
assert out.shape == x.shape
# Masked positions should be zero
assert torch.allclose(out[:, -3:], torch.zeros_like(out[:, -3:]))
def test_qkv_projections(self, attention):
"""Test that Q/K/V projections exist and have correct dimensions."""
assert hasattr(attention, "to_q")
assert hasattr(attention, "to_k")
assert hasattr(attention, "to_v")
assert attention.to_q.out_features == 512 # heads * dim_head
assert attention.to_k.out_features == 512
assert attention.to_v.out_features == 512
class TestDiTBlock:
"""Tests for DiTBlock."""
@pytest.fixture
def block(self):
from vllm_omni.diffusion.models.cosyvoice3_audio.cosyvoice3_dit import DiTBlock
return DiTBlock(dim=512, heads=8, dim_head=64, ff_mult=4, dropout=0.0)
def test_forward_shape(self, block):
"""Test block output shape."""
batch, seq_len, dim = 2, 16, 512
x = torch.randn(batch, seq_len, dim)
t = torch.randn(batch, dim) # Timestep embedding
out = block(x, t)
assert out.shape == x.shape
def test_adalayernorm_modulation(self, block):
"""Test that AdaLayerNorm modulates based on timestep."""
batch, seq_len, dim = 1, 8, 512
x = torch.randn(batch, seq_len, dim)
t1 = torch.zeros(batch, dim)
t2 = torch.ones(batch, dim)
out1 = block(x, t1)
out2 = block(x, t2)
# Different timesteps should produce different outputs
assert not torch.allclose(out1, out2)
class TestDiT:
"""Tests for the full DiT model."""
@pytest.fixture
def dit(self):
from vllm_omni.diffusion.models.cosyvoice3_audio.cosyvoice3_dit import DiT
return DiT(
dim=256,
depth=2,
heads=4,
dim_head=64,
dropout=0.0,
ff_mult=2,
mel_dim=80,
mu_dim=80,
spk_dim=80,
long_skip_connection=True,
)
def test_forward_shape(self, dit):
"""Test DiT forward output shape."""
batch, mel_dim, seq_len = 1, 80, 32
x = torch.randn(batch, mel_dim, seq_len)
mask = torch.ones(batch, 1, seq_len)
mu = torch.randn(batch, mel_dim, seq_len)
t = torch.tensor([0.5])
spks = torch.randn(batch, 80)
cond = torch.randn(batch, mel_dim, seq_len)
out = dit(x, mask, mu, t, spks=spks, cond=cond)
assert out.shape == (batch, mel_dim, seq_len)
def test_timestep_embedding(self, dit):
"""Test that different timesteps produce different outputs."""
batch, mel_dim, seq_len = 1, 80, 16
x = torch.randn(batch, mel_dim, seq_len)
mask = torch.ones(batch, 1, seq_len)
mu = torch.randn(batch, mel_dim, seq_len)
spks = torch.randn(batch, 80)
cond = torch.randn(batch, mel_dim, seq_len)
out1 = dit(x, mask, mu, torch.tensor([0.0]), spks=spks, cond=cond)
out2 = dit(x, mask, mu, torch.tensor([1.0]), spks=spks, cond=cond)
assert not torch.allclose(out1, out2)
class TestCFM:
"""Tests for Conditional Flow Matching classes."""
@pytest.fixture
def dummy_estimator(self):
"""Create a dummy estimator for testing."""
class DummyEstimator(nn.Module):
def __init__(self, mel_dim=80):
super().__init__()
self.mel_dim = mel_dim
def forward(self, x, mask, mu, t, spks=None, cond=None):
return torch.zeros_like(x)
return DummyEstimator()
def test_causal_conditional_cfm_forward(self, dummy_estimator):
"""Test CausalConditionalCFM forward pass."""
from omegaconf import DictConfig
from vllm_omni.model_executor.models.cosyvoice3.code2wav_core.cfm import CausalConditionalCFM
cfm_params = DictConfig(
{
"sigma_min": 1e-6,
"solver": "euler",
"t_scheduler": "cosine",
"training_cfg_rate": 0.2,
"inference_cfg_rate": 0.7,
}
)
cfm = CausalConditionalCFM(
in_channels=80,
cfm_params=cfm_params,
n_spks=1,
spk_emb_dim=80,
estimator=dummy_estimator,
)
batch, mel_dim, seq_len = 1, 80, 32
mu = torch.randn(batch, mel_dim, seq_len)
mask = torch.ones(batch, 1, seq_len)
spks = torch.randn(batch, 80)
cond = torch.randn(batch, mel_dim, seq_len)
out, _ = cfm(mu, mask, n_timesteps=2, spks=spks, cond=cond)
assert out.shape == mu.shape
class TestSDPAFallback:
"""Test SDPA fallback for float32 inputs."""
def test_float32_uses_sdpa(self):
"""Test that float32 inputs use SDPA fallback."""
from vllm_omni.diffusion.attention.layer import Attention
attn = Attention(
num_heads=8,
head_size=64,
causal=False,
softmax_scale=1.0 / 8.0,
)
batch, seq_len, heads, dim = 1, 16, 8, 64
q = torch.randn(batch, seq_len, heads, dim, dtype=torch.float32)
k = torch.randn(batch, seq_len, heads, dim, dtype=torch.float32)
v = torch.randn(batch, seq_len, heads, dim, dtype=torch.float32)
# Should not raise error - SDPA fallback handles float32
out = attn(q, k, v)
assert out.shape == (batch, seq_len, heads, dim)
assert out.dtype == torch.float32
@@ -0,0 +1,230 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for CosyVoice3 utility functions."""
import pytest
import torch
class TestMakePadMask:
"""Tests for make_pad_mask utility."""
def test_basic_mask_creation(self):
"""Test basic padding mask creation."""
from vllm_omni.model_executor.models.cosyvoice3.utils import make_pad_mask
lengths = torch.tensor([5, 3, 2])
mask = make_pad_mask(lengths)
# Expected: [[F,F,F,F,F], [F,F,F,T,T], [F,F,T,T,T]]
expected = torch.tensor(
[
[False, False, False, False, False],
[False, False, False, True, True],
[False, False, True, True, True],
]
)
assert torch.equal(mask, expected)
def test_single_sequence(self):
"""Test mask for single sequence."""
from vllm_omni.model_executor.models.cosyvoice3.utils import make_pad_mask
lengths = torch.tensor([3])
mask = make_pad_mask(lengths)
expected = torch.tensor([[False, False, False]])
assert torch.equal(mask, expected)
def test_explicit_max_len(self):
"""Test with explicit max_len parameter."""
from vllm_omni.model_executor.models.cosyvoice3.utils import make_pad_mask
lengths = torch.tensor([2, 3])
mask = make_pad_mask(lengths, max_len=5)
expected = torch.tensor(
[
[False, False, True, True, True],
[False, False, False, True, True],
]
)
assert torch.equal(mask, expected)
def test_zero_max_len_uses_max_length(self):
"""Test that max_len=0 falls back to max(lengths)."""
from vllm_omni.model_executor.models.cosyvoice3.utils import make_pad_mask
lengths = torch.tensor([2, 4])
mask = make_pad_mask(lengths, max_len=0)
# Should use max(lengths) = 4
assert mask.shape == (2, 4)
def test_full_length_sequence(self):
"""Test sequence that fills the entire length (no padding)."""
from vllm_omni.model_executor.models.cosyvoice3.utils import make_pad_mask
lengths = torch.tensor([5])
mask = make_pad_mask(lengths, max_len=5)
# No positions should be masked
assert not mask.any()
def test_empty_sequence(self):
"""Test sequence with zero length (all padding)."""
from vllm_omni.model_executor.models.cosyvoice3.utils import make_pad_mask
lengths = torch.tensor([0])
mask = make_pad_mask(lengths, max_len=3)
# All positions should be masked
assert mask.all()
def test_device_preservation(self):
"""Test that mask is created on the same device as input."""
from vllm_omni.model_executor.models.cosyvoice3.utils import make_pad_mask
lengths = torch.tensor([3, 2])
mask = make_pad_mask(lengths)
assert mask.device == lengths.device
class TestDynamicRangeCompression:
"""Tests for dynamic_range_compression_torch utility."""
def test_basic_compression(self):
"""Test basic compression with default parameters."""
from vllm_omni.model_executor.models.cosyvoice3.utils import dynamic_range_compression_torch
x = torch.tensor([1.0, 10.0, 100.0])
result = dynamic_range_compression_torch(x)
# Result should be log(x * 1) = log(x)
expected = torch.log(x)
assert torch.allclose(result, expected)
def test_clipping_small_values(self):
"""Test that small values are clipped."""
from vllm_omni.model_executor.models.cosyvoice3.utils import dynamic_range_compression_torch
x = torch.tensor([0.0, 1e-10, 1e-6])
clip_val = 1e-5
result = dynamic_range_compression_torch(x, clip_val=clip_val)
# All values below clip_val should be clipped
expected = torch.log(torch.tensor([clip_val, clip_val, clip_val]))
assert torch.allclose(result, expected)
def test_scaling_factor(self):
"""Test with different scaling factor c."""
from vllm_omni.model_executor.models.cosyvoice3.utils import dynamic_range_compression_torch
x = torch.tensor([1.0, 10.0])
c = 2.0
result = dynamic_range_compression_torch(x, c=c)
expected = torch.log(x * c)
assert torch.allclose(result, expected)
class TestSpectralNormalize:
"""Tests for spectral_normalize_torch utility."""
def test_is_wrapper_for_compression(self):
"""Test that spectral_normalize is a wrapper for dynamic_range_compression."""
from vllm_omni.model_executor.models.cosyvoice3.utils import (
dynamic_range_compression_torch,
spectral_normalize_torch,
)
magnitudes = torch.tensor([1.0, 10.0, 100.0])
result = spectral_normalize_torch(magnitudes)
expected = dynamic_range_compression_torch(magnitudes)
assert torch.allclose(result, expected)
class TestExactDiv:
"""Tests for exact_div utility."""
def test_exact_division(self):
"""Test exact division with valid inputs."""
from vllm_omni.model_executor.models.cosyvoice3.utils import exact_div
assert exact_div(10, 2) == 5
assert exact_div(100, 25) == 4
assert exact_div(0, 5) == 0
def test_non_exact_division_raises(self):
"""Test that non-exact division raises AssertionError."""
from vllm_omni.model_executor.models.cosyvoice3.utils import exact_div
with pytest.raises(AssertionError):
exact_div(10, 3)
with pytest.raises(AssertionError):
exact_div(7, 2)
class TestConcatTextWithPromptIds:
"""Tests for concat_text_with_prompt_ids utility."""
def test_basic_concat(self):
"""Test basic concatenation."""
from vllm_omni.model_executor.models.cosyvoice3.utils import concat_text_with_prompt_ids
text = torch.tensor([[5, 6, 7]], dtype=torch.int64)
text_len = torch.tensor([3], dtype=torch.int32)
prompt_text = torch.tensor([[1, 2]], dtype=torch.int64)
prompt_text_len = torch.tensor([2], dtype=torch.int32)
result, result_len = concat_text_with_prompt_ids(text, text_len, prompt_text, prompt_text_len)
assert result.tolist() == [[1, 2, 5, 6, 7]]
assert result_len.item() == 5
def test_empty_prompt(self):
"""Test with empty prompt."""
from vllm_omni.model_executor.models.cosyvoice3.utils import concat_text_with_prompt_ids
text = torch.tensor([[1, 2, 3]], dtype=torch.int64)
text_len = torch.tensor([3], dtype=torch.int32)
prompt_text = torch.tensor([[]], dtype=torch.int64).reshape(1, 0)
prompt_text_len = torch.tensor([0], dtype=torch.int32)
result, result_len = concat_text_with_prompt_ids(text, text_len, prompt_text, prompt_text_len)
assert result.tolist() == [[1, 2, 3]]
assert result_len.item() == 3
def test_batch_concat(self):
"""Test batched concatenation."""
from vllm_omni.model_executor.models.cosyvoice3.utils import concat_text_with_prompt_ids
text = torch.tensor([[5, 6], [7, 8]], dtype=torch.int64)
text_len = torch.tensor([2, 2], dtype=torch.int32)
prompt_text = torch.tensor([[1, 2], [3, 4]], dtype=torch.int64)
prompt_text_len = torch.tensor([2, 2], dtype=torch.int32)
result, result_len = concat_text_with_prompt_ids(text, text_len, prompt_text, prompt_text_len)
assert result.tolist() == [[1, 2, 5, 6], [3, 4, 7, 8]]
assert result_len.tolist() == [4, 4]
def test_prompt_comes_first(self):
"""Test that prompt tokens come before text tokens."""
from vllm_omni.model_executor.models.cosyvoice3.utils import concat_text_with_prompt_ids
text = torch.tensor([[100, 200]], dtype=torch.int64)
text_len = torch.tensor([2], dtype=torch.int32)
prompt_text = torch.tensor([[1, 2, 3]], dtype=torch.int64)
prompt_text_len = torch.tensor([3], dtype=torch.int32)
result, _ = concat_text_with_prompt_ids(text, text_len, prompt_text, prompt_text_len)
# First 3 tokens should be prompt
assert result[0, :3].tolist() == [1, 2, 3]
# Last 2 tokens should be text
assert result[0, 3:].tolist() == [100, 200]
+4
View File
@@ -188,6 +188,10 @@ def benchmark_params(request, omni_server):
if param_index >= len(all_params):
raise ValueError(f"No benchmark parameters found for index {param_index} in test: {test_name}")
if all_params[param_index]["dataset_name"] == "random-mm":
# TODO: Due to known issues, skip the random-mm dataset.
pytest.skip("Skipping parameter for random-mm dataset.")
current = param_index + 1
total = len(all_params)
print(f"\n Running benchmark {current}/{total} for {test_name}")
+4 -4
View File
@@ -18,8 +18,8 @@
4,
10
],
"random_input_len": 2500,
"random_output_len": 900,
"random_input_len": 100,
"random_output_len": 100,
"ignore_eos": true,
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration",
"baseline": {
@@ -102,8 +102,8 @@
4,
10
],
"random_input_len": 2500,
"random_output_len": 900,
"random_input_len": 100,
"random_output_len": 100,
"ignore_eos": true,
"percentile-metrics": "ttft,tpot,itl,e2el,audio_rtf,audio_ttfp,audio_duration",
"baseline": {