Merge branch 'main' into feat/moss-tts-nano
Signed-off-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
611 files changed
+48775
-14783
No files matched your search
@@ -12,6 +12,12 @@ Architecture:
|
||||
processing
|
||||
"""
|
||||
|
||||
# We import version early, because it will warn if vLLM / vLLM Omni
|
||||
# are not using the same major + minor version (if vLLM is installed).
|
||||
# We should do this before applying patch, because vLLM imports might
|
||||
# throw in patch if the versions differ.
|
||||
from .version import __version__, __version_tuple__ # isort:skip # noqa: F401
|
||||
|
||||
try:
|
||||
from . import patch # noqa: F401
|
||||
except ModuleNotFoundError as exc: # pragma: no cover - optional dependency
|
||||
@@ -25,8 +31,6 @@ from vllm_omni.transformers_utils import configs as _configs # noqa: F401, E402
|
||||
|
||||
from .config import OmniModelConfig
|
||||
|
||||
from .version import __version__, __version_tuple__ # isort:skip
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
# Lazy import for AsyncOmni and Omni to avoid pulling in heavy
|
||||
|
||||
@@ -0,0 +1,887 @@
|
||||
"""Daily-Omni Dataset loader for benchmark.
|
||||
|
||||
Daily-Omni is an audio-visual reasoning benchmark with 684 videos
|
||||
and 1,197 multiple-choice QA pairs across 6 major task types.
|
||||
|
||||
Dataset source: https://huggingface.co/datasets/liarliar/Daily-Omni
|
||||
|
||||
Supports loading QA metadata from:
|
||||
- Local JSON file (``qa_json_path``): recommended for offline/air-gapped environments
|
||||
- HuggingFace datasets (``dataset_path``): legacy online mode
|
||||
|
||||
The videos must be separately downloaded and extracted from Videos.tar.
|
||||
|
||||
Why ``BenchmarkDataset`` instead of ``HuggingFaceDataset``?
|
||||
vLLM's ``HuggingFaceDataset`` is a thin wrapper whose ``__init__`` always ends by calling
|
||||
``load_data()`` → ``datasets.load_dataset(...)`` with a required Hub id and split. That
|
||||
contract fits "Hub-only" benches, but Daily-Omni also needs **offline QA metadata** from a
|
||||
local ``qa.json`` without touching the network. Subclassing ``HuggingFaceDataset`` would
|
||||
mean fighting the parent constructor (fake ``dataset_path``, reordering ``load_data``, or
|
||||
duplicating half the parent) and would still imply ``datasets`` is always relevant.
|
||||
|
||||
This class therefore inherits only ``BenchmarkDataset`` (minimal: ``dataset_path``,
|
||||
``random_seed``, ``self.data``) and implements **two explicit loaders**:
|
||||
``_load_from_local_json`` (default path for air-gapped runs) and ``_load_from_huggingface``
|
||||
(optional legacy path for users who prefer ``datasets`` + Hub cache). The latter is **not**
|
||||
inheritance; it is the same Hub rows as before, factored into a helper so one class can
|
||||
serve both deployment modes without mandatory ``datasets`` when using ``qa_json_path``.
|
||||
|
||||
Usage:
|
||||
from vllm_omni.benchmarks.data_modules.daily_omni_dataset import DailyOmniDataset
|
||||
|
||||
# Local JSON mode (recommended)
|
||||
dataset = DailyOmniDataset(
|
||||
qa_json_path="/path/to/qa.json",
|
||||
video_dir="/path/to/Videos",
|
||||
random_seed=42,
|
||||
)
|
||||
|
||||
# HuggingFace mode (legacy, requires network)
|
||||
dataset = DailyOmniDataset(
|
||||
dataset_path="liarliar/Daily-Omni",
|
||||
dataset_split="train",
|
||||
random_seed=42,
|
||||
)
|
||||
requests = dataset.sample(
|
||||
tokenizer=tokenizer,
|
||||
num_requests=100,
|
||||
output_len=256,
|
||||
)
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
|
||||
try:
|
||||
from vllm.benchmarks.datasets import BenchmarkDataset, SampleRequest
|
||||
except ImportError:
|
||||
# Fallback: if BenchmarkDataset not available, use base class from same module
|
||||
from vllm.benchmarks.datasets import HuggingFaceDataset as BenchmarkDataset
|
||||
from vllm.benchmarks.datasets import SampleRequest
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
from vllm.tokenizers.hf import get_cached_tokenizer
|
||||
|
||||
try:
|
||||
from datasets import load_dataset
|
||||
except ImportError:
|
||||
load_dataset = None
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _ListDatasetIterator:
|
||||
"""Simple iterator wrapper around a list to mimic HuggingFace streaming dataset behavior."""
|
||||
|
||||
def __init__(self, data: list[dict[str, Any]]) -> None:
|
||||
self._data = data
|
||||
self._index = 0
|
||||
|
||||
def __iter__(self):
|
||||
self._index = 0
|
||||
return self
|
||||
|
||||
def __next__(self) -> dict[str, Any]:
|
||||
if self._index >= len(self._data):
|
||||
raise StopIteration
|
||||
item = self._data[self._index]
|
||||
self._index += 1
|
||||
return item
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self._data)
|
||||
|
||||
def __getitem__(self, idx: int | slice) -> dict[str, Any] | list[dict[str, Any]]:
|
||||
return self._data[idx]
|
||||
|
||||
|
||||
# Aligns with Lliar-liar/Daily-Omni CLI ``--input_mode`` (test_model/*/testmodel.py).
|
||||
DailyOmniInputMode = Literal["all", "visual", "audio"]
|
||||
|
||||
# ``build_conversation()`` in Daily-Omni ``test_model/Qwen2.5-Omni/testmodel.py`` (verbatim).
|
||||
DAILY_OMNI_SYSTEM_TEXT = (
|
||||
"You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, "
|
||||
"capable of perceiving auditory and visual inputs, as well as generating text and speech."
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DailyOmniSampleRequest(SampleRequest):
|
||||
"""``SampleRequest`` with Daily-Omni gold labels for post-run accuracy scoring."""
|
||||
|
||||
daily_omni_gold_answer: str = ""
|
||||
daily_omni_video_id: str = ""
|
||||
daily_omni_task_type: str = ""
|
||||
#: Official qa.json ``video_duration`` (e.g. ``30s``, ``60s``) for leaderboard-style breakdown.
|
||||
daily_omni_video_duration: str = ""
|
||||
#: Official ``video_category`` (YouTube-style category string) for per-category accuracy.
|
||||
daily_omni_video_category: str = ""
|
||||
#: Extra JSON fields merged into chat-completions ``extra_body`` (e.g. ``mm_processor_kwargs``).
|
||||
omni_extra_body: dict[str, Any] | None = None
|
||||
#: Full OpenAI ``messages`` (system + user) mirroring upstream Daily-Omni conversation.
|
||||
omni_chat_messages: list[dict[str, Any]] | None = None
|
||||
#: Used only when ``omni_chat_messages`` is None (non-Daily-Omni-style requests).
|
||||
omni_chat_mm_position: Literal["first", "last"] = "last"
|
||||
|
||||
|
||||
class DailyOmniDataset(BenchmarkDataset):
|
||||
"""Daily-Omni audio-visual QA dataset for benchmarking.
|
||||
|
||||
Inherits ``BenchmarkDataset`` only (not ``HuggingFaceDataset``): see module docstring for why
|
||||
Hub loading lives in ``_load_from_huggingface`` instead of subclassing the HF base class.
|
||||
|
||||
The dataset includes:
|
||||
- 684 videos from daily life scenarios (available in Videos.tar)
|
||||
- 1,197 multiple-choice QA pairs in qa.json
|
||||
- 6 major task categories
|
||||
|
||||
QA metadata can be loaded from:
|
||||
- Local JSON file (``qa_json_path``): recommended for offline/air-gapped environments
|
||||
- HuggingFace datasets (``dataset_path``): legacy online mode
|
||||
|
||||
The videos must be separately downloaded and extracted from Videos.tar.
|
||||
|
||||
Args:
|
||||
qa_json_path: Path to local qa.json file (offline mode, preferred). When provided,
|
||||
``dataset_path`` and ``dataset_split`` are ignored.
|
||||
dataset_path: HuggingFace dataset path (e.g., "liarliar/Daily-Omni"). Used only if
|
||||
``qa_json_path`` is not provided (legacy online mode).
|
||||
dataset_split: Dataset split to use (default: "train"). Used only in online mode.
|
||||
random_seed: Random seed for shuffling
|
||||
video_dir: Directory containing extracted video files (default: None)
|
||||
input_mode: Which modalities to send, matching upstream Daily-Omni ``--input_mode``:
|
||||
``all`` — video + WAV (default; official audio-visual protocol);
|
||||
``visual`` — video only;
|
||||
``audio`` — extracted WAV only (requires ``{video_id}/{video_id}_audio.wav`` under ``video_dir``).
|
||||
max_duration_seconds: Reserved for future ffprobe-based filtering; currently **not applied**
|
||||
when building requests (metadata ``video_duration`` is still passed through for eval).
|
||||
dataset_subset: Optional HuggingFace subset name (``load_dataset(..., name=...)``); used by bench
|
||||
``--hf-subset`` / patch.
|
||||
no_stream: If True, load the Hub split non-streaming (matches bench ``--no-stream``).
|
||||
inline_local_video: If True, embed local MP4 as ``data:video/mp4;base64,...`` in requests so
|
||||
the API server does not need ``--allowed-local-media-path`` (large JSON; use for small runs).
|
||||
When ``input_mode`` is ``audio`` or ``all``, local WAV is embedded the same way
|
||||
(``data:audio/wav;base64,...``).
|
||||
trust_remote_code: Whether to trust remote code when loading HuggingFace dataset
|
||||
(online mode only).
|
||||
"""
|
||||
|
||||
SUPPORTED_DATASET_PATHS: set[str] = {
|
||||
"liarliar/Daily-Omni",
|
||||
}
|
||||
#: Default Hub id for synthetic video URLs when ``qa_json_path`` is used (``dataset_path`` None).
|
||||
DEFAULT_HF_DATASET_ID = "liarliar/Daily-Omni"
|
||||
IS_MULTIMODAL = True
|
||||
DEFAULT_OUTPUT_LEN = 256
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
qa_json_path: str | None = None,
|
||||
dataset_path: str | None = None,
|
||||
dataset_split: str = "train",
|
||||
random_seed: int = 0,
|
||||
video_dir: str | None = None,
|
||||
input_mode: DailyOmniInputMode = "all",
|
||||
inline_local_video: bool = False,
|
||||
trust_remote_code: bool = False,
|
||||
max_duration_seconds: float | None = None,
|
||||
dataset_subset: str | None = None,
|
||||
no_stream: bool = False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
if input_mode not in ("all", "visual", "audio"):
|
||||
raise ValueError(f"input_mode must be 'all', 'visual', or 'audio', got {input_mode!r}")
|
||||
|
||||
# Validate arguments: need either local JSON or HF path
|
||||
if qa_json_path is None and dataset_path is None:
|
||||
raise ValueError(
|
||||
"Either 'qa_json_path' (local JSON) or 'dataset_path' (HuggingFace) must be provided. "
|
||||
"For offline/air-gapped environments, download qa.json and use qa_json_path."
|
||||
)
|
||||
|
||||
# Store configuration
|
||||
self.qa_json_path = Path(qa_json_path) if qa_json_path else None
|
||||
self.dataset_path = dataset_path
|
||||
self.dataset_split = dataset_split
|
||||
self.dataset_subset = dataset_subset
|
||||
#: Match vLLM ``HuggingFaceDataset`` / bench CLI ``--no-stream``.
|
||||
self._hf_streaming = not no_stream
|
||||
self.video_dir = Path(video_dir) if video_dir else None
|
||||
self.inline_local_video = inline_local_video
|
||||
self.input_mode: DailyOmniInputMode = input_mode
|
||||
self.max_duration_seconds = max_duration_seconds
|
||||
self.trust_remote_code = trust_remote_code
|
||||
|
||||
#: In-process cache of ffprobe durations only (no disk persistence).
|
||||
self._video_durations: dict[str, float] = {}
|
||||
|
||||
# Initialize parent BenchmarkDataset
|
||||
super().__init__(
|
||||
dataset_path=dataset_path if qa_json_path is None else None,
|
||||
random_seed=random_seed,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
# Load data based on mode
|
||||
self.load_data()
|
||||
|
||||
# Verify dataset info
|
||||
logger.info(
|
||||
"Loaded Daily-Omni dataset: mode=%s, source=%s, random_seed=%d, input_mode=%s, max_duration=%s",
|
||||
"local_json" if self.qa_json_path else "huggingface",
|
||||
str(self.qa_json_path) if self.qa_json_path else f"{dataset_path}/{dataset_split}",
|
||||
random_seed,
|
||||
input_mode,
|
||||
f"{max_duration_seconds}s" if max_duration_seconds else "unlimited",
|
||||
)
|
||||
|
||||
def load_data(self) -> None:
|
||||
"""Populate ``self.data`` from either local JSON or the Hub.
|
||||
|
||||
See module docstring: we do not subclass ``HuggingFaceDataset`` because Daily-Omni needs
|
||||
a first-class offline path; Hub loading is an optional branch implemented below.
|
||||
"""
|
||||
if self.qa_json_path is not None:
|
||||
self._load_from_local_json()
|
||||
else:
|
||||
self._load_from_huggingface()
|
||||
|
||||
def _load_from_local_json(self) -> None:
|
||||
"""Load QA data from local JSON file."""
|
||||
if not self.qa_json_path.exists():
|
||||
raise FileNotFoundError(f"QA JSON file not found: {self.qa_json_path}")
|
||||
|
||||
with open(self.qa_json_path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Support both list format and dict with "train"/"test" splits
|
||||
if isinstance(data, dict):
|
||||
# Try to get the requested split, fallback to first available
|
||||
split_data = data.get(self.dataset_split)
|
||||
if split_data is None:
|
||||
available = list(data.keys())
|
||||
if available:
|
||||
logger.warning(
|
||||
"Split '%s' not found in %s, using '%s' instead",
|
||||
self.dataset_split,
|
||||
self.qa_json_path,
|
||||
available[0],
|
||||
)
|
||||
split_data = data[available[0]]
|
||||
else:
|
||||
split_data = []
|
||||
data = split_data
|
||||
|
||||
if not isinstance(data, list):
|
||||
raise ValueError(f"Expected list of QA items in JSON, got {type(data).__name__}")
|
||||
|
||||
# Shuffle if requested
|
||||
if not getattr(self, "disable_shuffle", False) and self.random_seed is not None:
|
||||
import random
|
||||
|
||||
rng = random.Random(self.random_seed)
|
||||
shuffled = data[:]
|
||||
rng.shuffle(shuffled)
|
||||
data = shuffled
|
||||
|
||||
# Create an iterator-like wrapper for compatibility
|
||||
self.data = _ListDatasetIterator(data)
|
||||
|
||||
def _load_from_huggingface(self) -> None:
|
||||
"""Load QA rows via ``datasets.load_dataset`` (legacy / convenience path).
|
||||
|
||||
Kept for backward compatibility: callers can still pass ``dataset_path=liarliar/Daily-Omni``
|
||||
and get the same parquet-backed rows as the Hub dataset card, with streaming (or
|
||||
non-streaming if ``no_stream=True``) and shuffle.
|
||||
|
||||
This is intentionally **not** implemented by subclassing ``HuggingFaceDataset``: that base
|
||||
always runs Hub ``load_dataset`` from its constructor and expects a Hub id as the primary
|
||||
API; Daily-Omni instead chooses the source in ``load_data()`` (JSON vs Hub) while sharing
|
||||
one ``sample()`` / request-building implementation for both.
|
||||
"""
|
||||
if load_dataset is None:
|
||||
raise ImportError(
|
||||
"datasets library is required for HuggingFace mode. "
|
||||
"Install with: pip install datasets, or use local JSON mode instead."
|
||||
)
|
||||
|
||||
ds = load_dataset(
|
||||
self.dataset_path,
|
||||
name=self.dataset_subset,
|
||||
split=self.dataset_split,
|
||||
streaming=self._hf_streaming,
|
||||
trust_remote_code=self.trust_remote_code,
|
||||
)
|
||||
if not getattr(self, "disable_shuffle", False):
|
||||
ds = ds.shuffle(seed=self.random_seed)
|
||||
self.data = ds
|
||||
|
||||
def get_task_statistics(self) -> dict[str, int]:
|
||||
"""Get distribution of task types in the dataset.
|
||||
|
||||
Returns:
|
||||
Dict mapping task type to count
|
||||
"""
|
||||
stats: dict[str, int] = {}
|
||||
for item in self.data:
|
||||
row = self._coerce_row(item)
|
||||
fields = self._normalize_qa_fields(row)
|
||||
task_type = fields["task_type"] or "unknown"
|
||||
stats[task_type] = stats.get(task_type, 0) + 1
|
||||
return stats
|
||||
|
||||
@staticmethod
|
||||
def _coerce_row(item: Any) -> dict[str, Any]:
|
||||
"""Turn a dataset row into a plain dict (Arrow / Mapping)."""
|
||||
if isinstance(item, dict):
|
||||
return item
|
||||
if hasattr(item, "as_py"):
|
||||
return dict(item.as_py()) # pyarrow Row
|
||||
try:
|
||||
return dict(item)
|
||||
except (TypeError, ValueError):
|
||||
return {k: item[k] for k in item} # type: ignore[misc]
|
||||
|
||||
@staticmethod
|
||||
def _normalize_qa_fields(row: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Map official Daily-Omni qa.json / Hub schema to internal fields.
|
||||
|
||||
Official fields (see liarliar/Daily-Omni ``qa.json``): ``Question``, ``Choice`` (list),
|
||||
``Answer``, ``video_id``, ``Type``, ``video_duration`` (``30s`` / ``60s``), ``video_category``,
|
||||
plus other category columns. Legacy aliases (lowercase / older loaders) are still accepted.
|
||||
"""
|
||||
out: dict[str, Any] = {}
|
||||
|
||||
out["question"] = str(row.get("Question") or row.get("question") or "").strip()
|
||||
vid = row.get("video_id") if row.get("video_id") is not None else row.get("video")
|
||||
out["video_id"] = str(vid).strip() if vid is not None else ""
|
||||
out["task_type"] = str(row.get("Type") or row.get("task_type") or row.get("type") or "").strip()
|
||||
vc = row.get("video_category") if row.get("video_category") is not None else row.get("videoCategory")
|
||||
out["video_category"] = str(vc).strip() if vc is not None else ""
|
||||
vd = row.get("video_duration") if row.get("video_duration") is not None else row.get("videoDuration")
|
||||
out["video_duration"] = str(vd).strip() if vd is not None else ""
|
||||
out["answer"] = str(row.get("Answer") or row.get("answer") or "").strip()
|
||||
vu = row.get("video_url") if row.get("video_url") is not None else row.get("Video_URL")
|
||||
out["video_url"] = str(vu).strip() if vu is not None and str(vu).strip() else None
|
||||
|
||||
choice = row.get("Choice")
|
||||
if choice is None:
|
||||
choice = row.get("options") or row.get("choice")
|
||||
out["choice"] = choice
|
||||
|
||||
return out
|
||||
|
||||
def sample(
|
||||
self,
|
||||
tokenizer: TokenizerLike,
|
||||
num_requests: int,
|
||||
output_len: int | None = None,
|
||||
request_id_prefix: str = "",
|
||||
no_oversample: bool = False,
|
||||
**kwargs,
|
||||
) -> list[SampleRequest]:
|
||||
"""Sample requests from Daily-Omni dataset.
|
||||
|
||||
Args:
|
||||
tokenizer: Tokenizer for computing prompt length
|
||||
num_requests: Number of requests to sample
|
||||
output_len: Target output length in tokens (default: 256)
|
||||
request_id_prefix: Prefix for request IDs
|
||||
no_oversample: If True, do not oversample if fewer examples available
|
||||
**kwargs: Additional arguments (ignored)
|
||||
|
||||
Returns:
|
||||
List of SampleRequest objects with video URLs and prompts
|
||||
"""
|
||||
if output_len is None:
|
||||
output_len = self.DEFAULT_OUTPUT_LEN
|
||||
|
||||
sampled_requests: list[SampleRequest] = []
|
||||
ind = 0
|
||||
cached_tokenizer = get_cached_tokenizer(tokenizer)
|
||||
|
||||
# Iterate over shuffled dataset
|
||||
for item in self.data:
|
||||
if len(sampled_requests) >= num_requests:
|
||||
break
|
||||
|
||||
request = self._create_sample_request(
|
||||
self._coerce_row(item), cached_tokenizer, output_len, request_id_prefix, ind
|
||||
)
|
||||
if request:
|
||||
sampled_requests.append(request)
|
||||
ind += 1
|
||||
|
||||
logger.info("Created %d sample requests from Daily-Omni dataset", len(sampled_requests))
|
||||
|
||||
# Handle oversampling if needed
|
||||
self.maybe_oversample_requests(sampled_requests, num_requests, request_id_prefix, no_oversample)
|
||||
|
||||
return sampled_requests
|
||||
|
||||
def _create_sample_request(
|
||||
self,
|
||||
qa_item: dict[str, Any],
|
||||
tokenizer: TokenizerLike,
|
||||
output_len: int,
|
||||
request_id_prefix: str,
|
||||
index: int,
|
||||
) -> SampleRequest | None:
|
||||
"""Create a SampleRequest from a QA item.
|
||||
|
||||
Args:
|
||||
qa_item: QA pair from the dataset
|
||||
tokenizer: Tokenizer
|
||||
output_len: Target output length
|
||||
request_id_prefix: Prefix for request ID
|
||||
index: Request index
|
||||
|
||||
Returns:
|
||||
SampleRequest or None if invalid
|
||||
"""
|
||||
fields = self._normalize_qa_fields(qa_item)
|
||||
video_id = fields["video_id"]
|
||||
question = fields["question"]
|
||||
choice = fields["choice"]
|
||||
task_type = fields["task_type"]
|
||||
video_url = fields["video_url"]
|
||||
video_duration = fields.get("video_duration") or ""
|
||||
video_category = fields.get("video_category") or ""
|
||||
|
||||
if not video_id and not video_url:
|
||||
logger.warning("Skipping item: no video_id / video_url")
|
||||
return None
|
||||
|
||||
if not question:
|
||||
logger.warning("Skipping item: no question found")
|
||||
return None
|
||||
|
||||
# Official layout after extracting Videos.tar (see Lliar-liar/Daily-Omni test_model):
|
||||
# {video_base_dir}/{video_id}/{video_id}_video.mp4
|
||||
mm_payload, omni_extra, mm_pos = self._compose_daily_omni_multimodal(video_id, video_url)
|
||||
if not mm_payload:
|
||||
return None
|
||||
|
||||
messages = self._build_daily_omni_openai_messages(mm_payload, question, choice)
|
||||
user_text = self._official_daily_omni_user_prompt(question, choice)
|
||||
# Text-only length estimate (same as before: no MM token count in bench).
|
||||
prompt_len = len(tokenizer.encode(f"{DAILY_OMNI_SYSTEM_TEXT}\n{user_text}"))
|
||||
|
||||
return DailyOmniSampleRequest(
|
||||
prompt=user_text,
|
||||
prompt_len=prompt_len,
|
||||
expected_output_len=output_len,
|
||||
multi_modal_data=None,
|
||||
request_id=f"{request_id_prefix}{index}",
|
||||
daily_omni_gold_answer=fields["answer"],
|
||||
daily_omni_video_id=video_id,
|
||||
daily_omni_task_type=task_type,
|
||||
daily_omni_video_duration=video_duration,
|
||||
daily_omni_video_category=video_category,
|
||||
omni_extra_body=omni_extra,
|
||||
omni_chat_messages=messages,
|
||||
omni_chat_mm_position=mm_pos,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _official_video_relpath(video_id: str) -> str:
|
||||
"""Relative path inside extracted ``Videos/`` per upstream Daily-Omni scripts."""
|
||||
return f"{video_id}/{video_id}_video.mp4"
|
||||
|
||||
@staticmethod
|
||||
def _official_audio_relpath(video_id: str) -> str:
|
||||
"""Relative path for extracted WAV per upstream ``get_audio_path``."""
|
||||
return f"{video_id}/{video_id}_audio.wav"
|
||||
|
||||
def _resolve_local_video_path(self, video_id: str) -> Path | None:
|
||||
"""Pick an existing file under ``video_dir`` (official layout + flat fallback)."""
|
||||
if not self.video_dir or not video_id:
|
||||
return None
|
||||
|
||||
candidates = [
|
||||
self.video_dir / self._official_video_relpath(video_id),
|
||||
self.video_dir / f"{video_id}.mp4", # flat layout (custom mirrors / outdated docs)
|
||||
]
|
||||
seen: set[Path] = set()
|
||||
for p in candidates:
|
||||
rp = p.resolve()
|
||||
if rp in seen:
|
||||
continue
|
||||
seen.add(rp)
|
||||
if p.exists():
|
||||
return p
|
||||
return None
|
||||
|
||||
def _resolve_local_audio_path(self, video_id: str) -> Path | None:
|
||||
"""Pick an existing WAV under ``video_dir`` (official layout + flat fallback)."""
|
||||
if not self.video_dir or not video_id:
|
||||
return None
|
||||
candidates = [
|
||||
self.video_dir / self._official_audio_relpath(video_id),
|
||||
self.video_dir / f"{video_id}.wav",
|
||||
]
|
||||
seen: set[Path] = set()
|
||||
for p in candidates:
|
||||
rp = p.resolve()
|
||||
if rp in seen:
|
||||
continue
|
||||
seen.add(rp)
|
||||
if p.exists():
|
||||
return p
|
||||
return None
|
||||
|
||||
def _local_file_to_video_url_payload(self, video_path: Path) -> dict[str, Any]:
|
||||
"""Build OpenAI-style video_url part for a resolved local file.
|
||||
|
||||
vLLM rejects ``file://`` unless the server was started with
|
||||
``--allowed-local-media-path`` set to a directory that **contains** the file
|
||||
(typically the extracted ``Videos`` root). Use ``inline_local_video=True`` to
|
||||
send base64 data URLs instead (no server path allowlist; larger requests).
|
||||
"""
|
||||
path = video_path.expanduser().resolve()
|
||||
if self.inline_local_video:
|
||||
raw = path.read_bytes()
|
||||
b64 = base64.b64encode(raw).decode("ascii")
|
||||
return {
|
||||
"type": "video_url",
|
||||
"video_url": {"url": f"data:video/mp4;base64,{b64}"},
|
||||
}
|
||||
return {
|
||||
"type": "video_url",
|
||||
"video_url": {"url": path.as_uri()},
|
||||
}
|
||||
|
||||
def _local_file_to_audio_url_payload(self, audio_path: Path) -> dict[str, Any]:
|
||||
"""Build OpenAI-style ``audio_url`` part for a resolved local WAV file."""
|
||||
path = audio_path.expanduser().resolve()
|
||||
if self.inline_local_video:
|
||||
raw = path.read_bytes()
|
||||
b64 = base64.b64encode(raw).decode("ascii")
|
||||
return {
|
||||
"type": "audio_url",
|
||||
"audio_url": {"url": f"data:audio/wav;base64,{b64}"},
|
||||
}
|
||||
return {
|
||||
"type": "audio_url",
|
||||
"audio_url": {"url": path.as_uri()},
|
||||
}
|
||||
|
||||
def _get_video_content(
|
||||
self,
|
||||
video_id: str,
|
||||
video_url: str | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Resolve video for OpenAI-style ``video_url`` content.
|
||||
|
||||
Upstream uses ``get_video_path(video_id, base) -> base/video_id/video_id_video.mp4``.
|
||||
The Hub repo only publishes ``Videos.tar``; use ``--daily-omni-video-dir`` pointing
|
||||
at the extracted ``Videos`` folder (parent of per-``video_id`` subdirs).
|
||||
|
||||
For ``file://`` URLs, start ``vllm serve`` with e.g.
|
||||
``--allowed-local-media-path /same/path/as/daily-omni-video-dir``.
|
||||
"""
|
||||
if video_url:
|
||||
url = video_url
|
||||
if not url.startswith(("http://", "https://", "file://")):
|
||||
url = f"https://{url.lstrip('/')}"
|
||||
return {"type": "video_url", "video_url": {"url": url}}
|
||||
|
||||
if self.video_dir and video_id:
|
||||
video_path = self._resolve_local_video_path(video_id)
|
||||
if video_path is not None:
|
||||
return self._local_file_to_video_url_payload(video_path)
|
||||
logger.warning(
|
||||
"Video not found under video_dir=%s for video_id=%r (expected %s or %s)",
|
||||
self.video_dir,
|
||||
video_id,
|
||||
self._official_video_relpath(video_id),
|
||||
f"{video_id}.mp4",
|
||||
)
|
||||
|
||||
if video_id:
|
||||
repo = self.dataset_path or self.DEFAULT_HF_DATASET_ID
|
||||
rel = self._official_video_relpath(video_id)
|
||||
hf_video_url = f"https://huggingface.co/datasets/{repo}/resolve/main/Videos/{rel}"
|
||||
logger.debug(
|
||||
"Using HF video URL (likely 404 — Hub ships Videos.tar only): %s",
|
||||
hf_video_url,
|
||||
)
|
||||
return {"type": "video_url", "video_url": {"url": hf_video_url}}
|
||||
|
||||
logger.error("Could not determine video source for video_id=%r", video_id)
|
||||
return None
|
||||
|
||||
def _get_audio_content(self, video_id: str) -> dict[str, Any] | None:
|
||||
"""Resolve extracted WAV for OpenAI-style ``audio_url`` (local files only)."""
|
||||
if not self.video_dir or not video_id:
|
||||
logger.warning(
|
||||
"Daily-Omni input_mode %r requires --daily-omni-video-dir with %s",
|
||||
self.input_mode,
|
||||
self._official_audio_relpath(video_id),
|
||||
)
|
||||
return None
|
||||
audio_path = self._resolve_local_audio_path(video_id)
|
||||
if audio_path is not None:
|
||||
return self._local_file_to_audio_url_payload(audio_path)
|
||||
logger.warning(
|
||||
"Audio not found under video_dir=%s for video_id=%r (expected %s or %s)",
|
||||
self.video_dir,
|
||||
video_id,
|
||||
self._official_audio_relpath(video_id),
|
||||
f"{video_id}.wav",
|
||||
)
|
||||
return None
|
||||
|
||||
def _compose_daily_omni_multimodal(
|
||||
self,
|
||||
video_id: str,
|
||||
video_url: str | None,
|
||||
) -> tuple[dict[str, Any] | list[dict[str, Any]] | None, dict[str, Any] | None, Literal["first", "last"]]:
|
||||
"""Build ``multi_modal_data`` and request extras for the active ``input_mode``.
|
||||
|
||||
Mirrors upstream Daily-Omni: separate video + WAV with ``use_audio_in_video=False``.
|
||||
"""
|
||||
extra: dict[str, Any] = {"mm_processor_kwargs": {"use_audio_in_video": False}}
|
||||
mode = self.input_mode
|
||||
|
||||
if mode == "visual":
|
||||
v = self._get_video_content(video_id, video_url)
|
||||
return v, extra, "last"
|
||||
|
||||
if mode == "audio":
|
||||
a = self._get_audio_content(video_id)
|
||||
return a, extra, "first"
|
||||
|
||||
v = self._get_video_content(video_id, video_url)
|
||||
a = self._get_audio_content(video_id)
|
||||
if not v or not a:
|
||||
return None, None, "first"
|
||||
return [v, a], extra, "first"
|
||||
|
||||
@staticmethod
|
||||
def _media_desc_for_official_prompt(mode: DailyOmniInputMode) -> str:
|
||||
"""``media_desc`` in upstream ``build_conversation``."""
|
||||
if mode == "audio":
|
||||
return "given audio"
|
||||
if mode == "all":
|
||||
return "given video and audio together"
|
||||
return "given video"
|
||||
|
||||
@staticmethod
|
||||
def _choices_repr_for_official_prompt(choice: Any) -> str:
|
||||
"""Format ``Choice`` from qa.json for the model (one option per line when possible).
|
||||
|
||||
Using ``str(list)`` embeds Python list brackets and quotes, which is poor for MCQ
|
||||
reading; lists/tuples are joined with newlines instead. Other shapes fall back to
|
||||
``str(choice)`` for parity with exotic upstream payloads.
|
||||
"""
|
||||
if choice is None:
|
||||
return ""
|
||||
if isinstance(choice, (list, tuple)):
|
||||
lines = [str(x).strip() for x in choice if str(x).strip()]
|
||||
return "\n".join(lines)
|
||||
if isinstance(choice, dict):
|
||||
return "\n".join(f"{k}. {v}" for k, v in choice.items())
|
||||
return str(choice)
|
||||
|
||||
def _official_daily_omni_user_prompt(self, question: str, choice: Any) -> str:
|
||||
"""User text block from Daily-Omni ``build_conversation`` (after media parts)."""
|
||||
task_prompt = self._media_desc_for_official_prompt(self.input_mode)
|
||||
choices = self._choices_repr_for_official_prompt(choice)
|
||||
# Single f-string with explicit newlines avoids accidental implicit concatenation
|
||||
# gluing sentences (e.g. ``...media_desc.Select...``) when editing.
|
||||
return (
|
||||
"Your task is to accurately answer multiple-choice questions "
|
||||
f"based on the {task_prompt}.\n"
|
||||
"Select the single most accurate answer from the given choices.\n"
|
||||
f"Question: {question}\n"
|
||||
f"Choices: {choices}\n"
|
||||
"Your answer should be a capital letter representing your choice: "
|
||||
"A, B, C, or D. Don't generate any other text.\n"
|
||||
)
|
||||
|
||||
def _build_daily_omni_openai_messages(
|
||||
self,
|
||||
mm_payload: dict[str, Any] | list[dict[str, Any]],
|
||||
question: str,
|
||||
choice: Any,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Map upstream conversation to OpenAI Chat Completions ``messages`` (video_url / audio_url parts)."""
|
||||
user_text = self._official_daily_omni_user_prompt(question, choice)
|
||||
mm_list: list[dict[str, Any]] = mm_payload if isinstance(mm_payload, list) else [mm_payload]
|
||||
user_content: list[dict[str, Any]] = [*mm_list, {"type": "text", "text": user_text}]
|
||||
return [
|
||||
{"role": "system", "content": [{"type": "text", "text": DAILY_OMNI_SYSTEM_TEXT}]},
|
||||
{"role": "user", "content": user_content},
|
||||
]
|
||||
|
||||
def sample_by_task_type(
|
||||
self,
|
||||
tokenizer: TokenizerLike,
|
||||
task_type: str,
|
||||
num_samples: int,
|
||||
output_len: int | None = None,
|
||||
request_id_prefix: str = "",
|
||||
**kwargs,
|
||||
) -> list[SampleRequest]:
|
||||
"""Sample requests filtered by task type.
|
||||
|
||||
Args:
|
||||
tokenizer: Tokenizer
|
||||
task_type: Task type to filter by
|
||||
num_samples: Number of samples
|
||||
output_len: Target output length
|
||||
request_id_prefix: Prefix for request IDs
|
||||
**kwargs: Additional sampling arguments
|
||||
|
||||
Returns:
|
||||
List of SampleRequest objects matching the task type
|
||||
"""
|
||||
if output_len is None:
|
||||
output_len = self.DEFAULT_OUTPUT_LEN
|
||||
|
||||
filtered = [
|
||||
item for item in self.data if self._normalize_qa_fields(self._coerce_row(item))["task_type"] == task_type
|
||||
]
|
||||
|
||||
available = len(filtered)
|
||||
if available < num_samples:
|
||||
logger.warning(
|
||||
"Only %d samples available for task type '%s', requested %d",
|
||||
available,
|
||||
task_type,
|
||||
num_samples,
|
||||
)
|
||||
num_samples = available
|
||||
|
||||
sampled_requests: list[SampleRequest] = []
|
||||
cached_tokenizer = get_cached_tokenizer(tokenizer)
|
||||
|
||||
for i, item in enumerate(filtered[:num_samples]):
|
||||
request = self._create_sample_request(item, cached_tokenizer, output_len, request_id_prefix, i)
|
||||
if request:
|
||||
sampled_requests.append(request)
|
||||
|
||||
return sampled_requests
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"DailyOmniDataset("
|
||||
f"dataset_path={self.dataset_path!r}, "
|
||||
f"dataset_split={self.dataset_split!r}, "
|
||||
f"video_dir={self.video_dir!r}, "
|
||||
f"input_mode={self.input_mode!r}, "
|
||||
f"inline_local_video={self.inline_local_video!r}, "
|
||||
f"max_duration_seconds={self.max_duration_seconds}, "
|
||||
f"random_seed={self.random_seed}"
|
||||
f")"
|
||||
)
|
||||
|
||||
|
||||
def load_daily_omni_dataset(
|
||||
qa_json_path: str | None = None,
|
||||
dataset_path: str | None = None,
|
||||
dataset_split: str = "train",
|
||||
random_seed: int = 0,
|
||||
video_dir: str | None = None,
|
||||
input_mode: DailyOmniInputMode = "all",
|
||||
max_duration_seconds: float | None = None,
|
||||
dataset_subset: str | None = None,
|
||||
no_stream: bool = False,
|
||||
**kwargs,
|
||||
) -> DailyOmniDataset:
|
||||
"""Convenience function to load Daily-Omni dataset.
|
||||
|
||||
Args:
|
||||
qa_json_path: Path to local qa.json file (recommended for offline/air-gapped environments).
|
||||
When provided, ``dataset_path`` is ignored.
|
||||
dataset_path: HuggingFace dataset path (default: liarliar/Daily-Omni). Used only if
|
||||
``qa_json_path`` is not provided (legacy online mode).
|
||||
dataset_split: Dataset split to use (default: "train")
|
||||
random_seed: Random seed for shuffling
|
||||
video_dir: Directory containing extracted ``Videos/`` tree (MP4 and, for ``all``/``audio``, WAV)
|
||||
input_mode: ``visual`` | ``audio`` | ``all`` (same semantics as upstream Daily-Omni)
|
||||
max_duration_seconds: Maximum video duration in seconds (e.g., 30 for 30s subset, 60 for 60s subset);
|
||||
uses ffprobe on local files under ``video_dir`` (in-memory cache only for this process).
|
||||
**kwargs: Additional arguments passed to DailyOmniDataset
|
||||
|
||||
Returns:
|
||||
DailyOmniDataset instance
|
||||
|
||||
Example:
|
||||
>>> from vllm_omni.benchmarks.data_modules.daily_omni_dataset import load_daily_omni_dataset
|
||||
|
||||
# Local JSON mode (recommended for offline)
|
||||
>>> dataset = load_daily_omni_dataset(
|
||||
... qa_json_path="/path/to/qa.json",
|
||||
... video_dir="/path/to/Daily-Omni/Videos",
|
||||
... random_seed=42,
|
||||
... max_duration_seconds=30,
|
||||
... )
|
||||
|
||||
# HuggingFace mode (legacy online)
|
||||
>>> dataset = load_daily_omni_dataset(
|
||||
... dataset_path="liarliar/Daily-Omni",
|
||||
... video_dir="/path/to/Daily-Omni/Videos",
|
||||
... random_seed=42,
|
||||
... )
|
||||
>>> requests = dataset.sample(tokenizer, num_requests=100)
|
||||
"""
|
||||
return DailyOmniDataset(
|
||||
qa_json_path=qa_json_path,
|
||||
dataset_path=dataset_path,
|
||||
dataset_split=dataset_split,
|
||||
random_seed=random_seed,
|
||||
video_dir=video_dir,
|
||||
input_mode=input_mode,
|
||||
max_duration_seconds=max_duration_seconds,
|
||||
dataset_subset=dataset_subset,
|
||||
no_stream=no_stream,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def get_daily_omni_statistics(
|
||||
qa_json_path: str | None = None,
|
||||
dataset_path: str | None = DailyOmniDataset.DEFAULT_HF_DATASET_ID,
|
||||
dataset_split: str = "train",
|
||||
) -> dict[str, Any]:
|
||||
"""Get statistics about the Daily-Omni dataset.
|
||||
|
||||
Args:
|
||||
qa_json_path: Path to local qa.json file (recommended for offline/air-gapped environments).
|
||||
When provided, ``dataset_path`` is ignored.
|
||||
dataset_path: HuggingFace dataset path. Defaults to ``DailyOmniDataset.DEFAULT_HF_DATASET_ID``
|
||||
when ``qa_json_path`` is omitted. Pass ``None`` only together with ``qa_json_path``.
|
||||
dataset_split: Dataset split to use (default: "train")
|
||||
|
||||
Returns:
|
||||
Statistics dict with task type distribution and other info
|
||||
|
||||
Example:
|
||||
>>> from vllm_omni.benchmarks.data_modules.daily_omni_dataset import get_daily_omni_statistics
|
||||
|
||||
# Local JSON mode
|
||||
>>> stats = get_daily_omni_statistics(qa_json_path="/path/to/qa.json")
|
||||
|
||||
# HuggingFace mode
|
||||
>>> stats = get_daily_omni_statistics(dataset_path="liarliar/Daily-Omni")
|
||||
>>> print(f"Total QA pairs: {stats['total_qa_pairs']}")
|
||||
>>> print(f"Task distribution: {stats['task_distribution']}")
|
||||
"""
|
||||
dataset = DailyOmniDataset(
|
||||
qa_json_path=qa_json_path,
|
||||
dataset_path=dataset_path,
|
||||
dataset_split=dataset_split,
|
||||
)
|
||||
task_stats = dataset.get_task_statistics()
|
||||
|
||||
source = str(qa_json_path) if qa_json_path else f"{dataset_path}/{dataset_split}"
|
||||
return {
|
||||
"source": source,
|
||||
"total_qa_pairs": len(list(dataset.data)),
|
||||
"task_distribution": task_stats,
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
"""Daily-Omni multiple-choice accuracy scoring for vLLM-Omni bench serve.
|
||||
|
||||
Compares model ``generated_text`` to dataset ``Answer`` (A/B/C/D).
|
||||
|
||||
**Alignment with open-source** (`Lliar-liar/Daily-Omni` ``test_model/.../testmodel.py``):
|
||||
|
||||
- Answer extraction defaults to the same rules as ``extract_choice_letter`` (strip after an
|
||||
``assistant`` marker, then leading ``A``–``D``, else first ``\\b[A-D]\\b``). Set env
|
||||
``DAILY_OMNI_EXTRACT_MODE=relaxed`` to use the older vLLM-Omni heuristics (last ``answer:``,
|
||||
tail scan, etc.).
|
||||
- Overall accuracy comparable to the official script uses **successful HTTP responses only** as
|
||||
the denominator (their ``valid_questions = total - failed`` excludes inference / I/O skips).
|
||||
We also report ``daily_omni_accuracy_incl_http_fail`` where each failed request counts as a
|
||||
wrong answer in the denominator (stricter throughput-bench view).
|
||||
- **By video length:** mirrors upstream ``--- Accuracy by Video Duration ---`` for ``30s`` /
|
||||
``60s`` (``qa.json`` ``video_duration``): ``daily_omni_per_duration*`` metrics and a printed block.
|
||||
- **By video category:** mirrors ``--- Accuracy by Video Category ---`` using ``video_category``
|
||||
from ``qa.json`` (``daily_omni_per_category*``; empty category is bucketed as ``unknown``).
|
||||
- **Correctness:** uses the same ``evaluate_answer`` rule as upstream (truthy extracted letter vs
|
||||
raw ``Answer`` string, both ``strip().upper()``). Rows with empty ``Answer`` are skipped
|
||||
(``no_gold``), matching missing-field skips in the official loop.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from vllm.benchmarks.lib.endpoint_request_func import RequestFuncOutput
|
||||
|
||||
from vllm_omni.benchmarks.data_modules.daily_omni_dataset import DailyOmniSampleRequest
|
||||
|
||||
_VALID = frozenset("ABCD")
|
||||
|
||||
# Official ``testmodel.py`` buckets (``qa.json`` ``video_duration``).
|
||||
DAILY_OMNI_DURATION_KEYS: tuple[str, ...] = ("30s", "60s")
|
||||
|
||||
|
||||
def extract_choice_letter_official(text: str | None) -> str | None:
|
||||
"""Port of Daily-Omni ``extract_choice_letter`` (first A–D, assistant-tail semantics)."""
|
||||
if not text:
|
||||
return None
|
||||
raw = str(text).strip()
|
||||
if not raw:
|
||||
return None
|
||||
match = re.search(r"assistant\s*([\s\S]*)$", raw, flags=re.IGNORECASE)
|
||||
candidate = match.group(1).strip() if match else raw
|
||||
direct = re.match(r"(?i)^\s*([A-D])(?:[\s\.\)::]|$)", candidate)
|
||||
if direct:
|
||||
return direct.group(1).upper()
|
||||
fallback = re.search(r"\b([A-D])\b", candidate.upper())
|
||||
if fallback:
|
||||
return fallback.group(1)
|
||||
return None
|
||||
|
||||
|
||||
def evaluate_answer_official(model_answer: str | None, correct_answer: str) -> bool:
|
||||
"""Port of Daily-Omni ``evaluate_answer`` (strict string match after strip/upper)."""
|
||||
if not model_answer:
|
||||
return False
|
||||
return model_answer.strip().upper() == (correct_answer or "").strip().upper()
|
||||
|
||||
|
||||
def normalize_gold_answer(gold: str) -> str | None:
|
||||
"""Best-effort single letter from ``Answer`` (for ``gold_normalized`` in saved items only)."""
|
||||
g = (gold or "").strip().upper()
|
||||
if len(g) == 1 and g in _VALID:
|
||||
return g
|
||||
m = re.search(r"([ABCD])\b", g)
|
||||
if m:
|
||||
return m.group(1).upper()
|
||||
return None
|
||||
|
||||
|
||||
def _extract_predicted_choice_relaxed(text: str) -> str | None:
|
||||
"""Legacy vLLM-Omni heuristics (last ``answer:`` patterns, tail scan)."""
|
||||
if not text or not str(text).strip():
|
||||
return None
|
||||
t = str(text).strip()
|
||||
|
||||
strong_patterns = [
|
||||
r"(?i)\*\*answer\*\*\s*[::]?\s*\(?([ABCD])\)?",
|
||||
r"(?i)\banswer\s*[::]?\s*\(?([ABCD])\)?",
|
||||
r"(?i)\bfinal\s+answer\s*[::]?\s*\(?([ABCD])\)?",
|
||||
r"(?i)\bcorrect\s+(?:answer|option)\s*[::]?\s*\(?([ABCD])\)?",
|
||||
r"(?i)\bthe\s+(?:correct\s+)?option\s+(?:is|would\s+be)\s*\(?([ABCD])\)?",
|
||||
r"(?i)\bI\s+(?:would\s+)?(?:choose|select|pick)\s*\(?([ABCD])\)?",
|
||||
]
|
||||
last_letter: str | None = None
|
||||
for pat in strong_patterns:
|
||||
for m in re.finditer(pat, t):
|
||||
last_letter = m.group(1).upper()
|
||||
if last_letter:
|
||||
return last_letter
|
||||
|
||||
# Weaker phrases: first match can be spurious; still prefer last occurrence.
|
||||
weak_patterns = [
|
||||
r"(?i)\boption\s*[::]?\s*\(?([ABCD])\)?",
|
||||
r"(?i)\bchoice\s*[::]?\s*\(?([ABCD])\)?",
|
||||
]
|
||||
for pat in weak_patterns:
|
||||
for m in re.finditer(pat, t):
|
||||
last_letter = m.group(1).upper()
|
||||
if last_letter:
|
||||
return last_letter
|
||||
|
||||
paren = list(re.finditer(r"\(([ABCD])\)", t))
|
||||
if paren:
|
||||
return paren[-1].group(1).upper()
|
||||
|
||||
# First line sometimes is just "B" or "B." — allow if whole output is short
|
||||
one_line = t.split("\n", 1)[0].strip()
|
||||
if len(t) < 120 and len(one_line) <= 6:
|
||||
m0 = re.match(r"^([ABCD])\s*[.:\)]?\s*$", one_line, re.I)
|
||||
if m0:
|
||||
return m0.group(1).upper()
|
||||
|
||||
# Tail-only: avoids matching echoed "A. ..." option blocks at the start
|
||||
tail_len = min(500, len(t))
|
||||
tail = t[-tail_len:]
|
||||
# ``\b`` after the letter avoids "Because"/"Definitely" false positives
|
||||
m = re.search(r"(?:^|[^\w])([ABCD])\b", tail, re.I)
|
||||
if m:
|
||||
return m.group(1).upper()
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def extract_predicted_choice(text: str | None) -> str | None:
|
||||
"""Parse model output to A–D (official Daily-Omni rules by default)."""
|
||||
if not text or not str(text).strip():
|
||||
return None
|
||||
mode = os.environ.get("DAILY_OMNI_EXTRACT_MODE", "official").strip().lower()
|
||||
if mode in ("relaxed", "heuristic", "legacy"):
|
||||
return _extract_predicted_choice_relaxed(str(text))
|
||||
return extract_choice_letter_official(text)
|
||||
|
||||
|
||||
def compute_daily_omni_accuracy_metrics(
|
||||
input_requests: list[Any],
|
||||
outputs: list[RequestFuncOutput],
|
||||
*,
|
||||
include_per_item: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""If all requests are :class:`DailyOmniSampleRequest`, compute accuracy stats.
|
||||
|
||||
Rows with empty ``Answer`` (after strip) are skipped as ``no_gold``, like upstream missing
|
||||
``correct_answer``.
|
||||
|
||||
**Denominators:** The open-source script excludes items that hit inference / I/O failures
|
||||
from ``valid_questions``; we mirror that with ``daily_omni_accuracy`` (= correct /
|
||||
successful responses). Failed HTTP requests are also tracked and used in
|
||||
``daily_omni_accuracy_incl_http_fail`` (each failure counts as incorrect in the
|
||||
denominator).
|
||||
"""
|
||||
if not input_requests or len(input_requests) != len(outputs):
|
||||
return None
|
||||
if not all(isinstance(r, DailyOmniSampleRequest) for r in input_requests):
|
||||
return None
|
||||
|
||||
# total / correct: all rows with gold (incl. HTTP fail in total)
|
||||
# total_ok / correct_ok: successful HTTP only (GitHub-style per-type denominator)
|
||||
per_task: dict[str, dict[str, int]] = {}
|
||||
per_category: dict[str, dict[str, int]] = {}
|
||||
per_duration: dict[str, dict[str, int]] = {
|
||||
k: {"correct": 0, "total": 0, "correct_ok": 0, "total_ok": 0} for k in DAILY_OMNI_DURATION_KEYS
|
||||
}
|
||||
items: list[dict[str, Any]] = []
|
||||
correct = 0
|
||||
evaluated = 0
|
||||
no_gold = 0
|
||||
request_failed = 0
|
||||
parse_failed = 0 # success but could not extract A–D
|
||||
|
||||
for req, out in zip(input_requests, outputs, strict=True):
|
||||
assert isinstance(req, DailyOmniSampleRequest)
|
||||
gold_raw = (req.daily_omni_gold_answer or "").strip()
|
||||
gold_norm = normalize_gold_answer(req.daily_omni_gold_answer)
|
||||
tt = (req.daily_omni_task_type or "unknown").strip() or "unknown"
|
||||
dur_key = (req.daily_omni_video_duration or "").strip()
|
||||
dur_active = dur_key in per_duration
|
||||
cat_key = (req.daily_omni_video_category or "").strip() or "unknown"
|
||||
if tt not in per_task:
|
||||
per_task[tt] = {"correct": 0, "total": 0, "correct_ok": 0, "total_ok": 0}
|
||||
if cat_key not in per_category:
|
||||
per_category[cat_key] = {"correct": 0, "total": 0, "correct_ok": 0, "total_ok": 0}
|
||||
|
||||
if not gold_raw:
|
||||
no_gold += 1
|
||||
items.append(
|
||||
{
|
||||
"request_id": req.request_id,
|
||||
"skipped": True,
|
||||
"reason": "no_gold",
|
||||
"task_type": tt,
|
||||
"video_id": req.daily_omni_video_id,
|
||||
"video_duration": dur_key or None,
|
||||
"video_category": cat_key if cat_key != "unknown" else None,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
if not out.success:
|
||||
request_failed += 1
|
||||
evaluated += 1
|
||||
per_task[tt]["total"] += 1
|
||||
per_category[cat_key]["total"] += 1
|
||||
if dur_active:
|
||||
per_duration[dur_key]["total"] += 1
|
||||
# GitHub: failed inference not in valid_questions — do not increment total_ok
|
||||
items.append(
|
||||
{
|
||||
"request_id": req.request_id,
|
||||
"gold": gold_raw,
|
||||
"gold_normalized": gold_norm,
|
||||
"predicted": None,
|
||||
"correct": False,
|
||||
"task_type": tt,
|
||||
"video_id": req.daily_omni_video_id,
|
||||
"video_duration": dur_key or None,
|
||||
"video_category": cat_key if cat_key != "unknown" else None,
|
||||
"error": (out.error or "")[:500],
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
pred = extract_predicted_choice(out.generated_text)
|
||||
evaluated += 1
|
||||
per_task[tt]["total"] += 1
|
||||
per_task[tt]["total_ok"] += 1
|
||||
per_category[cat_key]["total"] += 1
|
||||
per_category[cat_key]["total_ok"] += 1
|
||||
if dur_active:
|
||||
per_duration[dur_key]["total"] += 1
|
||||
per_duration[dur_key]["total_ok"] += 1
|
||||
if pred is None:
|
||||
parse_failed += 1
|
||||
is_correct = evaluate_answer_official(pred, req.daily_omni_gold_answer)
|
||||
if is_correct:
|
||||
correct += 1
|
||||
per_task[tt]["correct"] += 1
|
||||
per_task[tt]["correct_ok"] += 1
|
||||
per_category[cat_key]["correct"] += 1
|
||||
per_category[cat_key]["correct_ok"] += 1
|
||||
if dur_active:
|
||||
per_duration[dur_key]["correct"] += 1
|
||||
per_duration[dur_key]["correct_ok"] += 1
|
||||
|
||||
items.append(
|
||||
{
|
||||
"request_id": req.request_id,
|
||||
"gold": gold_raw,
|
||||
"gold_normalized": gold_norm,
|
||||
"predicted": pred,
|
||||
"correct": is_correct,
|
||||
"parse_failed": pred is None,
|
||||
"task_type": tt,
|
||||
"video_id": req.daily_omni_video_id,
|
||||
"video_duration": dur_key or None,
|
||||
"video_category": cat_key if cat_key != "unknown" else None,
|
||||
}
|
||||
)
|
||||
|
||||
evaluated_ok = evaluated - request_failed
|
||||
accuracy_github = (correct / evaluated_ok) if evaluated_ok else None
|
||||
accuracy_incl_fail = (correct / evaluated) if evaluated else None
|
||||
|
||||
per_task_accuracy: dict[str, float | None] = {}
|
||||
per_task_accuracy_github: dict[str, float | None] = {}
|
||||
for name, st in per_task.items():
|
||||
tot = st["total"]
|
||||
per_task_accuracy[name] = (st["correct"] / tot) if tot else None
|
||||
tok = st["total_ok"]
|
||||
per_task_accuracy_github[name] = (st["correct_ok"] / tok) if tok else None
|
||||
|
||||
per_category_accuracy: dict[str, float | None] = {}
|
||||
per_category_accuracy_github: dict[str, float | None] = {}
|
||||
for name, st in per_category.items():
|
||||
tot = st["total"]
|
||||
per_category_accuracy[name] = (st["correct"] / tot) if tot else None
|
||||
tok = st["total_ok"]
|
||||
per_category_accuracy_github[name] = (st["correct_ok"] / tok) if tok else None
|
||||
|
||||
per_duration_accuracy: dict[str, float | None] = {}
|
||||
per_duration_accuracy_github: dict[str, float | None] = {}
|
||||
for name, st in per_duration.items():
|
||||
tot = st["total"]
|
||||
per_duration_accuracy[name] = (st["correct"] / tot) if tot else None
|
||||
tok = st["total_ok"]
|
||||
per_duration_accuracy_github[name] = (st["correct_ok"] / tok) if tok else None
|
||||
|
||||
out: dict[str, Any] = {
|
||||
# Comparable to GitHub testmodel.py: correct / successful inferences
|
||||
"daily_omni_accuracy": accuracy_github,
|
||||
"daily_omni_accuracy_incl_http_fail": accuracy_incl_fail,
|
||||
"daily_omni_correct": correct,
|
||||
"daily_omni_evaluated": evaluated,
|
||||
"daily_omni_evaluated_ok": evaluated_ok,
|
||||
"daily_omni_no_gold": no_gold,
|
||||
"daily_omni_request_failed": request_failed,
|
||||
"daily_omni_parse_failed": parse_failed,
|
||||
"daily_omni_per_task": {k: dict(v) for k, v in per_task.items()},
|
||||
"daily_omni_per_task_accuracy": per_task_accuracy,
|
||||
"daily_omni_per_task_accuracy_github_style": per_task_accuracy_github,
|
||||
"daily_omni_per_category": {k: dict(v) for k, v in per_category.items()},
|
||||
"daily_omni_per_category_accuracy": per_category_accuracy,
|
||||
"daily_omni_per_category_accuracy_github_style": per_category_accuracy_github,
|
||||
"daily_omni_per_duration": {k: dict(v) for k, v in per_duration.items()},
|
||||
"daily_omni_per_duration_accuracy": per_duration_accuracy,
|
||||
"daily_omni_per_duration_accuracy_github_style": per_duration_accuracy_github,
|
||||
}
|
||||
if include_per_item:
|
||||
out["daily_omni_eval_items"] = items
|
||||
return out
|
||||
|
||||
|
||||
def print_daily_omni_accuracy_summary(metrics: dict[str, Any]) -> None:
|
||||
"""Pretty-print accuracy block (stdout)."""
|
||||
acc = metrics.get("daily_omni_accuracy")
|
||||
acc_fail = metrics.get("daily_omni_accuracy_incl_http_fail")
|
||||
if acc is None and acc_fail is None and metrics.get("daily_omni_evaluated", 0) == 0:
|
||||
return
|
||||
print("{s:{c}^{n}}".format(s=" Daily-Omni accuracy (MCQ) ", n=50, c="="))
|
||||
ok = int(metrics.get("daily_omni_evaluated_ok", 0) or 0)
|
||||
cor = int(metrics.get("daily_omni_correct", 0) or 0)
|
||||
if ok > 0 and acc is not None:
|
||||
print(f"Overall Accuracy: {cor}/{ok} = {acc:.2%}")
|
||||
elif int(metrics.get("daily_omni_evaluated", 0) or 0) > 0:
|
||||
print("Overall Accuracy: 0/0 = N/A (no successful HTTP responses)")
|
||||
print(
|
||||
"{:<40} {:<10}".format(
|
||||
"Submitted (gold present):",
|
||||
metrics.get("daily_omni_evaluated", 0),
|
||||
)
|
||||
)
|
||||
print(
|
||||
"{:<40} {:<10}".format(
|
||||
"Successful HTTP (GitHub denom.):",
|
||||
metrics.get("daily_omni_evaluated_ok", 0),
|
||||
)
|
||||
)
|
||||
print("{:<40} {:<10}".format("Correct:", metrics.get("daily_omni_correct", 0)))
|
||||
if acc is not None:
|
||||
print("{:<40} {:<10.4f}".format("Accuracy (ratio, same as above):", acc))
|
||||
if acc_fail is not None and metrics.get("daily_omni_request_failed", 0):
|
||||
print(
|
||||
"{:<40} {:<10.4f}".format(
|
||||
"Accuracy (incl. HTTP as wrong):",
|
||||
acc_fail,
|
||||
)
|
||||
)
|
||||
print("{:<40} {:<10}".format("Skipped (no gold):", metrics.get("daily_omni_no_gold", 0)))
|
||||
print(
|
||||
"{:<40} {:<10}".format(
|
||||
"HTTP failed (excl. from GitHub acc.):",
|
||||
metrics.get("daily_omni_request_failed", 0),
|
||||
)
|
||||
)
|
||||
print(
|
||||
"{:<40} {:<10}".format(
|
||||
"Parsed OK but no A–D found:",
|
||||
metrics.get("daily_omni_parse_failed", 0),
|
||||
)
|
||||
)
|
||||
pt = metrics.get("daily_omni_per_task") or {}
|
||||
pta = metrics.get("daily_omni_per_task_accuracy_github_style") or {}
|
||||
if pta:
|
||||
print("\n--- Accuracy by QA Type ---")
|
||||
for name in sorted(pta.keys()):
|
||||
a = pta[name]
|
||||
st = pt.get(name) or {}
|
||||
tok = int(st.get("total_ok", 0) or 0)
|
||||
cok = int(st.get("correct_ok", 0) or 0)
|
||||
if tok and a is not None:
|
||||
print(f"{name}: {cok}/{tok} = {a:.2%}")
|
||||
else:
|
||||
print(f"{name}: 0/0 = N/A")
|
||||
|
||||
pc = metrics.get("daily_omni_per_category") or {}
|
||||
ptc = metrics.get("daily_omni_per_category_accuracy_github_style") or {}
|
||||
if ptc:
|
||||
print("\n--- Accuracy by Video Category ---")
|
||||
for name in sorted(ptc.keys()):
|
||||
a = ptc[name]
|
||||
st = pc.get(name) or {}
|
||||
tok = int(st.get("total_ok", 0) or 0)
|
||||
cok = int(st.get("correct_ok", 0) or 0)
|
||||
if tok and a is not None:
|
||||
print(f"{name}: {cok}/{tok} = {a:.2%}")
|
||||
else:
|
||||
print(f"{name}: 0/0 = N/A")
|
||||
|
||||
pdf = metrics.get("daily_omni_per_duration_accuracy_github_style") or {}
|
||||
if pdf:
|
||||
print("\n--- Accuracy by Video Duration ---")
|
||||
for name in DAILY_OMNI_DURATION_KEYS:
|
||||
a = pdf.get(name)
|
||||
st = (metrics.get("daily_omni_per_duration") or {}).get(name) or {}
|
||||
tok = int(st.get("total_ok", 0) or 0)
|
||||
cor = int(st.get("correct_ok", 0) or 0)
|
||||
if tok and a is not None:
|
||||
print(f"{name} Duration: {cor}/{tok} = {a:.2%}")
|
||||
else:
|
||||
print(f"{name} Duration: 0/0 = N/A")
|
||||
print("=" * 50)
|
||||
@@ -0,0 +1,255 @@
|
||||
"""Daily-Omni: optional consistency check between text stream and generated speech.
|
||||
|
||||
The benchmark MCQ accuracy uses ``generated_text`` only. When the omni server also
|
||||
streams ``modality=audio`` (TTS), this module can transcribe the concatenated WAV
|
||||
with Whisper and compare the inferred option letter to the one parsed from text.
|
||||
|
||||
Requires ``openai-whisper`` (``pip install openai-whisper``). Enable via env
|
||||
``DAILY_OMNI_TEXT_AUDIO_CONSISTENCY=1`` or CLI ``--daily-omni-text-audio-consistency``.
|
||||
|
||||
Whisper model name defaults to ``tiny`` (override with ``DAILY_OMNI_WHISPER_MODEL``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
from vllm_omni.benchmarks.data_modules.daily_omni_dataset import DailyOmniSampleRequest
|
||||
from vllm_omni.benchmarks.data_modules.daily_omni_eval import extract_predicted_choice
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_whisper_model = None
|
||||
_whisper_model_name: str | None = None
|
||||
_whisper_lock = threading.Lock()
|
||||
|
||||
|
||||
def env_text_audio_check_enabled() -> bool:
|
||||
return os.environ.get("DAILY_OMNI_TEXT_AUDIO_CONSISTENCY", "").lower() in (
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
)
|
||||
|
||||
|
||||
def extract_choice_from_asr_transcript(transcript: str) -> str | None:
|
||||
"""Parse A–D from ASR text; extends :func:`extract_predicted_choice` with spoken Chinese phrases."""
|
||||
c = extract_predicted_choice(transcript)
|
||||
if c:
|
||||
return c
|
||||
t = transcript or ""
|
||||
for pat in (
|
||||
r"(?i)选项\s*([ABCD])\b",
|
||||
r"(?i)选\s*([ABCD])\b",
|
||||
r"(?i)答案\s*是\s*([ABCD])\b",
|
||||
r"(?i)答案\s*([ABCD])\b",
|
||||
):
|
||||
m = re.search(pat, t)
|
||||
if m:
|
||||
return m.group(1).upper()
|
||||
return None
|
||||
|
||||
|
||||
def _get_whisper_model(model_name: str):
|
||||
global _whisper_model, _whisper_model_name
|
||||
with _whisper_lock:
|
||||
if _whisper_model is None or _whisper_model_name != model_name:
|
||||
import whisper
|
||||
|
||||
logger.warning(
|
||||
"Loading Whisper model %r for Daily-Omni text/audio consistency (one-time)...",
|
||||
model_name,
|
||||
)
|
||||
_whisper_model = whisper.load_model(model_name)
|
||||
_whisper_model_name = model_name
|
||||
return _whisper_model
|
||||
|
||||
|
||||
def transcribe_wav_bytes(
|
||||
wav_bytes: bytes,
|
||||
*,
|
||||
language: str | None = None,
|
||||
model_name: str | None = None,
|
||||
) -> tuple[str | None, str | None]:
|
||||
"""Transcribe WAV bytes. Returns ``(transcript, error)`` — one of them is set.
|
||||
|
||||
Args:
|
||||
wav_bytes: RIFF WAV file bytes.
|
||||
language: Optional Whisper language code (e.g. ``en``, ``zh``); improves accuracy/latency.
|
||||
model_name: Override model id; else ``DAILY_OMNI_WHISPER_MODEL`` or ``tiny``.
|
||||
"""
|
||||
if not wav_bytes:
|
||||
return None, "empty_wav"
|
||||
if model_name is None or not str(model_name).strip():
|
||||
model_name = os.environ.get("DAILY_OMNI_WHISPER_MODEL") or "tiny"
|
||||
model_name = str(model_name).strip() or "tiny"
|
||||
path: str | None = None
|
||||
try:
|
||||
import tempfile
|
||||
|
||||
model = _get_whisper_model(model_name)
|
||||
fd, path = tempfile.mkstemp(suffix=".wav")
|
||||
with os.fdopen(fd, "wb") as fp:
|
||||
fp.write(wav_bytes)
|
||||
kwargs: dict = {}
|
||||
if language:
|
||||
kwargs["language"] = language
|
||||
result = model.transcribe(path, **kwargs)
|
||||
text = (result.get("text") or "").strip()
|
||||
return (text if text else None), None
|
||||
except ImportError:
|
||||
return None, "openai-whisper is not installed (pip install openai-whisper)"
|
||||
except Exception as e:
|
||||
return None, str(e)[:500]
|
||||
finally:
|
||||
if path:
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def compute_daily_omni_text_audio_consistency_metrics(
|
||||
input_requests: list[Any],
|
||||
outputs: list[Any],
|
||||
*,
|
||||
include_per_item: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Compare option letter from ``generated_text`` vs Whisper transcript of output audio.
|
||||
|
||||
Only considers requests where ``outputs[i]`` has ``generated_audio_wav_bytes`` set
|
||||
(populated by the omni benchmark when TA check is enabled).
|
||||
"""
|
||||
if not input_requests or len(input_requests) != len(outputs):
|
||||
return None
|
||||
if not all(isinstance(r, DailyOmniSampleRequest) for r in input_requests):
|
||||
return None
|
||||
|
||||
ta_no_wav = 0
|
||||
ta_asr_failed = 0
|
||||
ta_text_unparsed = 0
|
||||
ta_audio_unparsed = 0
|
||||
ta_consistent = 0
|
||||
ta_mismatch = 0
|
||||
ta_both_parsed = 0
|
||||
items: list[dict[str, Any]] = []
|
||||
|
||||
for req, out in zip(input_requests, outputs, strict=True):
|
||||
assert isinstance(req, DailyOmniSampleRequest)
|
||||
rid = req.request_id
|
||||
if not getattr(out, "success", False):
|
||||
if include_per_item:
|
||||
items.append(
|
||||
{
|
||||
"request_id": rid,
|
||||
"skipped": True,
|
||||
"reason": "request_not_success",
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
wav = getattr(out, "generated_audio_wav_bytes", None)
|
||||
if not wav:
|
||||
ta_no_wav += 1
|
||||
if include_per_item:
|
||||
items.append(
|
||||
{
|
||||
"request_id": rid,
|
||||
"skipped": False,
|
||||
"reason": "no_output_audio",
|
||||
"text_choice": extract_predicted_choice(getattr(out, "generated_text", "") or ""),
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
transcript, asr_err = transcribe_wav_bytes(wav)
|
||||
if asr_err:
|
||||
ta_asr_failed += 1
|
||||
if include_per_item:
|
||||
items.append(
|
||||
{
|
||||
"request_id": rid,
|
||||
"asr_error": asr_err,
|
||||
"text_choice": extract_predicted_choice(getattr(out, "generated_text", "") or ""),
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
text_choice = extract_predicted_choice(getattr(out, "generated_text", "") or "")
|
||||
audio_choice = extract_choice_from_asr_transcript(transcript or "")
|
||||
|
||||
if text_choice is None:
|
||||
ta_text_unparsed += 1
|
||||
if audio_choice is None:
|
||||
ta_audio_unparsed += 1
|
||||
|
||||
if text_choice is not None and audio_choice is not None:
|
||||
ta_both_parsed += 1
|
||||
if text_choice == audio_choice:
|
||||
ta_consistent += 1
|
||||
else:
|
||||
ta_mismatch += 1
|
||||
|
||||
if include_per_item:
|
||||
consistent: bool | None
|
||||
if text_choice is None or audio_choice is None:
|
||||
consistent = None
|
||||
else:
|
||||
consistent = text_choice == audio_choice
|
||||
items.append(
|
||||
{
|
||||
"request_id": rid,
|
||||
"text_choice": text_choice,
|
||||
"audio_choice": audio_choice,
|
||||
"asr_transcript": (transcript or "")[:500],
|
||||
"text_audio_consistent": consistent,
|
||||
}
|
||||
)
|
||||
|
||||
comparable = ta_consistent + ta_mismatch
|
||||
rate = (ta_consistent / comparable) if comparable else None
|
||||
|
||||
out: dict[str, Any] = {
|
||||
"daily_omni_ta_enabled": True,
|
||||
"daily_omni_ta_no_output_audio": ta_no_wav,
|
||||
"daily_omni_ta_asr_failed": ta_asr_failed,
|
||||
"daily_omni_ta_text_unparsed": ta_text_unparsed,
|
||||
"daily_omni_ta_audio_unparsed": ta_audio_unparsed,
|
||||
"daily_omni_ta_both_parsed": ta_both_parsed,
|
||||
"daily_omni_ta_consistent": ta_consistent,
|
||||
"daily_omni_ta_mismatch": ta_mismatch,
|
||||
"daily_omni_ta_consistency_rate": rate,
|
||||
}
|
||||
if include_per_item:
|
||||
out["daily_omni_ta_items"] = items
|
||||
return out
|
||||
|
||||
|
||||
def print_daily_omni_text_audio_summary(metrics: dict[str, Any]) -> None:
|
||||
if not metrics.get("daily_omni_ta_enabled"):
|
||||
return
|
||||
print("{s:{c}^{n}}".format(s=" Daily-Omni text vs audio (ASR) ", n=50, c="="))
|
||||
print("{:<40} {:<10}".format("No output audio captured:", metrics.get("daily_omni_ta_no_output_audio", 0)))
|
||||
print("{:<40} {:<10}".format("ASR failed:", metrics.get("daily_omni_ta_asr_failed", 0)))
|
||||
print("{:<40} {:<10}".format("Both text+audio letter parsed:", metrics.get("daily_omni_ta_both_parsed", 0)))
|
||||
print("{:<40} {:<10}".format("Consistent (same letter):", metrics.get("daily_omni_ta_consistent", 0)))
|
||||
print("{:<40} {:<10}".format("Mismatch:", metrics.get("daily_omni_ta_mismatch", 0)))
|
||||
r = metrics.get("daily_omni_ta_consistency_rate")
|
||||
if r is not None:
|
||||
print("{:<40} {:<10.4f}".format("Consistency rate (of both parsed):", r))
|
||||
print(
|
||||
"{:<40} {:<10}".format(
|
||||
"Text unparsed (among w/ audio):",
|
||||
metrics.get("daily_omni_ta_text_unparsed", 0),
|
||||
)
|
||||
)
|
||||
print(
|
||||
"{:<40} {:<10}".format(
|
||||
"Audio unparsed (among w/ audio):",
|
||||
metrics.get("daily_omni_ta_audio_unparsed", 0),
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,272 @@
|
||||
"""Seed-TTS zero-shot evaluation-style prompts for ``vllm bench serve``.
|
||||
|
||||
Loads rows from the `meta.lst` format used in `BytedanceSpeech/seed-tts-eval`_ (or any
|
||||
HuggingFace dataset repo with the same layout)::
|
||||
|
||||
utt_id|prompt_transcript|prompt_wav_relative_path|text_to_synthesize
|
||||
|
||||
Each benchmark request supplies target text plus ``ref_text`` / ``ref_audio`` (Qwen3-TTS ``Base`` /
|
||||
voice clone), merged into the JSON body. By default ``ref_audio`` is an inline ``data:`` URL so
|
||||
the server does not need ``--allowed-local-media-path``. Use ``--seed-tts-file-ref-audio`` for
|
||||
``file://`` (smaller bodies; requires that flag). Use ``--backend openai-audio-speech``
|
||||
(``/v1/audio/speech``) or ``--backend openai-chat-omni`` (``/v1/chat/completions`` with the same
|
||||
fields on the body plus a Qwen3-Omni-style ``system`` message and the target text as ``user`` content).
|
||||
|
||||
.. _BytedanceSpeech/seed-tts-eval: https://github.com/BytedanceSpeech/seed-tts-eval
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from vllm.benchmarks.datasets import BenchmarkDataset, SampleRequest
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
from vllm.tokenizers.hf import get_cached_tokenizer
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Matches Qwen3-Omni serving examples (``openai_chat_completion_client_for_multimodal_generation`` /
|
||||
# ``qwen3_omni/gradio_demo``) plus explicit TTS / voice-clone instructions for chat completions.
|
||||
SEED_TTS_DEFAULT_OMNI_SYSTEM_PROMPT = (
|
||||
"You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, "
|
||||
"capable of perceiving auditory and visual inputs, as well as generating text and speech.\n"
|
||||
"For this request you act as a text-to-speech engine with zero-shot voice cloning: "
|
||||
"the API provides reference audio and its transcript (ref_audio, ref_text) and task_type Base. "
|
||||
"The user message is the exact text you must speak. "
|
||||
"Synthesize natural speech in the same language as that user text, "
|
||||
"matching the timbre, prosody, and speaking style of the reference audio while reading the new content clearly."
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SeedTTSSampleRequest(SampleRequest):
|
||||
"""``SampleRequest`` with per-row fields merged into ``/v1/audio/speech`` JSON."""
|
||||
|
||||
#: Shallow-merged into ``RequestFuncInput.extra_body`` (ref_audio, ref_text, task_type, …).
|
||||
seed_tts_speech_extra: dict[str, Any] | None = None
|
||||
seed_tts_utterance_id: str = ""
|
||||
seed_tts_locale: str = ""
|
||||
#: For ``openai-chat-omni``: becomes the chat ``system`` message (Qwen3-Omni + TTS behavior).
|
||||
seed_tts_system_prompt: str = ""
|
||||
#: Local path to reference prompt WAV (for SIM vs. synthesized PCM in ``seed_tts_eval``).
|
||||
seed_tts_ref_wav_path: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class _SeedTTSRow:
|
||||
utterance_id: str
|
||||
ref_text: str
|
||||
prompt_wav_rel: str
|
||||
target_text: str
|
||||
|
||||
|
||||
def _parse_meta_line(line: str) -> _SeedTTSRow | None:
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
return None
|
||||
parts = line.split("|")
|
||||
if len(parts) < 4:
|
||||
logger.warning("Skipping malformed meta.lst line (need 4 '|'-fields): %r", line[:120])
|
||||
return None
|
||||
utt_id, ref_text, wav_rel, target = parts[0], parts[1], parts[2], parts[3]
|
||||
if not target.strip():
|
||||
return None
|
||||
return _SeedTTSRow(
|
||||
utterance_id=utt_id.strip(),
|
||||
ref_text=ref_text.strip(),
|
||||
prompt_wav_rel=wav_rel.strip(),
|
||||
target_text=target.strip(),
|
||||
)
|
||||
|
||||
|
||||
def _load_meta_rows(meta_file: Path) -> list[_SeedTTSRow]:
|
||||
text = meta_file.read_text(encoding="utf-8")
|
||||
rows: list[_SeedTTSRow] = []
|
||||
for line in text.splitlines():
|
||||
r = _parse_meta_line(line)
|
||||
if r is not None:
|
||||
rows.append(r)
|
||||
return rows
|
||||
|
||||
|
||||
def resolve_seed_tts_root(dataset_path: str | None, *, explicit_root: str | None) -> Path:
|
||||
"""Return directory containing ``{locale}/meta.lst`` and ``{locale}/prompt-wavs/``."""
|
||||
if explicit_root:
|
||||
root = Path(explicit_root).expanduser().resolve()
|
||||
if not root.is_dir():
|
||||
raise FileNotFoundError(f"--seed-tts-root is not a directory: {root}")
|
||||
return root
|
||||
|
||||
if not dataset_path:
|
||||
raise ValueError("Seed-TTS requires --dataset-path (HF repo id or local root) or --seed-tts-root.")
|
||||
|
||||
p = Path(dataset_path).expanduser()
|
||||
if p.exists() and p.is_dir():
|
||||
return p.resolve()
|
||||
|
||||
repo_id = dataset_path.strip()
|
||||
try:
|
||||
from huggingface_hub import snapshot_download
|
||||
except ImportError as e:
|
||||
raise ImportError(
|
||||
"Install huggingface_hub to download Seed-TTS from the Hub, or clone the dataset "
|
||||
"locally and pass --dataset-path / --seed-tts-root to that directory."
|
||||
) from e
|
||||
cache = snapshot_download(repo_id=repo_id, repo_type="dataset")
|
||||
return Path(cache).resolve()
|
||||
|
||||
|
||||
def _ref_audio_payload(wav_path: Path, *, inline: bool) -> str:
|
||||
if inline:
|
||||
raw = wav_path.read_bytes()
|
||||
b64 = base64.b64encode(raw).decode("ascii")
|
||||
return f"data:audio/wav;base64,{b64}"
|
||||
return wav_path.expanduser().resolve().as_uri()
|
||||
|
||||
|
||||
class SeedTTSDataset(BenchmarkDataset):
|
||||
"""Seed-TTS-style zero-shot TTS rows for throughput/latency benchmarking.
|
||||
|
||||
Args:
|
||||
dataset_path: HuggingFace dataset repo id (``org/dataset``) or local directory with
|
||||
``en/meta.lst`` (and ``zh/meta.lst`` if using zh).
|
||||
locale: ``en`` or ``zh`` — which subfolder under the root to read.
|
||||
inline_ref_audio: If True (default), embed prompt WAV as ``data:audio/wav;base64,...``
|
||||
so Qwen3-TTS / ``/v1/audio/speech`` works without server
|
||||
``--allowed-local-media-path``. If False, use ``file://`` (smaller
|
||||
requests; server must set ``--allowed-local-media-path`` to the dataset root).
|
||||
seed_tts_root: Optional override for the root directory (same layout as HF dataset).
|
||||
system_prompt: Optional override for the chat system message when using
|
||||
``--backend openai-chat-omni``; defaults to :data:`SEED_TTS_DEFAULT_OMNI_SYSTEM_PROMPT`.
|
||||
"""
|
||||
|
||||
IS_MULTIMODAL = False
|
||||
DEFAULT_OUTPUT_LEN = 2048
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dataset_path: str,
|
||||
random_seed: int = 0,
|
||||
locale: str = "en",
|
||||
inline_ref_audio: bool = True,
|
||||
seed_tts_root: str | None = None,
|
||||
system_prompt: str | None = None,
|
||||
disable_shuffle: bool = False,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
if locale not in ("en", "zh"):
|
||||
raise ValueError("locale must be 'en' or 'zh'")
|
||||
self.locale = locale
|
||||
self.inline_ref_audio = inline_ref_audio
|
||||
self._explicit_root = seed_tts_root
|
||||
sp = (system_prompt or "").strip()
|
||||
self._system_prompt = sp if sp else SEED_TTS_DEFAULT_OMNI_SYSTEM_PROMPT
|
||||
super().__init__(
|
||||
dataset_path=dataset_path,
|
||||
random_seed=random_seed,
|
||||
disable_shuffle=disable_shuffle,
|
||||
**kwargs,
|
||||
)
|
||||
self._root = resolve_seed_tts_root(self.dataset_path, explicit_root=self._explicit_root)
|
||||
self._rows: list[_SeedTTSRow] = []
|
||||
self.load_data()
|
||||
|
||||
def load_data(self) -> None:
|
||||
meta = self._root / self.locale / "meta.lst"
|
||||
if not meta.is_file():
|
||||
raise FileNotFoundError(
|
||||
f"Seed-TTS meta not found: {meta}. "
|
||||
f"Expected layout from seed-tts-eval (e.g. {self._root}/{self.locale}/meta.lst)."
|
||||
)
|
||||
self._rows = _load_meta_rows(meta)
|
||||
if not self._rows:
|
||||
raise ValueError(f"No valid rows in {meta}")
|
||||
if not self.disable_shuffle:
|
||||
rng = random.Random(self.random_seed)
|
||||
rng.shuffle(self._rows)
|
||||
self.data = self._rows
|
||||
logger.info(
|
||||
"Loaded Seed-TTS: root=%s locale=%s rows=%d inline_ref_audio=%s",
|
||||
self._root,
|
||||
self.locale,
|
||||
len(self._rows),
|
||||
self.inline_ref_audio,
|
||||
)
|
||||
|
||||
def sample(
|
||||
self,
|
||||
tokenizer: TokenizerLike,
|
||||
num_requests: int,
|
||||
output_len: int | None = None,
|
||||
request_id_prefix: str = "",
|
||||
no_oversample: bool = False,
|
||||
**kwargs: Any,
|
||||
) -> list[SampleRequest]:
|
||||
if output_len is None:
|
||||
output_len = self.DEFAULT_OUTPUT_LEN
|
||||
|
||||
tok = get_cached_tokenizer(tokenizer)
|
||||
out: list[SampleRequest] = []
|
||||
for i, row in enumerate(self._rows):
|
||||
if len(out) >= num_requests:
|
||||
break
|
||||
wav_path = (self._root / self.locale / row.prompt_wav_rel).resolve()
|
||||
if not wav_path.is_file():
|
||||
logger.warning("Missing prompt wav for %s: %s", row.utterance_id, wav_path)
|
||||
continue
|
||||
|
||||
target = row.target_text
|
||||
prompt_len = len(tok.encode(f"{self._system_prompt}\n{target}"))
|
||||
lang = "English" if self.locale == "en" else "Chinese"
|
||||
ref_uri = _ref_audio_payload(wav_path, inline=self.inline_ref_audio)
|
||||
speech_extra: dict[str, Any] = {
|
||||
"ref_audio": ref_uri,
|
||||
"ref_text": row.ref_text,
|
||||
"task_type": "Base",
|
||||
"language": lang,
|
||||
"max_new_tokens": output_len,
|
||||
}
|
||||
|
||||
out.append(
|
||||
SeedTTSSampleRequest(
|
||||
prompt=target,
|
||||
prompt_len=prompt_len,
|
||||
expected_output_len=output_len,
|
||||
multi_modal_data=None,
|
||||
request_id=f"{request_id_prefix}{i}",
|
||||
seed_tts_speech_extra=speech_extra,
|
||||
seed_tts_utterance_id=row.utterance_id,
|
||||
seed_tts_locale=self.locale,
|
||||
seed_tts_system_prompt=self._system_prompt,
|
||||
seed_tts_ref_wav_path=str(wav_path),
|
||||
)
|
||||
)
|
||||
|
||||
logger.info("Seed-TTS: built %d requests (asked %d)", len(out), num_requests)
|
||||
self.maybe_oversample_requests(out, num_requests, request_id_prefix, no_oversample)
|
||||
return out
|
||||
|
||||
|
||||
def load_seed_tts_dataset(
|
||||
dataset_path: str,
|
||||
random_seed: int = 0,
|
||||
locale: str = "en",
|
||||
inline_ref_audio: bool = True,
|
||||
seed_tts_root: str | None = None,
|
||||
system_prompt: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> SeedTTSDataset:
|
||||
return SeedTTSDataset(
|
||||
dataset_path=dataset_path,
|
||||
random_seed=random_seed,
|
||||
locale=locale,
|
||||
inline_ref_audio=inline_ref_audio,
|
||||
seed_tts_root=seed_tts_root,
|
||||
system_prompt=system_prompt,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -0,0 +1,729 @@
|
||||
"""Seed-TTS WER aligned with Bytedance ``seed-tts-eval`` / ``run_wer.py``.
|
||||
|
||||
Matches the published protocol (see Hugging Face dataset card and
|
||||
https://github.com/BytedanceSpeech/seed-tts-eval):
|
||||
|
||||
- **EN**: ``openai/whisper-large-v3`` via ``transformers``, audio resampled to **16 kHz**
|
||||
(same as ``run_wer.py``).
|
||||
- **ZH**: ``funasr`` **paraformer-zh**, hypothesis converted with **zhconv** to zh-cn.
|
||||
- **WER**: ``jiwer`` after punctuation stripping (``zhon.hanzi.punctuation`` + ``string.punctuation``,
|
||||
preserving ``'``) and EN lowercasing / ZH per-character spacing. Supports jiwer 3.x
|
||||
(``compute_measures``) and 4.x (``process_words``).
|
||||
|
||||
- **SIM** (speaker similarity proxy): cosine similarity of L2-normalized mean-pooled **WavLM**
|
||||
embeddings (reference prompt WAV vs. synthesized PCM), 16 kHz. Official ``cal_sim.sh`` uses
|
||||
UniSpeech ``verification_pair_list_v2.py`` with a **fine-tuned** WavLM SV checkpoint — set
|
||||
``SEED_TTS_WAVLM_MODEL`` to another HF id if you need closer parity. Disable with
|
||||
``SEED_TTS_SIM_EVAL=0``. Optional: ``SEED_TTS_SIM_DEVICE`` (e.g. ``cpu``) to avoid GPU
|
||||
issues when Whisper already uses CUDA; ``SEED_TTS_WAVLM_MIN_SAMPLES`` pads very short
|
||||
waveforms so the WavLM CNN front-end does not fail.
|
||||
|
||||
- **UTMOS** (predicted MOS from TorchScript): default ``balacoon/utmos`` → ``utmos.jit``
|
||||
(Sarulab-style demo export). Uses ``torch`` + ``huggingface_hub`` only. Aggregate metrics
|
||||
are over **all requests with captured PCM** (independent of ASR/WER). Non-finite scores are
|
||||
dropped and counted as failures. Override repo/file via ``SEED_TTS_UTMOS_HF_REPO`` /
|
||||
``SEED_TTS_UTMOS_JIT_FILE``. **Device**: defaults to **CPU** when ``SEED_TTS_UTMOS_DEVICE``
|
||||
is unset; set ``SEED_TTS_UTMOS_DEVICE=cuda:0`` (or ``cuda:1`` etc.) to run on GPU. The JIT
|
||||
model is loaded directly onto the target device via ``map_location`` to avoid cross-device
|
||||
issues (some PyTorch builds/Windows have problems moving TorchScript modules after load).
|
||||
Forward uses **float32** waveform in ``[-1, 1]`` (same as the WER resampled array) so
|
||||
tensor dtypes match JIT weights; using int16 triggers
|
||||
``RuntimeError: input type and weight type should be same`` on common exports. Disable
|
||||
with ``SEED_TTS_UTMOS_EVAL=0``.
|
||||
|
||||
Enable with ``SEED_TTS_WER_EVAL=1`` or ``--seed-tts-wer-eval``. Install optional deps::
|
||||
|
||||
pip install 'vllm-omni[seed-tts-eval]'
|
||||
|
||||
Env: ``SEED_TTS_EVAL_DEVICE`` (e.g. ``cuda:0``, ``cpu``); ``SEED_TTS_HF_WHISPER_MODEL``
|
||||
defaults to ``openai/whisper-large-v3`` (override for debugging only).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import statistics
|
||||
import string
|
||||
import tempfile
|
||||
import threading
|
||||
import wave
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from vllm.benchmarks.datasets import SampleRequest
|
||||
|
||||
from vllm_omni.benchmarks.data_modules.seed_tts_dataset import SeedTTSSampleRequest
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Mirrors seed-tts-eval/run_wer.py
|
||||
OFFICIAL_WHISPER_HF_ID = "openai/whisper-large-v3"
|
||||
PARAFORMER_MODEL_ID = "paraformer-zh"
|
||||
|
||||
_lock = threading.Lock()
|
||||
_device: str | None = None
|
||||
_en_processor = None
|
||||
_en_model = None
|
||||
_zh_paraformer = None
|
||||
_wavlm_model = None
|
||||
_wavlm_processor = None
|
||||
_wavlm_device: str | None = None
|
||||
_utmos_jit_model = None
|
||||
_utmos_jit_device: str | None = None
|
||||
_utmos_jit_load_failed = False
|
||||
_utmos_forward_warned = False
|
||||
|
||||
|
||||
def pcm_s16le_mono_to_wav_bytes(pcm: bytes, *, sample_rate: int = 24000) -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with wave.open(buf, "wb") as wf:
|
||||
wf.setnchannels(1)
|
||||
wf.setsampwidth(2)
|
||||
wf.setframerate(sample_rate)
|
||||
wf.writeframes(pcm)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _get_eval_device() -> str:
|
||||
explicit = os.environ.get("SEED_TTS_EVAL_DEVICE", "").strip()
|
||||
if explicit:
|
||||
return explicit
|
||||
try:
|
||||
import torch
|
||||
|
||||
return "cuda:0" if torch.cuda.is_available() else "cpu"
|
||||
except ImportError:
|
||||
return "cpu"
|
||||
|
||||
|
||||
def _punctuation_all() -> str:
|
||||
from zhon.hanzi import punctuation
|
||||
|
||||
return punctuation + string.punctuation
|
||||
|
||||
|
||||
def _jiwer_wer(reference: str, hypothesis: str) -> float:
|
||||
"""Word-level WER; strings are normalized like ``run_wer.process_one``.
|
||||
|
||||
jiwer 4.x removed ``compute_measures`` (``ImportError``); fall back to ``process_words``.
|
||||
"""
|
||||
try:
|
||||
from jiwer import compute_measures
|
||||
|
||||
return float(compute_measures(reference, hypothesis)["wer"])
|
||||
except ImportError:
|
||||
import jiwer
|
||||
|
||||
out = jiwer.process_words(reference, hypothesis)
|
||||
return float(out.wer)
|
||||
|
||||
|
||||
def process_one_official(hypo: str, truth: str, lang: str) -> tuple[float, str, str]:
|
||||
"""Same normalization + ``jiwer`` call as ``run_wer.process_one`` (hypo=ASR, truth=reference)."""
|
||||
raw_truth = truth
|
||||
raw_hypo = hypo
|
||||
truth_n = truth
|
||||
hypo_n = hypo
|
||||
for x in _punctuation_all():
|
||||
if x == "'":
|
||||
continue
|
||||
truth_n = truth_n.replace(x, "")
|
||||
hypo_n = hypo_n.replace(x, "")
|
||||
truth_n = truth_n.replace(" ", " ")
|
||||
hypo_n = hypo_n.replace(" ", " ")
|
||||
if lang == "zh":
|
||||
truth_n = " ".join([x for x in truth_n])
|
||||
hypo_n = " ".join([x for x in hypo_n])
|
||||
elif lang == "en":
|
||||
truth_n = truth_n.lower()
|
||||
hypo_n = hypo_n.lower()
|
||||
else:
|
||||
raise ValueError(f"unsupported lang {lang!r}")
|
||||
wer = _jiwer_wer(truth_n, hypo_n)
|
||||
return wer, raw_truth, raw_hypo
|
||||
|
||||
|
||||
def _pcm_s16le_to_f32_16k(pcm: bytes, pcm_sample_rate: int = 24000) -> np.ndarray:
|
||||
import scipy.signal
|
||||
|
||||
if not pcm:
|
||||
return np.zeros(0, dtype=np.float32)
|
||||
raw = np.frombuffer(pcm, dtype=np.int16).astype(np.float32) / 32768.0
|
||||
target_len = int(len(raw) * 16000 / pcm_sample_rate)
|
||||
if target_len <= 0:
|
||||
return np.zeros(0, dtype=np.float32)
|
||||
return scipy.signal.resample(raw, target_len).astype(np.float32)
|
||||
|
||||
|
||||
def _eval_submetric_enabled(env_name: str, *, default: bool = True) -> bool:
|
||||
raw = os.environ.get(env_name, "").strip().lower()
|
||||
if raw in ("0", "false", "no", "off"):
|
||||
return False
|
||||
if raw in ("1", "true", "yes", "on"):
|
||||
return True
|
||||
return default
|
||||
|
||||
|
||||
def _audio_path_to_f32_16k(path: str) -> np.ndarray:
|
||||
import scipy.signal
|
||||
import soundfile as sf
|
||||
|
||||
data, sr = sf.read(path, dtype="float32", always_2d=True)
|
||||
mono = np.mean(data, axis=1).astype(np.float32)
|
||||
if int(sr) == 16000:
|
||||
return mono
|
||||
target_len = max(1, int(len(mono) * 16000 / int(sr)))
|
||||
return scipy.signal.resample(mono, target_len).astype(np.float32)
|
||||
|
||||
|
||||
def _ensure_wavlm_sim() -> None:
|
||||
global _wavlm_model, _wavlm_processor, _wavlm_device
|
||||
with _lock:
|
||||
if _wavlm_model is not None:
|
||||
return
|
||||
from transformers import AutoFeatureExtractor, AutoModel
|
||||
|
||||
mid = os.environ.get("SEED_TTS_WAVLM_MODEL", "microsoft/wavlm-base-plus").strip() or "microsoft/wavlm-base-plus"
|
||||
_wavlm_device = os.environ.get("SEED_TTS_SIM_DEVICE", "").strip() or _get_eval_device()
|
||||
logger.warning(
|
||||
"Loading WavLM %r on %s for Seed-TTS SIM (embedding cosine; not identical to "
|
||||
"seed-tts-eval UniSpeech SV checkpoint).",
|
||||
mid,
|
||||
_wavlm_device,
|
||||
)
|
||||
_wavlm_processor = AutoFeatureExtractor.from_pretrained(mid)
|
||||
_wavlm_model = AutoModel.from_pretrained(mid).to(_wavlm_device)
|
||||
_wavlm_model.eval()
|
||||
|
||||
|
||||
def _wavlm_prepare_waveform(wav: np.ndarray) -> np.ndarray:
|
||||
"""Trim, pad to a minimum length WavLM/Wav2Vec2 CNN stack accepts, float32 mono."""
|
||||
max_sec = float(os.environ.get("SEED_TTS_WAVLM_MAX_SECONDS", "30"))
|
||||
cap = int(max_sec * 16000)
|
||||
w = np.asarray(wav, dtype=np.float32).reshape(-1)
|
||||
if len(w) == 0:
|
||||
return w
|
||||
if len(w) > cap:
|
||||
w = w[:cap].copy()
|
||||
# Very short clips make the strided conv front-end fail (shape / empty time dim).
|
||||
min_samples = int(os.environ.get("SEED_TTS_WAVLM_MIN_SAMPLES", "4000"))
|
||||
if len(w) < min_samples:
|
||||
w = np.pad(w, (0, min_samples - len(w)), mode="constant")
|
||||
return w
|
||||
|
||||
|
||||
def _wavlm_mean_embedding_f32_16k(wav: np.ndarray) -> np.ndarray | None:
|
||||
import torch
|
||||
|
||||
_ensure_wavlm_sim()
|
||||
w = _wavlm_prepare_waveform(wav)
|
||||
if len(w) == 0:
|
||||
return None
|
||||
assert _wavlm_processor is not None and _wavlm_model is not None and _wavlm_device is not None
|
||||
# Single utterance: avoid padding=True (adds zeros that distort mean pooling). Still pass
|
||||
# attention_mask when the extractor provides it (sample-level; do not mix with hidden length).
|
||||
try:
|
||||
inputs = _wavlm_processor(
|
||||
w,
|
||||
sampling_rate=16000,
|
||||
return_tensors="pt",
|
||||
padding=False,
|
||||
return_attention_mask=True,
|
||||
)
|
||||
except TypeError:
|
||||
inputs = _wavlm_processor(
|
||||
w,
|
||||
sampling_rate=16000,
|
||||
return_tensors="pt",
|
||||
padding=False,
|
||||
)
|
||||
iv = inputs["input_values"].to(_wavlm_device)
|
||||
am = inputs.get("attention_mask")
|
||||
if am is not None:
|
||||
am = am.to(_wavlm_device)
|
||||
with torch.inference_mode():
|
||||
out = _wavlm_model(iv, attention_mask=am)
|
||||
h = out.last_hidden_state
|
||||
v = h.mean(dim=1).squeeze(0).float().cpu().numpy()
|
||||
n = float(np.linalg.norm(v))
|
||||
if not np.isfinite(n) or n < 1e-8:
|
||||
return None
|
||||
return (v / n).astype(np.float32)
|
||||
|
||||
|
||||
def _cosine_similarity_unit_vectors(a: np.ndarray, b: np.ndarray) -> float:
|
||||
return float(np.dot(a, b))
|
||||
|
||||
|
||||
def _ensure_utmos_jit_model() -> Any | None:
|
||||
"""Load UTMOS as TorchScript (``balacoon/utmos`` style): no ``import utmos`` / fairseq."""
|
||||
global _utmos_jit_model, _utmos_jit_device, _utmos_jit_load_failed
|
||||
with _lock:
|
||||
if _utmos_jit_load_failed:
|
||||
return None
|
||||
if _utmos_jit_model is not None:
|
||||
return _utmos_jit_model
|
||||
try:
|
||||
import torch
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
repo = os.environ.get("SEED_TTS_UTMOS_HF_REPO", "balacoon/utmos").strip() or "balacoon/utmos"
|
||||
fname = os.environ.get("SEED_TTS_UTMOS_JIT_FILE", "utmos.jit").strip() or "utmos.jit"
|
||||
logger.warning(
|
||||
"Loading UTMOS TorchScript from Hugging Face %r file %r (one-time download/cache)...",
|
||||
repo,
|
||||
fname,
|
||||
)
|
||||
path = hf_hub_download(repo_id=repo, filename=fname, repo_type="model")
|
||||
|
||||
# TODO The model weights in UTMOS must be loaded in cuda:0; otherwise, the model execution will fail.
|
||||
want = "cuda:0"
|
||||
if want.startswith("cuda") and torch.cuda.is_available():
|
||||
idx = want.split(":")[-1] if ":" in want else "0"
|
||||
target_dev = f"cuda:{idx}"
|
||||
else:
|
||||
target_dev = "cpu"
|
||||
|
||||
try:
|
||||
m = torch.jit.load(path, map_location=target_dev)
|
||||
m.eval()
|
||||
_utmos_jit_device = target_dev
|
||||
except Exception as load_e:
|
||||
if target_dev.startswith("cuda"):
|
||||
logger.warning(
|
||||
"UTMOS JIT load on %s failed (%s), retrying on CPU...",
|
||||
target_dev,
|
||||
load_e,
|
||||
)
|
||||
m = torch.jit.load(path, map_location="cpu")
|
||||
m.eval()
|
||||
_utmos_jit_device = "cpu"
|
||||
else:
|
||||
raise
|
||||
_utmos_jit_model = m
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"UTMOS JIT unavailable (install torch + huggingface_hub; check HF access): %s",
|
||||
e,
|
||||
)
|
||||
_utmos_jit_load_failed = True
|
||||
return None
|
||||
return _utmos_jit_model
|
||||
|
||||
|
||||
def _utmos_predict_f32_16k(wav_f32: np.ndarray) -> float | None:
|
||||
"""MOS from JIT model; input is float32 mono @ 16 kHz in ``[-1, 1]`` (WER pipeline).
|
||||
|
||||
``balacoon/utmos`` demos sometimes use int16 numpy, but the exported ``.jit`` weights are
|
||||
float32; passing int16 tensors causes: "RuntimeError: ... input type and weight type
|
||||
should be same".
|
||||
"""
|
||||
import torch
|
||||
|
||||
if len(wav_f32) == 0:
|
||||
return None
|
||||
model = _ensure_utmos_jit_model()
|
||||
if model is None:
|
||||
return None
|
||||
# Infer model's device from its first parameter/buffer to guarantee input sits with weights.
|
||||
try:
|
||||
model_dev = next(model.parameters()).device
|
||||
except StopIteration:
|
||||
try:
|
||||
model_dev = next(model.buffers()).device
|
||||
except StopIteration:
|
||||
model_dev = torch.device("cpu")
|
||||
w = np.ascontiguousarray(wav_f32, dtype=np.float32)
|
||||
x = torch.from_numpy(w).unsqueeze(0).to(device=model_dev, dtype=torch.float32)
|
||||
with torch.no_grad():
|
||||
out = model(x)
|
||||
val = float(out.reshape(-1)[0].item())
|
||||
if not math.isfinite(val):
|
||||
return None
|
||||
return val
|
||||
|
||||
|
||||
def _ensure_en_asr() -> None:
|
||||
global _en_processor, _en_model, _device
|
||||
with _lock:
|
||||
if _en_processor is not None:
|
||||
return
|
||||
from transformers import WhisperForConditionalGeneration, WhisperProcessor
|
||||
|
||||
_device = _get_eval_device()
|
||||
mid = os.environ.get("SEED_TTS_HF_WHISPER_MODEL", OFFICIAL_WHISPER_HF_ID).strip() or OFFICIAL_WHISPER_HF_ID
|
||||
logger.warning(
|
||||
"Loading Seed-TTS eval Whisper HF model %r on %s (one-time, seed-tts-eval protocol)...",
|
||||
mid,
|
||||
_device,
|
||||
)
|
||||
_en_processor = WhisperProcessor.from_pretrained(mid)
|
||||
_en_model = WhisperForConditionalGeneration.from_pretrained(mid).to(_device)
|
||||
_en_model.eval()
|
||||
|
||||
|
||||
def _ensure_zh_asr() -> None:
|
||||
global _zh_paraformer, _device
|
||||
with _lock:
|
||||
if _zh_paraformer is not None:
|
||||
return
|
||||
from funasr import AutoModel
|
||||
|
||||
_device = _get_eval_device()
|
||||
logger.warning(
|
||||
"Loading Seed-TTS eval Paraformer %r on %s (one-time, seed-tts-eval protocol)...",
|
||||
PARAFORMER_MODEL_ID,
|
||||
_device,
|
||||
)
|
||||
try:
|
||||
_zh_paraformer = AutoModel(model=PARAFORMER_MODEL_ID, device=_device)
|
||||
except TypeError:
|
||||
_zh_paraformer = AutoModel(model=PARAFORMER_MODEL_ID)
|
||||
|
||||
|
||||
def _transcribe_en_f32_16k(wav_f32: np.ndarray) -> str:
|
||||
import torch
|
||||
|
||||
_ensure_en_asr()
|
||||
if len(wav_f32) == 0:
|
||||
return ""
|
||||
with _lock:
|
||||
assert _en_processor is not None and _en_model is not None and _device is not None
|
||||
inputs = _en_processor(wav_f32, sampling_rate=16000, return_tensors="pt")
|
||||
input_features = inputs.input_features.to(_device)
|
||||
with torch.no_grad():
|
||||
try:
|
||||
forced = _en_processor.get_decoder_prompt_ids(language="english", task="transcribe")
|
||||
predicted_ids = _en_model.generate(input_features, forced_decoder_ids=forced)
|
||||
except Exception:
|
||||
predicted_ids = _en_model.generate(
|
||||
input_features,
|
||||
language="english",
|
||||
task="transcribe",
|
||||
)
|
||||
text = _en_processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
|
||||
return (text or "").strip()
|
||||
|
||||
|
||||
def _transcribe_zh_wav_path(wav_path: str) -> str:
|
||||
import zhconv
|
||||
|
||||
_ensure_zh_asr()
|
||||
with _lock:
|
||||
assert _zh_paraformer is not None
|
||||
res = _zh_paraformer.generate(input=wav_path, batch_size_s=300)
|
||||
transcription = res[0]["text"] if res else ""
|
||||
return zhconv.convert(transcription, "zh-cn").strip()
|
||||
|
||||
|
||||
def _missing_deps_message(lang: str) -> str | None:
|
||||
try:
|
||||
import jiwer # noqa: F401
|
||||
from zhon.hanzi import punctuation # noqa: F401
|
||||
except ImportError as e:
|
||||
return f"Seed-TTS WER eval needs jiwer and zhon ({e!s}). Install: pip install 'vllm-omni[seed-tts-eval]'"
|
||||
try:
|
||||
import scipy.signal # noqa: F401
|
||||
import soundfile # noqa: F401
|
||||
except ImportError as e:
|
||||
return f"Seed-TTS WER eval needs scipy and soundfile ({e!s})."
|
||||
if lang == "en":
|
||||
try:
|
||||
import torch # noqa: F401
|
||||
from transformers import WhisperForConditionalGeneration # noqa: F401
|
||||
except ImportError as e:
|
||||
return f"English WER needs torch and transformers ({e!s}). Install: pip install 'vllm-omni[seed-tts-eval]'"
|
||||
else:
|
||||
try:
|
||||
import zhconv # noqa: F401
|
||||
from funasr import AutoModel # noqa: F401
|
||||
except ImportError as e:
|
||||
return f"Chinese WER needs funasr and zhconv ({e!s}). Install: pip install 'vllm-omni[seed-tts-eval]'"
|
||||
return None
|
||||
|
||||
|
||||
def compute_seed_tts_wer_metrics(
|
||||
input_requests: list[SampleRequest],
|
||||
outputs: list[Any],
|
||||
*,
|
||||
include_per_item: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""If all requests are :class:`SeedTTSSampleRequest`, run seed-tts-eval-style WER."""
|
||||
global _utmos_forward_warned
|
||||
if not input_requests or len(input_requests) != len(outputs):
|
||||
return None
|
||||
if not all(isinstance(r, SeedTTSSampleRequest) for r in input_requests):
|
||||
return None
|
||||
|
||||
first = input_requests[0]
|
||||
assert isinstance(first, SeedTTSSampleRequest)
|
||||
lang = "zh" if (first.seed_tts_locale or "en").lower().startswith("zh") else "en"
|
||||
|
||||
setup_err = _missing_deps_message(lang)
|
||||
if setup_err:
|
||||
logger.error("%s", setup_err)
|
||||
return {
|
||||
"seed_tts_eval_setup_error": setup_err,
|
||||
"seed_tts_eval_protocol": "seed-tts-eval",
|
||||
"seed_tts_content_evaluated": 0,
|
||||
"seed_tts_content_error_mean": None,
|
||||
"seed_tts_content_error_median": None,
|
||||
"seed_tts_request_failed": 0,
|
||||
"seed_tts_no_pcm": 0,
|
||||
"seed_tts_asr_failed": 0,
|
||||
"seed_tts_content_metric": "wer",
|
||||
}
|
||||
|
||||
import soundfile as sf
|
||||
|
||||
errs: list[float] = []
|
||||
items: list[dict[str, Any]] = []
|
||||
asr_failed = 0
|
||||
no_pcm = 0
|
||||
request_failed = 0
|
||||
sim_values: list[float] = []
|
||||
utmos_values: list[float] = []
|
||||
sim_failed = 0
|
||||
sim_skipped_no_ref = 0
|
||||
utmos_failed = 0
|
||||
utmos_on = _eval_submetric_enabled("SEED_TTS_UTMOS_EVAL", default=True)
|
||||
|
||||
for req, out in zip(input_requests, outputs, strict=True):
|
||||
assert isinstance(req, SeedTTSSampleRequest)
|
||||
ref = req.prompt
|
||||
locale = req.seed_tts_locale or "en"
|
||||
row_lang = "zh" if locale.lower().startswith("zh") else "en"
|
||||
utmos_v: float | None = None
|
||||
|
||||
if not out.success:
|
||||
request_failed += 1
|
||||
if include_per_item:
|
||||
items.append(
|
||||
{
|
||||
"utterance_id": req.seed_tts_utterance_id,
|
||||
"locale": locale,
|
||||
"error": "request_failed",
|
||||
"detail": (out.error or "")[:500],
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
pcm = getattr(out, "tts_output_pcm_bytes", None)
|
||||
if not pcm:
|
||||
no_pcm += 1
|
||||
if include_per_item:
|
||||
items.append(
|
||||
{
|
||||
"utterance_id": req.seed_tts_utterance_id,
|
||||
"locale": locale,
|
||||
"error": "no_pcm",
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
wav_16k = _pcm_s16le_to_f32_16k(pcm)
|
||||
if len(wav_16k) == 0:
|
||||
asr_failed += 1
|
||||
if include_per_item:
|
||||
items.append(
|
||||
{
|
||||
"utterance_id": req.seed_tts_utterance_id,
|
||||
"locale": locale,
|
||||
"error": "empty_audio",
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
# UTMOS scores synthesized audio only; do not gate on ASR/WER (those can fail independently).
|
||||
if utmos_on:
|
||||
try:
|
||||
utmos_v = _utmos_predict_f32_16k(wav_16k)
|
||||
if utmos_v is not None:
|
||||
utmos_values.append(utmos_v)
|
||||
elif not _utmos_jit_load_failed:
|
||||
utmos_failed += 1
|
||||
except Exception:
|
||||
if not _utmos_forward_warned:
|
||||
_utmos_forward_warned = True
|
||||
logger.warning(
|
||||
"UTMOS JIT forward failed (first utterance=%s; set logging DEBUG for "
|
||||
"full trace). Check sample rate (16 kHz), input shape, or "
|
||||
"SEED_TTS_UTMOS_DEVICE.",
|
||||
req.seed_tts_utterance_id,
|
||||
exc_info=True,
|
||||
)
|
||||
else:
|
||||
logger.debug(
|
||||
"UTMOS forward failed for %s",
|
||||
req.seed_tts_utterance_id,
|
||||
exc_info=True,
|
||||
)
|
||||
utmos_failed += 1
|
||||
|
||||
try:
|
||||
if row_lang == "en":
|
||||
hyp = _transcribe_en_f32_16k(wav_16k)
|
||||
else:
|
||||
fd, tmp_wav = tempfile.mkstemp(suffix=".wav")
|
||||
os.close(fd)
|
||||
try:
|
||||
sf.write(tmp_wav, wav_16k, 16000, subtype="PCM_16")
|
||||
hyp = _transcribe_zh_wav_path(tmp_wav)
|
||||
finally:
|
||||
try:
|
||||
os.unlink(tmp_wav)
|
||||
except OSError:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.exception("Seed-TTS ASR failed for %s", req.seed_tts_utterance_id)
|
||||
asr_failed += 1
|
||||
if include_per_item:
|
||||
items.append(
|
||||
{
|
||||
"utterance_id": req.seed_tts_utterance_id,
|
||||
"locale": locale,
|
||||
"error": "asr_exception",
|
||||
"detail": str(e)[:500],
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
if not hyp:
|
||||
asr_failed += 1
|
||||
if include_per_item:
|
||||
items.append(
|
||||
{
|
||||
"utterance_id": req.seed_tts_utterance_id,
|
||||
"locale": locale,
|
||||
"error": "empty_asr",
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
try:
|
||||
wer, raw_truth, raw_hypo = process_one_official(hyp, ref, row_lang)
|
||||
except Exception as e:
|
||||
logger.warning("jiwer/normalize failed for %s: %s", req.seed_tts_utterance_id, e)
|
||||
asr_failed += 1
|
||||
if include_per_item:
|
||||
items.append(
|
||||
{
|
||||
"utterance_id": req.seed_tts_utterance_id,
|
||||
"locale": locale,
|
||||
"error": "wer_compute_failed",
|
||||
"detail": str(e)[:500],
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
errs.append(wer)
|
||||
sim_v: float | None = None
|
||||
|
||||
if _eval_submetric_enabled("SEED_TTS_SIM_EVAL", default=True):
|
||||
ref_path = getattr(req, "seed_tts_ref_wav_path", "") or ""
|
||||
if ref_path and os.path.isfile(ref_path):
|
||||
try:
|
||||
ref_wav = _audio_path_to_f32_16k(ref_path)
|
||||
e_ref = _wavlm_mean_embedding_f32_16k(ref_wav)
|
||||
e_hyp = _wavlm_mean_embedding_f32_16k(wav_16k)
|
||||
if e_ref is not None and e_hyp is not None:
|
||||
sim_v = _cosine_similarity_unit_vectors(e_ref, e_hyp)
|
||||
sim_values.append(sim_v)
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"SIM embedding failed for utterance=%s: %s: %s",
|
||||
req.seed_tts_utterance_id,
|
||||
type(e).__name__,
|
||||
e,
|
||||
)
|
||||
sim_failed += 1
|
||||
else:
|
||||
sim_skipped_no_ref += 1
|
||||
|
||||
if include_per_item:
|
||||
row: dict[str, Any] = {
|
||||
"utterance_id": req.seed_tts_utterance_id,
|
||||
"locale": locale,
|
||||
"wer": wer,
|
||||
"reference_raw": raw_truth,
|
||||
"asr_raw": raw_hypo,
|
||||
}
|
||||
if sim_v is not None:
|
||||
row["sim"] = sim_v
|
||||
if utmos_v is not None:
|
||||
row["utmos"] = utmos_v
|
||||
items.append(row)
|
||||
|
||||
result: dict[str, Any] = {
|
||||
"seed_tts_eval_protocol": "seed-tts-eval",
|
||||
"seed_tts_content_evaluated": len(errs),
|
||||
"seed_tts_content_error_mean": statistics.fmean(errs) if errs else None,
|
||||
"seed_tts_content_error_median": statistics.median(errs) if errs else None,
|
||||
"seed_tts_request_failed": request_failed,
|
||||
"seed_tts_no_pcm": no_pcm,
|
||||
"seed_tts_asr_failed": asr_failed,
|
||||
"seed_tts_content_metric": "wer",
|
||||
"seed_tts_sim_evaluated": len(sim_values),
|
||||
"seed_tts_sim_mean": statistics.fmean(sim_values) if sim_values else None,
|
||||
"seed_tts_sim_median": statistics.median(sim_values) if sim_values else None,
|
||||
"seed_tts_sim_failed": sim_failed,
|
||||
"seed_tts_sim_skipped_no_ref": sim_skipped_no_ref,
|
||||
"seed_tts_utmos_evaluated": len(utmos_values),
|
||||
"seed_tts_utmos_mean": statistics.fmean(utmos_values) if utmos_values else None,
|
||||
"seed_tts_utmos_median": statistics.median(utmos_values) if utmos_values else None,
|
||||
"seed_tts_utmos_failed": utmos_failed,
|
||||
}
|
||||
if include_per_item:
|
||||
result["seed_tts_wer_eval_items"] = items
|
||||
return result
|
||||
|
||||
|
||||
def print_seed_tts_wer_summary(metrics: dict[str, Any]) -> None:
|
||||
setup = metrics.get("seed_tts_eval_setup_error")
|
||||
if setup:
|
||||
print("{s:{c}^{n}}".format(s=" Seed-TTS eval (seed-tts-eval protocol) ", n=50, c="="))
|
||||
print(setup)
|
||||
return
|
||||
|
||||
ev = int(metrics.get("seed_tts_content_evaluated", 0) or 0)
|
||||
rf = int(metrics.get("seed_tts_request_failed", 0) or 0)
|
||||
npc = int(metrics.get("seed_tts_no_pcm", 0) or 0)
|
||||
af = int(metrics.get("seed_tts_asr_failed", 0) or 0)
|
||||
sim_ev = int(metrics.get("seed_tts_sim_evaluated", 0) or 0)
|
||||
ut_ev = int(metrics.get("seed_tts_utmos_evaluated", 0) or 0)
|
||||
if ev == 0 and rf == 0 and npc == 0 and af == 0 and sim_ev == 0 and ut_ev == 0:
|
||||
return
|
||||
print("{s:{c}^{n}}".format(s=" Seed-TTS eval (seed-tts-eval protocol) ", n=50, c="="))
|
||||
print("{:<40} {:<10}".format("Evaluated (WER, lower is better):", ev))
|
||||
mean = metrics.get("seed_tts_content_error_mean")
|
||||
if mean is not None:
|
||||
print("{:<40} {:<10.4f}".format("Mean WER:", float(mean)))
|
||||
med = metrics.get("seed_tts_content_error_median")
|
||||
if med is not None:
|
||||
print("{:<40} {:<10.4f}".format("Median WER:", float(med)))
|
||||
print("{:<40} {:<10}".format("Request failed:", metrics.get("seed_tts_request_failed", 0)))
|
||||
print("{:<40} {:<10}".format("No PCM captured:", metrics.get("seed_tts_no_pcm", 0)))
|
||||
print("{:<40} {:<10}".format("ASR / WER failed:", metrics.get("seed_tts_asr_failed", 0)))
|
||||
if sim_ev or metrics.get("seed_tts_sim_skipped_no_ref") or metrics.get("seed_tts_sim_failed"):
|
||||
print("{:<40} {:<10}".format("SIM evaluated (higher ~ closer):", sim_ev))
|
||||
sm = metrics.get("seed_tts_sim_mean")
|
||||
if sm is not None:
|
||||
print("{:<40} {:<10.4f}".format("Mean SIM:", float(sm)))
|
||||
s_med = metrics.get("seed_tts_sim_median")
|
||||
if s_med is not None:
|
||||
print("{:<40} {:<10.4f}".format("Median SIM:", float(s_med)))
|
||||
print("{:<40} {:<10}".format("SIM skipped (no ref path):", metrics.get("seed_tts_sim_skipped_no_ref", 0)))
|
||||
print("{:<40} {:<10}".format("SIM embedding errors:", metrics.get("seed_tts_sim_failed", 0)))
|
||||
if ut_ev or metrics.get("seed_tts_utmos_failed"):
|
||||
print("{:<40} {:<10}".format("UTMOS evaluated (JIT MOS, higher better):", ut_ev))
|
||||
um = metrics.get("seed_tts_utmos_mean")
|
||||
if um is not None:
|
||||
print("{:<40} {:<10.4f}".format("Mean UTMOS:", float(um)))
|
||||
u_med = metrics.get("seed_tts_utmos_median")
|
||||
if u_med is not None:
|
||||
print("{:<40} {:<10.4f}".format("Median UTMOS:", float(u_med)))
|
||||
print("{:<40} {:<10}".format("UTMOS errors:", metrics.get("seed_tts_utmos_failed", 0)))
|
||||
print("=" * 50)
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Omni benchmark monkey-patches (side effects in ``patch.patch``)."""
|
||||
|
||||
from . import patch as _patch_module # noqa: F401
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
import os
|
||||
import random
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from collections.abc import Iterable
|
||||
@@ -33,15 +34,245 @@ from vllm.logger import init_logger
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
from vllm_omni.benchmarks.data_modules.daily_omni_dataset import DailyOmniDataset, DailyOmniSampleRequest
|
||||
from vllm_omni.benchmarks.data_modules.random_multi_modal_dataset import OmniRandomMultiModalDataset
|
||||
from vllm_omni.benchmarks.data_modules.seed_tts_dataset import (
|
||||
SEED_TTS_DEFAULT_OMNI_SYSTEM_PROMPT,
|
||||
SeedTTSDataset,
|
||||
SeedTTSSampleRequest,
|
||||
)
|
||||
|
||||
get_samples_old = datasets.get_samples
|
||||
|
||||
_DEFAULT_DAILY_OMNI_REPO = "liarliar/Daily-Omni"
|
||||
|
||||
|
||||
def _seed_tts_capture_pcm_for_wer() -> bool:
|
||||
return os.environ.get("SEED_TTS_WER_EVAL", "").lower() in (
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
)
|
||||
|
||||
|
||||
def _merge_extra_body_mm_kwargs(base: dict | None, overlay: dict | None) -> dict | None:
|
||||
"""Shallow-merge ``extra_body`` dicts; deep-merge ``mm_processor_kwargs`` if both set."""
|
||||
if not base and not overlay:
|
||||
return None
|
||||
out = dict(base or {})
|
||||
if not overlay:
|
||||
return out
|
||||
for k, v in overlay.items():
|
||||
if k == "mm_processor_kwargs" and isinstance(v, dict):
|
||||
prev = out.get("mm_processor_kwargs")
|
||||
merged_kw = {**(prev if isinstance(prev, dict) else {}), **v}
|
||||
out["mm_processor_kwargs"] = merged_kw
|
||||
else:
|
||||
out[k] = v
|
||||
return out
|
||||
|
||||
|
||||
def _attach_daily_omni_to_request_func_input(sample: SampleRequest, rfi: RequestFuncInput) -> None:
|
||||
"""Apply per-request OpenAI fields (``mm_processor_kwargs``, messages) for Daily-Omni."""
|
||||
if not isinstance(sample, DailyOmniSampleRequest):
|
||||
return
|
||||
rfi.extra_body = _merge_extra_body_mm_kwargs(rfi.extra_body, sample.omni_extra_body)
|
||||
if sample.omni_chat_messages is not None:
|
||||
setattr(rfi, "omni_chat_messages", sample.omni_chat_messages)
|
||||
else:
|
||||
setattr(rfi, "mm_position", sample.omni_chat_mm_position)
|
||||
|
||||
|
||||
def _attach_seed_tts_to_request_func_input(sample: SampleRequest, rfi: RequestFuncInput) -> None:
|
||||
"""Merge Seed-TTS per-row TTS fields (ref_audio, ref_text, task_type, …) into ``extra_body``.
|
||||
|
||||
Used by both ``/v1/audio/speech`` and ``/v1/chat/completions`` (flattened into JSON body).
|
||||
For ``openai-chat-omni``, also sets ``omni_chat_messages`` (system + user) so Qwen3-Omni
|
||||
follows the same role layout as official TTS / multimodal demos. ``/v1/audio/speech`` ignores
|
||||
``messages`` and only uses ``input`` + body fields.
|
||||
Flags ``openai-chat-omni`` to request audio output and optionally export PCM for WER.
|
||||
"""
|
||||
if not isinstance(sample, SeedTTSSampleRequest):
|
||||
return
|
||||
ex = sample.seed_tts_speech_extra
|
||||
if not ex:
|
||||
return
|
||||
base = dict(rfi.extra_body) if rfi.extra_body else {}
|
||||
base.update(ex)
|
||||
rfi.extra_body = base
|
||||
# Used by request funcs to force streaming TTS behavior and to export PCM when WER is on.
|
||||
setattr(rfi, "seed_tts_row", True)
|
||||
sys_prompt = (sample.seed_tts_system_prompt or "").strip() or SEED_TTS_DEFAULT_OMNI_SYSTEM_PROMPT
|
||||
setattr(
|
||||
rfi,
|
||||
"omni_chat_messages",
|
||||
[
|
||||
{"role": "system", "content": [{"type": "text", "text": sys_prompt}]},
|
||||
{"role": "user", "content": [{"type": "text", "text": sample.prompt}]},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _daily_omni_repo_from_args(args) -> str | None:
|
||||
"""Resolve HuggingFace repo id for Daily-Omni from CLI args.
|
||||
|
||||
vLLM allows ``--dataset-path`` to be a local path while the real HF id is
|
||||
passed via ``--hf-name``. Upstream ``get_samples`` for ``hf`` only matches
|
||||
a fixed elif-chain and never discovers Omni's loader, so we must detect
|
||||
Daily-Omni here using either field.
|
||||
"""
|
||||
dp = getattr(args, "dataset_path", None)
|
||||
hn = getattr(args, "hf_name", None)
|
||||
if dp in DailyOmniDataset.SUPPORTED_DATASET_PATHS:
|
||||
return dp
|
||||
if hn in DailyOmniDataset.SUPPORTED_DATASET_PATHS:
|
||||
return hn
|
||||
return None
|
||||
|
||||
|
||||
def get_samples(args, tokenizer):
|
||||
if args.backend not in ["openai-chat-omni", "openai-audio-speech"]:
|
||||
# Daily-Omni: explicit dataset name, or hf + matching path/hf-name
|
||||
is_daily_omni = args.dataset_name == "daily-omni" or (
|
||||
args.dataset_name == "hf" and _daily_omni_repo_from_args(args) is not None
|
||||
)
|
||||
is_seed_tts = args.dataset_name == "seed-tts"
|
||||
|
||||
# Check if we need to handle omni-related backends/datasets
|
||||
is_omni_backend = args.backend in ["openai-chat-omni", "openai-audio-speech", "daily-omni"]
|
||||
is_omni_dataset = is_daily_omni or is_seed_tts or args.dataset_name == "random-mm"
|
||||
|
||||
if not is_omni_backend and not is_omni_dataset:
|
||||
# Not an omni-related request, delegate to original implementation
|
||||
return get_samples_old(args, tokenizer)
|
||||
elif args.dataset_name == "random-mm":
|
||||
|
||||
# Handle Daily-Omni dataset
|
||||
if is_daily_omni:
|
||||
# Support:
|
||||
# --dataset-name daily-omni [--dataset-path liarliar/Daily-Omni]
|
||||
# --dataset-name daily-omni --daily-omni-qa-json /path/to/qa.json (offline QA)
|
||||
# --dataset-name hf --dataset-path liarliar/Daily-Omni
|
||||
# --dataset-name hf --hf-name liarliar/Daily-Omni (dataset-path may be local)
|
||||
|
||||
# Validate backend supports multimodal (video)
|
||||
if args.backend not in ["openai-chat-omni", "daily-omni"]:
|
||||
raise ValueError(
|
||||
f"Daily-Omni dataset requires a multimodal backend that supports video. "
|
||||
f"Got backend='{args.backend}'. Please use '--backend openai-chat-omni'"
|
||||
)
|
||||
|
||||
# Determine video directory if specified (for local video files)
|
||||
video_dir = getattr(args, "daily_omni_video_dir", None)
|
||||
|
||||
# Get HF split (default to "train"; unused when loading from local qa.json)
|
||||
dataset_split = getattr(args, "hf_split", None) or "train"
|
||||
|
||||
qa_json = getattr(args, "daily_omni_qa_json", None)
|
||||
if isinstance(qa_json, str):
|
||||
qa_json = qa_json.strip() or None
|
||||
|
||||
if qa_json is not None:
|
||||
logger.info(
|
||||
"Loading Daily-Omni dataset: qa_json=%s, video_dir=%s (Hub not used for QA)",
|
||||
qa_json,
|
||||
video_dir,
|
||||
)
|
||||
dataset = DailyOmniDataset(
|
||||
qa_json_path=qa_json,
|
||||
dataset_path=None,
|
||||
dataset_split=dataset_split,
|
||||
random_seed=args.seed,
|
||||
video_dir=video_dir,
|
||||
input_mode=getattr(args, "daily_omni_input_mode", "all"),
|
||||
inline_local_video=getattr(args, "daily_omni_inline_local_video", False),
|
||||
trust_remote_code=getattr(args, "trust_remote_code", False),
|
||||
disable_shuffle=getattr(args, "disable_shuffle", False),
|
||||
)
|
||||
else:
|
||||
repo_id = _daily_omni_repo_from_args(args)
|
||||
if args.dataset_name == "daily-omni":
|
||||
if repo_id is None:
|
||||
repo_id = _DEFAULT_DAILY_OMNI_REPO
|
||||
elif repo_id is None:
|
||||
raise ValueError(
|
||||
"Daily-Omni with --dataset-name hf requires "
|
||||
f"--dataset-path {_DEFAULT_DAILY_OMNI_REPO} or "
|
||||
f"--hf-name {_DEFAULT_DAILY_OMNI_REPO}."
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Loading Daily-Omni dataset: hf_repo=%s, split=%s, video_dir=%s",
|
||||
repo_id,
|
||||
dataset_split,
|
||||
video_dir,
|
||||
)
|
||||
|
||||
dataset = DailyOmniDataset(
|
||||
dataset_path=repo_id,
|
||||
dataset_split=dataset_split,
|
||||
dataset_subset=getattr(args, "hf_subset", None),
|
||||
random_seed=args.seed,
|
||||
video_dir=video_dir,
|
||||
input_mode=getattr(args, "daily_omni_input_mode", "all"),
|
||||
inline_local_video=getattr(args, "daily_omni_inline_local_video", False),
|
||||
trust_remote_code=getattr(args, "trust_remote_code", False),
|
||||
no_stream=getattr(args, "no_stream", False),
|
||||
disable_shuffle=getattr(args, "disable_shuffle", False),
|
||||
)
|
||||
|
||||
out_len = getattr(args, "output_len", None)
|
||||
if out_len is None:
|
||||
out_len = getattr(args, "hf_output_len", None)
|
||||
if out_len is None:
|
||||
out_len = DailyOmniDataset.DEFAULT_OUTPUT_LEN
|
||||
|
||||
input_requests = dataset.sample(
|
||||
tokenizer=tokenizer,
|
||||
num_requests=args.num_prompts,
|
||||
output_len=out_len,
|
||||
request_id_prefix=args.request_id_prefix,
|
||||
no_oversample=args.no_oversample,
|
||||
)
|
||||
return input_requests
|
||||
|
||||
if is_seed_tts:
|
||||
if args.backend not in ("openai-audio-speech", "openai-chat-omni"):
|
||||
raise ValueError(
|
||||
"Seed-TTS requires --backend openai-audio-speech (POST /v1/audio/speech) or "
|
||||
"--backend openai-chat-omni (POST /v1/chat/completions with ref_audio/ref_text). "
|
||||
f"Got backend={args.backend!r}."
|
||||
)
|
||||
repo_id = getattr(args, "dataset_path", None) or getattr(args, "hf_name", None)
|
||||
if not repo_id:
|
||||
raise ValueError(
|
||||
"Seed-TTS requires --dataset-path (HF dataset repo id or local directory) or "
|
||||
"--hf-name for the Hub dataset id."
|
||||
)
|
||||
|
||||
dataset = SeedTTSDataset(
|
||||
dataset_path=repo_id,
|
||||
random_seed=args.seed,
|
||||
locale=getattr(args, "seed_tts_locale", "en"),
|
||||
inline_ref_audio=not getattr(args, "seed_tts_file_ref_audio", False),
|
||||
seed_tts_root=getattr(args, "seed_tts_root", None),
|
||||
system_prompt=getattr(args, "seed_tts_system_prompt", None),
|
||||
disable_shuffle=getattr(args, "disable_shuffle", False),
|
||||
)
|
||||
out_len = getattr(args, "output_len", None)
|
||||
if out_len is None:
|
||||
out_len = getattr(args, "hf_output_len", None)
|
||||
if out_len is None:
|
||||
out_len = SeedTTSDataset.DEFAULT_OUTPUT_LEN
|
||||
return dataset.sample(
|
||||
tokenizer=tokenizer,
|
||||
num_requests=args.num_prompts,
|
||||
output_len=out_len,
|
||||
request_id_prefix=args.request_id_prefix,
|
||||
no_oversample=args.no_oversample,
|
||||
)
|
||||
|
||||
# Handle random-mm dataset (Omni's synthetic multimodal dataset)
|
||||
if args.dataset_name == "random-mm":
|
||||
dataset = OmniRandomMultiModalDataset(random_seed=args.seed, dataset_path=args.dataset_path)
|
||||
input_requests = dataset.sample(
|
||||
tokenizer=tokenizer,
|
||||
@@ -64,6 +295,10 @@ def get_samples(args, tokenizer):
|
||||
|
||||
datasets.get_samples = get_samples
|
||||
|
||||
_serve_mod = sys.modules.get("vllm.benchmarks.serve")
|
||||
if _serve_mod is not None:
|
||||
_serve_mod.get_samples = get_samples
|
||||
|
||||
|
||||
@dataclass
|
||||
class MixRequestFuncOutput(RequestFuncOutput):
|
||||
@@ -72,6 +307,9 @@ class MixRequestFuncOutput(RequestFuncOutput):
|
||||
audio_frames: int = 0
|
||||
audio_rtf: float = 0.0
|
||||
text_latency: float = 0.0
|
||||
#: Raw PCM s16le mono at 24 kHz for Seed-TTS WER: from ``/v1/audio/speech`` stream or
|
||||
#: resampled export after ``openai-chat-omni`` audio deltas.
|
||||
tts_output_pcm_bytes: bytes | None = None
|
||||
|
||||
|
||||
async def async_request_openai_chat_omni_completions(
|
||||
@@ -83,13 +321,17 @@ async def async_request_openai_chat_omni_completions(
|
||||
api_url = request_func_input.api_url
|
||||
_validate_api_url(api_url, "OpenAI Chat Completions API", "chat/completions")
|
||||
|
||||
content = _get_chat_content(request_func_input, mm_position=mm_position)
|
||||
omni_messages = getattr(request_func_input, "omni_chat_messages", None)
|
||||
if omni_messages is not None:
|
||||
messages_payload = omni_messages
|
||||
else:
|
||||
effective_mm_position = getattr(request_func_input, "mm_position", mm_position)
|
||||
content = _get_chat_content(request_func_input, mm_position=effective_mm_position)
|
||||
messages_payload = [{"role": "user", "content": content}]
|
||||
|
||||
payload = {
|
||||
"model": request_func_input.model_name if request_func_input.model_name else request_func_input.model,
|
||||
"messages": [
|
||||
{"role": "user", "content": content},
|
||||
],
|
||||
"messages": messages_payload,
|
||||
"temperature": 0.0,
|
||||
"max_tokens": request_func_input.output_len,
|
||||
"stream": True,
|
||||
@@ -98,6 +340,10 @@ async def async_request_openai_chat_omni_completions(
|
||||
},
|
||||
}
|
||||
_update_payload_common(payload, request_func_input)
|
||||
# Seed-TTS via chat: voice-clone fields live on the body; ensure audio is streamed.
|
||||
if getattr(request_func_input, "seed_tts_row", False):
|
||||
if payload.get("modalities") is None:
|
||||
payload["modalities"] = ["text", "audio"]
|
||||
|
||||
response_format = payload.get("response_format", "wav")
|
||||
if response_format == "pcm":
|
||||
@@ -167,7 +413,10 @@ async def async_request_openai_chat_omni_completions(
|
||||
data = json.loads(chunk)
|
||||
if choices := data.get("choices"):
|
||||
modality = data.get("modality")
|
||||
content = choices[0]["delta"].get("content")
|
||||
delta = choices[0].get("delta") or {}
|
||||
content = delta.get("content")
|
||||
if not content and isinstance(delta.get("audio"), dict):
|
||||
content = delta["audio"].get("data")
|
||||
if modality == "text":
|
||||
# First token
|
||||
if ttft == 0.0:
|
||||
@@ -182,7 +431,7 @@ async def async_request_openai_chat_omni_completions(
|
||||
if output.audio_ttfp == 0.0:
|
||||
output.audio_ttfp = timestamp - st
|
||||
audio_generate_time = timestamp - st
|
||||
if content != "":
|
||||
if content:
|
||||
audio_bytes = base64.b64decode(content)
|
||||
seg = AudioSegment.from_file(io.BytesIO(audio_bytes))
|
||||
if seg is not None:
|
||||
@@ -214,6 +463,12 @@ async def async_request_openai_chat_omni_completions(
|
||||
else:
|
||||
output.audio_rtf = 0
|
||||
logger.warning("Audio duration is zero")
|
||||
if _seed_tts_capture_pcm_for_wer() and getattr(request_func_input, "seed_tts_row", False):
|
||||
try:
|
||||
seg = generated_audio.set_frame_rate(24000).set_channels(1).set_sample_width(2)
|
||||
output.tts_output_pcm_bytes = bytes(seg.raw_data)
|
||||
except Exception as ex:
|
||||
logger.warning("seed_tts WER PCM export failed: %s", ex)
|
||||
output.success = True
|
||||
else:
|
||||
output.error = response.reason or ""
|
||||
@@ -268,6 +523,10 @@ async def async_request_openai_audio_speech(
|
||||
"response_format": "pcm",
|
||||
}
|
||||
_update_payload_common(payload, request_func_input)
|
||||
# Seed-TTS + WER: ``--extra-body`` may set stream=false / other formats; speech must stream PCM.
|
||||
if getattr(request_func_input, "seed_tts_row", False) and _seed_tts_capture_pcm_for_wer():
|
||||
payload["stream"] = True
|
||||
payload["response_format"] = "pcm"
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
@@ -286,6 +545,8 @@ async def async_request_openai_audio_speech(
|
||||
st = time.perf_counter()
|
||||
output.start_time = st
|
||||
total_pcm_bytes = 0
|
||||
capture_wer_pcm = _seed_tts_capture_pcm_for_wer() and getattr(request_func_input, "seed_tts_row", False)
|
||||
pcm_capture = bytearray() if capture_wer_pcm else None
|
||||
try:
|
||||
async with session.post(url=api_url, json=payload, headers=headers) as response:
|
||||
if response.status == 200:
|
||||
@@ -297,6 +558,8 @@ async def async_request_openai_audio_speech(
|
||||
output.audio_ttfp = timestamp - st
|
||||
output.ttft = output.audio_ttfp
|
||||
total_pcm_bytes += len(chunk)
|
||||
if pcm_capture is not None:
|
||||
pcm_capture.extend(chunk)
|
||||
|
||||
end_time = time.perf_counter()
|
||||
output.latency = end_time - st
|
||||
@@ -309,6 +572,16 @@ async def async_request_openai_audio_speech(
|
||||
else:
|
||||
output.audio_rtf = 0
|
||||
logger.warning("Audio duration is zero")
|
||||
if pcm_capture is not None and pcm_capture:
|
||||
output.tts_output_pcm_bytes = bytes(pcm_capture)
|
||||
elif capture_wer_pcm:
|
||||
ct = response.headers.get("Content-Type", "")
|
||||
logger.warning(
|
||||
"Seed-TTS WER: HTTP 200 but no PCM bytes (Content-Type=%r, url=%s). "
|
||||
"Check stream=true and response_format=pcm on the server.",
|
||||
ct,
|
||||
api_url,
|
||||
)
|
||||
output.success = True
|
||||
else:
|
||||
output.error = response.reason or ""
|
||||
@@ -331,6 +604,12 @@ ASYNC_REQUEST_FUNCS["openai-audio-speech"] = async_request_openai_audio_speech
|
||||
if "openai-audio-speech" not in OPENAI_COMPATIBLE_BACKENDS:
|
||||
OPENAI_COMPATIBLE_BACKENDS.append("openai-audio-speech")
|
||||
|
||||
# Daily-Omni backend for audio-visual reasoning benchmark
|
||||
# Reuses openai-chat-omni completions for video+text understanding
|
||||
ASYNC_REQUEST_FUNCS["daily-omni"] = async_request_openai_chat_omni_completions
|
||||
if "daily-omni" not in OPENAI_COMPATIBLE_BACKENDS:
|
||||
OPENAI_COMPATIBLE_BACKENDS.append("daily-omni")
|
||||
|
||||
# ruff: noqa: E402
|
||||
# Prevent import order from causing patch failures
|
||||
from vllm.benchmarks import serve
|
||||
@@ -422,6 +701,8 @@ async def benchmark(
|
||||
extra_headers=extra_headers,
|
||||
extra_body=extra_body,
|
||||
)
|
||||
_attach_daily_omni_to_request_func_input(input_requests[0], test_input)
|
||||
_attach_seed_tts_to_request_func_input(input_requests[0], test_input)
|
||||
|
||||
if ready_check_timeout_sec > 0:
|
||||
test_output = await wait_for_endpoint(
|
||||
@@ -484,6 +765,8 @@ async def benchmark(
|
||||
extra_headers=extra_headers,
|
||||
extra_body=extra_body,
|
||||
)
|
||||
_attach_daily_omni_to_request_func_input(input_requests[0], profile_input)
|
||||
_attach_seed_tts_to_request_func_input(input_requests[0], profile_input)
|
||||
profile_output = await request_func(request_func_input=profile_input, session=session)
|
||||
if profile_output.success:
|
||||
print("Profiler started")
|
||||
@@ -564,6 +847,8 @@ async def benchmark(
|
||||
extra_body=extra_body,
|
||||
request_id=request_id,
|
||||
)
|
||||
_attach_daily_omni_to_request_func_input(request, request_func_input)
|
||||
_attach_seed_tts_to_request_func_input(request, request_func_input)
|
||||
tasks.append(
|
||||
asyncio.create_task(limited_request_func(request_func_input=request_func_input, session=session, pbar=pbar))
|
||||
)
|
||||
@@ -631,6 +916,37 @@ async def benchmark(
|
||||
"errors": [output.error for output in outputs],
|
||||
}
|
||||
|
||||
from vllm_omni.benchmarks.data_modules.daily_omni_eval import (
|
||||
compute_daily_omni_accuracy_metrics,
|
||||
print_daily_omni_accuracy_summary,
|
||||
)
|
||||
|
||||
_save_items = os.environ.get("DAILY_OMNI_SAVE_EVAL_ITEMS", "").lower() in (
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
)
|
||||
_daily_acc = compute_daily_omni_accuracy_metrics(input_requests, outputs, include_per_item=_save_items)
|
||||
if _daily_acc is not None:
|
||||
result.update(_daily_acc)
|
||||
print_daily_omni_accuracy_summary(_daily_acc)
|
||||
|
||||
if _seed_tts_capture_pcm_for_wer():
|
||||
from vllm_omni.benchmarks.data_modules.seed_tts_eval import (
|
||||
compute_seed_tts_wer_metrics,
|
||||
print_seed_tts_wer_summary,
|
||||
)
|
||||
|
||||
_save_wer = os.environ.get("SEED_TTS_WER_SAVE_ITEMS", "").lower() in (
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
)
|
||||
_wer_m = compute_seed_tts_wer_metrics(input_requests, outputs, include_per_item=_save_wer)
|
||||
if _wer_m is not None:
|
||||
result.update(_wer_m)
|
||||
print_seed_tts_wer_summary(_wer_m)
|
||||
|
||||
if rps_change_events:
|
||||
result["rps_change_events"] = rps_change_events
|
||||
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
import argparse
|
||||
import asyncio
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
from vllm.benchmarks.serve import main_async
|
||||
|
||||
# Import patch to register daily-omni dataset and omni backends
|
||||
# This monkey-patches vllm.benchmarks.datasets.get_samples before it's used
|
||||
# Must be imported before any vllm.benchmarks module usage
|
||||
import vllm_omni.benchmarks.patch.patch # noqa: F401
|
||||
|
||||
|
||||
def main(args: argparse.Namespace) -> dict[str, Any]:
|
||||
if getattr(args, "seed_tts_wer_eval", False):
|
||||
os.environ["SEED_TTS_WER_EVAL"] = "1"
|
||||
if getattr(args, "seed_tts_wer_save_items", False):
|
||||
os.environ["SEED_TTS_WER_SAVE_ITEMS"] = "1"
|
||||
if getattr(args, "daily_omni_save_eval_items", False):
|
||||
os.environ["DAILY_OMNI_SAVE_EVAL_ITEMS"] = "1"
|
||||
return asyncio.run(main_async(args))
|
||||
@@ -5,10 +5,18 @@ Configuration module for vLLM-Omni.
|
||||
from vllm_omni.config.lora import LoRAConfig
|
||||
from vllm_omni.config.model import OmniModelConfig
|
||||
from vllm_omni.config.stage_config import (
|
||||
DeployConfig,
|
||||
ModelPipeline,
|
||||
PipelineConfig,
|
||||
StageConfig,
|
||||
StageConfigFactory,
|
||||
StageDeployConfig,
|
||||
StageExecutionType,
|
||||
StagePipelineConfig,
|
||||
StageType,
|
||||
load_deploy_config,
|
||||
merge_pipeline_deploy,
|
||||
register_pipeline,
|
||||
)
|
||||
from vllm_omni.config.yaml_util import (
|
||||
create_config,
|
||||
@@ -24,6 +32,14 @@ __all__ = [
|
||||
"StageConfigFactory",
|
||||
"ModelPipeline",
|
||||
"StageType",
|
||||
"StageExecutionType",
|
||||
"StagePipelineConfig",
|
||||
"PipelineConfig",
|
||||
"StageDeployConfig",
|
||||
"DeployConfig",
|
||||
"load_deploy_config",
|
||||
"merge_pipeline_deploy",
|
||||
"register_pipeline",
|
||||
"create_config",
|
||||
"load_yaml_config",
|
||||
"merge_configs",
|
||||
|
||||
@@ -109,9 +109,11 @@ class OmniModelConfig(ModelConfig):
|
||||
"extra": {},
|
||||
}
|
||||
)
|
||||
subtalker_sampling_params: dict[str, Any] | None = None
|
||||
omni_kv_config: dict | None = None
|
||||
codec_frame_rate_hz: float | None = None
|
||||
task_type: str | None = None
|
||||
enable_sleep_mode: bool = False
|
||||
|
||||
@property
|
||||
def registry(self):
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Central declarative registry of all vllm-omni pipelines.
|
||||
|
||||
Mirrors the pattern in ``vllm/model_executor/models/registry.py``: each entry
|
||||
is ``model_type -> (module_path, variable_name)``, and the module is imported
|
||||
lazily on first lookup (see ``_LazyPipelineRegistry`` in
|
||||
``vllm_omni/config/stage_config.py``). Keeping every pipeline declared in one
|
||||
file makes it easy to spot a missing registration, which was the original
|
||||
motivation in https://github.com/vllm-project/vllm-omni/issues/2887 (item 4).
|
||||
|
||||
Per-model ``pipeline.py`` modules still define the ``PipelineConfig`` instance;
|
||||
they just no longer need to self-register via ``register_pipeline(...)``.
|
||||
|
||||
Adding a new pipeline:
|
||||
1. Define the ``PipelineConfig`` instance as a module-level variable in
|
||||
``vllm_omni/.../pipeline.py``.
|
||||
2. Add one line to ``_OMNI_PIPELINES`` or ``_DIFFUSION_PIPELINES`` below.
|
||||
|
||||
``register_pipeline(config)`` in ``stage_config`` is still supported for
|
||||
out-of-tree plugins and tests that create pipelines at runtime; those override
|
||||
the entries declared here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# --- Multi-stage omni pipelines (LLM-centric; audio / video I/O) ---
|
||||
_OMNI_PIPELINES: dict[str, tuple[str, str]] = {
|
||||
# model_type -> (module_path, variable_name)
|
||||
"qwen2_5_omni": (
|
||||
"vllm_omni.model_executor.models.qwen2_5_omni.pipeline",
|
||||
"QWEN2_5_OMNI_PIPELINE",
|
||||
),
|
||||
"qwen2_5_omni_thinker_only": (
|
||||
"vllm_omni.model_executor.models.qwen2_5_omni.pipeline",
|
||||
"QWEN2_5_OMNI_THINKER_ONLY_PIPELINE",
|
||||
),
|
||||
"qwen3_omni_moe": (
|
||||
"vllm_omni.model_executor.models.qwen3_omni.pipeline",
|
||||
"QWEN3_OMNI_PIPELINE",
|
||||
),
|
||||
"qwen3_tts": (
|
||||
"vllm_omni.model_executor.models.qwen3_tts.pipeline",
|
||||
"QWEN3_TTS_PIPELINE",
|
||||
),
|
||||
"voxcpm2": (
|
||||
"vllm_omni.model_executor.models.voxcpm2.pipeline",
|
||||
"VOXCPM2_PIPELINE",
|
||||
),
|
||||
"cosyvoice3": (
|
||||
"vllm_omni.model_executor.models.cosyvoice3.pipeline",
|
||||
"COSYVOICE3_PIPELINE",
|
||||
),
|
||||
"mimo_audio": (
|
||||
"vllm_omni.model_executor.models.mimo_audio.pipeline",
|
||||
"MIMO_AUDIO_PIPELINE",
|
||||
),
|
||||
"voxtral_tts": (
|
||||
"vllm_omni.model_executor.models.voxtral_tts.pipeline",
|
||||
"VOXTRAL_TTS_PIPELINE",
|
||||
),
|
||||
"fish_qwen3_omni": (
|
||||
"vllm_omni.model_executor.models.fish_speech.pipeline",
|
||||
"FISH_SPEECH_PIPELINE",
|
||||
),
|
||||
}
|
||||
|
||||
# --- Single-stage diffusion pipelines (populated in PR 3/N) ---
|
||||
_DIFFUSION_PIPELINES: dict[str, tuple[str, str]] = {}
|
||||
|
||||
# Union view used by ``_LazyPipelineRegistry``; don't mutate at runtime.
|
||||
_VLLM_OMNI_PIPELINES: dict[str, tuple[str, str]] = {
|
||||
**_OMNI_PIPELINES,
|
||||
**_DIFFUSION_PIPELINES,
|
||||
}
|
||||
+960
-156
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,264 @@
|
||||
"""
|
||||
Utilities for Prefix Caching in Omni models.
|
||||
"""
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.worker.gpu_input_batch import InputBatch
|
||||
|
||||
from vllm_omni.utils.mm_outputs import build_mm_cpu, to_payload_element
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class OmniTensorPrefixCache:
|
||||
"""Prefix cache for hidden states (model outputs) and model specific
|
||||
multimodal outputs.
|
||||
|
||||
This class implements prefix caching in a non-invasive way on top of
|
||||
vLLM by leveraging the same slot mappings that the vLLM scheduler uses
|
||||
for the KV Cache.
|
||||
|
||||
Conceptually, this means we are mapping vLLM's cache mapping:
|
||||
(num_blocks, block_size)
|
||||
|
||||
to 3D tensors of shape:
|
||||
(num_blocks, block_size, feature_size)
|
||||
|
||||
Note that feature_size may vary across multimodal_outputs.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_blocks: int,
|
||||
block_size: int,
|
||||
hidden_size: int,
|
||||
hs_dtype: torch.dtype,
|
||||
):
|
||||
self.num_blocks = num_blocks
|
||||
self.block_size = block_size
|
||||
self.default_hidden_size = hidden_size
|
||||
|
||||
# Initialize the hidden states cache immediately
|
||||
self.hidden_states_cache = self._get_cache_tensor(dtype=hs_dtype)
|
||||
|
||||
# Defer initialization of the mm_outputs_cache until we
|
||||
# actually see mm output tensors dependent on num tokens.
|
||||
self.mm_outputs_cache = {}
|
||||
self.mm_cache_keys = set()
|
||||
self._new_req_cache_hit_ids: set[str] = set()
|
||||
|
||||
def maybe_init_missing_mm_cache_keys(self, multimodal_outputs: dict, seq_len: int):
|
||||
"""Given multimodal outputs from executing the model, dynamically
|
||||
determine which multimodal outputs are tensors depending on sequence
|
||||
length and should be cached, and initialize the cache tensors
|
||||
accordingly.
|
||||
|
||||
NOTE: This is done to avoid the need for explicit specification of
|
||||
cache keys for every model/stage and aligns with the current way
|
||||
that we slice the multimodal outputs based on the first dimension.
|
||||
|
||||
This will usually be called by the first forward pass, i.e.,
|
||||
determined by the warmup.
|
||||
"""
|
||||
for key, val in multimodal_outputs.items():
|
||||
if isinstance(val, torch.Tensor) and val.shape[0] == seq_len and key not in self.mm_cache_keys:
|
||||
feat_dim = val.shape[-1]
|
||||
self.mm_outputs_cache[key] = self._get_cache_tensor(
|
||||
dtype=val.dtype,
|
||||
hidden_size=feat_dim,
|
||||
)
|
||||
self.mm_cache_keys.add(key)
|
||||
new_tensor_shape = self.mm_outputs_cache[key].shape
|
||||
logger.info("Initializing multimodal output cache of size %s for key: %s", list(new_tensor_shape), key)
|
||||
|
||||
def _get_cache_tensor(self, dtype: torch.dtype, hidden_size: int | None = None) -> torch.Tensor:
|
||||
"""Allocate a CPU cache tensor for a specific key."""
|
||||
actual_hidden_size = hidden_size if hidden_size is not None else self.default_hidden_size
|
||||
return torch.zeros(
|
||||
(self.num_blocks, self.block_size, actual_hidden_size),
|
||||
dtype=dtype,
|
||||
device="cpu",
|
||||
)
|
||||
|
||||
def add_prefix_cached_new_req_id(self, req_id: str):
|
||||
"""Adds a new request ID to the set of prefix cache hits on the batch."""
|
||||
self._new_req_cache_hit_ids.add(req_id)
|
||||
|
||||
def reset_prefix_cached_new_req_ids(self):
|
||||
"""Clears the cache hit IDs to prepare for a new engine step."""
|
||||
self._new_req_cache_hit_ids.clear()
|
||||
|
||||
@staticmethod
|
||||
def _coerce_to_cpu_tensor(maybe_gpu_tensor: torch.Tensor) -> torch.Tensor:
|
||||
"""Convert GPU tensors -> contiguous CPU tensors if needed."""
|
||||
return maybe_gpu_tensor.detach().cpu().contiguous()
|
||||
|
||||
def update_omni_tensor_prefix_cache(
|
||||
self,
|
||||
hidden_states: torch.Tensor | None,
|
||||
multimodal_outputs: dict[str, torch.Tensor] | None,
|
||||
num_tokens_unpadded: int,
|
||||
slot_mapping: torch.Tensor,
|
||||
num_tokens_padded: int | None = None,
|
||||
):
|
||||
"""Updates the hidden cache state for the provided hidden states and multimodal outputs.
|
||||
|
||||
Args:
|
||||
hidden_states: Hidden states tensor to cache (if any)
|
||||
multimodal_outputs: Multimodal dict whose tensors may be cached
|
||||
num_tokens_unpadded: Number of tokens without padding
|
||||
slot_mapping: Slot mapping for the input sequence
|
||||
num_tokens_padded: Total number of tokens including padding
|
||||
"""
|
||||
unpadded_slot_mapping = slot_mapping[:num_tokens_unpadded]
|
||||
if num_tokens_padded is None:
|
||||
num_tokens_padded = num_tokens_unpadded
|
||||
|
||||
if hidden_states is not None:
|
||||
# Slice to unpadded portion before caching
|
||||
hidden_states = hidden_states[:num_tokens_unpadded]
|
||||
# Ensure that hidden states are on the CPU
|
||||
hidden_states = OmniTensorPrefixCache._coerce_to_cpu_tensor(hidden_states)
|
||||
# View the cache as 2D so that we can treat our slots as row indices
|
||||
flat_cache = self.hidden_states_cache.view(-1, self.hidden_states_cache.shape[-1])
|
||||
flat_cache[unpadded_slot_mapping] = hidden_states
|
||||
logger.debug("Writing to hidden states for %s tokens", num_tokens_unpadded)
|
||||
|
||||
# Do the same for the stage's cached multimodal outputs
|
||||
if multimodal_outputs is not None:
|
||||
# If we haven't initialized the keys already, do it now
|
||||
# We check against the padded token count since we haven't sliced yet
|
||||
self.maybe_init_missing_mm_cache_keys(
|
||||
multimodal_outputs,
|
||||
seq_len=num_tokens_padded,
|
||||
)
|
||||
|
||||
for mm_out_key, mm_cache in self.mm_outputs_cache.items():
|
||||
if mm_out_key in multimodal_outputs:
|
||||
# Slice to unpadded portion before caching
|
||||
mm_state = multimodal_outputs[mm_out_key][:num_tokens_unpadded]
|
||||
mm_state = OmniTensorPrefixCache._coerce_to_cpu_tensor(mm_state)
|
||||
flat_cache = mm_cache.view(-1, mm_cache.shape[-1])
|
||||
flat_cache[unpadded_slot_mapping] = mm_state
|
||||
logger.debug("Writing to mm output cache for %s tokens", num_tokens_unpadded)
|
||||
|
||||
def _coerce_to_payload_dict(
|
||||
self,
|
||||
element: object,
|
||||
query_start_loc: torch.Tensor,
|
||||
input_batch: InputBatch,
|
||||
num_scheduled_tokens: dict[str, int],
|
||||
) -> dict[str, object]:
|
||||
"""Build the multimodal passthrough data per request for
|
||||
the object under consideration. This is identical to the case
|
||||
for no prefix cache when we tensor does have a first dimension
|
||||
matching the seq len.
|
||||
"""
|
||||
elem_dict = {}
|
||||
for req_id in input_batch.req_ids:
|
||||
req_idx = input_batch.req_id_to_index[req_id]
|
||||
start = query_start_loc[req_idx]
|
||||
end = start + num_scheduled_tokens[req_id]
|
||||
elem_dict[req_id] = to_payload_element(
|
||||
element, req_idx, start=start, end=end, pass_lists_through=True, seq_len=None
|
||||
)
|
||||
return elem_dict
|
||||
|
||||
def get_merged_multimodal_states(
|
||||
self,
|
||||
query_start_loc: torch.Tensor,
|
||||
input_batch: InputBatch,
|
||||
multimodal_outputs: dict,
|
||||
num_scheduled_tokens: dict[str, int],
|
||||
):
|
||||
"""Get the merged multimodal states if hidden state prefix caching is enabled."""
|
||||
combined_multimodal_outputs = {}
|
||||
# First get the prefix cached tensors that are present in the mm data
|
||||
for mm_key in self.mm_cache_keys:
|
||||
if mm_key in multimodal_outputs:
|
||||
combined_multimodal_outputs[mm_key] = self._get_merged_tensors(
|
||||
query_start_loc=query_start_loc,
|
||||
input_batch=input_batch,
|
||||
cache=self.mm_outputs_cache[mm_key],
|
||||
hidden_states=multimodal_outputs[mm_key],
|
||||
num_scheduled_tokens=num_scheduled_tokens,
|
||||
)
|
||||
|
||||
# Then, get everything else (passthrough data); first, convert to CPU
|
||||
# tensors similarly to the non prefix cached path, and then populate
|
||||
# the subdicts mapping request IDs -> payload objects
|
||||
passthrough_keys = set(multimodal_outputs.keys()) - self.mm_cache_keys
|
||||
passthrough_mm_data = {k: v for k, v in multimodal_outputs.items() if k in passthrough_keys}
|
||||
mm_cpu = build_mm_cpu(multimodal_outputs=passthrough_mm_data)
|
||||
|
||||
for mm_key, mm_val in mm_cpu.items():
|
||||
combined_multimodal_outputs[mm_key] = self._coerce_to_payload_dict(
|
||||
element=mm_val,
|
||||
query_start_loc=query_start_loc,
|
||||
input_batch=input_batch,
|
||||
num_scheduled_tokens=num_scheduled_tokens,
|
||||
)
|
||||
return combined_multimodal_outputs
|
||||
|
||||
def get_merged_hidden_states(self, *args, **kwargs) -> dict[str, torch.Tensor]:
|
||||
"""Get the merged hidden states."""
|
||||
return self._get_merged_tensors(
|
||||
*args,
|
||||
**kwargs,
|
||||
cache=self.hidden_states_cache,
|
||||
)
|
||||
|
||||
def _get_merged_tensors(
|
||||
self,
|
||||
query_start_loc: torch.Tensor,
|
||||
input_batch: InputBatch,
|
||||
cache: torch.Tensor,
|
||||
hidden_states: torch.Tensor,
|
||||
num_scheduled_tokens: dict[str, int],
|
||||
) -> dict[str, torch.Tensor]:
|
||||
"""When hidden state caching is enabled, takes the input hidden_states,
|
||||
which only correspond to the scheduled tokens, and returns a mapping
|
||||
from request IDs to their full hidden states. This is accomplished by
|
||||
looking up the block IDs & scheduled token counts to split the
|
||||
hidden_states.
|
||||
"""
|
||||
# We do not support hybrid caches at the moment.
|
||||
if len(input_batch.block_table.block_tables) > 1:
|
||||
logger.warning_once(
|
||||
"Omni prefix caching is enabled, but the batch block table appears to"
|
||||
" have multiple kv groups; only the first group will be used!"
|
||||
)
|
||||
|
||||
combined_hidden_states = {}
|
||||
hidden_states = OmniTensorPrefixCache._coerce_to_cpu_tensor(hidden_states)
|
||||
for req_id in input_batch.req_ids:
|
||||
req_idx = input_batch.req_id_to_index[req_id]
|
||||
|
||||
if req_id in self._new_req_cache_hit_ids:
|
||||
block_ids = self._get_cached_block_ids(req_idx, input_batch)
|
||||
cached_hs = cache[block_ids].reshape(-1, cache.shape[-1])
|
||||
|
||||
# Slice the hidden states corresponding to this request;
|
||||
# we do this by using the query start
|
||||
start = query_start_loc[req_idx]
|
||||
new_hs = hidden_states[start : start + num_scheduled_tokens[req_id]]
|
||||
combined_hidden_states[req_id] = torch.cat([cached_hs, new_hs], dim=0)
|
||||
else:
|
||||
# cache miss for this request, pass through normally
|
||||
start = query_start_loc[req_idx]
|
||||
new_hs = hidden_states[start : start + num_scheduled_tokens[req_id]]
|
||||
combined_hidden_states[req_id] = new_hs
|
||||
|
||||
return combined_hidden_states
|
||||
|
||||
def _get_cached_block_ids(self, req_idx: int, input_batch: InputBatch) -> torch.Tensor:
|
||||
"""Given an input batch and request index in the batch (not ID), get the
|
||||
block IDs corresponding to the cache hit.
|
||||
"""
|
||||
num_computed = input_batch.num_computed_tokens_cpu[req_idx]
|
||||
# NOTE: vLLM only caches full blocks
|
||||
num_cached_blocks = num_computed // self.block_size
|
||||
# Get the block IDs attached to this cache hit and reindex into
|
||||
# the flattened cached hidden states (i.e., 1 row per token).
|
||||
return input_batch.block_table[0].block_table.cpu[req_idx, :num_cached_blocks]
|
||||
@@ -15,9 +15,10 @@ from vllm.v1.core.sched.utils import remove_all
|
||||
from vllm.v1.engine import EngineCoreOutput, EngineCoreOutputs
|
||||
from vllm.v1.metrics.perf import PerfStats
|
||||
from vllm.v1.outputs import ModelRunnerOutput
|
||||
from vllm.v1.request import Request, RequestStatus
|
||||
from vllm.v1.request import Request, RequestStatus, StreamingUpdate
|
||||
from vllm.v1.spec_decode.metrics import SpecDecodingStats
|
||||
|
||||
from vllm_omni.core.sched.omni_scheduler_mixin import OmniSchedulerMixin
|
||||
from vllm_omni.core.sched.output import OmniSchedulerOutput
|
||||
from vllm_omni.distributed.omni_connectors.transfer_adapter.chunk_transfer_adapter import (
|
||||
OmniChunkTransferAdapter,
|
||||
@@ -38,7 +39,7 @@ class KVCacheTransferData:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
class OmniARScheduler(VLLMScheduler):
|
||||
class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
"""
|
||||
OmniARScheduler: Scheduler for vLLM-Omni multimodal processing.
|
||||
|
||||
@@ -76,6 +77,8 @@ class OmniARScheduler(VLLMScheduler):
|
||||
self.chunk_transfer_adapter = None
|
||||
if getattr(model_config, "async_chunk", False):
|
||||
self.chunk_transfer_adapter = OmniChunkTransferAdapter(self.vllm_config)
|
||||
# Snapshot prompt length for each streaming input update
|
||||
self._new_prompt_len_snapshot: dict[str, int] = {}
|
||||
|
||||
def _get_kv_transfer_criteria(self) -> dict | None:
|
||||
# Note: vllm_config is available in Scheduler after super().__init__
|
||||
@@ -338,6 +341,7 @@ class OmniARScheduler(VLLMScheduler):
|
||||
)
|
||||
|
||||
stopped = False
|
||||
is_segment_finished = False
|
||||
new_logprobs = None
|
||||
new_token_ids = generated_token_ids
|
||||
pooler_output = pooler_outputs[req_index] if pooler_outputs else None
|
||||
@@ -366,6 +370,7 @@ class OmniARScheduler(VLLMScheduler):
|
||||
# Capture finish_reason BEFORE _handle_stopped_request, which may
|
||||
# reset the status to WAITING for streaming requests that continue.
|
||||
finish_reason = request.get_finished_reason()
|
||||
is_segment_finished = request.is_finished() and request.resumable
|
||||
finished = self._handle_stopped_request(request)
|
||||
if finished:
|
||||
kv_transfer_params = self._free_request(request)
|
||||
@@ -418,6 +423,8 @@ class OmniARScheduler(VLLMScheduler):
|
||||
num_external_computed_tokens=request.num_external_computed_tokens,
|
||||
routed_experts=routed_experts,
|
||||
num_nans_in_logits=request.num_nans_in_logits,
|
||||
is_segment_finished=is_segment_finished,
|
||||
new_prompt_len_snapshot=self._new_prompt_len_snapshot.get(req_id, None),
|
||||
)
|
||||
)
|
||||
if self.chunk_transfer_adapter is not None:
|
||||
@@ -539,6 +546,39 @@ class OmniARScheduler(VLLMScheduler):
|
||||
|
||||
return engine_core_outputs
|
||||
|
||||
def finish_requests(self, request_ids: Any, finished_status: RequestStatus) -> list[tuple[str, int]]:
|
||||
"""Handles the finish signal from outside the scheduler.
|
||||
|
||||
For example, the API server can abort a request when the client
|
||||
disconnects.
|
||||
|
||||
If request_ids is None, all requests will be finished.
|
||||
|
||||
Returns:
|
||||
Tuple of (req_id, client_index) for requests that were aborted. Will not
|
||||
include any that were already finished.
|
||||
"""
|
||||
|
||||
if self.chunk_transfer_adapter:
|
||||
self.chunk_transfer_adapter.finish_requests(request_ids, finished_status, self.requests)
|
||||
|
||||
return super().finish_requests(request_ids, finished_status)
|
||||
|
||||
def _update_request_as_session(self, session: Request, update: StreamingUpdate) -> None:
|
||||
"""
|
||||
Override: Only extend prompt at stage 0, and replace
|
||||
the existing session with the next streaming update at other stages.
|
||||
|
||||
Discards the last sampled output token from the prior input chunk at stage 0.
|
||||
"""
|
||||
req_id = session.request_id
|
||||
self._new_prompt_len_snapshot[req_id] = len(update.prompt_token_ids)
|
||||
if self.vllm_config.model_config.stage_id != 0:
|
||||
self._replace_session_with_streaming_update(session, update)
|
||||
|
||||
else:
|
||||
super()._update_request_as_session(session, update)
|
||||
|
||||
def _free_request(self, request: Request, delay_free_blocks: bool = False) -> dict[str, Any] | None:
|
||||
# TODO(wzliu)! for offline mode, we should not end process until all data is transferred
|
||||
"""Mark a request as finished and free its resources."""
|
||||
@@ -552,6 +592,7 @@ class OmniARScheduler(VLLMScheduler):
|
||||
self.encoder_cache_manager.free(request)
|
||||
request_id = request.request_id
|
||||
self.finished_req_ids.add(request_id)
|
||||
self._new_prompt_len_snapshot.pop(request_id, None)
|
||||
if self.finished_req_ids_dict is not None:
|
||||
self.finished_req_ids_dict[request.client_index].add(request_id)
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
@@ -11,11 +13,16 @@ from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.core.sched.request_queue import create_request_queue
|
||||
from vllm.v1.core.sched.scheduler import Scheduler as VLLMScheduler
|
||||
from vllm.v1.core.sched.utils import remove_all
|
||||
from vllm.v1.engine import EngineCoreEventType, EngineCoreOutput, EngineCoreOutputs
|
||||
from vllm.v1.engine import (
|
||||
EngineCoreEventType,
|
||||
EngineCoreOutput,
|
||||
EngineCoreOutputs,
|
||||
)
|
||||
from vllm.v1.metrics.perf import PerfStats
|
||||
from vllm.v1.request import Request, RequestStatus
|
||||
from vllm.v1.request import Request, RequestStatus, StreamingUpdate
|
||||
from vllm.v1.spec_decode.metrics import SpecDecodingStats
|
||||
|
||||
from vllm_omni.core.sched.omni_scheduler_mixin import OmniSchedulerMixin
|
||||
from vllm_omni.core.sched.output import OmniCachedRequestData, OmniNewRequestData
|
||||
from vllm_omni.distributed.omni_connectors.transfer_adapter.chunk_transfer_adapter import (
|
||||
OmniChunkTransferAdapter,
|
||||
@@ -25,7 +32,7 @@ from vllm_omni.outputs import OmniModelRunnerOutput
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class OmniGenerationScheduler(VLLMScheduler):
|
||||
class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
model_config = self.vllm_config.model_config
|
||||
@@ -324,6 +331,24 @@ class OmniGenerationScheduler(VLLMScheduler):
|
||||
|
||||
return scheduler_output
|
||||
|
||||
def finish_requests(self, request_ids, finished_status: RequestStatus) -> list[tuple[str, int]]:
|
||||
"""Handles the finish signal from outside the scheduler.
|
||||
|
||||
For example, the API server can abort a request when the client
|
||||
disconnects.
|
||||
|
||||
If request_ids is None, all requests will be finished.
|
||||
|
||||
Returns:
|
||||
Tuple of (req_id, client_index) for requests that were aborted. Will not
|
||||
include any that were already finished.
|
||||
"""
|
||||
|
||||
if self.chunk_transfer_adapter:
|
||||
self.chunk_transfer_adapter.finish_requests(request_ids, finished_status, self.requests)
|
||||
|
||||
return super().finish_requests(request_ids, finished_status)
|
||||
|
||||
"""
|
||||
Scheduler for the diffusion model.
|
||||
This scheduler is modified to stop the request immediately for the diffusion model.
|
||||
@@ -581,3 +606,11 @@ class OmniGenerationScheduler(VLLMScheduler):
|
||||
eco.scheduler_stats = stats
|
||||
|
||||
return engine_core_outputs
|
||||
|
||||
def _update_request_as_session(self, session: Request, update: StreamingUpdate) -> None:
|
||||
"""
|
||||
Override: Just replace the existing session with the next streaming update.
|
||||
|
||||
Do not expend prompt id using update.
|
||||
"""
|
||||
self._replace_session_with_streaming_update(session, update)
|
||||
@@ -0,0 +1,33 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from vllm.v1.engine import EngineCoreEventType
|
||||
from vllm.v1.request import Request, RequestStatus, StreamingUpdate
|
||||
|
||||
|
||||
class OmniSchedulerMixin:
|
||||
"""Shared scheduler helpers for omni-specific request handling."""
|
||||
|
||||
def _replace_session_with_streaming_update(
|
||||
self,
|
||||
session: Request,
|
||||
update: StreamingUpdate,
|
||||
) -> None:
|
||||
"""For streaming input: Replace an existing streaming session payload with the latest update."""
|
||||
session._output_token_ids.clear()
|
||||
session._all_token_ids.clear()
|
||||
new_prompt = update.prompt_token_ids or ()
|
||||
session._all_token_ids.extend(new_prompt)
|
||||
session.num_computed_tokens = 0
|
||||
session.prompt_token_ids = update.prompt_token_ids or ()
|
||||
session.additional_information = update.additional_information or None
|
||||
# Update block hashes for the new tokens.
|
||||
session.update_block_hashes()
|
||||
session.num_prompt_tokens = len(session.prompt_token_ids)
|
||||
session.arrival_time = update.arrival_time
|
||||
session.sampling_params = update.sampling_params
|
||||
if session.status == RequestStatus.WAITING_FOR_STREAMING_REQ:
|
||||
self.num_waiting_for_streaming_input -= 1
|
||||
session.status = RequestStatus.WAITING
|
||||
|
||||
if self.log_stats:
|
||||
session.record_event(EngineCoreEventType.QUEUED)
|
||||
@@ -0,0 +1,58 @@
|
||||
# CosyVoice3 deploy: 2-stage talker → flow-matching code2wav.
|
||||
#
|
||||
# Default mode is async-chunk streaming through SharedMemoryConnector. Pass
|
||||
# ``--no-async-chunk`` to the serve CLI for the legacy sync path (stage 1
|
||||
# builds flow input from the full speech-token sequence via ``text2flow``).
|
||||
# The shared-memory connector definition and input/output_connectors
|
||||
# references stay in the yaml unconditionally; the runtime only activates
|
||||
# them when ``async_chunk: true``.
|
||||
#
|
||||
# enforce_eager=true everywhere:
|
||||
# * Stage 0 (talker) — cudagraph not verified on this checkpoint.
|
||||
# * Stage 1 (code2wav) — CUDA graphs don't work with dynamic conv shapes.
|
||||
async_chunk: true
|
||||
dtype: float32
|
||||
|
||||
connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
codec_streaming: true
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
connector_get_max_wait: 300
|
||||
codec_chunk_frames: 25
|
||||
codec_left_context_frames: 25
|
||||
codec_vocab_size: 6561
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.4
|
||||
enforce_eager: true
|
||||
devices: "0"
|
||||
output_connectors:
|
||||
to_stage_1: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
max_tokens: 2048
|
||||
top_k: 25
|
||||
top_p: 0.8
|
||||
# near-identity repetition penalty forces vLLM to track
|
||||
# output_token_ids for RAS (stop-token logit logsumexp).
|
||||
repetition_penalty: 1.0001
|
||||
disable_hybrid_kv_cache_manager: true
|
||||
mm_processor_cache_gb: 0
|
||||
skip_mm_profiling: true
|
||||
|
||||
- stage_id: 1
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.2
|
||||
enforce_eager: true
|
||||
max_model_len: 32768
|
||||
devices: "0"
|
||||
input_connectors:
|
||||
from_stage_0: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
max_tokens: 2048
|
||||
disable_hybrid_kv_cache_manager: true
|
||||
skip_mm_profiling: true
|
||||
@@ -0,0 +1,61 @@
|
||||
# Fish Speech S2 Pro deploy: async-chunk streaming slow_ar → dac_decoder.
|
||||
# Verified on 1× H20.
|
||||
# Registry key and filename use the HF ``model_type=fish_qwen3_omni`` for
|
||||
# auto-detection; human-readable "fish_speech" stays as the source directory.
|
||||
async_chunk: true
|
||||
enable_chunked_prefill: false
|
||||
|
||||
connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
codec_streaming: true
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
connector_get_max_wait: 300
|
||||
# ~21 Hz codec; 25 frames ≈ 1.16s of audio.
|
||||
codec_chunk_frames: 25
|
||||
codec_left_context_frames: 25
|
||||
initial_codec_chunk_frames: 4
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
max_num_seqs: 4
|
||||
gpu_memory_utilization: 0.6
|
||||
enforce_eager: false
|
||||
async_scheduling: false
|
||||
# vLLM >=0.19 requires max_num_batched_tokens >= max_model_len when
|
||||
# enable_chunked_prefill=false. Bumped from legacy 3072 to match
|
||||
# max_model_len; chunked prefill stays off because the SlowAR decode
|
||||
# loop isn't chunked-prefill-safe.
|
||||
max_num_batched_tokens: 16384
|
||||
max_model_len: 16384
|
||||
devices: "0"
|
||||
output_connectors:
|
||||
to_stage_1: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
temperature: 0.8
|
||||
top_k: 30
|
||||
top_p: 0.9
|
||||
max_tokens: 2048
|
||||
seed: 42
|
||||
repetition_penalty: 1.0
|
||||
|
||||
- stage_id: 1
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.1
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
max_num_batched_tokens: 16384
|
||||
max_model_len: 16384
|
||||
devices: "0"
|
||||
input_connectors:
|
||||
from_stage_0: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 65536
|
||||
seed: 42
|
||||
repetition_penalty: 1.0
|
||||
@@ -0,0 +1,56 @@
|
||||
# MiMo Audio deploy: 2-stage thinker+talker → code2wav.
|
||||
#
|
||||
# Default mode is async-chunk streaming on a single GPU (both stages on
|
||||
# device 0) through SharedMemoryConnector. For the legacy 2-GPU sync
|
||||
# pipeline (stage 1 on a second card), pass ``--no-async-chunk
|
||||
# --stage-1-devices 1 --stage-1-max-model-len 18192
|
||||
# --stage-1-max-num-batched-tokens 18192`` to the serve CLI.
|
||||
async_chunk: true
|
||||
dtype: bfloat16
|
||||
|
||||
connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 365536
|
||||
codec_streaming: true
|
||||
connector_get_sleep_s: 0.001
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
connector_get_max_wait: 300
|
||||
codec_chunk_frames: 3
|
||||
codec_left_context_frames: 3
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.3
|
||||
enforce_eager: true
|
||||
max_num_batched_tokens: 8192
|
||||
max_model_len: 8192
|
||||
devices: "0"
|
||||
output_connectors:
|
||||
to_stage_1: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
temperature: 0.6
|
||||
top_p: 0.95
|
||||
top_k: 50
|
||||
max_tokens: 18192
|
||||
seed: 42
|
||||
repetition_penalty: 1.1
|
||||
|
||||
- stage_id: 1
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.2
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
max_num_batched_tokens: 8192
|
||||
max_model_len: 8192
|
||||
devices: "0"
|
||||
input_connectors:
|
||||
from_stage_0: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 18192
|
||||
seed: 42
|
||||
@@ -0,0 +1,92 @@
|
||||
# Qwen2.5-Omni deploy: CUDA defaults + platform overrides, verified on 2x H100.
|
||||
# Stage 2 disables flashinfer autotune because its DiT block never invokes
|
||||
# flashinfer; the autotune dummy run OOMs the shared cuda:0 device otherwise.
|
||||
#
|
||||
# Fields omitted from a stage fall back to StageDeployConfig dataclass
|
||||
# defaults (see vllm_omni/config/stage_config.py). For instance, every
|
||||
# stage here uses vLLM's default max_num_batched_tokens=32768 because
|
||||
# chat-sized prefill comfortably fits; only models with codec prefill
|
||||
# (Qwen3-Omni, Qwen3-TTS) need to bump it above 32k.
|
||||
#
|
||||
# enforce_eager policy across the three deploy YAMLs:
|
||||
# * code2wav / generation stages: always true (cudagraph incompatible with
|
||||
# the custom generation loop — set explicitly everywhere).
|
||||
# * AR stages (thinker, talker): model-dependent. Qwen2.5-Omni runs eager
|
||||
# on CUDA (thinker uses custom ops that don't trace cleanly); NPU / XPU
|
||||
# platform overrides flip back to false where cudagraph is verified.
|
||||
# Qwen3-Omni / Qwen3-TTS AR stages use the default (false = cudagraph on).
|
||||
async_chunk: false
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.8
|
||||
enforce_eager: true
|
||||
mm_processor_cache_gb: 0
|
||||
devices: "0"
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 2048
|
||||
seed: 42
|
||||
repetition_penalty: 1.1
|
||||
|
||||
- stage_id: 1
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.8
|
||||
enforce_eager: true
|
||||
devices: "1"
|
||||
default_sampling_params:
|
||||
temperature: 0.9
|
||||
top_p: 0.8
|
||||
top_k: 40
|
||||
max_tokens: 2048
|
||||
seed: 42
|
||||
repetition_penalty: 1.05
|
||||
|
||||
- stage_id: 2
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.15
|
||||
enforce_eager: true
|
||||
enable_flashinfer_autotune: false
|
||||
async_scheduling: false
|
||||
devices: "0"
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 2048
|
||||
seed: 42
|
||||
repetition_penalty: 1.1
|
||||
|
||||
platforms:
|
||||
npu:
|
||||
stages:
|
||||
# NPU has cudagraph support for the thinker, unlike GPU which still
|
||||
# only runs eager.
|
||||
- stage_id: 0
|
||||
enforce_eager: false
|
||||
- stage_id: 2
|
||||
# 3-NPU layout: stage 2 lives on its own card.
|
||||
devices: "2"
|
||||
|
||||
rocm:
|
||||
stages:
|
||||
- stage_id: 2
|
||||
# 3-GPU MI325 layout: stage 2 on a separate card.
|
||||
devices: "2"
|
||||
|
||||
xpu:
|
||||
stages:
|
||||
# Verified on 2x Intel Arc Pro B60. Both AR stages use cudagraphs.
|
||||
- stage_id: 0
|
||||
gpu_memory_utilization: 0.9
|
||||
enforce_eager: false
|
||||
- stage_id: 1
|
||||
gpu_memory_utilization: 0.5
|
||||
enforce_eager: false
|
||||
- stage_id: 2
|
||||
gpu_memory_utilization: 0.3
|
||||
# Stage 2 colocates with stage 1's device on XPU.
|
||||
devices: "1"
|
||||
@@ -0,0 +1,98 @@
|
||||
# Qwen3-Omni-MoE production deploy, verified on 2x H100 (stage 0 on cuda:0,
|
||||
# stages 1+2 on cuda:1).
|
||||
#
|
||||
# Fields omitted from a stage fall back to StageDeployConfig defaults (see
|
||||
# vllm_omni/config/stage_config.py). Notable implicit defaults for this
|
||||
# model:
|
||||
# * Stages 0/1 (thinker, talker) do not set max_num_batched_tokens —
|
||||
# chat-sized prefill fits in the 32768 default.
|
||||
# * Stages 0/1 do not set enforce_eager — cudagraph runs by default
|
||||
# (false). Stage 2 (code2wav) sets true because its generation loop
|
||||
# is cudagraph-incompatible.
|
||||
# * Platform sections flip enforce_eager per-stage where platform
|
||||
# cudagraph support differs.
|
||||
async_chunk: true
|
||||
|
||||
connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
codec_chunk_frames: 25
|
||||
codec_left_context_frames: 25
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
gpu_memory_utilization: 0.9
|
||||
devices: "0"
|
||||
default_sampling_params:
|
||||
temperature: 0.4
|
||||
top_p: 0.9
|
||||
top_k: 1
|
||||
max_tokens: 2048
|
||||
seed: 42
|
||||
repetition_penalty: 1.05
|
||||
|
||||
- stage_id: 1
|
||||
gpu_memory_utilization: 0.6
|
||||
devices: "1"
|
||||
input_connectors:
|
||||
from_stage_0: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
temperature: 0.9
|
||||
top_k: 50
|
||||
max_tokens: 4096
|
||||
seed: 42
|
||||
repetition_penalty: 1.05
|
||||
|
||||
- stage_id: 2
|
||||
gpu_memory_utilization: 0.1
|
||||
max_num_seqs: 1
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
max_num_batched_tokens: 51200
|
||||
devices: "1"
|
||||
input_connectors:
|
||||
from_stage_1: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 65536
|
||||
seed: 42
|
||||
repetition_penalty: 1.1
|
||||
|
||||
platforms:
|
||||
npu:
|
||||
stages:
|
||||
- stage_id: 0
|
||||
gpu_memory_utilization: 0.6
|
||||
tensor_parallel_size: 2
|
||||
devices: "0,1"
|
||||
- stage_id: 1
|
||||
gpu_memory_utilization: 0.6
|
||||
enforce_eager: true
|
||||
devices: "2"
|
||||
- stage_id: 2
|
||||
gpu_memory_utilization: 0.3
|
||||
devices: "2"
|
||||
|
||||
rocm:
|
||||
stages:
|
||||
- stage_id: 0
|
||||
enforce_eager: true
|
||||
|
||||
xpu:
|
||||
stages:
|
||||
- stage_id: 0
|
||||
tensor_parallel_size: 4
|
||||
enforce_eager: true
|
||||
max_cudagraph_capture_size: 0
|
||||
devices: "0,1,2,3"
|
||||
- stage_id: 1
|
||||
enforce_eager: true
|
||||
max_cudagraph_capture_size: 0
|
||||
devices: "4"
|
||||
- stage_id: 2
|
||||
gpu_memory_utilization: 0.3
|
||||
max_cudagraph_capture_size: 0
|
||||
devices: "4"
|
||||
@@ -0,0 +1,86 @@
|
||||
# Qwen3-TTS deploy: talker → code2wav via shared-memory chunk streaming.
|
||||
# Verified on 1x H100.
|
||||
#
|
||||
# Fields omitted from a stage fall back to StageDeployConfig defaults (see
|
||||
# vllm_omni/config/stage_config.py). Notable choices for this model:
|
||||
# * Stage 0 (talker) sets max_num_batched_tokens=512 for async-chunk
|
||||
# latency tuning (not correctness) — small per-step batches keep
|
||||
# first-chunk latency low.
|
||||
# * Stage 1 (code2wav) sets max_num_batched_tokens=65536 for correctness:
|
||||
# codec prefill length (Q * num_frames) exceeds the 32k default.
|
||||
# * Stage 0 does not set enforce_eager — talker runs cudagraph by default.
|
||||
# Stage 1 sets true because its codec generation loop is not
|
||||
# cudagraph-compatible. NPU platform flips stage 0 to true where
|
||||
# cudagraph is not yet verified.
|
||||
async_chunk: true
|
||||
|
||||
connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
codec_streaming: true
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
connector_get_max_wait: 300
|
||||
# Must match the decoder sliding attention window.
|
||||
codec_chunk_frames: 25
|
||||
codec_left_context_frames: 72
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
max_num_seqs: 10
|
||||
gpu_memory_utilization: 0.3
|
||||
async_scheduling: true
|
||||
max_num_batched_tokens: 512
|
||||
max_model_len: 4096
|
||||
devices: "0"
|
||||
output_connectors:
|
||||
to_stage_1: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
temperature: 0.9
|
||||
top_k: 50
|
||||
max_tokens: 4096
|
||||
seed: 42
|
||||
repetition_penalty: 1.05
|
||||
subtalker_sampling_params:
|
||||
do_sample: true
|
||||
temperature: 0.9
|
||||
top_k: 50
|
||||
top_p: 1.0
|
||||
|
||||
- stage_id: 1
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.3
|
||||
enforce_eager: true
|
||||
async_scheduling: true
|
||||
# Must be divisible by num_code_groups and cover (left_context + chunk).
|
||||
# Prefill length is Q * num_frames (e.g. 16 * 2148 = 34368); keep
|
||||
# headroom past 32k.
|
||||
max_num_batched_tokens: 65536
|
||||
# async_chunk appends windows per step; max_model_len must cover the
|
||||
# accumulated flat codec stream.
|
||||
max_model_len: 65536
|
||||
devices: "0"
|
||||
input_connectors:
|
||||
from_stage_0: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 65536
|
||||
seed: 42
|
||||
repetition_penalty: 1.0
|
||||
|
||||
platforms:
|
||||
npu:
|
||||
stages:
|
||||
# NPU does not yet support async-scheduling for TTS, and the
|
||||
# talker fits at max_num_seqs=1 only.
|
||||
- stage_id: 0
|
||||
max_num_seqs: 1
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
- stage_id: 1
|
||||
gpu_memory_utilization: 0.2
|
||||
async_scheduling: false
|
||||
@@ -0,0 +1,29 @@
|
||||
# VoxCPM2 deploy: single-stage AR pipeline with per-request state batching.
|
||||
# Verified on 1x H20 141GB.
|
||||
#
|
||||
# Fields omitted from a stage fall back to StageDeployConfig defaults (see
|
||||
# vllm_omni/config/stage_config.py). Notable choices:
|
||||
# * enforce_eager=true because the talker's KV-cache save/restore loop is
|
||||
# not cudagraph-compatible (captured separately via voxcpm2_talker's own
|
||||
# _CapturedGraph path).
|
||||
# * max_num_seqs=4 matches the legacy max_batch_size=4 contract: concurrent
|
||||
# requests are supported via per-request StaticKVCache save/restore.
|
||||
async_chunk: false
|
||||
dtype: bfloat16
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
max_num_seqs: 4
|
||||
gpu_memory_utilization: 0.9
|
||||
enforce_eager: true
|
||||
async_scheduling: true
|
||||
max_num_batched_tokens: 4096
|
||||
max_model_len: 4096
|
||||
devices: "0"
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 4096
|
||||
seed: 42
|
||||
repetition_penalty: 1.0
|
||||
@@ -0,0 +1,65 @@
|
||||
# Voxtral TTS deploy: async-chunk streaming generator → audio tokenizer.
|
||||
# Verified on 1× H20.
|
||||
#
|
||||
# Mistral tokenizer/config/load flags are declared per-stage here because
|
||||
# DeployConfig does not yet expose them as pipeline-wide fields. They must
|
||||
# match on every stage so the engine args stay consistent across workers.
|
||||
async_chunk: true
|
||||
|
||||
connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
codec_streaming: true
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
connector_get_max_wait: 300
|
||||
codec_chunk_frames: 25
|
||||
codec_chunk_frames_at_begin: 5
|
||||
codec_left_context_frames: 25
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
max_num_seqs: 32
|
||||
gpu_memory_utilization: 0.8
|
||||
enforce_eager: false
|
||||
async_scheduling: true
|
||||
max_model_len: 4096
|
||||
devices: "0"
|
||||
output_connectors:
|
||||
to_stage_1: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 2048
|
||||
seed: 42
|
||||
repetition_penalty: 1.1
|
||||
tokenizer_mode: mistral
|
||||
config_format: mistral
|
||||
load_format: mistral
|
||||
skip_mm_profiling: true
|
||||
enable_chunked_prefill: false
|
||||
|
||||
- stage_id: 1
|
||||
max_num_seqs: 32
|
||||
gpu_memory_utilization: 0.1
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
max_num_batched_tokens: 65536
|
||||
max_model_len: 65536
|
||||
devices: "0"
|
||||
input_connectors:
|
||||
from_stage_0: connector_of_shared_memory
|
||||
default_sampling_params:
|
||||
temperature: 0.9
|
||||
top_p: 0.8
|
||||
top_k: 40
|
||||
max_tokens: 2048
|
||||
seed: 42
|
||||
repetition_penalty: 1.05
|
||||
tokenizer_mode: mistral
|
||||
config_format: mistral
|
||||
load_format: mistral
|
||||
skip_mm_profiling: true
|
||||
@@ -414,10 +414,6 @@ class UlyssesParallelAttention:
|
||||
def post_attention(self, attn_output: torch.Tensor, ctx: ParallelAttentionContext | None) -> torch.Tensor:
|
||||
assert isinstance(ctx, _UlyssesCtx), f"Unexpected ctx type: {type(ctx)!r}"
|
||||
|
||||
# If we have joint tensors (Text), they were Head-Sliced.
|
||||
# The main sequence (Image) was Sequence-Sliced.
|
||||
# attn_output contains [Joint_Sliced | Image_Sliced] (if strategy='front').
|
||||
|
||||
if ctx.joint_len > 0:
|
||||
joint_len = ctx.joint_len
|
||||
|
||||
|
||||
+78
-30
@@ -281,6 +281,7 @@ def enable_cache_for_longcat_image(pipeline: Any, cache_config: Any) -> Callable
|
||||
],
|
||||
forward_pattern=[ForwardPattern.Pattern_1, ForwardPattern.Pattern_1],
|
||||
params_modifiers=[modifier],
|
||||
has_separate_cfg=True,
|
||||
)
|
||||
),
|
||||
cache_config=db_cache_config,
|
||||
@@ -632,6 +633,7 @@ def enable_cache_for_ltx2(pipeline: Any, cache_config: Any) -> Callable[[int], N
|
||||
forward_pattern=ForwardPattern.Pattern_0,
|
||||
# Treat audio_hidden_states as encoder_hidden_states in Pattern_0
|
||||
check_forward_pattern=False,
|
||||
has_separate_cfg=True,
|
||||
),
|
||||
cache_config=db_cache_config,
|
||||
calibrator_config=calibrator_config,
|
||||
@@ -1168,36 +1170,6 @@ def enable_cache_for_bagel(pipeline: Any, cache_config: Any) -> Callable[[int],
|
||||
return refresh_cache_context
|
||||
|
||||
|
||||
def enable_cache_for_glm_image(pipeline: Any, cache_config: Any) -> Callable[[int], None]:
|
||||
"""Enable cache-dit for GLM-Image pipeline.
|
||||
|
||||
GLM-Image processes prompt and image by calling the transformer before the
|
||||
denoising loop. When an input image is provided (editing mode), the cache must
|
||||
be force-refreshed after the preprocessing step so stale hidden states are
|
||||
discarded. Set force_refresh_step_hint = 1 for editing, None for text-to-image.
|
||||
"""
|
||||
db_cache_config = _build_db_cache_config(cache_config)
|
||||
|
||||
calibrator_config = None
|
||||
if cache_config.enable_taylorseer:
|
||||
calibrator_config = TaylorSeerCalibratorConfig(taylorseer_order=cache_config.taylorseer_order)
|
||||
logger.info(f"TaylorSeer enabled with order={cache_config.taylorseer_order}")
|
||||
|
||||
logger.info(
|
||||
f"Enabling cache-dit on GLM-Image transformer: "
|
||||
f"Fn={db_cache_config.Fn_compute_blocks}, "
|
||||
f"Bn={db_cache_config.Bn_compute_blocks}, "
|
||||
f"W={db_cache_config.max_warmup_steps}, "
|
||||
f"force_refresh_step_hint={db_cache_config.force_refresh_step_hint}, "
|
||||
)
|
||||
|
||||
cache_dit.enable_cache(
|
||||
pipeline.transformer,
|
||||
cache_config=db_cache_config,
|
||||
calibrator_config=calibrator_config,
|
||||
)
|
||||
|
||||
|
||||
def enable_cache_for_flux2(pipeline: Any, cache_config: Any) -> Callable[[int], None]:
|
||||
"""Enable cache-dit for Flux.2-dev pipeline.
|
||||
|
||||
@@ -1272,6 +1244,82 @@ def enable_cache_for_flux2(pipeline: Any, cache_config: Any) -> Callable[[int],
|
||||
return refresh_cache_context
|
||||
|
||||
|
||||
def enable_cache_for_glm_image(pipeline: Any, cache_config: Any) -> Callable[[int], None]:
|
||||
"""Enable cache-dit for GlmImage pipeline.
|
||||
|
||||
Args:
|
||||
pipeline: The GlmImage pipeline instance.
|
||||
cache_config: DiffusionCacheConfig instance with cache configuration.
|
||||
Returns:
|
||||
A refresh function that can be called with a new ``num_inference_steps``
|
||||
to update the cache context for the pipeline.
|
||||
"""
|
||||
# Build DBCacheConfig for transformer
|
||||
db_cache_config = _build_db_cache_config(cache_config)
|
||||
|
||||
calibrator = None
|
||||
if cache_config.enable_taylorseer:
|
||||
taylorseer_order = cache_config.taylorseer_order
|
||||
calibrator = TaylorSeerCalibratorConfig(taylorseer_order=taylorseer_order)
|
||||
logger.info(f"TaylorSeer enabled with order={taylorseer_order}")
|
||||
|
||||
# Build ParamsModifier for transformer
|
||||
modifier = ParamsModifier(
|
||||
cache_config=db_cache_config,
|
||||
calibrator_config=calibrator,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Enabling cache-dit on GlmImage transformer with BlockAdapter: "
|
||||
f"Fn={db_cache_config.Fn_compute_blocks}, "
|
||||
f"Bn={db_cache_config.Bn_compute_blocks}, "
|
||||
f"W={db_cache_config.max_warmup_steps}, "
|
||||
)
|
||||
|
||||
# Enable cache-dit using BlockAdapter for transformer
|
||||
# Note: We don't use patch_functor here because it's designed for diffusers' GlmImage,
|
||||
# and our vllm-omni implementation has a different forward signature.
|
||||
# We use ForwardPattern.Pattern_0 because our block returns (hidden_states, encoder_hidden_states)
|
||||
cache_dit.enable_cache(
|
||||
(
|
||||
BlockAdapter(
|
||||
transformer=pipeline.transformer,
|
||||
blocks=pipeline.transformer.transformer_blocks,
|
||||
forward_pattern=ForwardPattern.Pattern_0,
|
||||
params_modifiers=[modifier],
|
||||
patch_functor=None,
|
||||
has_separate_cfg=True,
|
||||
)
|
||||
),
|
||||
cache_config=db_cache_config,
|
||||
)
|
||||
|
||||
def refresh_cache_context(pipeline: Any, num_inference_steps: int, verbose: bool = True) -> None:
|
||||
"""Refresh cache context for the transformer with new num_inference_steps.
|
||||
|
||||
Args:
|
||||
pipeline: The GlmImage pipeline instance.
|
||||
num_inference_steps: New number of inference steps.
|
||||
"""
|
||||
if cache_config.scm_steps_mask_policy is None:
|
||||
cache_dit.refresh_context(pipeline.transformer, num_inference_steps=num_inference_steps, verbose=verbose)
|
||||
else:
|
||||
cache_dit.refresh_context(
|
||||
pipeline.transformer,
|
||||
cache_config=DBCacheConfig().reset(
|
||||
num_inference_steps=num_inference_steps,
|
||||
steps_computation_mask=cache_dit.steps_mask(
|
||||
mask_policy=cache_config.scm_steps_mask_policy,
|
||||
total_steps=num_inference_steps,
|
||||
),
|
||||
steps_computation_policy=cache_config.scm_steps_policy,
|
||||
),
|
||||
verbose=verbose,
|
||||
)
|
||||
|
||||
return refresh_cache_context
|
||||
|
||||
|
||||
# Register custom cache-dit enablers after function definitions
|
||||
CUSTOM_DIT_ENABLERS.update(
|
||||
{
|
||||
|
||||
+62
-76
@@ -1,20 +1,18 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from vllm.config import LoadConfig
|
||||
from vllm.utils.torch_utils import set_default_torch_dtype
|
||||
from vllm.transformers_utils.config import get_hf_file_to_dict
|
||||
|
||||
from vllm_omni.diffusion.cache.teacache.extractors import get_extractor
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig, TransformerConfig
|
||||
from vllm_omni.diffusion.hooks import HookRegistry, ModelHook
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.bagel.pipeline_bagel import BagelPipeline
|
||||
from vllm_omni.diffusion.models.flux2.pipeline_flux2 import Flux2Pipeline
|
||||
from vllm_omni.diffusion.models.stable_audio.pipeline_stable_audio import StableAudioPipeline
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
@@ -36,6 +34,7 @@ class DataCollectionHook(ModelHook):
|
||||
|
||||
def new_forward(self, module: torch.nn.Module, *args: Any, **kwargs: Any) -> Any:
|
||||
ctx = self.extractor_fn(module, *args, **kwargs)
|
||||
# NOTE: We upcast to float32 to also handle bfloat16.
|
||||
modulated_input_cpu = ctx.modulated_input.detach().float().cpu().numpy()
|
||||
|
||||
outputs = ctx.run_transformer_blocks()
|
||||
@@ -54,19 +53,53 @@ class DataCollectionHook(ModelHook):
|
||||
return list(self.current_trajectory)
|
||||
|
||||
|
||||
class BagelAdapter:
|
||||
"""Adapter for Bagel model."""
|
||||
class DefaultAdapter:
|
||||
"""Default adapter for standard diffusers pipelines."""
|
||||
|
||||
model_class_name = None
|
||||
uses_tf_config = True
|
||||
|
||||
@classmethod
|
||||
def load_pipeline(cls, model_path: str, device: str, dtype: torch.dtype) -> Any:
|
||||
if cls.model_class_name is None:
|
||||
raise ValueError("Adapter doesn't have a set class name.")
|
||||
|
||||
od_config = OmniDiffusionConfig.from_kwargs(
|
||||
model_class_name=cls.model_class_name,
|
||||
model=model_path,
|
||||
dtype=dtype,
|
||||
)
|
||||
|
||||
if cls.uses_tf_config:
|
||||
# TODO (Alex): Refactor to handle tf_model_config in OmniDiffusionConfig
|
||||
# instead of OmniDiffusion and remove the manual population here
|
||||
tf_config_dict = get_hf_file_to_dict(
|
||||
os.path.join("transformer", "config.json"),
|
||||
od_config.model,
|
||||
)
|
||||
od_config.tf_model_config = TransformerConfig.from_dict(tf_config_dict)
|
||||
|
||||
loader = DiffusersPipelineLoader(LoadConfig(), od_config=od_config)
|
||||
# load_model will handle dtypes / device placement, put in .eval() mode
|
||||
return loader.load_model(od_config=od_config, load_device=device)
|
||||
|
||||
@staticmethod
|
||||
def load_pipeline(model_path: str, device: str = "cuda", dtype: torch.dtype = torch.bfloat16) -> BagelPipeline:
|
||||
od_config = OmniDiffusionConfig.from_kwargs(model=model_path, dtype=dtype)
|
||||
od_config.model_class_name = "BagelPipeline"
|
||||
def get_transformer(pipeline: Any) -> tuple[Any, str]:
|
||||
return pipeline.transformer, pipeline.transformer.__class__.__name__
|
||||
|
||||
pipeline = BagelPipeline(od_config=od_config)
|
||||
loader = DiffusersPipelineLoader(LoadConfig())
|
||||
loader.load_weights(pipeline)
|
||||
pipeline.to(device)
|
||||
return pipeline
|
||||
@staticmethod
|
||||
def install_hook(transformer: Any, hook: DataCollectionHook) -> None:
|
||||
registry = HookRegistry.get_or_create(transformer)
|
||||
registry.register_hook(hook._HOOK_NAME, hook)
|
||||
|
||||
|
||||
class BagelAdapter(DefaultAdapter):
|
||||
"""Adapter for Bagel model."""
|
||||
|
||||
model_class_name = "BagelPipeline"
|
||||
# Skip the hack for loading the tf model config,
|
||||
# because bagel doesn't use it.
|
||||
uses_tf_config = False
|
||||
|
||||
@staticmethod
|
||||
def get_transformer(pipeline: Any) -> tuple[Any, str]:
|
||||
@@ -78,78 +111,32 @@ class BagelAdapter:
|
||||
registry.register_hook(hook._HOOK_NAME, hook)
|
||||
|
||||
|
||||
class StableAudioAdapter:
|
||||
"""Adapter for Stable Audio Open 1.0 coefficient estimation."""
|
||||
|
||||
@staticmethod
|
||||
def load_pipeline(model_path: str, device: str = "cuda", dtype: torch.dtype = torch.float16) -> Any:
|
||||
od_config = OmniDiffusionConfig.from_kwargs(model=model_path, dtype=dtype)
|
||||
|
||||
# Strictly necessary because we bypass loader.load_model()
|
||||
with set_default_torch_dtype(dtype):
|
||||
pipeline = StableAudioPipeline(od_config=od_config)
|
||||
|
||||
loader = DiffusersPipelineLoader(LoadConfig())
|
||||
loader.load_weights(pipeline)
|
||||
pipeline.to(device)
|
||||
return pipeline
|
||||
|
||||
@staticmethod
|
||||
def get_transformer(pipeline: Any) -> tuple[Any, str]:
|
||||
return pipeline.transformer, "StableAudioDiTModel"
|
||||
|
||||
@staticmethod
|
||||
def install_hook(transformer: Any, hook: DataCollectionHook) -> None:
|
||||
registry = HookRegistry.get_or_create(transformer)
|
||||
registry.register_hook(hook._HOOK_NAME, hook)
|
||||
|
||||
|
||||
class Flux2Adapter:
|
||||
class Flux2Adapter(DefaultAdapter):
|
||||
"""Adapter for Flux2 model coefficient estimation."""
|
||||
|
||||
@staticmethod
|
||||
def load_pipeline(model_path: str, device: str = "cuda", dtype: torch.dtype = torch.bfloat16) -> Flux2Pipeline:
|
||||
"""Load Flux2 pipeline for coefficient estimation."""
|
||||
od_config = OmniDiffusionConfig.from_kwargs(model=model_path, dtype=dtype)
|
||||
od_config.model_class_name = "Flux2Pipeline"
|
||||
|
||||
pipeline = Flux2Pipeline(od_config=od_config)
|
||||
loader = DiffusersPipelineLoader(LoadConfig())
|
||||
loader.load_weights(pipeline)
|
||||
pipeline.to(device)
|
||||
return pipeline
|
||||
|
||||
@staticmethod
|
||||
def get_transformer(pipeline: Any) -> tuple[Any, str]:
|
||||
return pipeline.transformer, pipeline.transformer.__class__.__name__
|
||||
|
||||
@staticmethod
|
||||
def install_hook(transformer: Any, hook: DataCollectionHook) -> None:
|
||||
registry = HookRegistry.get_or_create(transformer)
|
||||
registry.register_hook(hook._HOOK_NAME, hook)
|
||||
model_class_name = "Flux2Pipeline"
|
||||
|
||||
|
||||
class DefaultAdapter:
|
||||
"""Default adapter for standard diffusers pipelines."""
|
||||
class LongCatAdapter(DefaultAdapter):
|
||||
"""Adapter for LongCat Image - NOTE: currently this model needs the vLLM
|
||||
context to be correctly configured to actually run the estimation, since it
|
||||
uses vLLM norm layers etc.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def load_pipeline(model_path: str, device: str, dtype: torch.dtype) -> Any:
|
||||
raise NotImplementedError("DefaultAdapter.load_pipeline not implemented")
|
||||
model_class_name = "LongCatImagePipeline"
|
||||
|
||||
@staticmethod
|
||||
def get_transformer(pipeline: Any) -> tuple[Any, str]:
|
||||
return pipeline.transformer, pipeline.transformer.__class__.__name__
|
||||
|
||||
@staticmethod
|
||||
def install_hook(transformer: Any, hook: DataCollectionHook) -> None:
|
||||
registry = HookRegistry.get_or_create(transformer)
|
||||
registry.register_hook(hook._HOOK_NAME, hook)
|
||||
class StableAudioAdapter(DefaultAdapter):
|
||||
"""Adapter for Stable Audio Open 1.0 coefficient estimation."""
|
||||
|
||||
model_class_name = "StableAudioPipeline"
|
||||
|
||||
|
||||
_MODEL_ADAPTERS: dict[str, type] = {
|
||||
"Bagel": BagelAdapter,
|
||||
"StableAudio": StableAudioAdapter,
|
||||
"Flux2": Flux2Adapter,
|
||||
"LongCat": LongCatAdapter,
|
||||
}
|
||||
|
||||
_EPSILON = 1e-6
|
||||
@@ -196,7 +183,6 @@ class TeaCacheCoefficientEstimator:
|
||||
device: str = "cuda",
|
||||
dtype: torch.dtype = torch.bfloat16,
|
||||
):
|
||||
# Add validation here ⬇️
|
||||
if model_type not in _MODEL_ADAPTERS:
|
||||
available_types = list(_MODEL_ADAPTERS.keys())
|
||||
raise ValueError(
|
||||
@@ -205,7 +191,7 @@ class TeaCacheCoefficientEstimator:
|
||||
f"To add support for a new model, add an entry to _MODEL_ADAPTERS."
|
||||
)
|
||||
|
||||
adapter = _MODEL_ADAPTERS.get(model_type, DefaultAdapter)
|
||||
adapter = _MODEL_ADAPTERS[model_type]
|
||||
self.pipeline = adapter.load_pipeline(model_path, device, dtype)
|
||||
self.transformer, self.transformer_type = adapter.get_transformer(self.pipeline)
|
||||
self.hook = DataCollectionHook(self.transformer_type)
|
||||
|
||||
@@ -73,6 +73,8 @@ _MODEL_COEFFICIENTS = {
|
||||
3.20000000e00,
|
||||
-2.00000000e-02,
|
||||
],
|
||||
# LongCat Image transformer coefficients
|
||||
"LongCatImageTransformer2DModel": [652.5980, -424.1615, 84.5526, -4.5923, 0.1694],
|
||||
}
|
||||
|
||||
|
||||
|
||||
+105
-1
@@ -19,10 +19,13 @@ from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CacheContext:
|
||||
@@ -222,7 +225,8 @@ def extract_qwen_context(
|
||||
block = module.transformer_blocks[0]
|
||||
img_mod_params = block.img_mod(temb)
|
||||
img_mod1, _ = img_mod_params.chunk(2, dim=-1)
|
||||
img_modulated, _ = block.img_norm1(hidden_states, img_mod1)
|
||||
img_scale1, img_shift1, _ = block._modulate(img_mod1)
|
||||
img_modulated = block.img_norm1(hidden_states, img_scale1, img_shift1)
|
||||
|
||||
# ============================================================================
|
||||
# DEFINE TRANSFORMER EXECUTION (Qwen-specific)
|
||||
@@ -722,6 +726,105 @@ def extract_flux2_klein_context(
|
||||
)
|
||||
|
||||
|
||||
def extract_longcat_context(
|
||||
module: nn.Module, # LongCatImageTransformer2DModel
|
||||
hidden_states,
|
||||
timestep,
|
||||
guidance,
|
||||
encoder_hidden_states,
|
||||
txt_ids,
|
||||
img_ids,
|
||||
**kwargs,
|
||||
) -> CacheContext:
|
||||
"""Extract the cache context for LongCat Image.
|
||||
|
||||
Similar to other extractors, this is currently the only code needed
|
||||
for TeaCache support for LongCat image, and encapsulates preprocessing,
|
||||
modulated input extraction, transformer execution, and postprocessing
|
||||
logic.
|
||||
|
||||
Args & kawrgs are identical to the inputs to LongCat Image's forward.
|
||||
|
||||
Returns:
|
||||
CacheContext with all information needed for generic caching
|
||||
"""
|
||||
# TODO (Alex) - Refactor TeaCache extractors to more tightly integrate with .forward
|
||||
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
||||
|
||||
# 1. Model specific preprocessing
|
||||
fwd_context = get_forward_context()
|
||||
sp_size = module.parallel_config.sequence_parallel_size
|
||||
if sp_size is not None and sp_size > 1:
|
||||
# NOTE: For now, we set this to False on the forward context
|
||||
# to be consistent with LongCat Image's current behavior when
|
||||
# TeaCache is enabled. We do not need to reset it in post process
|
||||
# since we should never split text embed in sp for this model.
|
||||
fwd_context.split_text_embed_in_sp = False
|
||||
|
||||
hidden_states = module.x_embedder(hidden_states)
|
||||
|
||||
timestep = timestep.to(hidden_states.dtype) * 1000
|
||||
|
||||
temb = module.time_embed(timestep, hidden_states.dtype)
|
||||
encoder_hidden_states = module.context_embedder(encoder_hidden_states)
|
||||
|
||||
# Compute RoPE embeddings via rope_preparer module
|
||||
# _sp_plan will automatically shard img_cos/img_sin (outputs 2, 3)
|
||||
# txt_cos/txt_sin (outputs 0, 1) remain replicated for dual-stream attention
|
||||
txt_cos, txt_sin, img_cos, img_sin = module.rope_preparer(txt_ids, img_ids)
|
||||
|
||||
# Reconstruct image_rotary_emb with chunked values
|
||||
# Final shape: (txt_seq_len + img_seq_len // SP, head_dim)
|
||||
image_rotary_emb = (
|
||||
torch.cat([txt_cos, img_cos], dim=0),
|
||||
torch.cat([txt_sin, img_sin], dim=0),
|
||||
)
|
||||
|
||||
# 2. Extract the modulated output from the first mm-DiT block
|
||||
first_block = module.transformer_blocks[0]
|
||||
img_modulated = first_block.norm1(hidden_states, emb=temb)[0]
|
||||
|
||||
# 3. Define the transformer execution
|
||||
def run_transformer_blocks():
|
||||
"""Execute all Longcat transformer blocks."""
|
||||
h = hidden_states
|
||||
e = encoder_hidden_states
|
||||
for block in module.transformer_blocks:
|
||||
e, h = block(
|
||||
hidden_states=h,
|
||||
encoder_hidden_states=e,
|
||||
temb=temb,
|
||||
image_rotary_emb=image_rotary_emb,
|
||||
)
|
||||
|
||||
for block in module.single_transformer_blocks:
|
||||
e, h = block(
|
||||
hidden_states=h,
|
||||
encoder_hidden_states=e,
|
||||
temb=temb,
|
||||
image_rotary_emb=image_rotary_emb,
|
||||
)
|
||||
# Hook expects hidden states to be first
|
||||
return (h, e)
|
||||
|
||||
# 4. Postprocessing
|
||||
def postprocess(h):
|
||||
"""Apply Longcat-specific output postprocessing."""
|
||||
h = module.norm_out(h, temb)
|
||||
output = module.proj_out(h)
|
||||
return Transformer2DModelOutput(sample=output)
|
||||
|
||||
# 5. Return the CacheContext
|
||||
return CacheContext(
|
||||
modulated_input=img_modulated,
|
||||
hidden_states=hidden_states,
|
||||
encoder_hidden_states=encoder_hidden_states,
|
||||
temb=temb,
|
||||
run_transformer_blocks=run_transformer_blocks,
|
||||
postprocess=postprocess,
|
||||
)
|
||||
|
||||
|
||||
def extract_stable_audio_context(
|
||||
module: nn.Module,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -979,6 +1082,7 @@ EXTRACTOR_REGISTRY: dict[str, Callable] = {
|
||||
"Flux2Klein": extract_flux2_klein_context,
|
||||
"StableAudioDiTModel": extract_stable_audio_context,
|
||||
"Flux2Transformer2DModel": extract_flux2_context,
|
||||
"LongCatImageTransformer2DModel": extract_longcat_context,
|
||||
# Future models:
|
||||
# "FluxTransformer2DModel": extract_flux_context,
|
||||
# "CogVideoXTransformer3DModel": extract_cogvideox_context,
|
||||
|
||||
@@ -18,6 +18,7 @@ from vllm.model_executor.layers.quantization.base_config import (
|
||||
QuantizationConfig,
|
||||
)
|
||||
|
||||
from vllm_omni.diffusion.model_metadata import get_diffusion_model_metadata
|
||||
from vllm_omni.diffusion.utils.network_utils import is_port_available
|
||||
from vllm_omni.quantization import build_quant_config
|
||||
|
||||
@@ -352,6 +353,8 @@ class DiffusionCacheConfig:
|
||||
@dataclass
|
||||
class OmniDiffusionConfig:
|
||||
# Model and path configuration (for convenience)
|
||||
stage_id: int = 0
|
||||
|
||||
model: str | None = None
|
||||
|
||||
model_class_name: str | None = None
|
||||
@@ -481,8 +484,10 @@ class OmniDiffusionConfig:
|
||||
# Scheduler flow_shift for Wan2.2 (12.0 for 480p, 5.0 for 720p)
|
||||
flow_shift: float | None = None
|
||||
|
||||
# support multi images input
|
||||
# Support multi-image inputs and expose any model-specific request limit
|
||||
# through a generic config field so serving code stays model-agnostic.
|
||||
supports_multimodal_inputs: bool = False
|
||||
max_multimodal_image_inputs: int | None = None
|
||||
|
||||
log_level: str = "info"
|
||||
|
||||
@@ -505,6 +510,8 @@ class OmniDiffusionConfig:
|
||||
# Step mode settings
|
||||
step_execution: bool = False
|
||||
|
||||
# sleep mode
|
||||
enable_sleep_mode: bool = False
|
||||
# Maximum number of sequences to generate in a batch
|
||||
max_num_seqs: int = 1
|
||||
|
||||
@@ -664,7 +671,54 @@ class OmniDiffusionConfig:
|
||||
)
|
||||
|
||||
def update_multimodal_support(self) -> None:
|
||||
self.supports_multimodal_inputs = self.model_class_name in {"QwenImageEditPlusPipeline"}
|
||||
# Resolve serving-visible multimodal behavior from shared metadata
|
||||
# instead of importing concrete pipeline modules into the config layer.
|
||||
metadata = get_diffusion_model_metadata(self.model_class_name)
|
||||
self.supports_multimodal_inputs = metadata.supports_multimodal_inputs
|
||||
self.max_multimodal_image_inputs = metadata.max_multimodal_image_inputs
|
||||
|
||||
def enrich_config(self) -> None:
|
||||
"""Load model metadata from HuggingFace and populate config fields.
|
||||
|
||||
Diffusers-style models expose ``model_index.json`` with ``_class_name``.
|
||||
Non-diffusers models (e.g. Bagel, NextStep) only have ``config.json``,
|
||||
so we fall back to reading that and mapping model_type manually.
|
||||
"""
|
||||
from vllm.transformers_utils.config import get_hf_file_to_dict
|
||||
|
||||
try:
|
||||
config_dict = get_hf_file_to_dict("model_index.json", self.model)
|
||||
if config_dict is not None:
|
||||
if self.model_class_name is None:
|
||||
self.model_class_name = config_dict.get("_class_name", None)
|
||||
self.update_multimodal_support()
|
||||
|
||||
tf_config_dict = get_hf_file_to_dict("transformer/config.json", self.model)
|
||||
self.tf_model_config = TransformerConfig.from_dict(tf_config_dict)
|
||||
else:
|
||||
raise FileNotFoundError("model_index.json not found")
|
||||
except (AttributeError, OSError, ValueError, FileNotFoundError):
|
||||
cfg = get_hf_file_to_dict("config.json", self.model)
|
||||
if cfg is None:
|
||||
raise ValueError(f"Could not find config.json or model_index.json for model {self.model}")
|
||||
|
||||
self.tf_model_config = TransformerConfig.from_dict(cfg)
|
||||
model_type = cfg.get("model_type")
|
||||
architectures = cfg.get("architectures") or []
|
||||
|
||||
if model_type == "bagel" or "BagelForConditionalGeneration" in architectures:
|
||||
self.model_class_name = "BagelPipeline"
|
||||
self.tf_model_config = TransformerConfig()
|
||||
self.update_multimodal_support()
|
||||
elif model_type == "nextstep":
|
||||
if self.model_class_name is None:
|
||||
self.model_class_name = "NextStep11Pipeline"
|
||||
self.tf_model_config = TransformerConfig()
|
||||
self.update_multimodal_support()
|
||||
elif architectures and len(architectures) == 1:
|
||||
self.model_class_name = architectures[0]
|
||||
else:
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def from_kwargs(cls, **kwargs: Any) -> "OmniDiffusionConfig":
|
||||
@@ -747,5 +801,43 @@ class AttentionBackendEnum(enum.Enum):
|
||||
return self.name.lower()
|
||||
|
||||
|
||||
@dataclass
|
||||
class OmniACK:
|
||||
"""
|
||||
Handshake payload from Workers to Orchestrator.
|
||||
"""
|
||||
|
||||
task_id: str
|
||||
status: str
|
||||
stage_id: int | None = None
|
||||
rank: int | None = None
|
||||
freed_bytes: int = 0
|
||||
metadata: dict[str, Any] = field(default_factory=dict)
|
||||
"""
|
||||
Additional telemetry such as:
|
||||
- max_contiguous_block: for fragmentation analysis.
|
||||
- cuda_graph_recalled: boolean if graphs were successfully destroyed/rebuilt.
|
||||
- latency_ms: time taken for the D2H/H2D transfer.
|
||||
"""
|
||||
error_msg: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class OmniSleepTask:
|
||||
"""Structured sleep instruction."""
|
||||
|
||||
task_id: str
|
||||
level: int = 2
|
||||
metadata: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class OmniWakeTask:
|
||||
"""Structured wake-up instruction."""
|
||||
|
||||
task_id: str
|
||||
tags: list[str] | None = None
|
||||
|
||||
|
||||
# Special message broadcast via scheduler queues to signal worker shutdown.
|
||||
SHUTDOWN_MESSAGE = {"type": "shutdown"}
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
@@ -13,6 +14,7 @@ import numpy as np
|
||||
import PIL.Image
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.engine.exceptions import EngineDeadError
|
||||
|
||||
from vllm_omni.diffusion.data import (
|
||||
DiffusionOutput,
|
||||
@@ -78,6 +80,12 @@ class DiffusionEngine:
|
||||
|
||||
self.post_process_func = get_diffusion_post_process_func(od_config)
|
||||
self.pre_process_func = get_diffusion_pre_process_func(od_config)
|
||||
# Cache whether the model-specific postprocess accepts request-level
|
||||
# sampling params so step() can support both legacy and extended hooks.
|
||||
self._post_process_accepts_sampling_params = bool(
|
||||
self.post_process_func is not None
|
||||
and "sampling_params" in inspect.signature(self.post_process_func).parameters
|
||||
)
|
||||
|
||||
executor_class = DiffusionExecutor.get_class(od_config)
|
||||
self.executor = executor_class(od_config)
|
||||
@@ -115,7 +123,7 @@ class DiffusionEngine:
|
||||
if output.aborted:
|
||||
raise DiffusionRequestAbortedError(output.abort_message or "Diffusion request aborted.")
|
||||
if output.error:
|
||||
raise RuntimeError(f"{output.error}")
|
||||
raise RuntimeError(output.error)
|
||||
logger.info("Generation completed successfully.")
|
||||
|
||||
if output.output is None:
|
||||
@@ -143,12 +151,22 @@ class DiffusionEngine:
|
||||
output_data = output_data.cpu()
|
||||
|
||||
postprocess_start_time = time.perf_counter()
|
||||
outputs = self.post_process_func(output_data) if self.post_process_func is not None else output_data
|
||||
if self.post_process_func is not None:
|
||||
# Some video pipelines need request-level controls during
|
||||
# postprocess (for example worker-side frame interpolation).
|
||||
if self._post_process_accepts_sampling_params:
|
||||
outputs = self.post_process_func(output_data, sampling_params=request.sampling_params)
|
||||
else:
|
||||
outputs = self.post_process_func(output_data)
|
||||
else:
|
||||
outputs = output_data
|
||||
audio_payload = None
|
||||
custom_output = output.custom_output or {}
|
||||
model_audio_sample_rate = None
|
||||
model_fps = None
|
||||
if isinstance(outputs, dict):
|
||||
audio_payload = outputs.get("audio")
|
||||
custom_output.update(outputs.get("custom_output") or {})
|
||||
model_audio_sample_rate = outputs.get("audio_sample_rate")
|
||||
model_fps = outputs.get("fps")
|
||||
outputs = outputs.get("video", outputs)
|
||||
@@ -225,7 +243,7 @@ class DiffusionEngine:
|
||||
trajectory_timesteps=output.trajectory_timesteps,
|
||||
trajectory_log_probs=output.trajectory_log_probs,
|
||||
trajectory_decoded=output.trajectory_decoded,
|
||||
custom_output=output.custom_output or {},
|
||||
custom_output=custom_output,
|
||||
multimodal_output=mm_output,
|
||||
stage_durations=output.stage_durations,
|
||||
peak_memory_mb=output.peak_memory_mb,
|
||||
@@ -295,7 +313,7 @@ class DiffusionEngine:
|
||||
trajectory_timesteps=output.trajectory_timesteps,
|
||||
trajectory_log_probs=output.trajectory_log_probs,
|
||||
trajectory_decoded=output.trajectory_decoded,
|
||||
custom_output=output.custom_output or {},
|
||||
custom_output=custom_output,
|
||||
multimodal_output=mm_output,
|
||||
stage_durations=output.stage_durations,
|
||||
peak_memory_mb=output.peak_memory_mb,
|
||||
@@ -341,6 +359,8 @@ class DiffusionEngine:
|
||||
sched_req_id = sched_output.scheduled_req_ids[0]
|
||||
try:
|
||||
runner_output = self.execute_fn(sched_output)
|
||||
except EngineDeadError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.error("Execution failed for diffusion request %s", sched_req_id, exc_info=True)
|
||||
runner_output = RunnerOutput(
|
||||
|
||||
@@ -54,9 +54,9 @@ class DistributedVaeExecutor:
|
||||
self.parallel_size = parallel_size
|
||||
|
||||
def gather_tensors(self, tensor: torch.Tensor):
|
||||
gather_list = [torch.empty_like(tensor) for _ in range(self.world_size)] if self.rank == 0 else None
|
||||
dist.gather(tensor, gather_list=gather_list, dst=0, group=self.group)
|
||||
return gather_list
|
||||
gather_list = [torch.empty_like(tensor) for _ in range(self.world_size)]
|
||||
dist.all_gather(gather_list, tensor, group=self.group)
|
||||
return gather_list if self.rank == 0 else None
|
||||
|
||||
def broadcast_tensor(self, tensor: torch.Tensor):
|
||||
dist.broadcast(tensor, src=0, group=self.group)
|
||||
|
||||
@@ -104,6 +104,7 @@ class GroupCoordinator:
|
||||
self.local_rank = local_rank
|
||||
self.device_group = None
|
||||
self.cpu_group = None
|
||||
self.shm_broadcaster = None
|
||||
|
||||
for ranks in group_ranks:
|
||||
device_group = torch.distributed.new_group(ranks, backend=torch_distributed_backend)
|
||||
@@ -316,7 +317,7 @@ class GroupCoordinator:
|
||||
|
||||
assert dst < self.world_size, f"Invalid dst rank ({dst})"
|
||||
|
||||
assert dst != self.rank, "Invalid destination rank. Destination rank is the same as the current rank."
|
||||
assert dst != self.rank_in_group, "Invalid destination rank. Destination rank is the same as the current rank."
|
||||
|
||||
# Serialize object to tensor and get the size as well
|
||||
object_tensor = torch.frombuffer(pickle.dumps(obj), dtype=torch.uint8)
|
||||
@@ -338,7 +339,7 @@ class GroupCoordinator:
|
||||
|
||||
assert src < self.world_size, f"Invalid src rank ({src})"
|
||||
|
||||
assert src != self.rank, "Invalid source rank. Source rank is the same as the current rank."
|
||||
assert src != self.rank_in_group, "Invalid source rank. Source rank is the same as the current rank."
|
||||
|
||||
size_tensor = torch.empty(1, dtype=torch.long, device="cpu")
|
||||
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import multiprocessing as mp
|
||||
import multiprocessing.connection
|
||||
import threading
|
||||
import time
|
||||
import weakref
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import zmq
|
||||
from vllm.distributed.device_communicators.shm_broadcast import MessageQueue
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.engine.exceptions import EngineDeadError
|
||||
|
||||
from vllm_omni.diffusion.data import SHUTDOWN_MESSAGE, DiffusionOutput
|
||||
from vllm_omni.diffusion.executor.abstract import DiffusionExecutor
|
||||
@@ -22,6 +26,8 @@ if TYPE_CHECKING:
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_DEQUEUE_TIMEOUT_S = 5.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class BackgroundResources:
|
||||
@@ -36,10 +42,14 @@ class BackgroundResources:
|
||||
|
||||
def __call__(self):
|
||||
"""Clean up background resources."""
|
||||
if hasattr(self, "wake_events") and self.wake_events:
|
||||
for ev in self.wake_events:
|
||||
ev.set()
|
||||
|
||||
if self.broadcast_mq is not None:
|
||||
try:
|
||||
for _ in range(self.num_workers):
|
||||
self.broadcast_mq.enqueue(SHUTDOWN_MESSAGE)
|
||||
self.broadcast_mq.enqueue(SHUTDOWN_MESSAGE, timeout=1.0)
|
||||
|
||||
self.broadcast_mq = None
|
||||
self.result_mq = None
|
||||
@@ -63,13 +73,17 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
def _init_executor(self) -> None:
|
||||
self._processes: list[mp.Process] = []
|
||||
self._closed = False
|
||||
self.is_failed = False
|
||||
self._failure_callbacks: list[Callable[[], None]] = []
|
||||
|
||||
num_workers = self.od_config.num_gpus
|
||||
self.wake_events = [mp.Event() for _ in range(num_workers)]
|
||||
|
||||
self._broadcast_mq = self._init_broadcast_queue(num_workers)
|
||||
broadcast_handle = self._broadcast_mq.export_handle()
|
||||
|
||||
# Launch workers
|
||||
processes, result_handle = self._launch_workers(broadcast_handle)
|
||||
processes, result_handle = self._launch_workers(broadcast_handle, self.wake_events)
|
||||
self._result_mq = self._init_result_queue(result_handle)
|
||||
self._processes = processes
|
||||
|
||||
@@ -81,6 +95,8 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
)
|
||||
self._finalizer = weakref.finalize(self, self.resources)
|
||||
|
||||
self.start_worker_monitor()
|
||||
|
||||
def _init_broadcast_queue(self, num_workers: int) -> MessageQueue:
|
||||
return MessageQueue(
|
||||
n_reader=num_workers,
|
||||
@@ -100,7 +116,24 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
if self._result_mq is None:
|
||||
raise RuntimeError("Result queue not initialized")
|
||||
|
||||
def _launch_workers(self, broadcast_handle):
|
||||
def _dequeue_one_with_failure_polling(self, deadline: float | None, method: str) -> Any:
|
||||
"""Block until one result message, polling ``is_failed`` between chunk timeouts."""
|
||||
while True:
|
||||
if deadline is None:
|
||||
chunk_timeout = _DEQUEUE_TIMEOUT_S
|
||||
else:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError(f"RPC call to {method} timed out.")
|
||||
chunk_timeout = min(_DEQUEUE_TIMEOUT_S, remaining)
|
||||
try:
|
||||
return self._result_mq.dequeue(timeout=chunk_timeout)
|
||||
except (TimeoutError, zmq.error.Again):
|
||||
if self.is_failed:
|
||||
raise EngineDeadError()
|
||||
continue
|
||||
|
||||
def _launch_workers(self, broadcast_handle, wake_events):
|
||||
od_config = self.od_config
|
||||
logger.info("Starting server...")
|
||||
|
||||
@@ -126,6 +159,7 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
od_config,
|
||||
writer,
|
||||
broadcast_handle,
|
||||
wake_events[i],
|
||||
worker_extension_cls,
|
||||
custom_pipeline_args,
|
||||
),
|
||||
@@ -164,6 +198,49 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
|
||||
return processes, result_handle
|
||||
|
||||
def start_worker_monitor(self) -> None:
|
||||
# Monitors worker process liveness. If any die unexpectedly,
|
||||
# logs an error, shuts down the executor and invokes the failure
|
||||
# callback to inform the engine.
|
||||
sentinels = [p.sentinel for p in self._processes]
|
||||
if not sentinels:
|
||||
return
|
||||
|
||||
def _monitor() -> None:
|
||||
try:
|
||||
finished = multiprocessing.connection.wait(sentinels)
|
||||
except OSError:
|
||||
return
|
||||
|
||||
if self._closed:
|
||||
return
|
||||
|
||||
dead = [p.name for p in self._processes if p.sentinel in finished]
|
||||
if dead:
|
||||
logger.error(
|
||||
"Diffusion worker(s) died unexpectedly: %s",
|
||||
dead,
|
||||
)
|
||||
self.is_failed = True
|
||||
|
||||
self.shutdown()
|
||||
|
||||
for cb in self._failure_callbacks:
|
||||
try:
|
||||
cb()
|
||||
except Exception:
|
||||
logger.exception("failure_callback raised")
|
||||
|
||||
t = threading.Thread(target=_monitor, daemon=True, name="diffusion-worker-monitor")
|
||||
t.start()
|
||||
|
||||
def register_failure_callback(
|
||||
self,
|
||||
callback: Callable[[], None],
|
||||
) -> None:
|
||||
"""Register a callback invoked when a worker process dies."""
|
||||
self._failure_callbacks.append(callback)
|
||||
|
||||
def add_req(self, request: OmniDiffusionRequest) -> DiffusionOutput:
|
||||
self._ensure_open()
|
||||
rpc_request = {
|
||||
@@ -286,27 +363,21 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
|
||||
responses = []
|
||||
for _ in range(num_responses):
|
||||
dequeue_timeout = None if deadline is None else max(0, deadline - time.monotonic())
|
||||
response = self._dequeue_one_with_failure_polling(deadline, method)
|
||||
|
||||
try:
|
||||
response = self._result_mq.dequeue(timeout=dequeue_timeout)
|
||||
unpack_diffusion_output_shm(response)
|
||||
except Exception as e:
|
||||
logger.warning("SHM unpack failed (data may already be inline): %s", e)
|
||||
|
||||
try:
|
||||
unpack_diffusion_output_shm(response)
|
||||
except Exception as e:
|
||||
logger.warning("SHM unpack failed (data may already be inline): %s", e)
|
||||
# Check if response indicates an error
|
||||
if isinstance(response, dict) and response.get("status") == "error":
|
||||
raise RuntimeError(
|
||||
f"Worker failed with error '{response.get('error')}', "
|
||||
"please check the stack trace above for the root cause"
|
||||
)
|
||||
|
||||
# Check if response indicates an error
|
||||
if isinstance(response, dict) and response.get("status") == "error":
|
||||
raise RuntimeError(
|
||||
f"Worker failed with error '{response.get('error')}', "
|
||||
"please check the stack trace above for the root cause"
|
||||
)
|
||||
|
||||
responses.append(response)
|
||||
except zmq.error.Again as e:
|
||||
raise TimeoutError(f"RPC call to {method} timed out.") from e
|
||||
except TimeoutError as e:
|
||||
raise TimeoutError(f"RPC call to {method} timed out.") from e
|
||||
responses.append(response)
|
||||
|
||||
return responses[0] if unique_reply_rank is not None else responses
|
||||
except Exception as e:
|
||||
@@ -314,10 +385,13 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
raise
|
||||
|
||||
def check_health(self) -> None:
|
||||
# Simple check if processes are alive
|
||||
self._ensure_open()
|
||||
if self.is_failed:
|
||||
raise EngineDeadError()
|
||||
for p in self._processes:
|
||||
if not p.is_alive():
|
||||
raise RuntimeError(f"Worker process {p.name} is dead")
|
||||
self.is_failed = True
|
||||
raise EngineDeadError(f"Worker process {p.name} is dead")
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self._closed = True
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
"""Inline Stage Diffusion Client for vLLM-Omni multi-stage runtime.
|
||||
|
||||
Runs DiffusionEngine in a ThreadPoolExecutor inside the Orchestrator process
|
||||
instead of spawning a separate StageDiffusionProc subprocess, eliminating ZMQ
|
||||
IPC overhead. Used when there is only a single diffusion stage.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
from PIL import Image
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionRequestAbortedError
|
||||
from vllm_omni.diffusion.diffusion_engine import DiffusionEngine
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.engine.stage_init_utils import StageMetadata
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.inputs.data import OmniPromptType
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class InlineStageDiffusionClient:
|
||||
"""Runs DiffusionEngine in a thread executor inside the Orchestrator."""
|
||||
|
||||
stage_type: str = "diffusion"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model: str,
|
||||
od_config: OmniDiffusionConfig,
|
||||
metadata: StageMetadata,
|
||||
batch_size: int = 1,
|
||||
) -> None:
|
||||
self.model = model
|
||||
self.od_config = od_config
|
||||
self.stage_id = metadata.stage_id
|
||||
self.final_output = metadata.final_output
|
||||
self.final_output_type = metadata.final_output_type
|
||||
self.default_sampling_params = metadata.default_sampling_params
|
||||
self.custom_process_input_func = metadata.custom_process_input_func
|
||||
self.engine_input_source = metadata.engine_input_source
|
||||
self.batch_size = batch_size
|
||||
|
||||
self._enrich_config()
|
||||
self._engine = DiffusionEngine.make_engine(self.od_config)
|
||||
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="inline-diffusion")
|
||||
|
||||
self._output_queue: asyncio.Queue[OmniRequestOutput] = asyncio.Queue()
|
||||
self._tasks: dict[str, asyncio.Task] = {}
|
||||
self._shutting_down = False
|
||||
|
||||
logger.info(
|
||||
"[InlineStageDiffusionClient] Stage-%s initialized inline (batch_size=%d)",
|
||||
self.stage_id,
|
||||
self.batch_size,
|
||||
)
|
||||
|
||||
def _enrich_config(self) -> None:
|
||||
"""Load model metadata from HuggingFace and populate od_config fields."""
|
||||
self.od_config.enrich_config()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Request processing
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def add_request_async(
|
||||
self,
|
||||
request_id: str,
|
||||
prompt: OmniPromptType,
|
||||
sampling_params: OmniDiffusionSamplingParams,
|
||||
kv_sender_info: dict[int, dict[str, Any]] | None = None,
|
||||
) -> None:
|
||||
task = asyncio.create_task(
|
||||
self._dispatch_request(
|
||||
request_id,
|
||||
prompt,
|
||||
sampling_params,
|
||||
kv_sender_info,
|
||||
)
|
||||
)
|
||||
self._tasks[request_id] = task
|
||||
|
||||
async def _dispatch_request(
|
||||
self,
|
||||
request_id: str,
|
||||
prompt: Any,
|
||||
sampling_params: OmniDiffusionSamplingParams,
|
||||
kv_sender_info: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
request = OmniDiffusionRequest(
|
||||
prompts=[prompt],
|
||||
sampling_params=sampling_params,
|
||||
request_ids=[request_id],
|
||||
request_id=request_id,
|
||||
kv_sender_info=kv_sender_info,
|
||||
)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
results = await loop.run_in_executor(self._executor, self._engine.step, request)
|
||||
result = results[0]
|
||||
if not result.request_id:
|
||||
result.request_id = request_id
|
||||
|
||||
self._output_queue.put_nowait(result)
|
||||
except DiffusionRequestAbortedError as e:
|
||||
logger.info("request_id: %s aborted: %s", request_id, str(e))
|
||||
except Exception as e:
|
||||
logger.exception("Diffusion request %s failed: %s", request_id, e)
|
||||
error_output = OmniRequestOutput.from_diffusion(
|
||||
request_id=request_id,
|
||||
images=[],
|
||||
)
|
||||
error_output.error = str(e)
|
||||
self._output_queue.put_nowait(error_output)
|
||||
finally:
|
||||
self._tasks.pop(request_id, None)
|
||||
|
||||
async def add_batch_request_async(
|
||||
self,
|
||||
request_id: str,
|
||||
prompts: list[OmniPromptType],
|
||||
sampling_params: OmniDiffusionSamplingParams,
|
||||
kv_sender_info: dict[int, dict[str, Any]] | None = None,
|
||||
) -> None:
|
||||
task = asyncio.create_task(
|
||||
self._dispatch_batch(
|
||||
request_id,
|
||||
prompts,
|
||||
sampling_params,
|
||||
kv_sender_info,
|
||||
)
|
||||
)
|
||||
self._tasks[request_id] = task
|
||||
|
||||
async def _dispatch_batch(
|
||||
self,
|
||||
request_id: str,
|
||||
prompts: list[Any],
|
||||
sampling_params: OmniDiffusionSamplingParams,
|
||||
kv_sender_info: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
request = OmniDiffusionRequest(
|
||||
prompts=prompts,
|
||||
sampling_params=sampling_params,
|
||||
request_ids=[f"{request_id}-{i}" for i in range(len(prompts))],
|
||||
request_id=request_id,
|
||||
kv_sender_info=kv_sender_info,
|
||||
)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
results = await loop.run_in_executor(self._executor, self._engine.step, request)
|
||||
|
||||
all_images: list = []
|
||||
merged_mm: dict[str, Any] = {}
|
||||
merged_metrics: dict[str, Any] = {}
|
||||
merged_durations: dict[str, float] = {}
|
||||
merged_custom: dict[str, Any] = {}
|
||||
peak_mem = 0.0
|
||||
latents = None
|
||||
trajectory_latents: list[torch.Tensor] | None = None
|
||||
trajectory_timesteps: list[torch.Tensor] | None = None
|
||||
trajectory_log_probs: torch.Tensor | None = None
|
||||
trajectory_decoded: list[Image.Image] | None = None
|
||||
final_output_type = "image"
|
||||
|
||||
for r in results:
|
||||
all_images.extend(r.images)
|
||||
merged_mm.update(r._multimodal_output)
|
||||
merged_metrics.update(r.metrics)
|
||||
merged_durations.update(r.stage_durations)
|
||||
merged_custom.update(r._custom_output)
|
||||
peak_mem = max(peak_mem, r.peak_memory_mb)
|
||||
if latents is None and r.latents is not None:
|
||||
latents = r.latents
|
||||
if trajectory_latents is None:
|
||||
trajectory_latents = r.trajectory_latents
|
||||
if trajectory_timesteps is None:
|
||||
trajectory_timesteps = r.trajectory_timesteps
|
||||
if trajectory_log_probs is None:
|
||||
trajectory_log_probs = r.trajectory_log_probs
|
||||
if trajectory_decoded is None:
|
||||
trajectory_decoded = r.trajectory_decoded
|
||||
if r.final_output_type != "image":
|
||||
final_output_type = r.final_output_type
|
||||
|
||||
result = OmniRequestOutput.from_diffusion(
|
||||
request_id=request_id,
|
||||
images=all_images,
|
||||
prompt=prompts[0] if len(prompts) == 1 else None,
|
||||
metrics=merged_metrics,
|
||||
latents=latents,
|
||||
trajectory_latents=trajectory_latents,
|
||||
trajectory_timesteps=trajectory_timesteps,
|
||||
trajectory_log_probs=trajectory_log_probs,
|
||||
trajectory_decoded=trajectory_decoded,
|
||||
custom_output=merged_custom or None,
|
||||
multimodal_output=merged_mm or None,
|
||||
final_output_type=final_output_type,
|
||||
stage_durations=merged_durations,
|
||||
peak_memory_mb=peak_mem,
|
||||
)
|
||||
|
||||
self._output_queue.put_nowait(result)
|
||||
except DiffusionRequestAbortedError as e:
|
||||
logger.info("request_id: %s aborted: %s", request_id, str(e))
|
||||
except Exception as e:
|
||||
logger.exception("Batch diffusion request %s failed: %s", request_id, e)
|
||||
error_output = OmniRequestOutput.from_diffusion(
|
||||
request_id=request_id,
|
||||
images=[],
|
||||
)
|
||||
error_output.error = str(e)
|
||||
self._output_queue.put_nowait(error_output)
|
||||
finally:
|
||||
self._tasks.pop(request_id, None)
|
||||
|
||||
def get_diffusion_output_nowait(self) -> OmniRequestOutput | None:
|
||||
try:
|
||||
return self._output_queue.get_nowait()
|
||||
except asyncio.QueueEmpty:
|
||||
return None
|
||||
|
||||
async def abort_requests_async(self, request_ids: list[str]) -> None:
|
||||
for rid in request_ids:
|
||||
task = self._tasks.pop(rid, None)
|
||||
if task:
|
||||
task.cancel()
|
||||
self._engine.abort(rid)
|
||||
|
||||
async def collective_rpc_async(
|
||||
self,
|
||||
method: str,
|
||||
timeout: float | None = None,
|
||||
args: tuple[Any, ...] = (),
|
||||
kwargs: dict[str, Any] | None = None,
|
||||
) -> Any:
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
if method == "profile":
|
||||
is_start = args[0] if args else True
|
||||
profile_prefix = args[1] if len(args) > 1 else None
|
||||
if is_start and profile_prefix is None:
|
||||
profile_prefix = f"stage_{self.stage_id}_diffusion_{int(time.time())}"
|
||||
return await loop.run_in_executor(
|
||||
self._executor,
|
||||
self._engine.profile,
|
||||
is_start,
|
||||
profile_prefix,
|
||||
)
|
||||
|
||||
kwargs = kwargs or {}
|
||||
|
||||
# LoRA methods
|
||||
if method == "add_lora":
|
||||
lora_request = args[0] if args else kwargs.get("lora_request")
|
||||
results = await loop.run_in_executor(
|
||||
self._executor,
|
||||
self._engine.collective_rpc,
|
||||
"add_lora",
|
||||
timeout,
|
||||
(),
|
||||
{"lora_request": lora_request},
|
||||
None,
|
||||
)
|
||||
return all(results) if isinstance(results, list) else results
|
||||
|
||||
if method == "remove_lora":
|
||||
results = await loop.run_in_executor(
|
||||
self._executor,
|
||||
self._engine.collective_rpc,
|
||||
"remove_lora",
|
||||
timeout,
|
||||
args,
|
||||
kwargs,
|
||||
None,
|
||||
)
|
||||
return all(results) if isinstance(results, list) else results
|
||||
|
||||
if method == "list_loras":
|
||||
results = await loop.run_in_executor(
|
||||
self._executor,
|
||||
self._engine.collective_rpc,
|
||||
"list_loras",
|
||||
timeout,
|
||||
(),
|
||||
{},
|
||||
None,
|
||||
)
|
||||
if not isinstance(results, list):
|
||||
return results or []
|
||||
merged: set[int] = set()
|
||||
for part in results:
|
||||
merged.update(part or [])
|
||||
return sorted(merged)
|
||||
|
||||
if method == "pin_lora":
|
||||
lora_id = args[0] if args else kwargs.get("adapter_id")
|
||||
results = await loop.run_in_executor(
|
||||
self._executor,
|
||||
self._engine.collective_rpc,
|
||||
"pin_lora",
|
||||
timeout,
|
||||
(),
|
||||
{"adapter_id": lora_id},
|
||||
None,
|
||||
)
|
||||
return all(results) if isinstance(results, list) else results
|
||||
|
||||
return await loop.run_in_executor(
|
||||
self._executor,
|
||||
self._engine.collective_rpc,
|
||||
method,
|
||||
timeout,
|
||||
args,
|
||||
kwargs,
|
||||
None,
|
||||
)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self._shutting_down = True
|
||||
|
||||
# Cancel all pending tasks
|
||||
for task in self._tasks.values():
|
||||
task.cancel()
|
||||
|
||||
try:
|
||||
# Cancel queued futures and wait for the running one to complete deterministically
|
||||
self._executor.shutdown(wait=True, cancel_futures=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
self._engine.close()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -7,6 +7,7 @@ from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
|
||||
from vllm_omni.diffusion.layers.custom_op import CustomOp
|
||||
from vllm_omni.diffusion.layers.norm import LayerNorm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
@@ -27,107 +28,63 @@ class AdaLayerNorm(CustomOp):
|
||||
self.eps = eps
|
||||
self.elementwise_affine = elementwise_affine
|
||||
self.hidden_size = hidden_size
|
||||
self.layernorm = nn.LayerNorm(self.hidden_size, elementwise_affine=self.elementwise_affine, eps=self.eps)
|
||||
|
||||
def preprocess(
|
||||
self,
|
||||
mod_params: torch.Tensor,
|
||||
index: torch.Tensor = None,
|
||||
) -> torch.Tensor:
|
||||
# shift: b d, scale: b d, gate: b d
|
||||
shift, scale, gate = mod_params.chunk(3, dim=-1)
|
||||
|
||||
if index is not None:
|
||||
# Assuming mod_params batch dim is 2*actual_batch (chunked into 2 parts)
|
||||
# So shift, scale, gate have shape [2*actual_batch, d]
|
||||
actual_batch = shift.size(0) // 2
|
||||
shift_0, shift_1 = shift[:actual_batch], shift[actual_batch:] # each: [actual_batch, d]
|
||||
scale_0, scale_1 = scale[:actual_batch], scale[actual_batch:]
|
||||
gate_0, gate_1 = gate[:actual_batch], gate[actual_batch:]
|
||||
|
||||
# index: [b, l] where b is actual batch size
|
||||
# Expand to [b, l, 1] to match feature dimension
|
||||
index_expanded = index.unsqueeze(-1) # [b, l, 1]
|
||||
|
||||
# Expand chunks to [b, 1, d] then broadcast to [b, l, d]
|
||||
shift_0_exp = shift_0.unsqueeze(1) # [b, 1, d]
|
||||
shift_1_exp = shift_1.unsqueeze(1) # [b, 1, d]
|
||||
scale_0_exp = scale_0.unsqueeze(1)
|
||||
scale_1_exp = scale_1.unsqueeze(1)
|
||||
gate_0_exp = gate_0.unsqueeze(1)
|
||||
gate_1_exp = gate_1.unsqueeze(1)
|
||||
|
||||
# Use torch.where to select based on index
|
||||
shift_result = torch.where(index_expanded == 0, shift_0_exp, shift_1_exp)
|
||||
scale_result = torch.where(index_expanded == 0, scale_0_exp, scale_1_exp)
|
||||
gate_result = torch.where(index_expanded == 0, gate_0_exp, gate_1_exp)
|
||||
else:
|
||||
shift_result = shift.unsqueeze(1)
|
||||
scale_result = scale.unsqueeze(1)
|
||||
gate_result = gate.unsqueeze(1)
|
||||
|
||||
return shift_result, scale_result, gate_result
|
||||
self.layernorm = LayerNorm(self.hidden_size, elementwise_affine=self.elementwise_affine, eps=self.eps)
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
mod_params: torch.Tensor,
|
||||
index: torch.Tensor = None,
|
||||
scale: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.forward_native(x, mod_params, index)
|
||||
return self.forward_native(x, scale, shift)
|
||||
|
||||
def forward_hip(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
mod_params: torch.Tensor,
|
||||
index: torch.Tensor = None,
|
||||
scale: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.forward_native(x, mod_params, index)
|
||||
return self.forward_native(x, scale, shift)
|
||||
|
||||
def forward_npu(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
mod_params: torch.Tensor,
|
||||
index: torch.Tensor = None,
|
||||
scale: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
shift_result, scale_result, gate_result = self.preprocess(mod_params, index)
|
||||
|
||||
if _HAS_MINDIESD:
|
||||
try:
|
||||
from mindiesd import layernorm_scale_shift
|
||||
|
||||
output = layernorm_scale_shift(self.layernorm, x, scale_result, shift_result, fused=True)
|
||||
output = layernorm_scale_shift(self.layernorm, x, scale, shift, fused=True)
|
||||
|
||||
return output, gate_result
|
||||
return output
|
||||
except ImportError as e:
|
||||
logger.warning_once(f"mindiesd import failed, falling back to torch_npu: {e}")
|
||||
|
||||
import torch_npu
|
||||
|
||||
output = (
|
||||
torch_npu.npu_layer_norm_eval(x, normalized_shape=[self.hidden_size], eps=self.eps) * (1 + scale_result)
|
||||
+ shift_result
|
||||
torch_npu.npu_layer_norm_eval(x, normalized_shape=[self.hidden_size], eps=self.eps) * (1 + scale) + shift
|
||||
)
|
||||
|
||||
return output, gate_result
|
||||
return output
|
||||
|
||||
def forward_xpu(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
mod_params: torch.Tensor,
|
||||
index: torch.Tensor = None,
|
||||
scale: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.forward_native(x, mod_params, index)
|
||||
return self.forward_native(x, scale, shift)
|
||||
|
||||
def forward_native(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
mod_params: torch.Tensor,
|
||||
index: torch.Tensor = None,
|
||||
scale: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
shift_result, scale_result, gate_result = self.preprocess(mod_params, index)
|
||||
|
||||
return self.layernorm(x) * (1 + scale_result) + shift_result, gate_result
|
||||
return self.layernorm(x) * (1 + scale) + shift
|
||||
|
||||
|
||||
class AdaLayerNormZero(nn.Module):
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
from importlib.util import find_spec
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.layers.custom_op import CustomOp
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_HAS_MINDIESD = find_spec("mindiesd") is not None
|
||||
|
||||
|
||||
class LayerNorm(nn.LayerNorm, CustomOp):
|
||||
"""
|
||||
LayerNorm implementation that inherits from both ``nn.LayerNorm`` and ``CustomOp``.
|
||||
NPU:
|
||||
Uses ``mindiesd.fast_layernorm(self, x)`` when MindIE-SD is installed.
|
||||
CUDA / HIP / XPU / native:
|
||||
Falls back to FP32 nn.LayerNorm implementation.
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int, eps: float = 1e-6, elementwise_affine: bool = True):
|
||||
super().__init__(normalized_shape=dim, eps=eps, elementwise_affine=elementwise_affine)
|
||||
# CustomOp.__init__ cannot be called here because it would re-run
|
||||
# nn.Module initialization and clear LayerNorm parameters.
|
||||
self._forward_method = CustomOp.dispatch_forward(self)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self._forward_method(x)
|
||||
|
||||
def forward_cuda(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
def forward_hip(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
def forward_xpu(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
def forward_npu(self, x: torch.Tensor) -> torch.Tensor:
|
||||
if _HAS_MINDIESD:
|
||||
try:
|
||||
from mindiesd import fast_layernorm
|
||||
|
||||
return fast_layernorm(self, x)
|
||||
except ImportError as e:
|
||||
logger.warning_once(
|
||||
"mindiesd.fast_layernorm import failed, falling back to FP32 layer_norm: %s",
|
||||
e,
|
||||
)
|
||||
|
||||
return self.forward_native(x)
|
||||
|
||||
def forward_native(self, x: torch.Tensor) -> torch.Tensor:
|
||||
origin_dtype = x.dtype
|
||||
return F.layer_norm(
|
||||
x.float(),
|
||||
self.normalized_shape,
|
||||
self.weight.float() if self.weight is not None else None,
|
||||
self.bias.float() if self.bias is not None else None,
|
||||
self.eps,
|
||||
).to(origin_dtype)
|
||||
|
||||
|
||||
class RMSNorm(CustomOp):
|
||||
def __init__(self, hidden_size: int, eps: float = 1e-6) -> None:
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
self.variance_epsilon = eps
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
def forward_hip(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
def forward_npu(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
import torch_npu
|
||||
|
||||
output = torch_npu.npu_rms_norm(x, gamma=self.weight, epsilon=self.variance_epsilon)[0]
|
||||
|
||||
return output
|
||||
|
||||
def forward_xpu(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
def forward_native(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
input_dtype = x.dtype
|
||||
x = x.to(torch.float32)
|
||||
variance = x.pow(2).mean(-1, keepdim=True)
|
||||
out = x * torch.rsqrt(variance + self.variance_epsilon)
|
||||
out = self.weight.to(torch.float32) * out
|
||||
return out.to(input_dtype)
|
||||
@@ -0,0 +1,31 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiffusionModelMetadata:
|
||||
# Keep serving-facing capability metadata in a lightweight shared module so
|
||||
# config/model plumbing can read it without importing concrete pipelines.
|
||||
supports_multimodal_inputs: bool = False
|
||||
max_multimodal_image_inputs: int | None = None
|
||||
|
||||
|
||||
QWEN_IMAGE_EDIT_PLUS_MAX_INPUT_IMAGES = 4
|
||||
|
||||
|
||||
_DIFFUSION_MODEL_METADATA: dict[str, DiffusionModelMetadata] = {
|
||||
"QwenImageEditPlusPipeline": DiffusionModelMetadata(
|
||||
supports_multimodal_inputs=True,
|
||||
max_multimodal_image_inputs=QWEN_IMAGE_EDIT_PLUS_MAX_INPUT_IMAGES,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def get_diffusion_model_metadata(model_class_name: str | None) -> DiffusionModelMetadata:
|
||||
# Unknown models fall back to "no special multimodal capabilities" so new
|
||||
# pipelines do not accidentally inherit limits meant for other models.
|
||||
if model_class_name is None:
|
||||
return DiffusionModelMetadata()
|
||||
return _DIFFUSION_MODEL_METADATA.get(model_class_name, DiffusionModelMetadata())
|
||||
@@ -365,35 +365,65 @@ class BagelPipeline(nn.Module, DiffusionPipelineProfilerMixin):
|
||||
if req.sampling_params.kv_metadata and "image_shape" in req.sampling_params.kv_metadata:
|
||||
image_shape = tuple(req.sampling_params.kv_metadata["image_shape"])
|
||||
|
||||
cfg_text_kv = getattr(req.sampling_params, "cfg_text_past_key_values", None)
|
||||
branch_kvs = getattr(req.sampling_params, "cfg_branch_past_key_values", None) or {}
|
||||
branch_metadata = getattr(req.sampling_params, "cfg_branch_kv_metadata", None) or {}
|
||||
active_branch = getattr(req.sampling_params, "cfg_active_branch", None)
|
||||
branch_roles = getattr(req.sampling_params, "cfg_branch_roles", None) or list(branch_kvs.keys())
|
||||
|
||||
cfg_text_kv = getattr(req.sampling_params, "cfg_text_past_key_values", None) or branch_kvs.get("cfg_text")
|
||||
cfg_text_metadata = getattr(req.sampling_params, "cfg_text_kv_metadata", None) or branch_metadata.get(
|
||||
"cfg_text"
|
||||
)
|
||||
cfg_img_kv = getattr(req.sampling_params, "cfg_img_past_key_values", None) or branch_kvs.get("cfg_img")
|
||||
cfg_img_metadata = getattr(req.sampling_params, "cfg_img_kv_metadata", None) or branch_metadata.get(
|
||||
"cfg_img"
|
||||
)
|
||||
|
||||
cfg_parallel_contract = (
|
||||
active_branch is not None or bool(branch_roles) or cfg_text_kv is not None or cfg_img_kv is not None
|
||||
)
|
||||
if cfg_parallel_contract:
|
||||
logger.info(
|
||||
"CFG enabled with injected branch KV context roles=%s active=%s",
|
||||
branch_roles,
|
||||
active_branch,
|
||||
)
|
||||
|
||||
if cfg_text_kv is not None:
|
||||
logger.info("CFG enabled with multi-KV: using injected cfg_text KV Cache")
|
||||
cfg_text_seq_len = cfg_text_kv.key_cache[0].shape[0]
|
||||
cfg_text_context["past_key_values"] = cfg_text_kv
|
||||
cfg_text_context["kv_lens"] = [cfg_text_seq_len]
|
||||
cfg_text_metadata = getattr(req.sampling_params, "cfg_text_kv_metadata", None)
|
||||
if cfg_text_metadata and "ropes" in cfg_text_metadata:
|
||||
cfg_text_context["ropes"] = cfg_text_metadata["ropes"]
|
||||
else:
|
||||
cfg_text_context["ropes"] = [cfg_text_seq_len]
|
||||
else:
|
||||
# No cfg_text companion received. For text2img this is the
|
||||
# expected path: original BAGEL uses an empty KV cache (0
|
||||
# tokens) as the text-unconditional branch. Keep the default
|
||||
# empty NaiveCache in cfg_text_context and preserve the
|
||||
# original cfg_text_scale so CFG still applies.
|
||||
pass
|
||||
|
||||
cfg_img_kv = getattr(req.sampling_params, "cfg_img_past_key_values", None) or injected_kv
|
||||
if cfg_img_kv is None:
|
||||
# text2img multi-stage: cfg_img reuses gen KV (positive prompt,
|
||||
# no image), mirroring forward_cache_update_text on cfg_img_context
|
||||
# in the single-stage path.
|
||||
cfg_img_seq_len = injected_kv.key_cache[0].shape[0]
|
||||
cfg_img_context["past_key_values"] = injected_kv
|
||||
cfg_img_context["kv_lens"] = [cfg_img_seq_len]
|
||||
if req.sampling_params.kv_metadata and "ropes" in req.sampling_params.kv_metadata:
|
||||
cfg_img_context["ropes"] = req.sampling_params.kv_metadata["ropes"]
|
||||
else:
|
||||
cfg_img_context["ropes"] = [cfg_img_seq_len]
|
||||
else:
|
||||
cfg_img_seq_len = cfg_img_kv.key_cache[0].shape[0]
|
||||
cfg_img_context["past_key_values"] = cfg_img_kv
|
||||
cfg_img_context["kv_lens"] = [cfg_img_seq_len]
|
||||
cfg_img_metadata = getattr(req.sampling_params, "cfg_img_kv_metadata", None)
|
||||
if cfg_img_metadata and "ropes" in cfg_img_metadata:
|
||||
cfg_img_context["ropes"] = cfg_img_metadata["ropes"]
|
||||
else:
|
||||
cfg_img_context["ropes"] = [cfg_img_seq_len]
|
||||
else:
|
||||
logger.warning("CFG is disabled: only single KV cache available")
|
||||
gen_params = BagelGenParams(
|
||||
num_timesteps=gen_params.num_timesteps,
|
||||
timestep_shift=gen_params.timestep_shift,
|
||||
cfg_text_scale=1.0,
|
||||
cfg_img_scale=1.0,
|
||||
)
|
||||
|
||||
else:
|
||||
image_input = (
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from vllm_omni.diffusion.models.dmd2.mixin import DMD2PipelineMixin
|
||||
|
||||
__all__ = [
|
||||
"DMD2PipelineMixin",
|
||||
]
|
||||
@@ -0,0 +1,88 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput
|
||||
from vllm_omni.diffusion.models.schedulers import DMD2EulerScheduler
|
||||
from vllm_omni.diffusion.models.utils import _load_json
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DMD2PipelineMixin:
|
||||
"""Mixin for FastGen DMD2-distilled models. Must appear before the base pipeline in MRO."""
|
||||
|
||||
def __init_dmd2__(self) -> None:
|
||||
"""Call after super().__init__() to apply DMD2 scheduler and read model_index."""
|
||||
local_files_only = os.path.exists(self.od_config.model)
|
||||
try:
|
||||
model_index = _load_json(self.od_config.model, "model_index.json", local_files_only)
|
||||
except Exception:
|
||||
model_index = {}
|
||||
|
||||
dmd2_timesteps = model_index.get("dmd2_denoising_timesteps", [999, 937, 833, 624])
|
||||
self.num_inference_steps = model_index.get("dmd2_num_inference_steps", 4)
|
||||
shift = model_index.get("dmd2_scheduler_shift", 1.0)
|
||||
self.dmd2_guidance_scale = model_index.get("dmd2_guidance_scale", 1.0)
|
||||
|
||||
self.scheduler = DMD2EulerScheduler(
|
||||
num_train_timesteps=1000,
|
||||
shift=shift,
|
||||
dmd2_timesteps=dmd2_timesteps,
|
||||
)
|
||||
|
||||
def _sanitize_dmd2_request(self, req: OmniDiffusionRequest) -> None:
|
||||
"""Sanitize CFG-related fields in-place. Mutates req.sampling_params and req.prompts."""
|
||||
sp = req.sampling_params
|
||||
|
||||
if sp.num_inference_steps and sp.num_inference_steps != self.num_inference_steps:
|
||||
logger.warning(
|
||||
"DMD2: ignoring num_inference_steps=%d, forcing %d.",
|
||||
sp.num_inference_steps,
|
||||
self.num_inference_steps,
|
||||
)
|
||||
sp.num_inference_steps = self.num_inference_steps
|
||||
|
||||
if sp.guidance_scale_provided and sp.guidance_scale != self.dmd2_guidance_scale:
|
||||
logger.warning(
|
||||
"DMD2: ignoring guidance_scale=%.2f, forcing %.2f.",
|
||||
sp.guidance_scale,
|
||||
self.dmd2_guidance_scale,
|
||||
)
|
||||
sp.guidance_scale = self.dmd2_guidance_scale
|
||||
sp.guidance_scale_provided = False
|
||||
|
||||
if sp.guidance_scale_2 is not None:
|
||||
logger.warning("DMD2: ignoring guidance_scale_2.")
|
||||
sp.guidance_scale_2 = None
|
||||
|
||||
if sp.true_cfg_scale is not None:
|
||||
logger.warning("DMD2: ignoring true_cfg_scale.")
|
||||
sp.true_cfg_scale = None
|
||||
|
||||
sp.do_classifier_free_guidance = False
|
||||
sp.is_cfg_negative = False
|
||||
|
||||
fixed = []
|
||||
for p in req.prompts:
|
||||
if isinstance(p, dict) and "negative_prompt" in p:
|
||||
logger.warning("DMD2: ignoring negative_prompt.")
|
||||
p = {k: v for k, v in p.items() if k != "negative_prompt"}
|
||||
fixed.append(p)
|
||||
req.prompts = fixed
|
||||
|
||||
def forward(self, req: OmniDiffusionRequest, **kwargs) -> DiffusionOutput:
|
||||
self._sanitize_dmd2_request(req)
|
||||
kwargs.pop("guidance_scale", None)
|
||||
kwargs.pop("num_inference_steps", None)
|
||||
return super().forward(
|
||||
req,
|
||||
guidance_scale=self.dmd2_guidance_scale,
|
||||
num_inference_steps=self.num_inference_steps,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -1,3 +1,5 @@
|
||||
import re
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.logger import init_logger
|
||||
@@ -15,78 +17,26 @@ from vllm_omni.diffusion.models.dreamid_omni.wan2_2 import WanModel, rope_apply
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class FusionModel(nn.Module):
|
||||
def __init__(self, video_config=None, audio_config=None):
|
||||
super().__init__()
|
||||
has_video = True
|
||||
has_audio = True
|
||||
if video_config is not None:
|
||||
self.video_model = WanModel(**video_config)
|
||||
else:
|
||||
has_video = False
|
||||
self.video_model = None
|
||||
logger.warning("No video model is provided!")
|
||||
class FusedBlock(nn.Module):
|
||||
"""Wrapper pairing a video block and audio block for layerwise offloading.
|
||||
|
||||
if audio_config is not None:
|
||||
self.audio_model = WanModel(**audio_config)
|
||||
else:
|
||||
has_audio = False
|
||||
self.audio_model = None
|
||||
logger.warning("No audio model is provided!")
|
||||
Registers both blocks as submodules so their parameters are visible to the offload hooks.
|
||||
"""
|
||||
|
||||
if has_video and has_audio:
|
||||
assert len(self.video_model.blocks) == len(self.audio_model.blocks)
|
||||
self.num_blocks = len(self.video_model.blocks)
|
||||
|
||||
self.inject_cross_attention_kv_projections()
|
||||
self.device = get_local_device()
|
||||
|
||||
self.num_heads = self.video_model.num_heads
|
||||
self.head_dim = self.video_model.dim // self.video_model.num_heads
|
||||
self.attn = Attention(
|
||||
num_heads=self.num_heads,
|
||||
head_size=self.head_dim,
|
||||
num_kv_heads=self.num_heads,
|
||||
softmax_scale=1.0 / (self.head_dim**0.5),
|
||||
causal=False,
|
||||
)
|
||||
|
||||
def inject_cross_attention_kv_projections(self):
|
||||
for vid_block in self.video_model.blocks:
|
||||
vid_block.cross_attn.k_fusion = nn.Linear(vid_block.dim, vid_block.dim)
|
||||
vid_block.cross_attn.v_fusion = nn.Linear(vid_block.dim, vid_block.dim)
|
||||
vid_block.cross_attn.pre_attn_norm_fusion = WanLayerNorm(vid_block.dim, elementwise_affine=True)
|
||||
vid_block.cross_attn.norm_k_fusion = (
|
||||
WanRMSNorm(vid_block.dim, eps=1e-6) if vid_block.qk_norm else nn.Identity()
|
||||
)
|
||||
|
||||
for audio_block in self.audio_model.blocks:
|
||||
audio_block.cross_attn.k_fusion = nn.Linear(audio_block.dim, audio_block.dim)
|
||||
audio_block.cross_attn.v_fusion = nn.Linear(audio_block.dim, audio_block.dim)
|
||||
audio_block.cross_attn.pre_attn_norm_fusion = WanLayerNorm(audio_block.dim, elementwise_affine=True)
|
||||
audio_block.cross_attn.norm_k_fusion = (
|
||||
WanRMSNorm(audio_block.dim, eps=1e-6) if audio_block.qk_norm else nn.Identity()
|
||||
)
|
||||
|
||||
def merge_kwargs(self, vid_kwargs, audio_kwargs):
|
||||
"""
|
||||
keys in each kwarg:
|
||||
e
|
||||
seq_lens
|
||||
grid_sizes
|
||||
freqs
|
||||
context
|
||||
context_lens
|
||||
"""
|
||||
merged_kwargs = {}
|
||||
for key in vid_kwargs:
|
||||
merged_kwargs[f"vid_{key}"] = vid_kwargs[key]
|
||||
for key in audio_kwargs:
|
||||
merged_kwargs[f"audio_{key}"] = audio_kwargs[key]
|
||||
return merged_kwargs
|
||||
|
||||
def single_fusion_cross_attention_forward(
|
||||
def __init__(
|
||||
self,
|
||||
vid_block: nn.Module,
|
||||
audio_block: nn.Module,
|
||||
device: torch.device,
|
||||
):
|
||||
super().__init__()
|
||||
self.vid_block = vid_block
|
||||
self.audio_block = audio_block
|
||||
self.device = device
|
||||
|
||||
def _cross_attention_forward(
|
||||
self,
|
||||
attn: Attention,
|
||||
cross_attn_block,
|
||||
src_seq,
|
||||
src_grid_sizes,
|
||||
@@ -104,21 +54,17 @@ class FusionModel(nn.Module):
|
||||
):
|
||||
b, n, d = src_seq.size(0), cross_attn_block.num_heads, cross_attn_block.head_dim
|
||||
if hasattr(cross_attn_block, "k_img"):
|
||||
## means is i2v block
|
||||
q, k, v, k_img, v_img = cross_attn_block.qkv_fn(src_seq, context)
|
||||
else:
|
||||
## means is t2v block
|
||||
q, k, v = cross_attn_block.qkv_fn(src_seq, context)
|
||||
k_img = v_img = None
|
||||
|
||||
x = self.attn(q, k, v)
|
||||
x = attn(q, k, v)
|
||||
|
||||
if k_img is not None:
|
||||
img_x = self.attn(q, k_img, v_img)
|
||||
img_x = attn(q, k_img, v_img)
|
||||
x = x + img_x
|
||||
|
||||
# is_vid = src_grid_sizes.shape[1] > 1
|
||||
# compute target attention
|
||||
target_seq = cross_attn_block.pre_attn_norm_fusion(target_seq)
|
||||
k_target = cross_attn_block.norm_k_fusion(cross_attn_block.k_fusion(target_seq)).view(b, -1, n, d)
|
||||
v_target = cross_attn_block.v_fusion(target_seq).view(b, -1, n, d)
|
||||
@@ -132,17 +78,16 @@ class FusionModel(nn.Module):
|
||||
freqs_scaling=target_freqs_scaling,
|
||||
)
|
||||
|
||||
target_x = self.attn(q, k_target, v_target)
|
||||
target_x = attn(q, k_target, v_target)
|
||||
|
||||
x = x + target_x
|
||||
|
||||
x = x.flatten(2) # [B, L/P, C]
|
||||
|
||||
x = x.flatten(2)
|
||||
x = cross_attn_block.o(x)
|
||||
return x
|
||||
|
||||
def single_fusion_cross_attention_ffn_forward(
|
||||
def _cross_attention_ffn_forward(
|
||||
self,
|
||||
attn: Attention,
|
||||
attn_block,
|
||||
src_seq,
|
||||
src_grid_sizes,
|
||||
@@ -159,7 +104,8 @@ class FusionModel(nn.Module):
|
||||
target_ref_lengths=None,
|
||||
target_freqs_scaling=None,
|
||||
):
|
||||
src_seq = src_seq + self.single_fusion_cross_attention_forward(
|
||||
src_seq = src_seq + self._cross_attention_forward(
|
||||
attn,
|
||||
attn_block.cross_attn,
|
||||
attn_block.norm3(src_seq),
|
||||
src_grid_sizes=src_grid_sizes,
|
||||
@@ -180,12 +126,11 @@ class FusionModel(nn.Module):
|
||||
src_seq = src_seq + y * src_e[5].squeeze(2)
|
||||
return src_seq
|
||||
|
||||
def single_fusion_block_forward(
|
||||
def forward(
|
||||
self,
|
||||
vid_block,
|
||||
audio_block,
|
||||
vid,
|
||||
audio,
|
||||
attn: Attention,
|
||||
vid_e,
|
||||
vid_seq_lens,
|
||||
vid_grid_sizes,
|
||||
@@ -203,6 +148,9 @@ class FusionModel(nn.Module):
|
||||
audio_ref_lengths,
|
||||
audio_freqs_scaling,
|
||||
):
|
||||
vid_block = self.vid_block
|
||||
audio_block = self.audio_block
|
||||
|
||||
## audio modulation
|
||||
assert audio_e.dtype == torch.bfloat16
|
||||
assert len(audio_e.shape) == 4 and audio_e.size(2) == 6 and audio_e.shape[1] == audio.shape[1], (
|
||||
@@ -246,7 +194,8 @@ class FusionModel(nn.Module):
|
||||
og_audio = audio
|
||||
|
||||
# audio cross-attention
|
||||
audio = self.single_fusion_cross_attention_ffn_forward(
|
||||
audio = self._cross_attention_ffn_forward(
|
||||
attn,
|
||||
audio_block,
|
||||
audio,
|
||||
audio_grid_sizes,
|
||||
@@ -267,7 +216,8 @@ class FusionModel(nn.Module):
|
||||
assert not torch.equal(og_audio, audio), "Audio should be changed after cross-attention!"
|
||||
|
||||
# video cross-attention
|
||||
vid = self.single_fusion_cross_attention_ffn_forward(
|
||||
vid = self._cross_attention_ffn_forward(
|
||||
attn,
|
||||
vid_block,
|
||||
vid,
|
||||
vid_grid_sizes,
|
||||
@@ -287,6 +237,128 @@ class FusionModel(nn.Module):
|
||||
|
||||
return vid, audio
|
||||
|
||||
|
||||
class FusionModel(nn.Module):
|
||||
_layerwise_offload_blocks_attrs = ["fused_blocks"]
|
||||
|
||||
def __init__(self, video_config=None, audio_config=None):
|
||||
super().__init__()
|
||||
has_video = True
|
||||
has_audio = True
|
||||
self.device = get_local_device()
|
||||
if video_config is not None:
|
||||
self.video_model = WanModel(**video_config)
|
||||
else:
|
||||
has_video = False
|
||||
self.video_model = None
|
||||
logger.warning("No video model is provided!")
|
||||
|
||||
if audio_config is not None:
|
||||
self.audio_model = WanModel(**audio_config)
|
||||
else:
|
||||
has_audio = False
|
||||
self.audio_model = None
|
||||
logger.warning("No audio model is provided!")
|
||||
|
||||
if has_video and has_audio:
|
||||
assert len(self.video_model.blocks) == len(self.audio_model.blocks)
|
||||
self.num_blocks = len(self.video_model.blocks)
|
||||
|
||||
self.inject_cross_attention_kv_projections()
|
||||
|
||||
self.num_heads = self.video_model.num_heads
|
||||
self.head_dim = self.video_model.dim // self.video_model.num_heads
|
||||
# Make a single shared instance to pass in at forward time
|
||||
self.attn = Attention(
|
||||
num_heads=self.num_heads,
|
||||
head_size=self.head_dim,
|
||||
num_kv_heads=self.num_heads,
|
||||
softmax_scale=1.0 / (self.head_dim**0.5),
|
||||
causal=False,
|
||||
)
|
||||
|
||||
if has_video and has_audio:
|
||||
self.fused_blocks = nn.ModuleList(
|
||||
[
|
||||
FusedBlock(
|
||||
self.video_model.blocks[i],
|
||||
self.audio_model.blocks[i],
|
||||
self.device,
|
||||
)
|
||||
for i in range(self.num_blocks)
|
||||
]
|
||||
)
|
||||
|
||||
def load_state_dict(self, state_dict, strict=True, assign=False):
|
||||
"""Remap checkpoints where blocks are stored under
|
||||
`video_model.blocks.N.*` / `audio_model.blocks.N.*` to the current
|
||||
`fused_blocks.N.vid_block.*` / `fused_blocks.N.audio_block.*`.
|
||||
"""
|
||||
needs_remap = any(re.match(r"^(video_model|audio_model)\.blocks\.\d+\.", k) for k in state_dict)
|
||||
if needs_remap:
|
||||
remapped = {}
|
||||
for k, v in state_dict.items():
|
||||
new_k = re.sub(r"^video_model\.blocks\.(\d+)\.", r"fused_blocks.\1.vid_block.", k)
|
||||
new_k = re.sub(r"^audio_model\.blocks\.(\d+)\.", r"fused_blocks.\1.audio_block.", new_k)
|
||||
remapped[new_k] = v
|
||||
state_dict = remapped
|
||||
|
||||
self._detach_blocks_from_backbones()
|
||||
|
||||
return super().load_state_dict(state_dict, strict=strict, assign=assign)
|
||||
|
||||
def inject_cross_attention_kv_projections(self):
|
||||
for vid_block in self.video_model.blocks:
|
||||
vid_block.cross_attn.k_fusion = nn.Linear(vid_block.dim, vid_block.dim)
|
||||
vid_block.cross_attn.v_fusion = nn.Linear(vid_block.dim, vid_block.dim)
|
||||
vid_block.cross_attn.pre_attn_norm_fusion = WanLayerNorm(vid_block.dim, elementwise_affine=True)
|
||||
vid_block.cross_attn.norm_k_fusion = (
|
||||
WanRMSNorm(vid_block.dim, eps=1e-6) if vid_block.qk_norm else nn.Identity()
|
||||
)
|
||||
|
||||
for audio_block in self.audio_model.blocks:
|
||||
audio_block.cross_attn.k_fusion = nn.Linear(audio_block.dim, audio_block.dim)
|
||||
audio_block.cross_attn.v_fusion = nn.Linear(audio_block.dim, audio_block.dim)
|
||||
audio_block.cross_attn.pre_attn_norm_fusion = WanLayerNorm(audio_block.dim, elementwise_affine=True)
|
||||
audio_block.cross_attn.norm_k_fusion = (
|
||||
WanRMSNorm(audio_block.dim, eps=1e-6) if audio_block.qk_norm else nn.Identity()
|
||||
)
|
||||
|
||||
def _detach_blocks_from_backbones(self) -> None:
|
||||
"""Keep offloadable blocks owned only by a single place.
|
||||
|
||||
NOTE: This is a special workaround to support layerwise offloading.
|
||||
The model registers the same Wan blocks under both the video/audio
|
||||
backbones and `fused_blocks` which is a wrapper for unified blocks
|
||||
walking through. However, layerwise offloading will only consider
|
||||
`fused_blocks` as offloadable components and will materialize all
|
||||
other modules onto device, including the same blocks owned by both
|
||||
`fused_blocks` and `video_model` and `audio_model`.
|
||||
"""
|
||||
video_blocks = list(self.video_model.blocks)
|
||||
audio_blocks = list(self.audio_model.blocks)
|
||||
self.video_model._modules.pop("blocks", None)
|
||||
self.audio_model._modules.pop("blocks", None)
|
||||
self.video_model.blocks = tuple(video_blocks)
|
||||
self.audio_model.blocks = tuple(audio_blocks)
|
||||
|
||||
def merge_kwargs(self, vid_kwargs, audio_kwargs):
|
||||
"""
|
||||
keys in each kwarg:
|
||||
e
|
||||
seq_lens
|
||||
grid_sizes
|
||||
freqs
|
||||
context
|
||||
context_lens
|
||||
"""
|
||||
merged_kwargs = {}
|
||||
for key in vid_kwargs:
|
||||
merged_kwargs[f"vid_{key}"] = vid_kwargs[key]
|
||||
for key in audio_kwargs:
|
||||
merged_kwargs[f"audio_{key}"] = audio_kwargs[key]
|
||||
return merged_kwargs
|
||||
|
||||
def forward(
|
||||
self,
|
||||
vid,
|
||||
@@ -316,17 +388,8 @@ class FusionModel(nn.Module):
|
||||
|
||||
kwargs = self.merge_kwargs(vid_kwargs, audio_kwargs)
|
||||
|
||||
for i in range(self.num_blocks):
|
||||
"""
|
||||
1 fusion block refers to 1 audio block with 1 video block.
|
||||
"""
|
||||
|
||||
vid_block = self.video_model.blocks[i]
|
||||
audio_block = self.audio_model.blocks[i]
|
||||
|
||||
vid, audio = self.single_fusion_block_forward(
|
||||
vid_block=vid_block, audio_block=audio_block, vid=vid, audio=audio, **kwargs
|
||||
)
|
||||
for fused_block in self.fused_blocks:
|
||||
vid, audio = fused_block(vid, audio, self.attn, **kwargs)
|
||||
|
||||
vid = self.video_model.post_transformer_block_out(vid, vid_kwargs["grid_sizes"], vid_e)
|
||||
audio = self.audio_model.post_transformer_block_out(audio, audio_kwargs["grid_sizes"], audio_e)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
from collections.abc import Iterable
|
||||
|
||||
import torch
|
||||
import torch.distributed
|
||||
@@ -16,6 +17,7 @@ from tqdm import tqdm
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.interface import SupportAudioInput, SupportImageInput
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
|
||||
@@ -27,7 +29,6 @@ try:
|
||||
init_mmaudio_vae,
|
||||
init_text_model,
|
||||
init_wan_vae_2_2,
|
||||
load_fusion_checkpoint,
|
||||
)
|
||||
from dreamid_omni.utils.rearrange import Rearrange
|
||||
from dreamid_omni.utils.resize import NaResize
|
||||
@@ -38,6 +39,21 @@ from vllm_omni.diffusion.models.dreamid_omni.fusion import FusionModel
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_dreamid_omni_post_process_func(*args, **kwargs):
|
||||
def post_process(output):
|
||||
if isinstance(output, tuple) and len(output) == 2:
|
||||
video, audio = output
|
||||
return {
|
||||
"video": video,
|
||||
"audio": audio,
|
||||
"audio_sample_rate": 16000,
|
||||
"fps": 24,
|
||||
}
|
||||
return output
|
||||
|
||||
return post_process
|
||||
|
||||
|
||||
AUDIO_CONFIG = {
|
||||
"patch_size": [1],
|
||||
"model_type": "t2a",
|
||||
@@ -107,16 +123,24 @@ class DreamIDOmniPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Suppor
|
||||
self.text_model = init_text_model(model, rank=self.device)
|
||||
self.text_encoder = self.text_model.model
|
||||
|
||||
# Fusion model
|
||||
## load audio/video model config
|
||||
Fusion_model = FusionModel(VIDEO_CONFIG, AUDIO_CONFIG)
|
||||
|
||||
checkpoint_path = self.od_config.tf_model_config.get("fusion", None)
|
||||
assert checkpoint_path is not None, "fusion checkpoint path is None"
|
||||
load_fusion_checkpoint(Fusion_model, checkpoint_path=os.path.join(model, checkpoint_path))
|
||||
self.model = Fusion_model
|
||||
# Fusion model — weights are loaded later via load_weights()
|
||||
self.model = FusionModel(VIDEO_CONFIG, AUDIO_CONFIG)
|
||||
self.transformer = self.model
|
||||
|
||||
fusion_path = self.od_config.tf_model_config.get("fusion", None)
|
||||
assert fusion_path is not None, "fusion checkpoint path is None in transformer config"
|
||||
fusion_subfolder = os.path.dirname(fusion_path) or None
|
||||
fusion_filename = os.path.basename(fusion_path)
|
||||
self.weights_sources = [
|
||||
DiffusersPipelineLoader.ComponentSource(
|
||||
model_or_path=model,
|
||||
subfolder=fusion_subfolder,
|
||||
revision=None,
|
||||
prefix="model.",
|
||||
allow_patterns_overrides=[fusion_filename],
|
||||
)
|
||||
]
|
||||
|
||||
# Fixed attributes, non-configurable
|
||||
self.audio_latent_channel = AUDIO_CONFIG.get("in_dim")
|
||||
self.video_latent_channel = VIDEO_CONFIG.get("in_dim")
|
||||
@@ -211,8 +235,11 @@ class DreamIDOmniPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Suppor
|
||||
|
||||
return ref_vae_latents, ref_audio_lengths
|
||||
|
||||
def load_weights(self, weights):
|
||||
pass
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
prefix = "model."
|
||||
state_dict = {name[len(prefix) :]: tensor for name, tensor in weights if name.startswith(prefix)}
|
||||
self.model.load_state_dict(state_dict, strict=True)
|
||||
return {prefix + k for k in state_dict}
|
||||
|
||||
def get_scheduler_time_steps(self, sampling_steps, solver_name="unipc", device=0, shift=5.0):
|
||||
torch.manual_seed(4)
|
||||
|
||||
@@ -381,7 +381,9 @@ class FluxSingleTransformerBlock(nn.Module):
|
||||
super().__init__()
|
||||
self.mlp_hidden_dim = int(dim * mlp_ratio)
|
||||
|
||||
self.norm = AdaLayerNormZeroSingle(dim, quant_config=quant_config, prefix=f"{prefix}.norm")
|
||||
# Modulation linear kept full precision; shift/scale/gate outputs
|
||||
# are multiplied into the residual stream every block (see #2728).
|
||||
self.norm = AdaLayerNormZeroSingle(dim, quant_config=None, prefix=f"{prefix}.norm")
|
||||
self.proj_mlp = ReplicatedLinear(
|
||||
dim,
|
||||
self.mlp_hidden_dim,
|
||||
@@ -524,10 +526,10 @@ class FluxTransformer2DModel(nn.Module):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
od_config: OmniDiffusionConfig = None,
|
||||
od_config: OmniDiffusionConfig | None = None,
|
||||
patch_size: int = 1,
|
||||
in_channels: int = 64,
|
||||
out_channels: int = None,
|
||||
out_channels: int | None = None,
|
||||
num_layers: int = 19,
|
||||
num_single_layers: int = 38,
|
||||
attention_head_dim: int = 128,
|
||||
@@ -563,13 +565,16 @@ class FluxTransformer2DModel(nn.Module):
|
||||
self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim)
|
||||
self.x_embedder = nn.Linear(in_channels, self.inner_dim)
|
||||
|
||||
# Dual-stream blocks kept full precision — FP8 on their joint
|
||||
# attention path causes noise on FLUX (#2728). Single-stream
|
||||
# blocks (38 vs 19) still get FP8 for memory savings.
|
||||
self.transformer_blocks = nn.ModuleList(
|
||||
[
|
||||
FluxTransformerBlock(
|
||||
dim=self.inner_dim,
|
||||
num_attention_heads=num_attention_heads,
|
||||
attention_head_dim=attention_head_dim,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
prefix=f"transformer_blocks.{i}",
|
||||
)
|
||||
for i in range(num_layers)
|
||||
@@ -589,12 +594,13 @@ class FluxTransformer2DModel(nn.Module):
|
||||
]
|
||||
)
|
||||
|
||||
# Final modulation feeds proj_out; keep full precision (see #2728).
|
||||
self.norm_out = AdaLayerNormContinuous(
|
||||
self.inner_dim,
|
||||
self.inner_dim,
|
||||
elementwise_affine=False,
|
||||
eps=1e-6,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
prefix="norm_out",
|
||||
)
|
||||
self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
|
||||
|
||||
@@ -30,6 +30,7 @@ from vllm_omni.diffusion.models.flux.flux_pipeline_mixin import FluxPipelineMixi
|
||||
from vllm_omni.diffusion.models.t5_encoder import T5EncoderModel
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.utils.tf_utils import get_transformer_config_kwargs
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -106,7 +107,11 @@ class FluxPipeline(nn.Module, FluxPipelineMixin, CFGParallelMixin, DiffusionPipe
|
||||
self.vae = AutoencoderKL.from_pretrained(model, subfolder="vae", local_files_only=local_files_only).to(
|
||||
self.device
|
||||
)
|
||||
self.transformer = FluxTransformer2DModel(od_config=od_config, quant_config=od_config.quantization_config)
|
||||
|
||||
transformer_kwargs = get_transformer_config_kwargs(od_config.tf_model_config, FluxTransformer2DModel)
|
||||
self.transformer = FluxTransformer2DModel(
|
||||
**transformer_kwargs, od_config=od_config, quant_config=od_config.quantization_config
|
||||
)
|
||||
|
||||
self.tokenizer = CLIPTokenizer.from_pretrained(model, subfolder="tokenizer", local_files_only=local_files_only)
|
||||
self.tokenizer_2 = T5TokenizerFast.from_pretrained(
|
||||
|
||||
@@ -234,7 +234,15 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
self.transformer = Flux2Transformer2DModel(quant_config=od_config.quantization_config, **transformer_kwargs)
|
||||
|
||||
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
|
||||
self.latent_channels = self.vae.config.latent_channels if hasattr(self.vae, "config") else 16
|
||||
self.image_processor = Flux2ImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
|
||||
self.mask_processor = VaeImageProcessor(
|
||||
vae_scale_factor=self.vae_scale_factor * 2,
|
||||
vae_latent_channels=self.latent_channels,
|
||||
do_normalize=False,
|
||||
do_binarize=True,
|
||||
do_convert_grayscale=True,
|
||||
)
|
||||
self.tokenizer_max_length = 512
|
||||
self.default_sample_size = 128
|
||||
|
||||
@@ -247,6 +255,14 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
enable_diffusion_pipeline_profiler=self.od_config.enable_diffusion_pipeline_profiler
|
||||
)
|
||||
|
||||
def get_timesteps(self, num_inference_steps, strength, device):
|
||||
init_timestep = min(num_inference_steps * strength, num_inference_steps)
|
||||
t_start = int(max(num_inference_steps - init_timestep, 0))
|
||||
timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
|
||||
if hasattr(self.scheduler, "set_begin_index"):
|
||||
self.scheduler.set_begin_index(t_start * self.scheduler.order)
|
||||
return timesteps, num_inference_steps - t_start
|
||||
|
||||
@staticmethod
|
||||
def _get_qwen3_prompt_embeds(
|
||||
text_encoder: Qwen3ForCausalLM,
|
||||
@@ -582,6 +598,54 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
|
||||
return image_latents, image_latent_ids
|
||||
|
||||
def prepare_mask_latents(
|
||||
self,
|
||||
mask,
|
||||
masked_image,
|
||||
batch_size,
|
||||
num_channels_latents,
|
||||
num_images_per_prompt,
|
||||
height,
|
||||
width,
|
||||
dtype,
|
||||
device,
|
||||
generator,
|
||||
):
|
||||
height = 2 * (int(height) // (self.vae_scale_factor * 2))
|
||||
width = 2 * (int(width) // (self.vae_scale_factor * 2))
|
||||
mask = torch.nn.functional.interpolate(mask, size=(height, width))
|
||||
mask = mask.to(device=device, dtype=dtype)
|
||||
|
||||
batch_size = batch_size * num_images_per_prompt
|
||||
|
||||
if masked_image is not None:
|
||||
masked_image = masked_image.to(device=device, dtype=dtype)
|
||||
if masked_image.shape[1] != num_channels_latents:
|
||||
masked_image_latents = self._encode_vae_image(image=masked_image, generator=generator)
|
||||
else:
|
||||
masked_image_latents = masked_image
|
||||
else:
|
||||
masked_image_latents = None
|
||||
|
||||
if mask.shape[0] < batch_size:
|
||||
if not batch_size % mask.shape[0] == 0:
|
||||
raise ValueError("The passed mask and the required batch size don't match.")
|
||||
mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
|
||||
if masked_image_latents is not None and masked_image_latents.shape[0] < batch_size:
|
||||
if not batch_size % masked_image_latents.shape[0] == 0:
|
||||
raise ValueError("The passed mask and the required batch size don't match.")
|
||||
masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
|
||||
|
||||
if masked_image_latents is not None:
|
||||
masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
|
||||
masked_image_latents = self._pack_latents(masked_image_latents)
|
||||
|
||||
mask = mask.repeat(1, self.latent_channels, 1, 1)
|
||||
mask = self._patchify_latents(mask)
|
||||
mask = self._pack_latents(mask)
|
||||
|
||||
return mask, masked_image_latents
|
||||
|
||||
def check_inputs(
|
||||
self,
|
||||
prompt,
|
||||
@@ -590,7 +654,15 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
prompt_embeds=None,
|
||||
callback_on_step_end_tensor_inputs=None,
|
||||
guidance_scale=None,
|
||||
strength=None,
|
||||
num_inference_steps=None,
|
||||
):
|
||||
if strength is not None:
|
||||
if strength < 0 or strength > 1:
|
||||
raise ValueError(f"strength must be between 0 and 1, got {strength}")
|
||||
if num_inference_steps is not None and num_inference_steps <= 0:
|
||||
raise ValueError(f"num_inference_steps must be positive, got {num_inference_steps}")
|
||||
|
||||
if (
|
||||
height is not None
|
||||
and height % (self.vae_scale_factor * 2) != 0
|
||||
@@ -622,7 +694,7 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
||||
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
||||
|
||||
if guidance_scale > 1.0 and self.is_distilled:
|
||||
if guidance_scale is not None and guidance_scale > 1.0 and self.is_distilled:
|
||||
logger.warning(f"Guidance scale {guidance_scale} is ignored for step-wise distilled models.")
|
||||
|
||||
@property
|
||||
@@ -653,11 +725,14 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
self,
|
||||
req: OmniDiffusionRequest,
|
||||
image: PIL.Image.Image | list[PIL.Image.Image] | None = None,
|
||||
reference_image: PIL.Image.Image | list[PIL.Image.Image] | None = None,
|
||||
mask_image: PIL.Image.Image | list[PIL.Image.Image] | None = None,
|
||||
prompt: str | list[str] | None = None,
|
||||
height: int | None = None,
|
||||
width: int | None = None,
|
||||
num_inference_steps: int = 50,
|
||||
sigmas: list[float] | None = None,
|
||||
strength: float = 1.0,
|
||||
guidance_scale: float | None = 4.0,
|
||||
num_images_per_prompt: int = 1,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
@@ -671,6 +746,7 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
||||
max_sequence_length: int = 512,
|
||||
text_encoder_out_layers: tuple[int, ...] = (9, 18, 27),
|
||||
padding_mask_crop: int | None = None,
|
||||
) -> DiffusionOutput:
|
||||
r"""
|
||||
Function invoked when calling the pipeline for generation.
|
||||
@@ -804,6 +880,8 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
prompt_embeds=prompt_embeds,
|
||||
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
||||
guidance_scale=guidance_scale,
|
||||
strength=strength,
|
||||
num_inference_steps=num_inference_steps,
|
||||
)
|
||||
|
||||
self._guidance_scale = guidance_scale
|
||||
@@ -848,6 +926,9 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
if image is not None and not isinstance(image, list):
|
||||
image = [image]
|
||||
|
||||
multiple_of = self.vae_scale_factor * 2
|
||||
crops_coords = None
|
||||
resize_mode = "crop"
|
||||
condition_images = None
|
||||
if image is not None:
|
||||
for img in image:
|
||||
@@ -860,10 +941,14 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
img = self.image_processor._resize_to_target_area(img, 1024 * 1024)
|
||||
image_width, image_height = img.size
|
||||
|
||||
multiple_of = self.vae_scale_factor * 2
|
||||
image_width = (image_width // multiple_of) * multiple_of
|
||||
image_height = (image_height // multiple_of) * multiple_of
|
||||
img = self.image_processor.preprocess(img, height=image_height, width=image_width, resize_mode="crop")
|
||||
if padding_mask_crop is not None:
|
||||
crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)
|
||||
resize_mode = "fill"
|
||||
img = self.image_processor.preprocess(
|
||||
img, height=image_height, width=image_width, crops_coords=crops_coords, resize_mode=resize_mode
|
||||
)
|
||||
condition_images.append(img)
|
||||
height = height or image_height
|
||||
width = width or image_width
|
||||
@@ -871,6 +956,16 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
height = height or self.default_sample_size * self.vae_scale_factor
|
||||
width = width or self.default_sample_size * self.vae_scale_factor
|
||||
|
||||
# Get mask_image and reference_image
|
||||
multi_modal_data = req.prompts[0].get("multi_modal_data", {}) if req.prompts else {}
|
||||
mask_image = multi_modal_data.get("mask_image")
|
||||
reference_image = multi_modal_data.get("reference_image")
|
||||
|
||||
if mask_image is not None and (image is None or (isinstance(image, list) and len(image) == 0)):
|
||||
raise ValueError("image must be provided when using mask_image for inpainting")
|
||||
|
||||
init_image = condition_images[0] if condition_images else None
|
||||
|
||||
# 5. prepare latent variables
|
||||
num_channels_latents = self.transformer.config.in_channels // 4
|
||||
latents, latent_ids = self.prepare_latents(
|
||||
@@ -884,6 +979,8 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
latents=latents,
|
||||
)
|
||||
|
||||
original_latent_ids = latent_ids
|
||||
|
||||
image_latents = None
|
||||
image_latent_ids = None
|
||||
if condition_images is not None:
|
||||
@@ -895,6 +992,71 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
dtype=self.vae.dtype,
|
||||
)
|
||||
|
||||
# Preprocess reference_image
|
||||
if reference_image is not None and not (
|
||||
isinstance(reference_image, torch.Tensor) and reference_image.size(1) == self.latent_channels
|
||||
):
|
||||
if (
|
||||
isinstance(reference_image, list)
|
||||
and isinstance(reference_image[0], torch.Tensor)
|
||||
and reference_image[0].ndim == 4
|
||||
):
|
||||
reference_image = torch.cat(reference_image, dim=0)
|
||||
img_reference = reference_image[0] if isinstance(reference_image, list) else reference_image
|
||||
reference_image_height, reference_image_width = self.image_processor.get_default_height_width(img_reference)
|
||||
|
||||
reference_image_width = reference_image_width // multiple_of * multiple_of
|
||||
reference_image_height = reference_image_height // multiple_of * multiple_of
|
||||
reference_image = self.image_processor.resize(
|
||||
reference_image, reference_image_height, reference_image_width
|
||||
)
|
||||
reference_image = self.image_processor.preprocess(
|
||||
reference_image,
|
||||
reference_image_height,
|
||||
reference_image_width,
|
||||
crops_coords=crops_coords,
|
||||
resize_mode=resize_mode,
|
||||
)
|
||||
else:
|
||||
pass
|
||||
|
||||
reference_image_latents = None
|
||||
reference_image_latent_ids = None
|
||||
if reference_image is not None:
|
||||
reference_image_latents, reference_image_latent_ids = self.prepare_image_latents(
|
||||
images=[reference_image],
|
||||
batch_size=batch_size * num_images_per_prompt,
|
||||
generator=generator,
|
||||
device=device,
|
||||
dtype=self.vae.dtype,
|
||||
)
|
||||
|
||||
if reference_image_latent_ids is not None:
|
||||
latent_ids = torch.cat([latent_ids, reference_image_latent_ids], dim=1)
|
||||
elif image_latent_ids is not None:
|
||||
latent_ids = torch.cat([latent_ids, image_latent_ids], dim=1)
|
||||
|
||||
mask = None
|
||||
if mask_image is not None:
|
||||
mask_condition = self.mask_processor.preprocess(
|
||||
mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
|
||||
)
|
||||
if init_image is not None:
|
||||
masked_image = init_image * (mask_condition < 0.5).to(init_image.dtype)
|
||||
else:
|
||||
masked_image = None
|
||||
mask, _ = self.prepare_mask_latents(
|
||||
mask_condition,
|
||||
masked_image,
|
||||
batch_size,
|
||||
self.latent_channels,
|
||||
num_images_per_prompt,
|
||||
height,
|
||||
width,
|
||||
prompt_embeds.dtype,
|
||||
device,
|
||||
generator,
|
||||
)
|
||||
# 6. Prepare timesteps
|
||||
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
|
||||
if hasattr(self.scheduler.config, "use_flow_sigmas") and self.scheduler.config.use_flow_sigmas:
|
||||
@@ -908,6 +1070,13 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
sigmas=sigmas,
|
||||
mu=mu,
|
||||
)
|
||||
if reference_image is not None or mask_image is not None:
|
||||
timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
|
||||
if num_inference_steps < 1:
|
||||
raise ValueError(
|
||||
f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
|
||||
f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
|
||||
)
|
||||
self._num_timesteps = len(timesteps)
|
||||
|
||||
# 7. Denoising loop
|
||||
@@ -924,7 +1093,10 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
latent_model_input = latents.to(self.transformer.dtype)
|
||||
latent_image_ids = latent_ids
|
||||
|
||||
if image_latents is not None:
|
||||
if reference_image_latents is not None:
|
||||
latent_model_input = torch.cat([latents, reference_image_latents], dim=1)
|
||||
latent_image_ids = latent_ids
|
||||
elif image_latents is not None:
|
||||
latent_model_input = torch.cat([latents, image_latents], dim=1).to(self.transformer.dtype)
|
||||
latent_image_ids = torch.cat([latent_ids, image_latent_ids], dim=1)
|
||||
|
||||
@@ -953,7 +1125,9 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
negative_kwargs = None
|
||||
|
||||
# For editing pipelines, we need to slice the output to remove condition latents
|
||||
output_slice = latents.size(1) if image_latents is not None else None
|
||||
output_slice = (
|
||||
latents.size(1) if (image_latents is not None or reference_image_latents is not None) else None
|
||||
)
|
||||
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=self.do_classifier_free_guidance,
|
||||
@@ -964,9 +1138,22 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
output_slice=output_slice,
|
||||
)
|
||||
|
||||
latents_dtype = latents.dtype
|
||||
# Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, self.do_classifier_free_guidance)
|
||||
|
||||
if mask is not None and image_latents is not None:
|
||||
init_latents_proper = image_latents
|
||||
if i < len(timesteps) - 1:
|
||||
noise_timestep = timesteps[i + 1]
|
||||
init_latents_proper = self.scheduler.scale_noise(
|
||||
init_latents_proper, torch.tensor([noise_timestep], device=device), latents
|
||||
)
|
||||
latents = (1 - mask) * init_latents_proper + mask * latents
|
||||
|
||||
if latents.dtype != latents_dtype and torch.backends.mps.is_available():
|
||||
latents = latents.to(latents_dtype)
|
||||
|
||||
if callback_on_step_end is not None:
|
||||
callback_kwargs = {}
|
||||
for k in callback_on_step_end_tensor_inputs:
|
||||
@@ -978,7 +1165,7 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
|
||||
|
||||
self._current_timestep = None
|
||||
|
||||
latents = self._unpack_latents_with_ids(latents, latent_ids)
|
||||
latents = self._unpack_latents_with_ids(latents, original_latent_ids)
|
||||
|
||||
latents_bn_mean = self.vae.bn.running_mean.view(1, -1, 1, 1).to(latents.device, latents.dtype)
|
||||
latents_bn_std = torch.sqrt(self.vae.bn.running_var.view(1, -1, 1, 1) + self.vae.config.batch_norm_eps).to(
|
||||
|
||||
@@ -19,10 +19,16 @@ from vllm.model_executor.layers.linear import (
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.cache.base import CachedTransformer
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.data import DiffusionParallelConfig, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.hsdp_utils import is_transformer_block_module
|
||||
from vllm_omni.diffusion.distributed.sp_plan import (
|
||||
SequenceParallelInput,
|
||||
SequenceParallelOutput,
|
||||
)
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -108,8 +114,8 @@ class GlmImageImageProjector(nn.Module):
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
batch_size, channel, height, width = hidden_states.shape
|
||||
post_patch_height = height // self.patch_size
|
||||
post_patch_width = width // self.patch_size
|
||||
post_patch_height = torch.tensor(height // self.patch_size, device=hidden_states.device, dtype=torch.int64)
|
||||
post_patch_width = torch.tensor(width // self.patch_size, device=hidden_states.device, dtype=torch.int64)
|
||||
|
||||
# Reshape: [B, C, H, W] -> [B, H', W', C*p*p] -> [B, H'*W', C*p*p]
|
||||
hidden_states = hidden_states.reshape(
|
||||
@@ -159,6 +165,65 @@ class GlmImageRotaryPosEmbed(nn.Module):
|
||||
return (freqs.cos(), freqs.sin())
|
||||
|
||||
|
||||
class GlmImagePrepare(nn.Module):
|
||||
"""Prepare module for GLM-Image that handles patch embedding and RoPE computation.
|
||||
|
||||
This module encapsulates the input processing pipeline to create a module boundary
|
||||
where _sp_plan can shard outputs via split_output=True.
|
||||
|
||||
Similar to Qwen-Image's ImageRopePrepare, this ensures hidden_states and RoPE
|
||||
embeddings are sharded together to maintain dimension alignment.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
image_projector: nn.Module,
|
||||
rope: GlmImageRotaryPosEmbed,
|
||||
patch_size: int,
|
||||
):
|
||||
super().__init__()
|
||||
self.image_projector = image_projector
|
||||
self.rope = rope
|
||||
self.patch_size = patch_size
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
prior_hidden_states: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Process hidden_states and compute RoPE embeddings.
|
||||
|
||||
Args:
|
||||
hidden_states: Input latent tensor [B, C, H, W]
|
||||
prior_hidden_states: Optional prior embedding to add
|
||||
|
||||
Returns:
|
||||
hidden_states: Patched hidden states [B, seq_len, D]
|
||||
rope_cos: RoPE cos embeddings [seq_len, dim]
|
||||
rope_sin: RoPE sin embeddings [seq_len, dim]
|
||||
post_patch_height: Scalar tensor for height after patching
|
||||
post_patch_width: Scalar tensor for width after patching
|
||||
"""
|
||||
batch_size, num_channels, height, width = hidden_states.shape
|
||||
|
||||
post_patch_height = torch.tensor(height // self.patch_size, device=hidden_states.device, dtype=torch.int64)
|
||||
post_patch_width = torch.tensor(width // self.patch_size, device=hidden_states.device, dtype=torch.int64)
|
||||
|
||||
# Compute RoPE (uses original 4D hidden_states shape)
|
||||
image_rotary_emb = self.rope(hidden_states)
|
||||
rope_cos = image_rotary_emb[0].to(hidden_states.device)
|
||||
rope_sin = image_rotary_emb[1].to(hidden_states.device)
|
||||
|
||||
# Patch embedding: [B, C, H, W] -> [B, seq_len, D]
|
||||
hidden_states = self.image_projector(hidden_states)
|
||||
|
||||
# Add prior embedding if provided
|
||||
if prior_hidden_states is not None:
|
||||
hidden_states = hidden_states + prior_hidden_states
|
||||
|
||||
return hidden_states, rope_cos, rope_sin, post_patch_height, post_patch_width
|
||||
|
||||
|
||||
class GlmImageAdaLayerNormZero(nn.Module):
|
||||
"""Adaptive LayerNorm with zero initialization for both image and text streams."""
|
||||
|
||||
@@ -397,6 +462,7 @@ class GlmImageAttention(nn.Module):
|
||||
dim: int,
|
||||
num_heads: int,
|
||||
head_dim: int,
|
||||
parallel_config: DiffusionParallelConfig | None = None,
|
||||
out_bias: bool = True,
|
||||
eps: float = 1e-5,
|
||||
):
|
||||
@@ -404,6 +470,7 @@ class GlmImageAttention(nn.Module):
|
||||
self.dim = dim
|
||||
self.total_num_heads = num_heads
|
||||
self.head_dim = head_dim
|
||||
self.parallel_config = parallel_config
|
||||
|
||||
# QKV projection (fused for efficiency)
|
||||
self.to_qkv = QKVParallelLinear(
|
||||
@@ -450,16 +517,19 @@ class GlmImageAttention(nn.Module):
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
kv_cache: GlmImageLayerKVCache | None = None,
|
||||
kv_cache_mode: KVCacheMode | None = None,
|
||||
hidden_states_mask: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Forward pass for joint attention.
|
||||
|
||||
Args:
|
||||
hidden_states: Image hidden states [B, img_seq_len, D]
|
||||
encoder_hidden_states: Text hidden states [B, text_seq_len, D]
|
||||
image_rotary_emb: Tuple of (cos, sin) for RoPE
|
||||
hidden_states: Image hidden states [B, img_seq_len, D] (sharded in SP mode)
|
||||
encoder_hidden_states: Text hidden states [B, text_seq_len, D] (full in SP mode)
|
||||
image_rotary_emb: Tuple of (cos, sin) for RoPE (sharded in SP mode)
|
||||
attention_mask: Optional attention mask
|
||||
kv_cache: Optional layer KV cache for image editing
|
||||
kv_cache_mode: Cache mode (WRITE, READ, SKIP)
|
||||
hidden_states_mask: Mask for SP padding (True=valid, False=padding)
|
||||
|
||||
Returns:
|
||||
Tuple of (image_hidden_states, text_hidden_states)
|
||||
@@ -467,6 +537,13 @@ class GlmImageAttention(nn.Module):
|
||||
dtype = encoder_hidden_states.dtype
|
||||
batch_size, text_seq_length, _ = encoder_hidden_states.shape
|
||||
|
||||
# Check if SP is enabled
|
||||
sp_size = self.parallel_config.sequence_parallel_size if self.parallel_config else None
|
||||
use_sp = sp_size is not None and sp_size > 1
|
||||
if use_sp:
|
||||
forward_ctx = get_forward_context()
|
||||
use_sp = not forward_ctx.split_text_embed_in_sp
|
||||
|
||||
# Concatenate text and image: [text, image]
|
||||
hidden_states_combined = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
||||
|
||||
@@ -485,41 +562,88 @@ class GlmImageAttention(nn.Module):
|
||||
query = self.norm_q(query).to(dtype=dtype)
|
||||
key = self.norm_k(key).to(dtype=dtype)
|
||||
|
||||
# Apply RoPE only to image tokens (not text tokens)
|
||||
if image_rotary_emb is not None:
|
||||
# Only apply RoPE to image part (after text_seq_length)
|
||||
query_img = query[:, text_seq_length:, :, :]
|
||||
key_img = key[:, text_seq_length:, :, :]
|
||||
from diffusers.models.embeddings import apply_rotary_emb
|
||||
if use_sp:
|
||||
# SP mode: use joint attention mechanism
|
||||
# Split Q/K/V into text and image parts
|
||||
text_query = query[:, :text_seq_length, :, :]
|
||||
text_key = key[:, :text_seq_length, :, :]
|
||||
text_value = value[:, :text_seq_length, :, :]
|
||||
img_query = query[:, text_seq_length:, :, :]
|
||||
img_key = key[:, text_seq_length:, :, :]
|
||||
img_value = value[:, text_seq_length:, :, :]
|
||||
|
||||
query_img = apply_rotary_emb(query_img, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
|
||||
key_img = apply_rotary_emb(key_img, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
|
||||
query = torch.cat([query[:, :text_seq_length, :, :], query_img], dim=1)
|
||||
key = torch.cat([key[:, :text_seq_length, :, :], key_img], dim=1)
|
||||
# Apply RoPE only to image part
|
||||
if image_rotary_emb is not None:
|
||||
from diffusers.models.embeddings import apply_rotary_emb
|
||||
|
||||
# Handle KV cache for image editing
|
||||
if kv_cache is not None and kv_cache_mode is not None:
|
||||
if kv_cache_mode == KVCacheMode.WRITE:
|
||||
kv_cache.store(key, value)
|
||||
elif kv_cache_mode == KVCacheMode.READ:
|
||||
k_cached, v_cached = kv_cache.get()
|
||||
if k_cached is not None:
|
||||
key = torch.cat([k_cached, key], dim=1)
|
||||
value = torch.cat([v_cached, value], dim=1)
|
||||
# KVCacheMode.SKIP: do nothing
|
||||
img_query = apply_rotary_emb(img_query, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
|
||||
img_key = apply_rotary_emb(img_key, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
|
||||
|
||||
# Attention computation
|
||||
hidden_states_out = self.attn(query, key, value)
|
||||
hidden_states_out = hidden_states_out.flatten(2, 3)
|
||||
hidden_states_out = hidden_states_out.to(dtype)
|
||||
# Create attention metadata for joint attention
|
||||
attn_metadata = AttentionMetadata(
|
||||
joint_query=text_query,
|
||||
joint_key=text_key,
|
||||
joint_value=text_value,
|
||||
joint_strategy="front",
|
||||
)
|
||||
|
||||
# Output projection
|
||||
for module in self.to_out:
|
||||
hidden_states_out = module(hidden_states_out)
|
||||
# Add padding mask for SP if available
|
||||
if hidden_states_mask is not None:
|
||||
attn_metadata.attn_mask = hidden_states_mask
|
||||
|
||||
# Split back to text and image
|
||||
encoder_hidden_states_out = hidden_states_out[:, :text_seq_length, :]
|
||||
hidden_states_out = hidden_states_out[:, text_seq_length:, :]
|
||||
# Attention computation with joint text/image
|
||||
# Note: Ulysses post_attention returns [text, image] concatenated
|
||||
joint_hidden_states_out = self.attn(img_query, img_key, img_value, attn_metadata)
|
||||
|
||||
# Project combined [text, image] outputs, then split.
|
||||
# This keeps SP numerically aligned with the non-SP path.
|
||||
joint_hidden_states_out = joint_hidden_states_out.flatten(2, 3).to(dtype)
|
||||
for module in self.to_out:
|
||||
joint_hidden_states_out = module(joint_hidden_states_out)
|
||||
|
||||
encoder_hidden_states_out = joint_hidden_states_out[:, :text_seq_length, :]
|
||||
hidden_states_out = joint_hidden_states_out[:, text_seq_length:, :]
|
||||
else:
|
||||
# Non-SP mode: original logic
|
||||
# Apply RoPE only to image tokens (not text tokens)
|
||||
if image_rotary_emb is not None:
|
||||
query_img = query[:, text_seq_length:, :, :]
|
||||
key_img = key[:, text_seq_length:, :, :]
|
||||
from diffusers.models.embeddings import apply_rotary_emb
|
||||
|
||||
query_img = apply_rotary_emb(query_img, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
|
||||
key_img = apply_rotary_emb(key_img, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
|
||||
query = torch.cat([query[:, :text_seq_length, :, :], query_img], dim=1)
|
||||
key = torch.cat([key[:, :text_seq_length, :, :], key_img], dim=1)
|
||||
|
||||
# Handle KV cache for image editing
|
||||
if kv_cache is not None and kv_cache_mode is not None:
|
||||
if kv_cache_mode == KVCacheMode.WRITE:
|
||||
kv_cache.store(key, value)
|
||||
elif kv_cache_mode == KVCacheMode.READ:
|
||||
k_cached, v_cached = kv_cache.get()
|
||||
if k_cached is not None:
|
||||
key = torch.cat([k_cached, key], dim=1)
|
||||
value = torch.cat([v_cached, value], dim=1)
|
||||
|
||||
# Attention computation
|
||||
attn_metadata = None
|
||||
if attention_mask is not None:
|
||||
if attention_mask.dim() == 3:
|
||||
attention_mask = attention_mask.unsqueeze(1)
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask)
|
||||
|
||||
hidden_states_out = self.attn(query, key, value, attn_metadata)
|
||||
hidden_states_out = hidden_states_out.flatten(2, 3)
|
||||
hidden_states_out = hidden_states_out.to(dtype)
|
||||
|
||||
# Output projection
|
||||
for module in self.to_out:
|
||||
hidden_states_out = module(hidden_states_out)
|
||||
|
||||
# Split back to text and image
|
||||
encoder_hidden_states_out = hidden_states_out[:, :text_seq_length, :]
|
||||
hidden_states_out = hidden_states_out[:, text_seq_length:, :]
|
||||
|
||||
return hidden_states_out, encoder_hidden_states_out
|
||||
|
||||
@@ -628,6 +752,7 @@ class GlmImageTransformerBlock(nn.Module):
|
||||
attention_head_dim: int = 40,
|
||||
time_embed_dim: int = 512,
|
||||
ffn_hidden_dim: int | None = None,
|
||||
parallel_config: DiffusionParallelConfig | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
|
||||
@@ -637,6 +762,7 @@ class GlmImageTransformerBlock(nn.Module):
|
||||
dim=dim,
|
||||
num_heads=num_attention_heads,
|
||||
head_dim=attention_head_dim,
|
||||
parallel_config=parallel_config,
|
||||
)
|
||||
|
||||
# 2. Feedforward
|
||||
@@ -654,6 +780,7 @@ class GlmImageTransformerBlock(nn.Module):
|
||||
attention_kwargs: dict[str, Any] | None = None,
|
||||
kv_cache: GlmImageLayerKVCache | None = None,
|
||||
kv_cache_mode: KVCacheMode | None = None,
|
||||
hidden_states_mask: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Forward pass for transformer block.
|
||||
@@ -667,6 +794,7 @@ class GlmImageTransformerBlock(nn.Module):
|
||||
attention_kwargs: Additional attention arguments
|
||||
kv_cache: Layer-specific KV cache for image editing
|
||||
kv_cache_mode: Cache mode (WRITE, READ, SKIP)
|
||||
hidden_states_mask: Mask for SP padding (True=valid, False=padding)
|
||||
|
||||
Returns:
|
||||
Tuple of (image_hidden_states, text_hidden_states)
|
||||
@@ -693,6 +821,7 @@ class GlmImageTransformerBlock(nn.Module):
|
||||
attention_mask=attention_mask,
|
||||
kv_cache=kv_cache,
|
||||
kv_cache_mode=kv_cache_mode,
|
||||
hidden_states_mask=hidden_states_mask,
|
||||
)
|
||||
hidden_states = hidden_states + attn_hidden_states * gate_msa.unsqueeze(1)
|
||||
encoder_hidden_states = encoder_hidden_states + attn_encoder_hidden_states * c_gate_msa.unsqueeze(1)
|
||||
@@ -724,6 +853,26 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
"""
|
||||
|
||||
_repeated_blocks = ["GlmImageTransformerBlock"]
|
||||
# SP plan using GlmImagePrepare module for sharding hidden_states and RoPE together.
|
||||
# Similar to Qwen-Image's ImageRopePrepare, this creates a module boundary where
|
||||
# _sp_plan can shard outputs via split_output=True.
|
||||
#
|
||||
# Key insight: hidden_states and RoPE embeddings MUST be sharded together
|
||||
# to maintain dimension alignment for RoPE computation in attention layers.
|
||||
_sp_plan = {
|
||||
# Shard GlmImagePrepare outputs (hidden_states and RoPE must be sharded together)
|
||||
"prepare": {
|
||||
# hidden_states: [B, seq_len, D] - shard along sequence dimension
|
||||
0: SequenceParallelInput(split_dim=1, expected_dims=3, split_output=True, auto_pad=True),
|
||||
# RoPE cos: [seq_len, dim] - shard along sequence dimension
|
||||
1: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True, auto_pad=True),
|
||||
# RoPE sin: [seq_len, dim] - shard along sequence dimension
|
||||
2: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True, auto_pad=True),
|
||||
# post_patch_height and post_patch_width are scalars, not sharded
|
||||
},
|
||||
# Gather output at proj_out
|
||||
"proj_out": SequenceParallelOutput(gather_dim=1, expected_dims=3),
|
||||
}
|
||||
|
||||
_hsdp_shard_conditions = [is_transformer_block_module]
|
||||
|
||||
@@ -790,6 +939,9 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
dim=inner_dim, dim_out=inner_dim, inner_dim=inner_dim, activation_fn="linear-silu"
|
||||
)
|
||||
|
||||
# Prepare module for SP (encapsulates patch embedding and RoPE for _sp_plan)
|
||||
self.prepare = GlmImagePrepare(self.image_projector, self.rope, patch_size)
|
||||
|
||||
self.time_condition_embed = GlmImageCombinedTimestepSizeEmbeddings(
|
||||
embedding_dim=time_embed_dim,
|
||||
condition_dim=condition_dim,
|
||||
@@ -806,6 +958,7 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
attention_head_dim,
|
||||
time_embed_dim,
|
||||
ffn_hidden_dim=ffn_hidden_dim,
|
||||
parallel_config=self.parallel_config,
|
||||
)
|
||||
for _ in range(num_layers)
|
||||
]
|
||||
@@ -859,33 +1012,51 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
# Get KV cache mode
|
||||
kv_cache_mode = kv_cache.mode if kv_cache is not None else None
|
||||
|
||||
# 1. RoPE
|
||||
if image_rotary_emb is None:
|
||||
image_rotary_emb = self.rope(hidden_states)
|
||||
# Move to correct device
|
||||
image_rotary_emb = (
|
||||
image_rotary_emb[0].to(hidden_states.device),
|
||||
image_rotary_emb[1].to(hidden_states.device),
|
||||
)
|
||||
# Set SP context if enabled
|
||||
sp_size = self.parallel_config.sequence_parallel_size
|
||||
if sp_size is not None and sp_size > 1:
|
||||
get_forward_context().split_text_embed_in_sp = False
|
||||
|
||||
# 2. Patch & Timestep embeddings
|
||||
p = self.patch_size
|
||||
post_patch_height = height // p
|
||||
post_patch_width = width // p
|
||||
|
||||
hidden_states = self.image_projector(hidden_states)
|
||||
# Text embedding projection
|
||||
encoder_hidden_states = self.glyph_projector(encoder_hidden_states)
|
||||
|
||||
# Prior embedding with dropout
|
||||
prior_embedding = self.prior_token_embedding(prior_token_id)
|
||||
prior_embedding[prior_token_drop] *= 0.0
|
||||
prior_hidden_states = self.prior_projector(prior_embedding)
|
||||
hidden_states = hidden_states + prior_hidden_states
|
||||
|
||||
# 1. Prepare hidden_states and RoPE via GlmImagePrepare module
|
||||
# _sp_plan will shard hidden_states and RoPE together via split_output=True
|
||||
hidden_states, rope_cos, rope_sin, post_patch_height_t, post_patch_width_t = self.prepare(
|
||||
hidden_states, prior_hidden_states
|
||||
)
|
||||
image_rotary_emb = (rope_cos, rope_sin)
|
||||
post_patch_height = int(post_patch_height_t.item())
|
||||
post_patch_width = int(post_patch_width_t.item())
|
||||
|
||||
# Timestep conditioning
|
||||
temb = self.time_condition_embed(timestep, target_size, crop_coords, hidden_states.dtype)
|
||||
|
||||
# 3. Transformer blocks
|
||||
# Create padding mask for SP if needed (after _sp_plan hooks have run)
|
||||
hidden_states_mask = None
|
||||
if sp_size is not None and sp_size > 1:
|
||||
from vllm_omni.diffusion.forward_context import is_forward_context_available
|
||||
|
||||
if is_forward_context_available():
|
||||
ctx = get_forward_context()
|
||||
if ctx.sp_original_seq_len is not None and ctx.sp_padding_size > 0:
|
||||
img_padded_seq_len = ctx.sp_original_seq_len + ctx.sp_padding_size
|
||||
hidden_states_mask = torch.ones(
|
||||
batch_size,
|
||||
img_padded_seq_len,
|
||||
dtype=torch.bool,
|
||||
device=hidden_states.device,
|
||||
)
|
||||
hidden_states_mask[:, ctx.sp_original_seq_len :] = False
|
||||
if hidden_states_mask.all():
|
||||
hidden_states_mask = None
|
||||
|
||||
# 2. Transformer blocks
|
||||
for layer_idx, block in enumerate(self.transformer_blocks):
|
||||
# Get layer-specific KV cache if available
|
||||
layer_kv_cache = kv_cache[layer_idx] if kv_cache is not None else None
|
||||
@@ -899,13 +1070,16 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
attention_kwargs,
|
||||
kv_cache=layer_kv_cache,
|
||||
kv_cache_mode=kv_cache_mode,
|
||||
hidden_states_mask=hidden_states_mask,
|
||||
)
|
||||
|
||||
# 4. Output norm & projection
|
||||
# 3. Output norm & projection
|
||||
# _sp_plan will gather hidden_states via proj_out hook
|
||||
hidden_states = self.norm_out(hidden_states, temb)
|
||||
hidden_states = self.proj_out(hidden_states)
|
||||
|
||||
# 5. Unpatchify: [B, H'*W', C*p*p] -> [B, C, H, W]
|
||||
# 4. Unpatchify: [B, H'*W', C*p*p] -> [B, C, H, W]
|
||||
p = self.patch_size
|
||||
hidden_states = hidden_states.reshape(batch_size, post_patch_height, post_patch_width, -1, p, p)
|
||||
output = hidden_states.permute(0, 3, 1, 4, 2, 5).flatten(4, 5).flatten(2, 3)
|
||||
|
||||
|
||||
@@ -712,6 +712,14 @@ class GlmImagePipeline(nn.Module, DiffusionPipelineProfilerMixin):
|
||||
if img is not None:
|
||||
preprocessed_images = [img]
|
||||
|
||||
# Priority: prompt dict (from ar2diffusion) > sampling_params
|
||||
# ar2diffusion returns adjusted height/width that matches prior_token_ids
|
||||
if not isinstance(first_prompt, str):
|
||||
ar_height = first_prompt.get("height")
|
||||
ar_width = first_prompt.get("width")
|
||||
else:
|
||||
ar_height = ar_width = None
|
||||
|
||||
img_height = req.sampling_params.height
|
||||
img_width = req.sampling_params.width
|
||||
|
||||
@@ -719,12 +727,19 @@ class GlmImagePipeline(nn.Module, DiffusionPipelineProfilerMixin):
|
||||
# Treat that as t2i warmup to avoid requiring i2i-only KV-cache inputs.
|
||||
is_image_edit = (preprocessed_images is not None) and (not is_dummy_warmup)
|
||||
|
||||
# Use image dimensions as default if available
|
||||
height = req.sampling_params.height or img_height or self.default_sample_size * self.vae_scale_factor
|
||||
width = req.sampling_params.width or img_width or self.default_sample_size * self.vae_scale_factor
|
||||
# Use prompt dict dimensions (from ar2diffusion) as priority, then sampling_params
|
||||
height = (
|
||||
ar_height or req.sampling_params.height or img_height or self.default_sample_size * self.vae_scale_factor
|
||||
)
|
||||
width = ar_width or req.sampling_params.width or img_width or self.default_sample_size * self.vae_scale_factor
|
||||
num_inference_steps = req.sampling_params.num_inference_steps or 50
|
||||
guidance_scale = req.sampling_params.guidance_scale or 1.5
|
||||
|
||||
# Ensure dimensions are multiples of vae_scale_factor * patch_size
|
||||
multiple_of = self.vae_scale_factor * self._patch_size
|
||||
height = height // multiple_of * multiple_of
|
||||
width = width // multiple_of * multiple_of
|
||||
|
||||
self.check_inputs(prompt=prompt, height=height, width=width, prompt_embeds=prompt_embeds)
|
||||
|
||||
batch_size = 1
|
||||
@@ -753,6 +768,20 @@ class GlmImagePipeline(nn.Module, DiffusionPipelineProfilerMixin):
|
||||
prior_token_id = prior_token_id.to(device=self.device, dtype=torch.long)
|
||||
if prior_token_id.dim() == 1:
|
||||
prior_token_id = prior_token_id.unsqueeze(0)
|
||||
|
||||
# Validate that prior_token_id seq_len matches dimensions
|
||||
prior_seq_len = prior_token_id.shape[1]
|
||||
expected_seq_len = (height // self.vae_scale_factor // self._patch_size) * (
|
||||
width // self.vae_scale_factor // self._patch_size
|
||||
)
|
||||
if prior_seq_len != expected_seq_len:
|
||||
raise ValueError(
|
||||
f"prior_token_ids seq_len ({prior_seq_len}) doesn't match dimensions "
|
||||
f"({height}x{width}, expected seq_len={expected_seq_len}). "
|
||||
f"This indicates a mismatch between AR output and Diffusion input. "
|
||||
f"Please ensure ar2diffusion returns correct height/width."
|
||||
)
|
||||
|
||||
prior_token_image_ids = None
|
||||
if external_prior_image_ids is not None:
|
||||
if isinstance(external_prior_image_ids, torch.Tensor):
|
||||
|
||||
@@ -62,10 +62,16 @@ def apply_rotary_emb_helios(
|
||||
"""
|
||||
x_1, x_2 = hidden_states.unflatten(-1, (-1, 2)).unbind(-1)
|
||||
cos, sin = freqs_cis.unsqueeze(-2).chunk(2, dim=-1)
|
||||
out = torch.empty_like(hidden_states)
|
||||
out[..., 0::2] = x_1 * cos[..., 0::2] - x_2 * sin[..., 1::2]
|
||||
out[..., 1::2] = x_1 * sin[..., 1::2] + x_2 * cos[..., 0::2]
|
||||
return out.type_as(hidden_states)
|
||||
# Use stack+flatten instead of strided slice assignment for contiguous
|
||||
# memory layout and better performance on GPU/NPU (#2436, cf. PR #2393).
|
||||
rotated = torch.stack(
|
||||
(
|
||||
x_1 * cos[..., 0::2] - x_2 * sin[..., 1::2],
|
||||
x_1 * sin[..., 1::2] + x_2 * cos[..., 0::2],
|
||||
),
|
||||
dim=-1,
|
||||
)
|
||||
return rotated.flatten(-2, -1).type_as(hidden_states)
|
||||
|
||||
|
||||
class DistributedRMSNorm(nn.Module):
|
||||
|
||||
+3
-3
@@ -2,12 +2,12 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Hunyuan Image 3 diffusion model components."""
|
||||
|
||||
from vllm_omni.diffusion.models.hunyuan_image_3.hunyuan_fused_moe import HunyuanFusedMoE
|
||||
from vllm_omni.diffusion.models.hunyuan_image_3.hunyuan_image_3_transformer import (
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.hunyuan_fused_moe import HunyuanFusedMoE
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.hunyuan_image3_transformer import (
|
||||
HunyuanImage3Model,
|
||||
HunyuanImage3Text2ImagePipeline,
|
||||
)
|
||||
from vllm_omni.diffusion.models.hunyuan_image_3.pipeline_hunyuan_image_3 import (
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.pipeline_hunyuan_image3 import (
|
||||
HunyuanImage3Pipeline,
|
||||
)
|
||||
|
||||
File renamed without changes.
File renamed without changes.
+1
-1
@@ -13,7 +13,7 @@ from diffusers.utils.outputs import BaseOutput
|
||||
from transformers import AutoTokenizer
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from .hunyuan_image_3_transformer import ImageInfo, JointImageInfo, default
|
||||
from .hunyuan_image3_transformer import ImageInfo, JointImageInfo, default
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
+3
-2
@@ -74,7 +74,7 @@ from vllm_omni.diffusion.distributed.sp_plan import (
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
|
||||
from vllm_omni.diffusion.models.hunyuan_image_3.hunyuan_fused_moe import HunyuanFusedMoE
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.hunyuan_fused_moe import HunyuanFusedMoE
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -1684,7 +1684,8 @@ class HunYuanAttention(nn.Module):
|
||||
else:
|
||||
attn_output = self.attn(q, k, v)
|
||||
# For o_proj
|
||||
attn_output = attn_output.view(q.shape[0], -1)
|
||||
# image_attn may return a non-contiguous tensor; reshape is safe here.
|
||||
attn_output = attn_output.reshape(q.shape[0], -1)
|
||||
output, _ = self.o_proj(attn_output)
|
||||
output = output.reshape(bsz, q_len, -1)
|
||||
return output, None, past_key_value
|
||||
+4
-6
@@ -6,7 +6,6 @@ import os
|
||||
from collections.abc import Iterable
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from diffusers.schedulers.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler
|
||||
@@ -25,8 +24,8 @@ from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPi
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
|
||||
from .autoencoder import AutoencoderKLConv3D
|
||||
from .hunyuan_image_3_tokenizer import TokenizerWrapper
|
||||
from .hunyuan_image_3_transformer import (
|
||||
from .hunyuan_image3_tokenizer import TokenizerWrapper
|
||||
from .hunyuan_image3_transformer import (
|
||||
CausalMMOutputWithPast,
|
||||
HunyuanImage3ImageProcessor,
|
||||
HunyuanImage3Model,
|
||||
@@ -544,7 +543,7 @@ class HunyuanImage3Pipeline(HunyuanImage3PreTrainedModel, GenerationMixin, Diffu
|
||||
generator = [torch.Generator(self.device).manual_seed(seed) for seed in seeds]
|
||||
|
||||
# 3. apply chat template
|
||||
cfg_factor = {"gen_text": 1, "gen_image": 2}
|
||||
cfg_factor = {"gen_text": 1, "gen_image": 1 + int(guidance_scale > 1.0)}
|
||||
bot_task = kwargs.pop("bot_task", "auto")
|
||||
# If `drop_think` enabled, always drop <think> parts in the context.
|
||||
drop_think = kwargs.get("drop_think", self.generation_config.drop_think)
|
||||
@@ -1009,8 +1008,7 @@ class HunyuanImage3Pipeline(HunyuanImage3PreTrainedModel, GenerationMixin, Diffu
|
||||
if req.sampling_params.guidance_scale_provided:
|
||||
guidance_scale = req.sampling_params.guidance_scale
|
||||
if guidance_scale <= 1.0:
|
||||
logger.warning("HunyuanImage3.0 does not support guidance_scale <= 1.0, will set it to 1.0 + epsilon.")
|
||||
guidance_scale = 1.0 + np.finfo(float).eps
|
||||
logger.info("HunyuanImage3.0 runs without classifier-free guidance when guidance_scale <= 1.0.")
|
||||
image_size = (height, width)
|
||||
model_inputs = self.prepare_model_inputs(
|
||||
prompt=prompt,
|
||||
File renamed without changes.
@@ -4,12 +4,14 @@
|
||||
from vllm_omni.diffusion.models.ltx2.ltx2_transformer import LTX2VideoTransformer3DModel
|
||||
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2 import (
|
||||
LTX2Pipeline,
|
||||
LTX2T2VDMD2Pipeline,
|
||||
LTX2TwoStagesPipeline,
|
||||
create_transformer_from_config,
|
||||
get_ltx2_post_process_func,
|
||||
load_transformer_config,
|
||||
)
|
||||
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_image2video import (
|
||||
LTX2I2VDMD2Pipeline,
|
||||
LTX2ImageToVideoPipeline,
|
||||
LTX2ImageToVideoTwoStagesPipeline,
|
||||
)
|
||||
@@ -17,7 +19,9 @@ from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_latent_upsample import LTX2La
|
||||
|
||||
__all__ = [
|
||||
"LTX2Pipeline",
|
||||
"LTX2T2VDMD2Pipeline",
|
||||
"LTX2ImageToVideoPipeline",
|
||||
"LTX2I2VDMD2Pipeline",
|
||||
"LTX2LatentUpsamplePipeline",
|
||||
"LTX2TwoStagesPipeline",
|
||||
"LTX2ImageToVideoTwoStagesPipeline",
|
||||
|
||||
@@ -41,6 +41,7 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.distributed.hsdp_utils import is_transformer_block_module
|
||||
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelInput, SequenceParallelOutput
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
|
||||
|
||||
@@ -1264,6 +1265,8 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
_supports_gradient_checkpointing = True
|
||||
_skip_layerwise_casting_patterns = ["norm"]
|
||||
_repeated_blocks = ["LTX2VideoTransformerBlock"]
|
||||
_layerwise_offload_blocks_attrs = ["transformer_blocks"]
|
||||
_hsdp_shard_conditions = [is_transformer_block_module]
|
||||
_sp_plan: dict[str, Any] | None = None
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -33,6 +33,7 @@ from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.lora.manager import DiffusionLoRAManager
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
@@ -1304,3 +1305,11 @@ class LTX2TwoStagesPipeline(nn.Module):
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
loader = AutoWeightsLoader(self)
|
||||
return loader.load_weights(weights)
|
||||
|
||||
|
||||
class LTX2T2VDMD2Pipeline(DMD2PipelineMixin, LTX2Pipeline):
|
||||
"""LTX-2 T2V pipeline for FastGen DMD2-distilled models."""
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
|
||||
super().__init__(od_config=od_config, prefix=prefix)
|
||||
self.__init_dmd2__()
|
||||
@@ -25,6 +25,7 @@ from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.lora.manager import DiffusionLoRAManager
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
|
||||
@@ -889,3 +890,11 @@ class LTX2ImageToVideoTwoStagesPipeline(nn.Module):
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
loader = AutoWeightsLoader(self)
|
||||
return loader.load_weights(weights)
|
||||
|
||||
|
||||
class LTX2I2VDMD2Pipeline(DMD2PipelineMixin, LTX2ImageToVideoPipeline):
|
||||
"""LTX-2 I2V pipeline for FastGen DMD2-distilled models."""
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
|
||||
super().__init__(od_config=od_config, prefix=prefix)
|
||||
self.__init_dmd2__()
|
||||
@@ -48,6 +48,7 @@ from vllm_omni.diffusion.model_loader.diffusers_loader import (
|
||||
)
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
|
||||
from vllm_omni.diffusion.models.t5_encoder.t5_gemma_encoder import T5GemmaEncoderModelTP
|
||||
from vllm_omni.diffusion.models.utils import _load_json
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import (
|
||||
DiffusionPipelineProfilerMixin,
|
||||
)
|
||||
@@ -1640,20 +1641,6 @@ def get_magi_human_post_process_func(*args, **kwargs):
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
def _load_json(model_path: str, filename: str, local_files_only: bool = True) -> dict:
|
||||
"""Load a JSON config file from a local path or HuggingFace Hub repo."""
|
||||
if local_files_only:
|
||||
path = os.path.join(model_path, *filename.split("/"))
|
||||
with open(path) as f:
|
||||
return json.load(f)
|
||||
else:
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
cached = hf_hub_download(repo_id=model_path, filename=filename)
|
||||
with open(cached) as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def _resolve_subdir(
|
||||
model_path: str,
|
||||
subfolder: str,
|
||||
|
||||
@@ -5,6 +5,8 @@ from types import SimpleNamespace
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import vllm._custom_ops as ops
|
||||
from diffusers.models.activations import get_activation
|
||||
from diffusers.models.embeddings import Timesteps, get_1d_rotary_pos_embed
|
||||
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
||||
@@ -16,6 +18,7 @@ from vllm.model_executor.layers.linear import (
|
||||
QKVParallelLinear,
|
||||
RowParallelLinear,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
@@ -24,6 +27,105 @@ from vllm_omni.platforms import current_omni_platform
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _patch_cutlass_padded_fp8():
|
||||
"""Monkey-patch vllm._custom_ops.cutlass_scaled_mm to pad tensors whose
|
||||
dimensions are not multiples of 16, so the CUTLASS FP8 kernel is used.
|
||||
|
||||
OmniGen2 has hidden_size=2520 (2520 % 16 == 8). Without this patch,
|
||||
vLLM's cutlass_scaled_mm falls back to a Triton scaled_mm kernel for
|
||||
every FP8 linear layer (QKV, attn output, gate_up_proj, down_proj),
|
||||
which is dramatically slower than the native CUTLASS FP8 tensor-core
|
||||
path on H100/H200 GPUs.
|
||||
|
||||
Weight tensors (b) are constant across forward passes, so padded
|
||||
versions are computed once and cached by data_ptr to avoid repeated
|
||||
allocation and column-major conversion overhead.
|
||||
"""
|
||||
_orig_cutlass_scaled_mm = ops.cutlass_scaled_mm
|
||||
# Cache: data_ptr → (padded_b, padded_bias, padded_scale_b, pad_k, pad_n, orig_n)
|
||||
_weight_cache: dict[int, tuple] = {}
|
||||
|
||||
def _padded_cutlass_scaled_mm(
|
||||
a: torch.Tensor,
|
||||
b: torch.Tensor,
|
||||
scale_a: torch.Tensor,
|
||||
scale_b: torch.Tensor,
|
||||
out_dtype: torch.dtype,
|
||||
bias: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
if b.shape[0] % 16 == 0 and b.shape[1] % 16 == 0:
|
||||
return _orig_cutlass_scaled_mm(a, b, scale_a, scale_b, out_dtype, bias)
|
||||
|
||||
# Reshape to 2D (mirrors the original function)
|
||||
target_shape = (*a.shape[:-1], b.shape[1])
|
||||
a = a.view(-1, a.shape[-1])
|
||||
orig_n = b.shape[1]
|
||||
|
||||
# Cache the padded weight — it's a model parameter that never changes.
|
||||
key = b.data_ptr()
|
||||
if key not in _weight_cache:
|
||||
pad_k = (16 - b.shape[0] % 16) % 16
|
||||
pad_n = (16 - orig_n % 16) % 16
|
||||
b_pad = b
|
||||
if pad_k > 0:
|
||||
b_pad = F.pad(b_pad, (0, 0, 0, pad_k))
|
||||
if pad_n > 0:
|
||||
b_pad = F.pad(b_pad, (0, pad_n))
|
||||
# CUTLASS requires b column-major (stride(0)==1).
|
||||
b_pad = b_pad.t().contiguous().t()
|
||||
|
||||
bias_pad = None
|
||||
if bias is not None and pad_n > 0:
|
||||
bias_pad = F.pad(bias, (0, pad_n))
|
||||
|
||||
scale_b_pad = scale_b
|
||||
if scale_b.numel() > 1 and pad_n > 0:
|
||||
scale_b_pad = F.pad(
|
||||
scale_b.view(-1, scale_b.shape[-1]),
|
||||
(0, pad_n),
|
||||
value=1.0,
|
||||
)
|
||||
|
||||
_weight_cache[key] = (
|
||||
b_pad,
|
||||
bias_pad,
|
||||
scale_b_pad,
|
||||
pad_k,
|
||||
pad_n,
|
||||
orig_n,
|
||||
)
|
||||
|
||||
b_pad, bias_pad, scale_b_pad, pad_k, pad_n, orig_n = _weight_cache[key]
|
||||
|
||||
# Pad activations on K dimension (cheap — activations are small).
|
||||
if pad_k > 0:
|
||||
a = F.pad(a, (0, pad_k)).contiguous()
|
||||
|
||||
out = torch.empty((a.shape[0], b_pad.shape[1]), dtype=out_dtype, device=a.device)
|
||||
torch.ops._C.cutlass_scaled_mm(
|
||||
out,
|
||||
a,
|
||||
b_pad,
|
||||
scale_a,
|
||||
scale_b_pad,
|
||||
bias_pad if bias is not None else None,
|
||||
)
|
||||
|
||||
if pad_n > 0:
|
||||
out = out[:, :orig_n]
|
||||
|
||||
return out.view(*target_shape)
|
||||
|
||||
ops.cutlass_scaled_mm = _padded_cutlass_scaled_mm
|
||||
logger.info(
|
||||
"Patched vllm._custom_ops.cutlass_scaled_mm with CUTLASS-padded FP8 "
|
||||
"variant (avoids slow Triton fallback for non-%%16 dimensions)"
|
||||
)
|
||||
|
||||
|
||||
_patch_cutlass_padded_fp8()
|
||||
|
||||
|
||||
class OmniGen2Attention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
@@ -31,6 +133,8 @@ class OmniGen2Attention(nn.Module):
|
||||
num_heads: int,
|
||||
num_kv_heads: int,
|
||||
eps: float = 1e-5,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
@@ -46,12 +150,26 @@ class OmniGen2Attention(nn.Module):
|
||||
total_num_kv_heads=num_kv_heads,
|
||||
disable_tp=True,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.to_qkv",
|
||||
)
|
||||
|
||||
self.norm_q = RMSNorm(self.head_dim, eps=eps)
|
||||
self.norm_k = RMSNorm(self.head_dim, eps=eps)
|
||||
|
||||
self.to_out = nn.ModuleList([nn.Linear(dim, dim, bias=False)])
|
||||
self.to_out = nn.ModuleList(
|
||||
[
|
||||
RowParallelLinear(
|
||||
dim,
|
||||
dim,
|
||||
bias=False,
|
||||
input_is_parallel=False,
|
||||
quant_config=quant_config,
|
||||
return_bias=False,
|
||||
prefix=f"{prefix}.to_out.0",
|
||||
)
|
||||
]
|
||||
)
|
||||
self.attn = Attention(
|
||||
num_heads=num_heads,
|
||||
head_size=self.head_dim,
|
||||
@@ -78,6 +196,9 @@ class OmniGen2Attention(nn.Module):
|
||||
"""
|
||||
batch_size = hidden_states.shape[0]
|
||||
|
||||
# Contiguous layout for FP8 quantized linear GEMMs (matches FLUX DiT).
|
||||
hidden_states = hidden_states.contiguous()
|
||||
|
||||
# Get Query-Key-Value Pair
|
||||
qkv, _ = self.to_qkv(hidden_states)
|
||||
|
||||
@@ -121,7 +242,7 @@ class OmniGen2Attention(nn.Module):
|
||||
hidden_states = hidden_states.reshape(batch_size, -1, self.num_heads * self.head_dim)
|
||||
hidden_states = hidden_states.to(dtype)
|
||||
|
||||
hidden_states = self.to_out[0](hidden_states)
|
||||
hidden_states = self.to_out[0](hidden_states.contiguous())
|
||||
|
||||
return hidden_states
|
||||
|
||||
@@ -233,6 +354,7 @@ class LuminaRMSNormZero(nn.Module):
|
||||
embedding_dim: int,
|
||||
norm_eps: float,
|
||||
norm_elementwise_affine: bool,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
self.silu = nn.SiLU()
|
||||
@@ -325,6 +447,8 @@ class LuminaFeedForward(nn.Module):
|
||||
inner_dim: int,
|
||||
multiple_of: int | None = 256,
|
||||
ffn_dim_multiplier: float | None = None,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
@@ -338,6 +462,8 @@ class LuminaFeedForward(nn.Module):
|
||||
[inner_dim, inner_dim],
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.gate_up_proj",
|
||||
)
|
||||
self.act_fn = get_act_and_mul_fn("silu")
|
||||
self.down_proj = RowParallelLinear(
|
||||
@@ -346,6 +472,8 @@ class LuminaFeedForward(nn.Module):
|
||||
bias=False,
|
||||
input_is_parallel=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.down_proj",
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
@@ -591,6 +719,8 @@ class OmniGen2TransformerBlock(nn.Module):
|
||||
ffn_dim_multiplier: float,
|
||||
norm_eps: float,
|
||||
modulation: bool = True,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
"""Initialize the transformer block."""
|
||||
super().__init__()
|
||||
@@ -602,6 +732,8 @@ class OmniGen2TransformerBlock(nn.Module):
|
||||
num_heads=num_attention_heads,
|
||||
num_kv_heads=num_kv_heads,
|
||||
eps=1e-5,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.attn",
|
||||
)
|
||||
|
||||
# Initialize feed-forward network
|
||||
@@ -610,11 +742,19 @@ class OmniGen2TransformerBlock(nn.Module):
|
||||
inner_dim=4 * dim,
|
||||
multiple_of=multiple_of,
|
||||
ffn_dim_multiplier=ffn_dim_multiplier,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.feed_forward",
|
||||
)
|
||||
|
||||
# Initialize normalization layers
|
||||
if modulation:
|
||||
self.norm1 = LuminaRMSNormZero(embedding_dim=dim, norm_eps=norm_eps, norm_elementwise_affine=True)
|
||||
self.norm1 = LuminaRMSNormZero(
|
||||
embedding_dim=dim,
|
||||
norm_eps=norm_eps,
|
||||
norm_elementwise_affine=True,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.norm1",
|
||||
)
|
||||
else:
|
||||
self.norm1 = RMSNorm(dim, eps=norm_eps)
|
||||
|
||||
@@ -713,6 +853,7 @@ class OmniGen2Transformer2DModel(nn.Module):
|
||||
axes_lens: tuple[int, int, int] = (1024, 1664, 1664),
|
||||
text_feat_dim: int = 2048,
|
||||
timestep_scale: float = 1000.0,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
) -> None:
|
||||
"""Initialize the OmniGen2 transformer model."""
|
||||
super().__init__()
|
||||
@@ -770,8 +911,10 @@ class OmniGen2Transformer2DModel(nn.Module):
|
||||
ffn_dim_multiplier,
|
||||
norm_eps,
|
||||
modulation=True,
|
||||
quant_config=quant_config,
|
||||
prefix=f"noise_refiner.{i}",
|
||||
)
|
||||
for _ in range(num_refiner_layers)
|
||||
for i in range(num_refiner_layers)
|
||||
]
|
||||
)
|
||||
|
||||
@@ -785,8 +928,10 @@ class OmniGen2Transformer2DModel(nn.Module):
|
||||
ffn_dim_multiplier,
|
||||
norm_eps,
|
||||
modulation=True,
|
||||
quant_config=quant_config,
|
||||
prefix=f"ref_image_refiner.{i}",
|
||||
)
|
||||
for _ in range(num_refiner_layers)
|
||||
for i in range(num_refiner_layers)
|
||||
]
|
||||
)
|
||||
|
||||
@@ -800,8 +945,10 @@ class OmniGen2Transformer2DModel(nn.Module):
|
||||
ffn_dim_multiplier,
|
||||
norm_eps,
|
||||
modulation=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"context_refiner.{i}",
|
||||
)
|
||||
for _ in range(num_refiner_layers)
|
||||
for i in range(num_refiner_layers)
|
||||
]
|
||||
)
|
||||
|
||||
@@ -816,8 +963,10 @@ class OmniGen2Transformer2DModel(nn.Module):
|
||||
ffn_dim_multiplier,
|
||||
norm_eps,
|
||||
modulation=True,
|
||||
quant_config=quant_config,
|
||||
prefix=f"layers.{i}",
|
||||
)
|
||||
for _ in range(num_layers)
|
||||
for i in range(num_layers)
|
||||
]
|
||||
)
|
||||
|
||||
@@ -847,11 +996,25 @@ class OmniGen2Transformer2DModel(nn.Module):
|
||||
temb,
|
||||
):
|
||||
batch_size = len(hidden_states)
|
||||
has_ref_tokens = any(ref_img_len > 0 for ref_lens in l_effective_ref_img_len for ref_img_len in ref_lens)
|
||||
max_combined_img_len = max(
|
||||
[img_len + sum(ref_img_len) for img_len, ref_img_len in zip(l_effective_img_len, l_effective_ref_img_len)]
|
||||
)
|
||||
|
||||
hidden_states = self.x_embedder(hidden_states)
|
||||
if not has_ref_tokens:
|
||||
# FP8 kernels do not support zero-token GEMM on ref_image_patch_embedder; skip that path only.
|
||||
# Still run noise_refiner and return the same combined layout as the no-ref case below
|
||||
# (batch, max_combined_img_len, hidden) — not raw noise tokens alone.
|
||||
for layer in self.noise_refiner:
|
||||
hidden_states = layer(hidden_states, padded_img_mask, noise_rotary_emb, temb)
|
||||
combined_img_hidden_states = hidden_states.new_zeros(
|
||||
batch_size, max_combined_img_len, self.config.hidden_size
|
||||
)
|
||||
for i, img_len in enumerate(l_effective_img_len):
|
||||
combined_img_hidden_states[i, :img_len] = hidden_states[i, :img_len]
|
||||
return combined_img_hidden_states
|
||||
|
||||
ref_image_hidden_states = self.ref_image_patch_embedder(ref_image_hidden_states)
|
||||
|
||||
for i in range(batch_size):
|
||||
|
||||
@@ -676,7 +676,10 @@ class OmniGen2Pipeline(CFGParallelMixin, nn.Module):
|
||||
)
|
||||
|
||||
transformer_kwargs = get_transformer_config_kwargs(od_config.tf_model_config, OmniGen2Transformer2DModel)
|
||||
self.transformer = OmniGen2Transformer2DModel(**transformer_kwargs)
|
||||
self.transformer = OmniGen2Transformer2DModel(
|
||||
**transformer_kwargs,
|
||||
quant_config=od_config.quantization_config,
|
||||
)
|
||||
self.mllm = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
||||
model, subfolder="mllm", local_files_only=local_files_only
|
||||
).to(self.device)
|
||||
@@ -1253,8 +1256,6 @@ class OmniGen2Pipeline(CFGParallelMixin, nn.Module):
|
||||
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
||||
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
||||
|
||||
batch_size, num_channels_latents, height, width = latents.shape
|
||||
|
||||
optional_kwargs = {}
|
||||
if "ref_image_hidden_states" in set(inspect.signature(self.transformer.forward).parameters.keys()):
|
||||
optional_kwargs["ref_image_hidden_states"] = ref_image_hidden_states
|
||||
|
||||
@@ -34,6 +34,9 @@ from vllm_omni.diffusion.models.qwen_image.qwen_image_transformer import (
|
||||
)
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.utils.prompt_utils import (
|
||||
validate_prompt_sequence_lengths,
|
||||
)
|
||||
from vllm_omni.diffusion.utils.size_utils import (
|
||||
normalize_min_aligned_size,
|
||||
)
|
||||
@@ -363,8 +366,10 @@ class QwenImagePipeline(nn.Module, QwenImageCFGParallelMixin, DiffusionPipelineP
|
||||
"that was used to generate `negative_prompt_embeds`."
|
||||
)
|
||||
|
||||
if max_sequence_length is not None and max_sequence_length > 1024:
|
||||
raise ValueError(f"`max_sequence_length` cannot be greater than 1024 but is {max_sequence_length}")
|
||||
if max_sequence_length is not None and max_sequence_length > self.tokenizer_max_length:
|
||||
raise ValueError(
|
||||
f"`max_sequence_length` cannot be greater than {self.tokenizer_max_length} but is {max_sequence_length}"
|
||||
)
|
||||
|
||||
def _extract_masked_hidden(self, hidden_states: torch.Tensor, mask: torch.Tensor):
|
||||
bool_mask = mask.bool()
|
||||
@@ -378,6 +383,8 @@ class QwenImagePipeline(nn.Module, QwenImageCFGParallelMixin, DiffusionPipelineP
|
||||
self,
|
||||
prompt: str | list[str] = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
max_sequence_length: int | None = None,
|
||||
prompt_name: str = "prompt",
|
||||
):
|
||||
dtype = dtype or self.text_encoder.dtype
|
||||
|
||||
@@ -388,12 +395,27 @@ class QwenImagePipeline(nn.Module, QwenImageCFGParallelMixin, DiffusionPipelineP
|
||||
txt = [template.format(e) for e in prompt]
|
||||
txt_tokens = self.tokenizer(
|
||||
txt,
|
||||
max_length=self.tokenizer_max_length + drop_idx,
|
||||
padding=True,
|
||||
truncation=True,
|
||||
truncation=False,
|
||||
return_tensors="pt",
|
||||
).to(self.device)
|
||||
# print(f"attention mask: {txt_tokens.attention_mask}")
|
||||
# Validate only the user prompt contribution. The Qwen template also
|
||||
# adds a fixed suffix after the user text, so subtracting only
|
||||
# prompt_template_encode_start_idx would overcount near-limit prompts.
|
||||
template_tokens = self.tokenizer(
|
||||
[template.format("")],
|
||||
padding=True,
|
||||
truncation=False,
|
||||
return_tensors="pt",
|
||||
).to(self.device)
|
||||
validate_prompt_sequence_lengths(
|
||||
txt_tokens.attention_mask,
|
||||
max_sequence_length=max_sequence_length or self.tokenizer_max_length,
|
||||
supported_max_sequence_length=self.tokenizer_max_length,
|
||||
prompt_name=prompt_name,
|
||||
baseline_attention_mask=template_tokens.attention_mask,
|
||||
error_context="after applying the Qwen prompt template",
|
||||
)
|
||||
encoder_hidden_states = self.text_encoder(
|
||||
input_ids=txt_tokens.input_ids,
|
||||
attention_mask=txt_tokens.attention_mask,
|
||||
@@ -422,6 +444,7 @@ class QwenImagePipeline(nn.Module, QwenImageCFGParallelMixin, DiffusionPipelineP
|
||||
prompt_embeds: torch.Tensor | None = None,
|
||||
prompt_embeds_mask: torch.Tensor | None = None,
|
||||
max_sequence_length: int = 1024,
|
||||
prompt_name: str = "prompt",
|
||||
):
|
||||
r"""
|
||||
|
||||
@@ -439,7 +462,11 @@ class QwenImagePipeline(nn.Module, QwenImageCFGParallelMixin, DiffusionPipelineP
|
||||
batch_size = len(prompt) if prompt_embeds is None else prompt_embeds.shape[0]
|
||||
|
||||
if prompt_embeds is None:
|
||||
prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(prompt)
|
||||
prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(
|
||||
prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
prompt_name=prompt_name,
|
||||
)
|
||||
|
||||
prompt_embeds = prompt_embeds[:, :max_sequence_length]
|
||||
prompt_embeds_mask = prompt_embeds_mask[:, :max_sequence_length]
|
||||
@@ -632,6 +659,7 @@ class QwenImagePipeline(nn.Module, QwenImageCFGParallelMixin, DiffusionPipelineP
|
||||
prompt_embeds_mask=negative_prompt_embeds_mask,
|
||||
num_images_per_prompt=num_images_per_prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
prompt_name="negative_prompt",
|
||||
)
|
||||
else:
|
||||
negative_prompt_embeds = None
|
||||
@@ -703,7 +731,7 @@ class QwenImagePipeline(nn.Module, QwenImageCFGParallelMixin, DiffusionPipelineP
|
||||
num_images_per_prompt=sampling.num_outputs_per_prompt if sampling.num_outputs_per_prompt > 0 else 1,
|
||||
generator=sampling.generator,
|
||||
true_cfg_scale=sampling.true_cfg_scale or 4.0,
|
||||
max_sequence_length=sampling.max_sequence_length or 512,
|
||||
max_sequence_length=sampling.max_sequence_length or self.tokenizer_max_length,
|
||||
attention_kwargs=kwargs.get("attention_kwargs"),
|
||||
)
|
||||
|
||||
@@ -934,7 +962,7 @@ class QwenImagePipeline(nn.Module, QwenImageCFGParallelMixin, DiffusionPipelineP
|
||||
output_type: str | None = "pil",
|
||||
attention_kwargs: dict[str, Any] | None = None,
|
||||
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
||||
max_sequence_length: int = 512,
|
||||
max_sequence_length: int = 1024,
|
||||
) -> DiffusionOutput:
|
||||
extracted_prompt, negative_prompt = self._extract_prompts(req.prompts)
|
||||
prompt = extracted_prompt or prompt
|
||||
|
||||
@@ -37,6 +37,9 @@ from vllm_omni.diffusion.models.qwen_image.qwen_image_transformer import (
|
||||
)
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.utils.prompt_utils import (
|
||||
validate_prompt_sequence_lengths,
|
||||
)
|
||||
from vllm_omni.diffusion.utils.size_utils import (
|
||||
normalize_min_aligned_size,
|
||||
)
|
||||
@@ -323,8 +326,10 @@ class QwenImageEditPipeline(nn.Module, SupportImageInput, QwenImageCFGParallelMi
|
||||
"that was used to generate `negative_prompt_embeds`."
|
||||
)
|
||||
|
||||
if max_sequence_length is not None and max_sequence_length > 1024:
|
||||
raise ValueError(f"`max_sequence_length` cannot be greater than 1024 but is {max_sequence_length}")
|
||||
if max_sequence_length is not None and max_sequence_length > self.tokenizer_max_length:
|
||||
raise ValueError(
|
||||
f"`max_sequence_length` cannot be greater than {self.tokenizer_max_length} but is {max_sequence_length}"
|
||||
)
|
||||
|
||||
def _extract_masked_hidden(self, hidden_states: torch.Tensor, mask: torch.Tensor):
|
||||
bool_mask = mask.bool()
|
||||
@@ -384,6 +389,8 @@ class QwenImageEditPipeline(nn.Module, SupportImageInput, QwenImageCFGParallelMi
|
||||
prompt: str | list[str] = None,
|
||||
image: PIL.Image.Image | torch.Tensor | None = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
max_sequence_length: int | None = None,
|
||||
prompt_name: str = "prompt",
|
||||
):
|
||||
"""Get prompt embeddings with image support for editing."""
|
||||
dtype = dtype or self.text_encoder.dtype
|
||||
@@ -393,6 +400,33 @@ class QwenImageEditPipeline(nn.Module, SupportImageInput, QwenImageCFGParallelMi
|
||||
template = self.prompt_template_encode
|
||||
drop_idx = self.prompt_template_encode_start_idx
|
||||
txt = [template.format(e) for e in prompt]
|
||||
txt_tokens = self.tokenizer(
|
||||
txt,
|
||||
padding=True,
|
||||
truncation=False,
|
||||
return_tensors="pt",
|
||||
).to(self.device)
|
||||
# The edit template contains fixed multimodal scaffolding around the
|
||||
# instruction. Validate against the empty-template baseline so image
|
||||
# placeholder text does not consume the user's text budget.
|
||||
template_tokens = self.tokenizer(
|
||||
[template.format("")],
|
||||
padding=True,
|
||||
truncation=False,
|
||||
return_tensors="pt",
|
||||
).to(self.device)
|
||||
# Qwen-Image-Edit expands image placeholders into many vision tokens
|
||||
# inside the processor. `max_sequence_length` is meant to constrain the
|
||||
# prompt text length, so validate on the text template before image
|
||||
# token expansion.
|
||||
validate_prompt_sequence_lengths(
|
||||
txt_tokens.attention_mask,
|
||||
max_sequence_length=max_sequence_length or self.tokenizer_max_length,
|
||||
supported_max_sequence_length=self.tokenizer_max_length,
|
||||
prompt_name=prompt_name,
|
||||
baseline_attention_mask=template_tokens.attention_mask,
|
||||
error_context="after applying the Qwen prompt template",
|
||||
)
|
||||
|
||||
# Use processor to handle both text and image inputs
|
||||
model_inputs = self.processor(
|
||||
@@ -434,6 +468,7 @@ class QwenImageEditPipeline(nn.Module, SupportImageInput, QwenImageCFGParallelMi
|
||||
prompt_embeds: torch.Tensor | None = None,
|
||||
prompt_embeds_mask: torch.Tensor | None = None,
|
||||
max_sequence_length: int = 1024,
|
||||
prompt_name: str = "prompt",
|
||||
):
|
||||
r"""
|
||||
|
||||
@@ -453,7 +488,12 @@ class QwenImageEditPipeline(nn.Module, SupportImageInput, QwenImageCFGParallelMi
|
||||
batch_size = len(prompt) if prompt_embeds is None else prompt_embeds.shape[0]
|
||||
|
||||
if prompt_embeds is None:
|
||||
prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(prompt, image)
|
||||
prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(
|
||||
prompt,
|
||||
image,
|
||||
max_sequence_length=max_sequence_length,
|
||||
prompt_name=prompt_name,
|
||||
)
|
||||
|
||||
_, seq_len, _ = prompt_embeds.shape
|
||||
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
||||
@@ -624,7 +664,7 @@ class QwenImageEditPipeline(nn.Module, SupportImageInput, QwenImageCFGParallelMi
|
||||
output_type: str | None = "pil",
|
||||
attention_kwargs: dict[str, Any] | None = None,
|
||||
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
||||
max_sequence_length: int = 512,
|
||||
max_sequence_length: int = 1024,
|
||||
) -> DiffusionOutput:
|
||||
"""Forward pass for image editing."""
|
||||
# TODO: In online mode, sometimes it receives [{"negative_prompt": None}, {...}], so cannot use .get("...", "")
|
||||
@@ -739,6 +779,7 @@ class QwenImageEditPipeline(nn.Module, SupportImageInput, QwenImageCFGParallelMi
|
||||
prompt_embeds_mask=negative_prompt_embeds_mask,
|
||||
num_images_per_prompt=num_images_per_prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
prompt_name="negative_prompt",
|
||||
)
|
||||
|
||||
num_channels_latents = self.transformer.in_channels // 4
|
||||
|
||||
@@ -25,6 +25,7 @@ from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_metadata import QWEN_IMAGE_EDIT_PLUS_MAX_INPUT_IMAGES
|
||||
from vllm_omni.diffusion.models.interface import SupportImageInput
|
||||
from vllm_omni.diffusion.models.qwen_image.cfg_parallel import (
|
||||
QwenImageCFGParallelMixin,
|
||||
@@ -40,6 +41,9 @@ from vllm_omni.diffusion.models.qwen_image.qwen_image_transformer import (
|
||||
)
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.utils.prompt_utils import (
|
||||
validate_prompt_sequence_lengths,
|
||||
)
|
||||
from vllm_omni.diffusion.utils.size_utils import (
|
||||
normalize_min_aligned_size,
|
||||
)
|
||||
@@ -53,6 +57,12 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
CONDITION_IMAGE_SIZE = 384 * 384
|
||||
VAE_IMAGE_SIZE = 1024 * 1024
|
||||
# Keep this in sync with the practical conditioning-token budget for
|
||||
# Qwen-Image-Edit-2511. Empirically, 4 images stays within the supported range
|
||||
# while 5 images overflows the prompt/conditioning path and fails downstream.
|
||||
# Re-export the shared metadata value locally so this pipeline keeps a nearby,
|
||||
# descriptive constant for validation and tests without becoming the source of truth.
|
||||
MAX_QWEN_IMAGE_EDIT_PLUS_INPUT_IMAGES = QWEN_IMAGE_EDIT_PLUS_MAX_INPUT_IMAGES
|
||||
|
||||
|
||||
def get_qwen_image_edit_plus_pre_process_func(
|
||||
@@ -90,6 +100,11 @@ def get_qwen_image_edit_plus_pre_process_func(
|
||||
|
||||
if not isinstance(raw_image, list):
|
||||
raw_image = [raw_image]
|
||||
if len(raw_image) > MAX_QWEN_IMAGE_EDIT_PLUS_INPUT_IMAGES:
|
||||
raise ValueError(
|
||||
f"Received {len(raw_image)} input images. "
|
||||
f"At most {MAX_QWEN_IMAGE_EDIT_PLUS_INPUT_IMAGES} images are supported by this model."
|
||||
)
|
||||
image = [
|
||||
PIL.Image.open(im) if isinstance(im, str) else cast(PIL.Image.Image | np.ndarray | torch.Tensor, im)
|
||||
for im in raw_image
|
||||
@@ -283,8 +298,10 @@ class QwenImageEditPlusPipeline(
|
||||
"that was used to generate `negative_prompt_embeds`."
|
||||
)
|
||||
|
||||
if max_sequence_length is not None and max_sequence_length > 1024:
|
||||
raise ValueError(f"`max_sequence_length` cannot be greater than 1024 but is {max_sequence_length}")
|
||||
if max_sequence_length is not None and max_sequence_length > self.tokenizer_max_length:
|
||||
raise ValueError(
|
||||
f"`max_sequence_length` cannot be greater than {self.tokenizer_max_length} but is {max_sequence_length}"
|
||||
)
|
||||
|
||||
def _extract_masked_hidden(self, hidden_states: torch.Tensor, mask: torch.Tensor):
|
||||
bool_mask = mask.bool()
|
||||
@@ -299,6 +316,8 @@ class QwenImageEditPlusPipeline(
|
||||
prompt: str | list[str],
|
||||
image: list[torch.Tensor] | torch.Tensor | None = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
max_sequence_length: int | None = None,
|
||||
prompt_name: str = "prompt",
|
||||
):
|
||||
"""Get prompt embeddings with support for multiple images."""
|
||||
dtype = dtype or self.text_encoder.dtype
|
||||
@@ -319,6 +338,32 @@ class QwenImageEditPlusPipeline(
|
||||
template = self.prompt_template_encode
|
||||
drop_idx = self.prompt_template_encode_start_idx
|
||||
txt = [template.format(base_img_prompt + e) for e in prompt]
|
||||
txt_tokens = self.tokenizer(
|
||||
txt,
|
||||
padding=True,
|
||||
truncation=False,
|
||||
return_tensors="pt",
|
||||
).to(self.device)
|
||||
# Multi-image edit prepends "Picture N" placeholders before the user
|
||||
# instruction. Subtract the placeholder-aware baseline so attached
|
||||
# images do not reduce the remaining prompt budget.
|
||||
template_tokens = self.tokenizer(
|
||||
[template.format(base_img_prompt)],
|
||||
padding=True,
|
||||
truncation=False,
|
||||
return_tensors="pt",
|
||||
).to(self.device)
|
||||
# The processor expands image placeholders into many vision tokens.
|
||||
# `max_sequence_length` should guard the prompt text length before that
|
||||
# multimodal expansion happens.
|
||||
validate_prompt_sequence_lengths(
|
||||
txt_tokens.attention_mask,
|
||||
max_sequence_length=max_sequence_length or self.tokenizer_max_length,
|
||||
supported_max_sequence_length=self.tokenizer_max_length,
|
||||
prompt_name=prompt_name,
|
||||
baseline_attention_mask=template_tokens.attention_mask,
|
||||
error_context="after applying the Qwen prompt template",
|
||||
)
|
||||
|
||||
# Use processor to handle both text and image inputs
|
||||
model_inputs = self.processor(
|
||||
@@ -360,6 +405,7 @@ class QwenImageEditPlusPipeline(
|
||||
prompt_embeds: torch.Tensor | None = None,
|
||||
prompt_embeds_mask: torch.Tensor | None = None,
|
||||
max_sequence_length: int = 1024,
|
||||
prompt_name: str = "prompt",
|
||||
):
|
||||
r"""
|
||||
|
||||
@@ -379,7 +425,12 @@ class QwenImageEditPlusPipeline(
|
||||
batch_size = len(prompt) if prompt_embeds is None else prompt_embeds.shape[0]
|
||||
|
||||
if prompt_embeds is None:
|
||||
prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(prompt, image)
|
||||
prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(
|
||||
prompt,
|
||||
image,
|
||||
max_sequence_length=max_sequence_length,
|
||||
prompt_name=prompt_name,
|
||||
)
|
||||
|
||||
_, seq_len, _ = prompt_embeds.shape
|
||||
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
||||
@@ -557,7 +608,7 @@ class QwenImageEditPlusPipeline(
|
||||
output_type: str | None = "pil",
|
||||
attention_kwargs: dict[str, Any] | None = None,
|
||||
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
||||
max_sequence_length: int = 512,
|
||||
max_sequence_length: int = 1024,
|
||||
) -> DiffusionOutput:
|
||||
"""Forward pass for image editing with support for multiple images."""
|
||||
# TODO: In online mode, sometimes it receives [{"negative_prompt": None}, {...}], so cannot use .get("...", "")
|
||||
@@ -692,6 +743,7 @@ class QwenImageEditPlusPipeline(
|
||||
prompt_embeds_mask=negative_prompt_embeds_mask,
|
||||
num_images_per_prompt=num_images_per_prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
prompt_name="negative_prompt",
|
||||
)
|
||||
|
||||
num_channels_latents = self.transformer.in_channels // 4
|
||||
|
||||
@@ -36,6 +36,9 @@ from vllm_omni.diffusion.models.qwen_image.qwen_image_transformer import (
|
||||
)
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.utils.prompt_utils import (
|
||||
validate_prompt_sequence_lengths,
|
||||
)
|
||||
from vllm_omni.diffusion.utils.size_utils import (
|
||||
normalize_min_aligned_size,
|
||||
)
|
||||
@@ -340,8 +343,10 @@ the image\n<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>as
|
||||
"generate `negative_prompt_embeds`."
|
||||
)
|
||||
|
||||
if max_sequence_length is not None and max_sequence_length > 1024:
|
||||
raise ValueError(f"`max_sequence_length` cannot be greater than 1024 but is {max_sequence_length}")
|
||||
if max_sequence_length is not None and max_sequence_length > self.tokenizer_max_length:
|
||||
raise ValueError(
|
||||
f"`max_sequence_length` cannot be greater than {self.tokenizer_max_length} but is {max_sequence_length}"
|
||||
)
|
||||
|
||||
def _extract_masked_hidden(self, hidden_states: torch.Tensor, mask: torch.Tensor):
|
||||
bool_mask = mask.bool()
|
||||
@@ -356,6 +361,8 @@ the image\n<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>as
|
||||
prompt: str | list[str] | None = None,
|
||||
device: torch.device | None = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
max_sequence_length: int | None = None,
|
||||
prompt_name: str = "prompt",
|
||||
):
|
||||
device = device or self.device
|
||||
dtype = dtype or self.text_encoder.dtype
|
||||
@@ -368,8 +375,26 @@ the image\n<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>as
|
||||
txt_tokens = self.tokenizer(
|
||||
txt,
|
||||
padding=True,
|
||||
truncation=False,
|
||||
return_tensors="pt",
|
||||
).to(device)
|
||||
# The layered template also appends fixed non-user tokens after the
|
||||
# editable text, so use the empty-template tokenized baseline instead of
|
||||
# counting everything after prompt_template_encode_start_idx.
|
||||
template_tokens = self.tokenizer(
|
||||
[template.format("")],
|
||||
padding=True,
|
||||
truncation=False,
|
||||
return_tensors="pt",
|
||||
).to(device)
|
||||
validate_prompt_sequence_lengths(
|
||||
txt_tokens.attention_mask,
|
||||
max_sequence_length=max_sequence_length or self.tokenizer_max_length,
|
||||
supported_max_sequence_length=self.tokenizer_max_length,
|
||||
prompt_name=prompt_name,
|
||||
baseline_attention_mask=template_tokens.attention_mask,
|
||||
error_context="after applying the Qwen prompt template",
|
||||
)
|
||||
encoder_hidden_states = self.text_encoder(
|
||||
input_ids=txt_tokens.input_ids,
|
||||
attention_mask=txt_tokens.attention_mask,
|
||||
@@ -399,6 +424,7 @@ the image\n<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>as
|
||||
prompt_embeds: torch.Tensor | None = None,
|
||||
prompt_embeds_mask: torch.Tensor | None = None,
|
||||
max_sequence_length: int = 1024,
|
||||
prompt_name: str = "prompt",
|
||||
):
|
||||
r"""
|
||||
|
||||
@@ -419,7 +445,11 @@ the image\n<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>as
|
||||
batch_size = len(prompt) if prompt_embeds is None else prompt_embeds.shape[0]
|
||||
|
||||
if prompt_embeds is None:
|
||||
prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(prompt)
|
||||
prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(
|
||||
prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
prompt_name=prompt_name,
|
||||
)
|
||||
|
||||
prompt_embeds = prompt_embeds[:, :max_sequence_length]
|
||||
prompt_embeds_mask = prompt_embeds_mask[:, :max_sequence_length]
|
||||
@@ -603,7 +633,7 @@ the image\n<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>as
|
||||
negative_prompt_embeds_mask: torch.Tensor | None = None,
|
||||
output_type: str | None = "pil",
|
||||
attention_kwargs: dict[str, Any] | None = None,
|
||||
max_sequence_length: int = 512,
|
||||
max_sequence_length: int = 1024,
|
||||
resolution: int = 640,
|
||||
cfg_normalize: bool = False,
|
||||
use_en_prompt: bool = False,
|
||||
@@ -736,6 +766,7 @@ the image\n<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>as
|
||||
device=self.device,
|
||||
num_images_per_prompt=num_images_per_prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
prompt_name="negative_prompt",
|
||||
)
|
||||
|
||||
# 4. Prepare latent variables
|
||||
|
||||
@@ -169,12 +169,15 @@ class QwenTimestepProjEmbeddings(nn.Module):
|
||||
|
||||
self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0, scale=1000)
|
||||
self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
|
||||
# Time embedding MLP is kept full precision (quant_config=None) —
|
||||
# small layers that feed per-block modulation; precision-sensitive
|
||||
# (see #2728).
|
||||
self.timestep_embedder.linear_1 = ReplicatedLinear(
|
||||
256,
|
||||
embedding_dim,
|
||||
bias=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
prefix="timestep_embedder.linear_1",
|
||||
)
|
||||
self.timestep_embedder.linear_2 = ReplicatedLinear(
|
||||
@@ -182,7 +185,7 @@ class QwenTimestepProjEmbeddings(nn.Module):
|
||||
embedding_dim,
|
||||
bias=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
prefix="timestep_embedder.linear_2",
|
||||
)
|
||||
self.use_additional_t_cond = use_additional_t_cond
|
||||
@@ -701,7 +704,10 @@ class QwenImageTransformerBlock(nn.Module):
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.attention_head_dim = attention_head_dim
|
||||
|
||||
# Image processing modules
|
||||
# Image processing modules.
|
||||
# Modulation linear is kept full precision (quant_config=None) — it
|
||||
# produces shift/scale/gate values that are precision-sensitive
|
||||
# (see #2728).
|
||||
self.img_mod = nn.Sequential(
|
||||
nn.SiLU(),
|
||||
ReplicatedLinear(
|
||||
@@ -709,7 +715,7 @@ class QwenImageTransformerBlock(nn.Module):
|
||||
6 * dim,
|
||||
bias=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
prefix="img_mod.1",
|
||||
),
|
||||
)
|
||||
@@ -725,7 +731,7 @@ class QwenImageTransformerBlock(nn.Module):
|
||||
self.img_norm2 = AdaLayerNorm(dim, elementwise_affine=False, eps=eps)
|
||||
self.img_mlp = FeedForward(dim=dim, dim_out=dim, quant_config=quant_config, prefix="img_mlp")
|
||||
|
||||
# Text processing modules
|
||||
# Text processing modules.
|
||||
self.txt_mod = nn.Sequential(
|
||||
nn.SiLU(),
|
||||
ReplicatedLinear(
|
||||
@@ -733,7 +739,7 @@ class QwenImageTransformerBlock(nn.Module):
|
||||
6 * dim,
|
||||
bias=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
prefix="txt_mod.1",
|
||||
),
|
||||
)
|
||||
@@ -744,9 +750,9 @@ class QwenImageTransformerBlock(nn.Module):
|
||||
|
||||
self.zero_cond_t = zero_cond_t
|
||||
|
||||
def _modulate(self, x, mod_params, index=None):
|
||||
def _modulate(self, mod_params, index=None):
|
||||
"""Apply modulation to input tensor"""
|
||||
# x: b l d, shift: b d, scale: b d, gate: b d
|
||||
# shift: b d, scale: b d, gate: b d
|
||||
shift, scale, gate = mod_params.chunk(3, dim=-1)
|
||||
|
||||
if index is not None:
|
||||
@@ -778,7 +784,7 @@ class QwenImageTransformerBlock(nn.Module):
|
||||
scale_result = scale.unsqueeze(1)
|
||||
gate_result = gate.unsqueeze(1)
|
||||
|
||||
return x * (1 + scale_result) + shift_result, gate_result
|
||||
return scale_result, shift_result, gate_result
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -804,10 +810,12 @@ class QwenImageTransformerBlock(nn.Module):
|
||||
txt_mod1, txt_mod2 = txt_mod_params.chunk(2, dim=-1) # Each [B, 3*dim]
|
||||
|
||||
# Process image stream - norm1 + modulation
|
||||
img_modulated, img_gate1 = self.img_norm1(hidden_states, img_mod1, modulate_index)
|
||||
img_scale1, img_shift1, img_gate1 = self._modulate(img_mod1, modulate_index)
|
||||
img_modulated = self.img_norm1(hidden_states, img_scale1, img_shift1)
|
||||
|
||||
# Process text stream - norm1 + modulation
|
||||
txt_modulated, txt_gate1 = self.txt_norm1(encoder_hidden_states, txt_mod1)
|
||||
txt_scale1, txt_shift1, txt_gate1 = self._modulate(txt_mod1)
|
||||
txt_modulated = self.txt_norm1(encoder_hidden_states, txt_scale1, txt_shift1)
|
||||
|
||||
# Use QwenAttnProcessor2_0 for joint attention computation
|
||||
# This directly implements the DoubleStreamLayerMegatron logic:
|
||||
@@ -832,13 +840,16 @@ class QwenImageTransformerBlock(nn.Module):
|
||||
encoder_hidden_states = encoder_hidden_states + txt_gate1 * txt_attn_output
|
||||
|
||||
# Process image stream - norm2 + MLP
|
||||
img_modulated2, img_gate2 = self.img_norm2(hidden_states, img_mod2, modulate_index)
|
||||
img_scale2, img_shift2, img_gate2 = self._modulate(img_mod2, modulate_index)
|
||||
img_modulated2 = self.img_norm2(hidden_states, img_scale2, img_shift2)
|
||||
|
||||
img_mlp_output = self.img_mlp(img_modulated2)
|
||||
hidden_states = hidden_states + img_gate2 * img_mlp_output
|
||||
|
||||
# Process text stream - norm2 + MLP
|
||||
txt_modulated2, txt_gate2 = self.txt_norm2(encoder_hidden_states, txt_mod2)
|
||||
txt_scale2, txt_shift2, txt_gate2 = self._modulate(txt_mod2)
|
||||
txt_modulated2 = self.txt_norm2(encoder_hidden_states, txt_scale2, txt_shift2)
|
||||
|
||||
txt_mlp_output = self.txt_mlp(txt_modulated2)
|
||||
encoder_hidden_states = encoder_hidden_states + txt_gate2 * txt_mlp_output
|
||||
|
||||
@@ -958,12 +969,14 @@ class QwenImageTransformer2DModel(CachedTransformer):
|
||||
|
||||
self.txt_norm = RMSNorm(joint_attention_dim, eps=1e-6)
|
||||
|
||||
# Entry projections (image/text) are kept full precision —
|
||||
# small sensitive layers at the network boundary (see #2728).
|
||||
self.img_in = ReplicatedLinear(
|
||||
in_channels,
|
||||
self.inner_dim,
|
||||
bias=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
prefix="img_in",
|
||||
)
|
||||
self.txt_in = ReplicatedLinear(
|
||||
@@ -971,7 +984,7 @@ class QwenImageTransformer2DModel(CachedTransformer):
|
||||
self.inner_dim,
|
||||
bias=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
prefix="txt_in",
|
||||
)
|
||||
|
||||
@@ -988,13 +1001,16 @@ class QwenImageTransformer2DModel(CachedTransformer):
|
||||
]
|
||||
)
|
||||
|
||||
# Final modulation and output projection are kept full precision —
|
||||
# they produce the output latent and are precision-sensitive
|
||||
# (see #2728).
|
||||
self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
|
||||
self.norm_out.linear = ReplicatedLinear(
|
||||
self.inner_dim,
|
||||
2 * self.inner_dim,
|
||||
bias=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
prefix="norm_out.linear",
|
||||
)
|
||||
self.proj_out = ReplicatedLinear(
|
||||
@@ -1002,7 +1018,7 @@ class QwenImageTransformer2DModel(CachedTransformer):
|
||||
patch_size * patch_size * self.out_channels,
|
||||
bias=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
prefix="proj_out",
|
||||
)
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from vllm_omni.diffusion.models.schedulers.scheduling_dmd2_euler import DMD2EulerScheduler
|
||||
from vllm_omni.diffusion.models.schedulers.scheduling_flow_unipc_multistep import (
|
||||
FlowUniPCMultistepScheduler,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"DMD2EulerScheduler",
|
||||
"FlowUniPCMultistepScheduler",
|
||||
]
|
||||
@@ -0,0 +1,23 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from diffusers import FlowMatchEulerDiscreteScheduler
|
||||
|
||||
|
||||
class DMD2EulerScheduler(FlowMatchEulerDiscreteScheduler):
|
||||
"""Euler scheduler that always uses the fixed DMD2 training timestep schedule."""
|
||||
|
||||
def __init__(self, *args, dmd2_timesteps: list[int], **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._dmd2_timesteps = dmd2_timesteps
|
||||
|
||||
def set_timesteps(
|
||||
self,
|
||||
num_inference_steps: int | None = None,
|
||||
device: str | torch.device | None = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().set_timesteps(timesteps=self._dmd2_timesteps, device=device)
|
||||
@@ -17,6 +17,7 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.hsdp_utils import is_transformer_block_module
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -376,6 +377,7 @@ class StableAudioDiTModel(nn.Module):
|
||||
"""
|
||||
|
||||
_repeated_blocks = ["StableAudioDiTBlock"]
|
||||
_hsdp_shard_conditions = [is_transformer_block_module]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
|
||||
def _load_json(model_path: str, filename: str, local_files_only: bool = True) -> dict:
|
||||
"""Load a JSON config file from a local path or HuggingFace Hub repo."""
|
||||
if local_files_only:
|
||||
path = os.path.join(model_path, *filename.split("/"))
|
||||
with open(path) as f:
|
||||
return json.load(f)
|
||||
else:
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
cached = hf_hub_download(repo_id=model_path, filename=filename)
|
||||
with open(cached) as f:
|
||||
return json.load(f)
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
from .pipeline_wan2_2 import (
|
||||
Wan22Pipeline,
|
||||
WanT2VDMD2Pipeline,
|
||||
create_transformer_from_config,
|
||||
get_wan22_post_process_func,
|
||||
get_wan22_pre_process_func,
|
||||
@@ -11,6 +12,7 @@ from .pipeline_wan2_2 import (
|
||||
)
|
||||
from .pipeline_wan2_2_i2v import (
|
||||
Wan22I2VPipeline,
|
||||
WanI2VDMD2Pipeline,
|
||||
get_wan22_i2v_post_process_func,
|
||||
get_wan22_i2v_pre_process_func,
|
||||
)
|
||||
@@ -28,6 +30,7 @@ from .wan2_2_transformer import WanTransformer3DModel
|
||||
from .wan2_2_vace_transformer import VaceWanTransformerBlock, WanVACETransformer3DModel
|
||||
|
||||
__all__ = [
|
||||
"WanT2VDMD2Pipeline",
|
||||
"Wan22Pipeline",
|
||||
"get_wan22_post_process_func",
|
||||
"get_wan22_pre_process_func",
|
||||
@@ -35,6 +38,7 @@ __all__ = [
|
||||
"load_transformer_config",
|
||||
"create_transformer_from_config",
|
||||
"Wan22I2VPipeline",
|
||||
"WanI2VDMD2Pipeline",
|
||||
"get_wan22_i2v_post_process_func",
|
||||
"get_wan22_i2v_pre_process_func",
|
||||
"Wan22TI2VPipeline",
|
||||
|
||||
@@ -22,10 +22,12 @@ from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import Dist
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin, _is_rank_zero
|
||||
from vllm_omni.diffusion.models.schedulers import FlowUniPCMultistepScheduler
|
||||
from vllm_omni.diffusion.models.wan2_2.scheduling_wan_euler import WanEulerScheduler
|
||||
from vllm_omni.diffusion.models.wan2_2.wan2_2_transformer import WanTransformer3DModel
|
||||
from vllm_omni.diffusion.postprocess import interpolate_video_tensor
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.inputs.data import OmniTextPrompt
|
||||
@@ -162,10 +164,23 @@ def get_wan22_post_process_func(
|
||||
def post_process_func(
|
||||
video: torch.Tensor,
|
||||
output_type: str = "np",
|
||||
sampling_params=None,
|
||||
):
|
||||
if output_type == "latent":
|
||||
return video
|
||||
return video_processor.postprocess_video(video, output_type=output_type)
|
||||
custom_output = {}
|
||||
if sampling_params is not None and getattr(sampling_params, "enable_frame_interpolation", False):
|
||||
video, multiplier = interpolate_video_tensor(
|
||||
video,
|
||||
exp=sampling_params.frame_interpolation_exp,
|
||||
scale=sampling_params.frame_interpolation_scale,
|
||||
model_path=sampling_params.frame_interpolation_model_path,
|
||||
)
|
||||
custom_output["video_fps_multiplier"] = multiplier
|
||||
return {
|
||||
"video": video_processor.postprocess_video(video, output_type=output_type),
|
||||
"custom_output": custom_output,
|
||||
}
|
||||
|
||||
return post_process_func
|
||||
|
||||
@@ -175,9 +190,6 @@ def get_wan22_pre_process_func(
|
||||
):
|
||||
"""Pre-process function for Wan2.2: optionally load and resize input image for I2V mode."""
|
||||
import numpy as np
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
|
||||
video_processor = VideoProcessor(vae_scale_factor=8)
|
||||
|
||||
def pre_process_func(request: OmniDiffusionRequest) -> OmniDiffusionRequest:
|
||||
for i, prompt in enumerate(request.prompts):
|
||||
@@ -221,10 +233,6 @@ def get_wan22_pre_process_func(
|
||||
)
|
||||
prompt["multi_modal_data"]["image"] = image # type: ignore # key existence already checked above
|
||||
|
||||
# Preprocess for VAE
|
||||
prompt["additional_information"]["preprocessed_image"] = video_processor.preprocess(
|
||||
image, height=request.sampling_params.height, width=request.sampling_params.width
|
||||
)
|
||||
request.prompts[i] = prompt
|
||||
return request
|
||||
|
||||
@@ -373,6 +381,102 @@ class Wan22Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin, DiffusionPipe
|
||||
def current_timestep(self):
|
||||
return self._current_timestep
|
||||
|
||||
def diffuse(
|
||||
self,
|
||||
latents: torch.Tensor,
|
||||
timesteps: torch.Tensor,
|
||||
prompt_embeds: torch.Tensor,
|
||||
negative_prompt_embeds: torch.Tensor | None,
|
||||
guidance_low: float,
|
||||
guidance_high: float,
|
||||
boundary_timestep: float | None,
|
||||
dtype: torch.dtype,
|
||||
attention_kwargs: dict[str, Any],
|
||||
latent_condition: torch.Tensor | None = None,
|
||||
first_frame_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
self._current_timestep = t
|
||||
|
||||
# Select model based on timestep and boundary_ratio
|
||||
# High noise stage (t >= boundary_timestep): use transformer
|
||||
# Low noise stage (t < boundary_timestep): use transformer_2
|
||||
if boundary_timestep is not None and t < boundary_timestep:
|
||||
# Low noise stage - always use guidance_high for this stage
|
||||
current_guidance_scale = guidance_high
|
||||
if self.transformer_2 is not None:
|
||||
current_model = self.transformer_2
|
||||
elif self.transformer is not None:
|
||||
# Fallback to transformer if transformer_2 not loaded
|
||||
current_model = self.transformer
|
||||
else:
|
||||
raise RuntimeError("No transformer available for low-noise stage")
|
||||
else:
|
||||
# High noise stage - always use guidance_low for this stage
|
||||
current_guidance_scale = guidance_low
|
||||
if self.transformer is not None:
|
||||
current_model = self.transformer
|
||||
elif self.transformer_2 is not None:
|
||||
# Fallback to transformer_2 if transformer not loaded
|
||||
current_model = self.transformer_2
|
||||
else:
|
||||
raise RuntimeError("No transformer available for high-noise stage")
|
||||
|
||||
if self.expand_timesteps and latent_condition is not None:
|
||||
# I2V mode: blend condition with latents using mask
|
||||
latent_model_input = (1 - first_frame_mask) * latent_condition + first_frame_mask * latents
|
||||
latent_model_input = latent_model_input.to(dtype)
|
||||
|
||||
# Expand timesteps per patch - use floor division to match patch embedding
|
||||
patch_size = self.transformer_config.patch_size
|
||||
patch_height = latents.shape[3] // patch_size[1]
|
||||
patch_width = latents.shape[4] // patch_size[2]
|
||||
|
||||
# Create mask at patch resolution (same as hidden states sequence length)
|
||||
patch_mask = first_frame_mask[:, :, :, :: patch_size[1], :: patch_size[2]]
|
||||
patch_mask = patch_mask[:, :, :, :patch_height, :patch_width] # Ensure correct dimensions
|
||||
temp_ts = (patch_mask[0][0] * t).flatten()
|
||||
timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
|
||||
else:
|
||||
# T2V mode: standard forward
|
||||
latent_model_input = latents.to(dtype)
|
||||
timestep = t.expand(latents.shape[0])
|
||||
|
||||
do_true_cfg = current_guidance_scale > 1.0 and negative_prompt_embeds is not None
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": current_model,
|
||||
}
|
||||
if do_true_cfg:
|
||||
negative_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": negative_prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": current_model,
|
||||
}
|
||||
else:
|
||||
negative_kwargs = None
|
||||
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=current_guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
)
|
||||
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
|
||||
pbar.update()
|
||||
|
||||
return latents
|
||||
|
||||
def forward(
|
||||
self,
|
||||
req: OmniDiffusionRequest,
|
||||
@@ -615,90 +719,19 @@ class Wan22Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin, DiffusionPipe
|
||||
|
||||
if DEBUG_PERF:
|
||||
_t_denoise_start = time.perf_counter()
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
self._current_timestep = t
|
||||
|
||||
# Select model based on timestep and boundary_ratio
|
||||
# High noise stage (t >= boundary_timestep): use transformer
|
||||
# Low noise stage (t < boundary_timestep): use transformer_2
|
||||
if boundary_timestep is not None and t < boundary_timestep:
|
||||
# Low noise stage - always use guidance_high for this stage
|
||||
current_guidance_scale = guidance_high
|
||||
if self.transformer_2 is not None:
|
||||
current_model = self.transformer_2
|
||||
elif self.transformer is not None:
|
||||
# Fallback to transformer if transformer_2 not loaded
|
||||
current_model = self.transformer
|
||||
else:
|
||||
raise RuntimeError("No transformer available for low-noise stage")
|
||||
else:
|
||||
# High noise stage - always use guidance_low for this stage
|
||||
current_guidance_scale = guidance_low
|
||||
if self.transformer is not None:
|
||||
current_model = self.transformer
|
||||
elif self.transformer_2 is not None:
|
||||
# Fallback to transformer_2 if transformer not loaded
|
||||
current_model = self.transformer_2
|
||||
else:
|
||||
raise RuntimeError("No transformer available for high-noise stage")
|
||||
|
||||
if self.expand_timesteps and latent_condition is not None:
|
||||
# I2V mode: blend condition with latents using mask
|
||||
latent_model_input = (1 - first_frame_mask) * latent_condition + first_frame_mask * latents
|
||||
latent_model_input = latent_model_input.to(dtype)
|
||||
|
||||
# Expand timesteps per patch - use floor division to match patch embedding
|
||||
patch_size = self.transformer_config.patch_size
|
||||
num_latent_frames = latents.shape[2]
|
||||
patch_height = latents.shape[3] // patch_size[1]
|
||||
patch_width = latents.shape[4] // patch_size[2]
|
||||
|
||||
# Create mask at patch resolution (same as hidden states sequence length)
|
||||
patch_mask = first_frame_mask[:, :, :, :: patch_size[1], :: patch_size[2]]
|
||||
patch_mask = patch_mask[:, :, :, :patch_height, :patch_width] # Ensure correct dimensions
|
||||
temp_ts = (patch_mask[0][0] * t).flatten()
|
||||
timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
|
||||
else:
|
||||
# T2V mode: standard forward
|
||||
latent_model_input = latents.to(dtype)
|
||||
timestep = t.expand(latents.shape[0])
|
||||
|
||||
do_true_cfg = current_guidance_scale > 1.0 and negative_prompt_embeds is not None
|
||||
# Prepare kwargs for positive and negative predictions
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": current_model,
|
||||
}
|
||||
if do_true_cfg:
|
||||
negative_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": negative_prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": current_model,
|
||||
}
|
||||
else:
|
||||
negative_kwargs = None
|
||||
|
||||
# Predict noise with automatic CFG parallel handling
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=current_guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
)
|
||||
|
||||
# Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
|
||||
|
||||
pbar.update()
|
||||
latents = self.diffuse(
|
||||
latents=latents,
|
||||
timesteps=timesteps,
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
guidance_low=guidance_low,
|
||||
guidance_high=guidance_high,
|
||||
boundary_timestep=boundary_timestep,
|
||||
dtype=dtype,
|
||||
attention_kwargs=attention_kwargs,
|
||||
latent_condition=latent_condition,
|
||||
first_frame_mask=first_frame_mask,
|
||||
)
|
||||
|
||||
# Wan2.2 is prone to out of memory errors when predicting large videos
|
||||
# so we empty the cache here to avoid OOM before vae decoding.
|
||||
@@ -916,3 +949,16 @@ class Wan22Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin, DiffusionPipe
|
||||
|
||||
if boundary_ratio is None and guidance_scale_2 is not None:
|
||||
raise ValueError("`guidance_scale_2` is only supported when `boundary_ratio` is set.")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DMD2-distilled variant
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WanT2VDMD2Pipeline(DMD2PipelineMixin, Wan22Pipeline):
|
||||
"""Wan 2.x T2V pipeline for FastGen DMD2-distilled models."""
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
|
||||
super().__init__(od_config=od_config, prefix=prefix)
|
||||
self.__init_dmd2__()
|
||||
@@ -12,6 +12,7 @@ from typing import Any, cast
|
||||
import numpy as np
|
||||
import PIL.Image
|
||||
import torch
|
||||
import torchvision.transforms.functional as TF
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
from torch import nn
|
||||
from transformers import AutoTokenizer, CLIPImageProcessor, CLIPVisionModel, UMT5EncoderModel
|
||||
@@ -22,8 +23,10 @@ from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import Dist
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
from vllm_omni.diffusion.models.interface import SupportImageInput
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin, _is_rank_zero
|
||||
from vllm_omni.diffusion.models.utils import _load_json
|
||||
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
|
||||
build_wan_scheduler,
|
||||
create_transformer_from_config,
|
||||
@@ -32,6 +35,7 @@ from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
|
||||
resolve_wan_sample_solver,
|
||||
retrieve_latents,
|
||||
)
|
||||
from vllm_omni.diffusion.postprocess import interpolate_video_tensor
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.inputs.data import OmniTextPrompt
|
||||
@@ -41,29 +45,6 @@ logger = logging.getLogger(__name__)
|
||||
DEBUG_PERF = False
|
||||
|
||||
|
||||
def _load_model_index(model: str, local_files_only: bool) -> dict:
|
||||
"""Load model_index.json from local path or HF Hub."""
|
||||
if local_files_only:
|
||||
model_index_path = os.path.join(model, "model_index.json")
|
||||
if os.path.exists(model_index_path):
|
||||
import json
|
||||
|
||||
with open(model_index_path) as f:
|
||||
return json.load(f)
|
||||
else:
|
||||
try:
|
||||
import json
|
||||
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
model_index_path = hf_hub_download(model, "model_index.json")
|
||||
with open(model_index_path) as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def get_wan22_i2v_post_process_func(
|
||||
od_config: OmniDiffusionConfig,
|
||||
):
|
||||
@@ -74,10 +55,23 @@ def get_wan22_i2v_post_process_func(
|
||||
def post_process_func(
|
||||
video: torch.Tensor,
|
||||
output_type: str = "np",
|
||||
sampling_params=None,
|
||||
):
|
||||
if output_type == "latent":
|
||||
return video
|
||||
return video_processor.postprocess_video(video, output_type=output_type)
|
||||
custom_output = {}
|
||||
if sampling_params is not None and getattr(sampling_params, "enable_frame_interpolation", False):
|
||||
video, multiplier = interpolate_video_tensor(
|
||||
video,
|
||||
exp=sampling_params.frame_interpolation_exp,
|
||||
scale=sampling_params.frame_interpolation_scale,
|
||||
model_path=sampling_params.frame_interpolation_model_path,
|
||||
)
|
||||
custom_output["video_fps_multiplier"] = multiplier
|
||||
return {
|
||||
"video": video_processor.postprocess_video(video, output_type=output_type),
|
||||
"custom_output": custom_output,
|
||||
}
|
||||
|
||||
return post_process_func
|
||||
|
||||
@@ -86,9 +80,6 @@ def get_wan22_i2v_pre_process_func(
|
||||
od_config: OmniDiffusionConfig,
|
||||
):
|
||||
"""Pre-process function for I2V: load and resize input image."""
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
|
||||
video_processor = VideoProcessor(vae_scale_factor=8)
|
||||
|
||||
def pre_process_func(request: OmniDiffusionRequest) -> OmniDiffusionRequest:
|
||||
for i, prompt in enumerate(request.prompts):
|
||||
@@ -134,10 +125,6 @@ def get_wan22_i2v_pre_process_func(
|
||||
)
|
||||
prompt["multi_modal_data"]["image"] = image # type: ignore # key existence already checked above
|
||||
|
||||
# Preprocess for VAE
|
||||
prompt["additional_information"]["preprocessed_image"] = video_processor.preprocess(
|
||||
image, height=request.sampling_params.height, width=request.sampling_params.width
|
||||
)
|
||||
request.prompts[i] = prompt
|
||||
return request
|
||||
|
||||
@@ -181,7 +168,10 @@ class Wan22I2VPipeline(
|
||||
]
|
||||
|
||||
# Load model_index.json to detect available components
|
||||
model_index = _load_model_index(model, local_files_only)
|
||||
try:
|
||||
model_index = _load_json(model, "model_index.json", local_files_only)
|
||||
except Exception:
|
||||
model_index = {}
|
||||
|
||||
# Check if this is a two-stage model (MoE with transformer_2)
|
||||
self.has_transformer_2 = "transformer_2" in model_index
|
||||
@@ -270,6 +260,82 @@ class Wan22I2VPipeline(
|
||||
def current_timestep(self):
|
||||
return self._current_timestep
|
||||
|
||||
def diffuse(
|
||||
self,
|
||||
latents: torch.Tensor,
|
||||
timesteps: torch.Tensor,
|
||||
prompt_embeds: torch.Tensor,
|
||||
negative_prompt_embeds: torch.Tensor | None,
|
||||
image_embeds: torch.Tensor | None,
|
||||
guidance_low: float,
|
||||
guidance_high: float,
|
||||
boundary_timestep: float | None,
|
||||
dtype: torch.dtype,
|
||||
attention_kwargs: dict[str, Any],
|
||||
condition: torch.Tensor,
|
||||
first_frame_mask: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
self._current_timestep = t
|
||||
|
||||
# Select model and guidance scale based on timestep
|
||||
current_model = self.transformer
|
||||
current_guidance_scale = guidance_low
|
||||
if boundary_timestep is not None and t < boundary_timestep and self.transformer_2 is not None:
|
||||
current_model = self.transformer_2
|
||||
current_guidance_scale = guidance_high
|
||||
|
||||
# Prepare latent input
|
||||
if self.expand_timesteps:
|
||||
# TI2V-5B style: blend condition with latents using mask
|
||||
latent_model_input = (1 - first_frame_mask) * condition + first_frame_mask * latents
|
||||
latent_model_input = latent_model_input.to(dtype)
|
||||
|
||||
# Expand timesteps for each patch
|
||||
temp_ts = (first_frame_mask[0][0][:, ::2, ::2] * t).flatten()
|
||||
timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
|
||||
else:
|
||||
# Wan2.1 style: concatenate condition with latents
|
||||
latent_model_input = torch.cat([latents, condition], dim=1).to(dtype)
|
||||
timestep = t.expand(latents.shape[0])
|
||||
|
||||
do_true_cfg = current_guidance_scale > 1.0 and negative_prompt_embeds is not None
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": prompt_embeds,
|
||||
"encoder_hidden_states_image": image_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": current_model,
|
||||
}
|
||||
if do_true_cfg:
|
||||
negative_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": negative_prompt_embeds,
|
||||
"encoder_hidden_states_image": image_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": current_model,
|
||||
}
|
||||
else:
|
||||
negative_kwargs = None
|
||||
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=current_guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
)
|
||||
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
|
||||
pbar.update()
|
||||
|
||||
return latents
|
||||
|
||||
def encode_image(
|
||||
self,
|
||||
image: PIL.Image.Image | list[PIL.Image.Image],
|
||||
@@ -464,6 +530,7 @@ class Wan22I2VPipeline(
|
||||
video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
||||
|
||||
if isinstance(image, PIL.Image.Image):
|
||||
image = TF.to_tensor(image).to(device)
|
||||
image_tensor = video_processor.preprocess(image, height=height, width=width)
|
||||
else:
|
||||
image_tensor = image
|
||||
@@ -472,6 +539,7 @@ class Wan22I2VPipeline(
|
||||
# Handle last_image if provided
|
||||
if last_image is not None:
|
||||
if isinstance(last_image, PIL.Image.Image):
|
||||
image = TF.to_tensor(last_image).to(device)
|
||||
last_image_tensor = video_processor.preprocess(last_image, height=height, width=width)
|
||||
else:
|
||||
last_image_tensor = last_image
|
||||
@@ -502,68 +570,20 @@ class Wan22I2VPipeline(
|
||||
|
||||
if DEBUG_PERF:
|
||||
_t_denoise_start = time.perf_counter()
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
self._current_timestep = t
|
||||
|
||||
# Select model and guidance scale based on timestep
|
||||
current_model = self.transformer
|
||||
current_guidance_scale = guidance_low
|
||||
if boundary_timestep is not None and t < boundary_timestep and self.transformer_2 is not None:
|
||||
current_model = self.transformer_2
|
||||
current_guidance_scale = guidance_high
|
||||
|
||||
# Prepare latent input
|
||||
if self.expand_timesteps:
|
||||
# TI2V-5B style: blend condition with latents using mask
|
||||
latent_model_input = (1 - first_frame_mask) * condition + first_frame_mask * latents
|
||||
latent_model_input = latent_model_input.to(dtype)
|
||||
|
||||
# Expand timesteps for each patch
|
||||
temp_ts = (first_frame_mask[0][0][:, ::2, ::2] * t).flatten()
|
||||
timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
|
||||
else:
|
||||
# Wan2.1 style: concatenate condition with latents
|
||||
latent_model_input = torch.cat([latents, condition], dim=1).to(dtype)
|
||||
timestep = t.expand(latents.shape[0])
|
||||
|
||||
do_true_cfg = current_guidance_scale > 1.0 and negative_prompt_embeds is not None
|
||||
# Prepare kwargs for positive and negative predictions
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": prompt_embeds,
|
||||
"encoder_hidden_states_image": image_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": current_model,
|
||||
}
|
||||
if do_true_cfg:
|
||||
negative_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": negative_prompt_embeds,
|
||||
"encoder_hidden_states_image": image_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": current_model,
|
||||
}
|
||||
else:
|
||||
negative_kwargs = None
|
||||
|
||||
# Predict noise with automatic CFG parallel handling
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=current_guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
)
|
||||
|
||||
# Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
|
||||
|
||||
pbar.update()
|
||||
latents = self.diffuse(
|
||||
latents=latents,
|
||||
timesteps=timesteps,
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
image_embeds=image_embeds,
|
||||
guidance_low=guidance_low,
|
||||
guidance_high=guidance_high,
|
||||
boundary_timestep=boundary_timestep,
|
||||
dtype=dtype,
|
||||
attention_kwargs=attention_kwargs,
|
||||
condition=condition,
|
||||
first_frame_mask=first_frame_mask,
|
||||
)
|
||||
|
||||
# Wan2.2 is prone to out of memory errors when predicting large videos
|
||||
# so we empty the cache here to avoid OOM before vae decoding.
|
||||
@@ -794,12 +814,14 @@ class Wan22I2VPipeline(
|
||||
return latents, latent_condition, first_frame_mask
|
||||
|
||||
# Wan2.1 style: create mask and concatenate with condition
|
||||
mask_lat_size = torch.ones(batch_size, 1, num_frames, latent_height, latent_width)
|
||||
mask_lat_size = torch.ones(
|
||||
batch_size, 1, num_frames, latent_height, latent_width, device=latent_condition.device
|
||||
)
|
||||
|
||||
if last_image is None:
|
||||
mask_lat_size[:, :, list(range(1, num_frames))] = 0
|
||||
mask_lat_size[:, :, 1:] = 0
|
||||
else:
|
||||
mask_lat_size[:, :, list(range(1, num_frames - 1))] = 0
|
||||
mask_lat_size[:, :, 1 : num_frames - 1] = 0
|
||||
|
||||
first_frame_mask = mask_lat_size[:, :, 0:1]
|
||||
first_frame_mask = torch.repeat_interleave(first_frame_mask, dim=2, repeats=self.vae_scale_factor_temporal)
|
||||
@@ -856,3 +878,16 @@ class Wan22I2VPipeline(
|
||||
"""Load weights using AutoWeightsLoader for vLLM integration."""
|
||||
loader = AutoWeightsLoader(self)
|
||||
return loader.load_weights(weights)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DMD2-distilled variant
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WanI2VDMD2Pipeline(DMD2PipelineMixin, Wan22I2VPipeline):
|
||||
"""Wan 2.x I2V pipeline for FastGen DMD2-distilled models."""
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
|
||||
super().__init__(od_config=od_config, prefix=prefix)
|
||||
self.__init_dmd2__()
|
||||
@@ -44,6 +44,7 @@ from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
|
||||
resolve_wan_sample_solver,
|
||||
retrieve_latents,
|
||||
)
|
||||
from vllm_omni.diffusion.postprocess import interpolate_video_tensor
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.inputs.data import OmniTextPrompt
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
@@ -61,10 +62,23 @@ def get_wan22_ti2v_post_process_func(
|
||||
def post_process_func(
|
||||
video: torch.Tensor,
|
||||
output_type: str = "np",
|
||||
sampling_params=None,
|
||||
):
|
||||
if output_type == "latent":
|
||||
return video
|
||||
return video_processor.postprocess_video(video, output_type=output_type)
|
||||
custom_output = {}
|
||||
if sampling_params is not None and getattr(sampling_params, "enable_frame_interpolation", False):
|
||||
video, multiplier = interpolate_video_tensor(
|
||||
video,
|
||||
exp=sampling_params.frame_interpolation_exp,
|
||||
scale=sampling_params.frame_interpolation_scale,
|
||||
model_path=sampling_params.frame_interpolation_model_path,
|
||||
)
|
||||
custom_output["video_fps_multiplier"] = multiplier
|
||||
return {
|
||||
"video": video_processor.postprocess_video(video, output_type=output_type),
|
||||
"custom_output": custom_output,
|
||||
}
|
||||
|
||||
return post_process_func
|
||||
|
||||
@@ -73,9 +87,6 @@ def get_wan22_ti2v_pre_process_func(
|
||||
od_config: OmniDiffusionConfig,
|
||||
):
|
||||
"""Pre-process function for TI2V: optionally load and resize input image."""
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
|
||||
video_processor = VideoProcessor(vae_scale_factor=8)
|
||||
|
||||
def pre_process_func(request: OmniDiffusionRequest) -> OmniDiffusionRequest:
|
||||
for i, prompt in enumerate(request.prompts):
|
||||
@@ -121,10 +132,6 @@ def get_wan22_ti2v_pre_process_func(
|
||||
)
|
||||
prompt["multi_modal_data"]["image"] = image # type: ignore # key existence already checked above
|
||||
|
||||
# Preprocess for VAE
|
||||
prompt["additional_information"]["preprocessed_image"] = video_processor.preprocess(
|
||||
image, height=request.sampling_params.height, width=request.sampling_params.width
|
||||
)
|
||||
request.prompts[i] = prompt
|
||||
return request
|
||||
|
||||
@@ -216,6 +223,77 @@ class Wan22TI2VPipeline(nn.Module, SupportImageInput, CFGParallelMixin, Progress
|
||||
def current_timestep(self):
|
||||
return self._current_timestep
|
||||
|
||||
def diffuse(
|
||||
self,
|
||||
latents: torch.Tensor,
|
||||
timesteps: torch.Tensor,
|
||||
prompt_embeds: torch.Tensor,
|
||||
negative_prompt_embeds: torch.Tensor | None,
|
||||
guidance_scale: float,
|
||||
dtype: torch.dtype,
|
||||
attention_kwargs: dict[str, Any],
|
||||
num_latent_frames: int,
|
||||
latent_height: int,
|
||||
latent_width: int,
|
||||
latent_condition: torch.Tensor | None = None,
|
||||
first_frame_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
self._current_timestep = t
|
||||
|
||||
# Prepare latent input
|
||||
if latent_condition is not None:
|
||||
# I2V mode: blend condition with latents using mask
|
||||
latent_model_input = (1 - first_frame_mask) * latent_condition + first_frame_mask * latents
|
||||
latent_model_input = latent_model_input.to(dtype)
|
||||
|
||||
# Expand timesteps for each patch (TI2V style)
|
||||
temp_ts = (first_frame_mask[0][0][:, ::2, ::2] * t).flatten()
|
||||
timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
|
||||
else:
|
||||
# T2V mode: use latents directly
|
||||
latent_model_input = latents.to(dtype)
|
||||
|
||||
# Expand timesteps for TI2V model architecture
|
||||
mask = torch.ones(1, 1, num_latent_frames, latent_height, latent_width, device=latents.device)
|
||||
temp_ts = (mask[0][0][:, ::2, ::2] * t).flatten()
|
||||
timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
|
||||
|
||||
do_true_cfg = guidance_scale > 1.0 and negative_prompt_embeds is not None
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": self.transformer,
|
||||
}
|
||||
if do_true_cfg:
|
||||
negative_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": negative_prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": self.transformer,
|
||||
}
|
||||
else:
|
||||
negative_kwargs = None
|
||||
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
)
|
||||
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
|
||||
pbar.update()
|
||||
|
||||
return latents
|
||||
|
||||
def forward(
|
||||
self,
|
||||
req: OmniDiffusionRequest,
|
||||
@@ -385,64 +463,20 @@ class Wan22TI2VPipeline(nn.Module, SupportImageInput, CFGParallelMixin, Progress
|
||||
if attention_kwargs is None:
|
||||
attention_kwargs = {}
|
||||
|
||||
# Denoising loop
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
self._current_timestep = t
|
||||
|
||||
# Prepare latent input
|
||||
if latent_condition is not None:
|
||||
# I2V mode: blend condition with latents using mask
|
||||
latent_model_input = (1 - first_frame_mask) * latent_condition + first_frame_mask * latents
|
||||
latent_model_input = latent_model_input.to(dtype)
|
||||
|
||||
# Expand timesteps for each patch (TI2V style)
|
||||
temp_ts = (first_frame_mask[0][0][:, ::2, ::2] * t).flatten()
|
||||
timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
|
||||
else:
|
||||
# T2V mode: use latents directly
|
||||
latent_model_input = latents.to(dtype)
|
||||
|
||||
# Expand timesteps for TI2V model architecture
|
||||
mask = torch.ones(1, 1, num_latent_frames, latent_height, latent_width, device=device)
|
||||
temp_ts = (mask[0][0][:, ::2, ::2] * t).flatten()
|
||||
timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
|
||||
|
||||
do_true_cfg = guidance_scale > 1.0 and negative_prompt_embeds is not None
|
||||
# Prepare kwargs for positive and negative predictions
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": self.transformer,
|
||||
}
|
||||
if do_true_cfg:
|
||||
negative_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": negative_prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
"current_model": self.transformer,
|
||||
}
|
||||
else:
|
||||
negative_kwargs = None
|
||||
|
||||
# Predict noise with automatic CFG parallel handling
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
)
|
||||
|
||||
# Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
|
||||
|
||||
pbar.update()
|
||||
latents = self.diffuse(
|
||||
latents=latents,
|
||||
timesteps=timesteps,
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
guidance_scale=guidance_scale,
|
||||
dtype=dtype,
|
||||
attention_kwargs=attention_kwargs,
|
||||
num_latent_frames=num_latent_frames,
|
||||
latent_height=latent_height,
|
||||
latent_width=latent_width,
|
||||
latent_condition=latent_condition,
|
||||
first_frame_mask=first_frame_mask,
|
||||
)
|
||||
|
||||
# Wan2.2 is prone to out of memory errors when predicting large videos
|
||||
# so we empty the cache here to avoid OOM before vae decoding.
|
||||
|
||||
@@ -176,6 +176,62 @@ class Wan22VACEPipeline(Wan22Pipeline, SupportImageInput):
|
||||
"""Build VACE transformer directly from config dict."""
|
||||
return create_vace_transformer_from_config(config)
|
||||
|
||||
def diffuse(
|
||||
self,
|
||||
latents: torch.Tensor,
|
||||
timesteps: torch.Tensor,
|
||||
prompt_embeds: torch.Tensor,
|
||||
negative_prompt_embeds: torch.Tensor | None,
|
||||
guidance_scale: float,
|
||||
dtype: torch.dtype,
|
||||
attention_kwargs: dict[str, object],
|
||||
vace_context: torch.Tensor | None,
|
||||
vace_context_scale: float,
|
||||
) -> torch.Tensor:
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
self._current_timestep = t
|
||||
latent_model_input = latents.to(dtype)
|
||||
timestep = t.expand(latents.shape[0])
|
||||
|
||||
do_true_cfg = guidance_scale > 1.0 and negative_prompt_embeds is not None
|
||||
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"vace_context": vace_context,
|
||||
"vace_context_scale": vace_context_scale,
|
||||
"return_dict": False,
|
||||
}
|
||||
negative_kwargs = (
|
||||
{
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": negative_prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"vace_context": vace_context,
|
||||
"vace_context_scale": vace_context_scale,
|
||||
"return_dict": False,
|
||||
}
|
||||
if do_true_cfg
|
||||
else None
|
||||
)
|
||||
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
)
|
||||
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
|
||||
pbar.update()
|
||||
|
||||
return latents
|
||||
|
||||
def check_inputs(
|
||||
self,
|
||||
prompt,
|
||||
@@ -569,48 +625,17 @@ class Wan22VACEPipeline(Wan22Pipeline, SupportImageInput):
|
||||
timesteps = self.scheduler.timesteps
|
||||
self._num_timesteps = len(timesteps)
|
||||
|
||||
# Denoising loop
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
self._current_timestep = t
|
||||
latent_model_input = latents.to(dtype)
|
||||
timestep = t.expand(latents.shape[0])
|
||||
|
||||
do_true_cfg = guidance_scale > 1.0 and negative_prompt_embeds is not None
|
||||
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"vace_context": vace_context,
|
||||
"vace_context_scale": vace_context_scale,
|
||||
"return_dict": False,
|
||||
}
|
||||
negative_kwargs = (
|
||||
{
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
"encoder_hidden_states": negative_prompt_embeds,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"vace_context": vace_context,
|
||||
"vace_context_scale": vace_context_scale,
|
||||
"return_dict": False,
|
||||
}
|
||||
if do_true_cfg
|
||||
else None
|
||||
)
|
||||
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
)
|
||||
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
|
||||
pbar.update()
|
||||
latents = self.diffuse(
|
||||
latents=latents,
|
||||
timesteps=timesteps,
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
guidance_scale=guidance_scale,
|
||||
dtype=dtype,
|
||||
attention_kwargs=attention_kwargs,
|
||||
vace_context=vace_context,
|
||||
vace_context_scale=vace_context_scale,
|
||||
)
|
||||
|
||||
self._current_timestep = None
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import torch.nn.functional as F
|
||||
from diffusers.models.attention import FeedForward
|
||||
from diffusers.models.embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps
|
||||
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
||||
from diffusers.models.normalization import FP32LayerNorm
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
@@ -29,6 +28,8 @@ from vllm_omni.diffusion.distributed.sp_plan import (
|
||||
SequenceParallelOutput,
|
||||
)
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context
|
||||
from vllm_omni.diffusion.layers.adalayernorm import AdaLayerNorm
|
||||
from vllm_omni.diffusion.layers.norm import LayerNorm, RMSNorm
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -235,9 +236,9 @@ class WanImageEmbedding(nn.Module):
|
||||
def __init__(self, in_features: int, out_features: int, pos_embed_seq_len: int | None = None):
|
||||
super().__init__()
|
||||
|
||||
self.norm1 = FP32LayerNorm(in_features)
|
||||
self.norm1 = LayerNorm(in_features)
|
||||
self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
|
||||
self.norm2 = FP32LayerNorm(out_features)
|
||||
self.norm2 = LayerNorm(out_features)
|
||||
if pos_embed_seq_len is not None:
|
||||
self.pos_embed = nn.Parameter(torch.zeros(1, pos_embed_seq_len, in_features))
|
||||
else:
|
||||
@@ -377,8 +378,12 @@ class WanSelfAttention(nn.Module):
|
||||
self.tp_inner_dim = self.num_heads * head_dim
|
||||
|
||||
# QK normalization using vLLM's RMSNorm
|
||||
self.norm_q = DistributedRMSNorm(self.tp_inner_dim, eps=eps)
|
||||
self.norm_k = DistributedRMSNorm(self.tp_inner_dim, eps=eps)
|
||||
if get_tensor_model_parallel_world_size() > 1:
|
||||
self.norm_q = DistributedRMSNorm(self.tp_inner_dim, eps=eps)
|
||||
self.norm_k = DistributedRMSNorm(self.tp_inner_dim, eps=eps)
|
||||
else:
|
||||
self.norm_q = RMSNorm(self.tp_inner_dim, eps=eps)
|
||||
self.norm_k = RMSNorm(self.tp_inner_dim, eps=eps)
|
||||
|
||||
self.to_out = RowParallelLinear(
|
||||
self.inner_dim,
|
||||
@@ -497,8 +502,12 @@ class WanCrossAttention(nn.Module):
|
||||
self.tp_inner_dim = self.num_heads * head_dim
|
||||
|
||||
# QK normalization
|
||||
self.norm_q = DistributedRMSNorm(self.tp_inner_dim, eps=eps)
|
||||
self.norm_k = DistributedRMSNorm(self.tp_inner_dim, eps=eps)
|
||||
if get_tensor_model_parallel_world_size() > 1:
|
||||
self.norm_q = DistributedRMSNorm(self.tp_inner_dim, eps=eps)
|
||||
self.norm_k = DistributedRMSNorm(self.tp_inner_dim, eps=eps)
|
||||
else:
|
||||
self.norm_q = RMSNorm(self.tp_inner_dim, eps=eps)
|
||||
self.norm_k = RMSNorm(self.tp_inner_dim, eps=eps)
|
||||
|
||||
# Optional added KV projections for I2V (image embeddings)
|
||||
self.added_kv_proj_dim = added_kv_proj_dim
|
||||
@@ -517,7 +526,10 @@ class WanCrossAttention(nn.Module):
|
||||
gather_output=False,
|
||||
return_bias=False,
|
||||
)
|
||||
self.norm_added_k = DistributedRMSNorm(self.tp_inner_dim, eps=eps)
|
||||
if get_tensor_model_parallel_world_size() > 1:
|
||||
self.norm_added_k = DistributedRMSNorm(self.tp_inner_dim, eps=eps)
|
||||
else:
|
||||
self.norm_added_k = RMSNorm(self.tp_inner_dim, eps=eps)
|
||||
else:
|
||||
self.add_k_proj = None
|
||||
self.add_v_proj = None
|
||||
@@ -620,7 +632,7 @@ class WanTransformerBlock(nn.Module):
|
||||
head_dim = dim // num_heads
|
||||
|
||||
# 1. Self-attention
|
||||
self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
||||
self.norm1 = AdaLayerNorm(dim, elementwise_affine=False, eps=eps)
|
||||
self.attn1 = WanSelfAttention(
|
||||
dim=dim,
|
||||
num_heads=num_heads,
|
||||
@@ -636,11 +648,11 @@ class WanTransformerBlock(nn.Module):
|
||||
eps=eps,
|
||||
added_kv_proj_dim=added_kv_proj_dim,
|
||||
)
|
||||
self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
|
||||
self.norm2 = LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
|
||||
|
||||
# 3. Feed-forward
|
||||
self.ffn = WanFeedForward(dim=dim, inner_dim=ffn_dim, dim_out=dim)
|
||||
self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
||||
self.norm3 = AdaLayerNorm(dim, elementwise_affine=False, eps=eps)
|
||||
|
||||
# Scale-shift table for modulation
|
||||
self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
|
||||
@@ -656,7 +668,7 @@ class WanTransformerBlock(nn.Module):
|
||||
if temb.ndim == 4:
|
||||
# temb: batch_size, seq_len, 6, inner_dim (wan2.2 ti2v)
|
||||
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
||||
self.scale_shift_table.unsqueeze(0) + temb.float()
|
||||
self.scale_shift_table.unsqueeze(0) + temb
|
||||
).chunk(6, dim=2)
|
||||
shift_msa = shift_msa.squeeze(2)
|
||||
scale_msa = scale_msa.squeeze(2)
|
||||
@@ -667,25 +679,23 @@ class WanTransformerBlock(nn.Module):
|
||||
else:
|
||||
# temb: batch_size, 6, inner_dim (wan2.1/wan2.2 14B)
|
||||
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
||||
self.scale_shift_table + temb.float()
|
||||
self.scale_shift_table + temb
|
||||
).chunk(6, dim=1)
|
||||
|
||||
# 1. Self-attention
|
||||
norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
|
||||
norm_hidden_states = self.norm1(hidden_states, scale_msa, shift_msa).type_as(hidden_states)
|
||||
attn_output = self.attn1(norm_hidden_states, rotary_emb, hidden_states_mask)
|
||||
hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
|
||||
hidden_states = (hidden_states + attn_output * gate_msa).type_as(hidden_states)
|
||||
|
||||
# 2. Cross-attention
|
||||
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
|
||||
norm_hidden_states = self.norm2(hidden_states).type_as(hidden_states)
|
||||
attn_output = self.attn2(norm_hidden_states, encoder_hidden_states)
|
||||
hidden_states = hidden_states + attn_output
|
||||
|
||||
# 3. Feed-forward
|
||||
norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
|
||||
hidden_states
|
||||
)
|
||||
norm_hidden_states = self.norm3(hidden_states, c_scale_msa, c_shift_msa).type_as(hidden_states)
|
||||
ff_output = self.ffn(norm_hidden_states)
|
||||
hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
|
||||
hidden_states = (hidden_states + ff_output * c_gate_msa).type_as(hidden_states)
|
||||
|
||||
return hidden_states
|
||||
|
||||
@@ -854,7 +864,7 @@ class WanTransformer3DModel(nn.Module):
|
||||
)
|
||||
|
||||
# 4. Output norm & projection
|
||||
self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
|
||||
self.norm_out = AdaLayerNorm(inner_dim, elementwise_affine=False, eps=eps)
|
||||
self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
|
||||
|
||||
# SP helper modules
|
||||
@@ -942,7 +952,7 @@ class WanTransformer3DModel(nn.Module):
|
||||
shift = shift.unsqueeze(1)
|
||||
scale = scale.unsqueeze(1)
|
||||
|
||||
hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
|
||||
hidden_states = self.norm_out(hidden_states, scale, shift).type_as(hidden_states)
|
||||
hidden_states = self.proj_out(hidden_states)
|
||||
|
||||
hidden_states = hidden_states.reshape(
|
||||
|
||||
@@ -239,7 +239,7 @@ class WanVACETransformer3DModel(WanTransformer3DModel):
|
||||
shift = shift.unsqueeze(1)
|
||||
scale = scale.unsqueeze(1)
|
||||
|
||||
hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
|
||||
hidden_states = self.norm_out(hidden_states, scale, shift).type_as(hidden_states)
|
||||
hidden_states = self.proj_out(hidden_states)
|
||||
|
||||
hidden_states = hidden_states.reshape(
|
||||
|
||||
@@ -214,12 +214,14 @@ class TimestepEmbedder(nn.Module):
|
||||
super().__init__()
|
||||
if mid_size is None:
|
||||
mid_size = out_size
|
||||
# Time embedding MLP is kept full precision (quant_config=None) —
|
||||
# small layers that feed adaLN; precision-sensitive (see #2728).
|
||||
self.mlp = nn.Sequential(
|
||||
ReplicatedLinear(
|
||||
frequency_embedding_size,
|
||||
mid_size,
|
||||
bias=True,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
return_bias=False,
|
||||
),
|
||||
nn.SiLU(),
|
||||
@@ -227,7 +229,7 @@ class TimestepEmbedder(nn.Module):
|
||||
mid_size,
|
||||
out_size,
|
||||
bias=True,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
return_bias=False,
|
||||
),
|
||||
)
|
||||
@@ -426,9 +428,16 @@ class ZImageTransformerBlock(nn.Module):
|
||||
|
||||
self.modulation = modulation
|
||||
if modulation:
|
||||
# Modulation linear is kept at full precision (quant_config=None)
|
||||
# — it produces scale/gate values that are precision-sensitive
|
||||
# (see #2728, mirrors OmniGen2 fix).
|
||||
self.adaLN_modulation = nn.Sequential(
|
||||
ReplicatedLinear(
|
||||
min(dim, ADALN_EMBED_DIM), 4 * dim, bias=True, return_bias=False, quant_config=quant_config
|
||||
min(dim, ADALN_EMBED_DIM),
|
||||
4 * dim,
|
||||
bias=True,
|
||||
quant_config=None,
|
||||
return_bias=False,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -485,14 +494,24 @@ class FinalLayer(nn.Module):
|
||||
def __init__(self, hidden_size, out_channels, quant_config: "QuantizationConfig | None" = None):
|
||||
super().__init__()
|
||||
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
||||
# Final output projection and its modulation are precision-sensitive
|
||||
# (produce the output latent); keep at full precision (see #2728).
|
||||
self.linear = ReplicatedLinear(
|
||||
hidden_size, out_channels, bias=True, quant_config=quant_config, return_bias=False
|
||||
hidden_size,
|
||||
out_channels,
|
||||
bias=True,
|
||||
quant_config=None,
|
||||
return_bias=False,
|
||||
)
|
||||
|
||||
self.adaLN_modulation = nn.Sequential(
|
||||
nn.SiLU(),
|
||||
ReplicatedLinear(
|
||||
min(hidden_size, ADALN_EMBED_DIM), hidden_size, bias=True, quant_config=quant_config, return_bias=False
|
||||
min(hidden_size, ADALN_EMBED_DIM),
|
||||
hidden_size,
|
||||
bias=True,
|
||||
quant_config=None,
|
||||
return_bias=False,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -673,11 +692,13 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
all_x_embedder = {}
|
||||
all_final_layer = {}
|
||||
for patch_idx, (patch_size, f_patch_size) in enumerate(zip(all_patch_size, all_f_patch_size)):
|
||||
# x_embedder (patch embed) is a small precision-sensitive entry
|
||||
# layer; keep full precision (see #2728).
|
||||
x_embedder = ReplicatedLinear(
|
||||
f_patch_size * patch_size * patch_size * in_channels,
|
||||
dim,
|
||||
bias=True,
|
||||
quant_config=quant_config,
|
||||
quant_config=None,
|
||||
return_bias=False,
|
||||
)
|
||||
all_x_embedder[f"{patch_size}-{f_patch_size}"] = x_embedder
|
||||
@@ -720,9 +741,17 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
]
|
||||
)
|
||||
self.t_embedder = TimestepEmbedder(min(dim, ADALN_EMBED_DIM), mid_size=1024, quant_config=quant_config)
|
||||
# Caption embedder maps text features -> hidden; keep full precision
|
||||
# (see #2728).
|
||||
self.cap_embedder = nn.Sequential(
|
||||
RMSNorm(cap_feat_dim, eps=norm_eps),
|
||||
ReplicatedLinear(cap_feat_dim, dim, bias=True, return_bias=False, quant_config=quant_config),
|
||||
ReplicatedLinear(
|
||||
cap_feat_dim,
|
||||
dim,
|
||||
bias=True,
|
||||
quant_config=None,
|
||||
return_bias=False,
|
||||
),
|
||||
)
|
||||
|
||||
self.x_pad_token = nn.Parameter(torch.empty((1, dim)))
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from __future__ import annotations
|
||||
|
||||
from itertools import chain
|
||||
from typing import Any
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Diffusion post-processing helpers."""
|
||||
|
||||
from vllm_omni.diffusion.postprocess.rife_interpolator import (
|
||||
FrameInterpolator,
|
||||
interpolate_video_tensor,
|
||||
)
|
||||
|
||||
__all__ = ["FrameInterpolator", "interpolate_video_tensor"]
|
||||
@@ -0,0 +1,443 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
RIFE 4.22.lite frame interpolation for vLLM-Omni video generation.
|
||||
|
||||
RIFE model code is vendored and adapted from:
|
||||
- https://github.com/hzwer/ECCV2022-RIFE (MIT License)
|
||||
- https://github.com/hzwer/Practical-RIFE (MIT License)
|
||||
Copyright (c) 2021 Zhewei Huang
|
||||
|
||||
The FrameInterpolator wrapper and vLLM-Omni integration code are original work.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_DEFAULT_RIFE_HF_REPO = "elfgum/RIFE-4.22.lite"
|
||||
_MODEL_CACHE: dict[tuple[str, str], Model] = {}
|
||||
_MODEL_CACHE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def warp(ten_input: torch.Tensor, ten_flow: torch.Tensor) -> torch.Tensor:
|
||||
"""Warp input tensor by optical flow using grid_sample."""
|
||||
ten_horizontal = (
|
||||
torch.linspace(-1.0, 1.0, ten_flow.shape[3], device=ten_flow.device)
|
||||
.view(1, 1, 1, ten_flow.shape[3])
|
||||
.expand(ten_flow.shape[0], -1, ten_flow.shape[2], -1)
|
||||
)
|
||||
ten_vertical = (
|
||||
torch.linspace(-1.0, 1.0, ten_flow.shape[2], device=ten_flow.device)
|
||||
.view(1, 1, ten_flow.shape[2], 1)
|
||||
.expand(ten_flow.shape[0], -1, -1, ten_flow.shape[3])
|
||||
)
|
||||
ten_grid = torch.cat([ten_horizontal, ten_vertical], dim=1)
|
||||
|
||||
ten_flow = torch.cat(
|
||||
[
|
||||
ten_flow[:, 0:1, :, :] / ((ten_input.shape[3] - 1.0) / 2.0),
|
||||
ten_flow[:, 1:2, :, :] / ((ten_input.shape[2] - 1.0) / 2.0),
|
||||
],
|
||||
dim=1,
|
||||
)
|
||||
grid = (ten_grid + ten_flow).permute(0, 2, 3, 1)
|
||||
return F.grid_sample(
|
||||
input=ten_input,
|
||||
grid=grid,
|
||||
mode="bilinear",
|
||||
padding_mode="border",
|
||||
align_corners=True,
|
||||
)
|
||||
|
||||
|
||||
def _conv(
|
||||
in_planes: int,
|
||||
out_planes: int,
|
||||
kernel_size: int = 3,
|
||||
stride: int = 1,
|
||||
padding: int = 1,
|
||||
dilation: int = 1,
|
||||
) -> nn.Sequential:
|
||||
return nn.Sequential(
|
||||
nn.Conv2d(
|
||||
in_planes,
|
||||
out_planes,
|
||||
kernel_size=kernel_size,
|
||||
stride=stride,
|
||||
padding=padding,
|
||||
dilation=dilation,
|
||||
bias=True,
|
||||
),
|
||||
nn.LeakyReLU(0.2, True),
|
||||
)
|
||||
|
||||
|
||||
class ResConv(nn.Module):
|
||||
"""Residual convolution block with learnable beta scaling."""
|
||||
|
||||
def __init__(self, c: int, dilation: int = 1):
|
||||
super().__init__()
|
||||
self.conv = nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1)
|
||||
self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True)
|
||||
self.relu = nn.LeakyReLU(0.2, True)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.relu(self.conv(x) * self.beta + x)
|
||||
|
||||
|
||||
class IFBlock(nn.Module):
|
||||
"""Single-scale optical flow, mask, and feature block."""
|
||||
|
||||
def __init__(self, in_planes: int, c: int = 64):
|
||||
super().__init__()
|
||||
self.conv0 = nn.Sequential(
|
||||
_conv(in_planes, c // 2, 3, 2, 1),
|
||||
_conv(c // 2, c, 3, 2, 1),
|
||||
)
|
||||
self.convblock = nn.Sequential(
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
)
|
||||
self.lastconv = nn.Sequential(
|
||||
nn.ConvTranspose2d(c, 4 * 13, 4, 2, 1),
|
||||
nn.PixelShuffle(2),
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
flow: torch.Tensor | None = None,
|
||||
scale: float = 1.0,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
x = F.interpolate(x, scale_factor=1.0 / scale, mode="bilinear", align_corners=False)
|
||||
if flow is not None:
|
||||
flow = (
|
||||
F.interpolate(
|
||||
flow,
|
||||
scale_factor=1.0 / scale,
|
||||
mode="bilinear",
|
||||
align_corners=False,
|
||||
)
|
||||
* 1.0
|
||||
/ scale
|
||||
)
|
||||
x = torch.cat((x, flow), 1)
|
||||
feat = self.conv0(x)
|
||||
feat = self.convblock(feat)
|
||||
tmp = self.lastconv(feat)
|
||||
tmp = F.interpolate(tmp, scale_factor=scale, mode="bilinear", align_corners=False)
|
||||
flow = tmp[:, :4] * scale
|
||||
mask = tmp[:, 4:5]
|
||||
feat = tmp[:, 5:]
|
||||
return flow, mask, feat
|
||||
|
||||
|
||||
class Head(nn.Module):
|
||||
"""Feature encoder producing four-channel features at full resolution."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.cnn0 = nn.Conv2d(3, 16, 3, 2, 1)
|
||||
self.cnn1 = nn.Conv2d(16, 16, 3, 1, 1)
|
||||
self.cnn2 = nn.Conv2d(16, 16, 3, 1, 1)
|
||||
self.cnn3 = nn.ConvTranspose2d(16, 4, 4, 2, 1)
|
||||
self.relu = nn.LeakyReLU(0.2, True)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
x0 = self.cnn0(x)
|
||||
x = self.relu(x0)
|
||||
x1 = self.cnn1(x)
|
||||
x = self.relu(x1)
|
||||
x2 = self.cnn2(x)
|
||||
x = self.relu(x2)
|
||||
x3 = self.cnn3(x)
|
||||
return x3
|
||||
|
||||
|
||||
class IFNet(nn.Module):
|
||||
"""Four-scale IFNet optical flow network."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.block0 = IFBlock(7 + 8, c=192)
|
||||
self.block1 = IFBlock(8 + 4 + 8 + 8, c=128)
|
||||
self.block2 = IFBlock(8 + 4 + 8 + 8, c=64)
|
||||
self.block3 = IFBlock(8 + 4 + 8 + 8, c=32)
|
||||
self.encode = Head()
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
timestep: float = 0.5,
|
||||
scale_list: list[float] | None = None,
|
||||
) -> tuple[list[torch.Tensor], torch.Tensor, list[tuple[torch.Tensor, torch.Tensor] | torch.Tensor]]:
|
||||
if scale_list is None:
|
||||
scale_list = [8, 4, 2, 1]
|
||||
|
||||
channel = x.shape[1] // 2
|
||||
img0 = x[:, :channel]
|
||||
img1 = x[:, channel:]
|
||||
|
||||
if not torch.is_tensor(timestep):
|
||||
timestep = (x[:, :1].clone() * 0 + 1) * timestep
|
||||
else:
|
||||
timestep = timestep.repeat(1, 1, img0.shape[2], img0.shape[3])
|
||||
|
||||
f0 = self.encode(img0[:, :3])
|
||||
f1 = self.encode(img1[:, :3])
|
||||
|
||||
flow_list: list[torch.Tensor] = []
|
||||
merged: list[tuple[torch.Tensor, torch.Tensor] | torch.Tensor] = []
|
||||
mask_list: list[torch.Tensor] = []
|
||||
warped_img0 = img0
|
||||
warped_img1 = img1
|
||||
flow = None
|
||||
mask = None
|
||||
|
||||
for i, block in enumerate([self.block0, self.block1, self.block2, self.block3]):
|
||||
if flow is None:
|
||||
flow, mask, feat = block(
|
||||
torch.cat((img0[:, :3], img1[:, :3], f0, f1, timestep), 1),
|
||||
None,
|
||||
scale=scale_list[i],
|
||||
)
|
||||
else:
|
||||
wf0 = warp(f0, flow[:, :2])
|
||||
wf1 = warp(f1, flow[:, 2:4])
|
||||
fd, m0, feat = block(
|
||||
torch.cat(
|
||||
(
|
||||
warped_img0[:, :3],
|
||||
warped_img1[:, :3],
|
||||
wf0,
|
||||
wf1,
|
||||
timestep,
|
||||
mask,
|
||||
feat,
|
||||
),
|
||||
1,
|
||||
),
|
||||
flow,
|
||||
scale=scale_list[i],
|
||||
)
|
||||
mask = m0
|
||||
flow = flow + fd
|
||||
|
||||
mask_list.append(mask)
|
||||
flow_list.append(flow)
|
||||
warped_img0 = warp(img0, flow[:, :2])
|
||||
warped_img1 = warp(img1, flow[:, 2:4])
|
||||
merged.append((warped_img0, warped_img1))
|
||||
|
||||
mask = torch.sigmoid(mask)
|
||||
merged[3] = warped_img0 * mask + warped_img1 * (1 - mask)
|
||||
return flow_list, mask_list[3], merged
|
||||
|
||||
|
||||
class Model:
|
||||
"""Wraps IFNet and exposes RIFE-compatible load/inference helpers."""
|
||||
|
||||
def __init__(self):
|
||||
self.flownet = IFNet()
|
||||
|
||||
def eval(self) -> Model:
|
||||
self.flownet.eval()
|
||||
return self
|
||||
|
||||
def device(self) -> torch.device:
|
||||
return next(self.flownet.parameters()).device
|
||||
|
||||
def load_model(self, path: str) -> None:
|
||||
flownet_path = os.path.join(path, "flownet.pkl")
|
||||
if not os.path.isfile(flownet_path):
|
||||
raise FileNotFoundError(
|
||||
f"RIFE weight file not found: {flownet_path}. Expected layout: <model_path>/flownet.pkl"
|
||||
)
|
||||
|
||||
state = torch.load(flownet_path, map_location="cpu", weights_only=False)
|
||||
state = {k.removeprefix("module."): v for k, v in state.items()}
|
||||
self.flownet.load_state_dict(state, strict=False)
|
||||
logger.info("Loaded RIFE weights from %s", flownet_path)
|
||||
|
||||
def inference(
|
||||
self,
|
||||
img0: torch.Tensor,
|
||||
img1: torch.Tensor,
|
||||
scale: float = 1.0,
|
||||
timestep: float = 0.5,
|
||||
) -> torch.Tensor:
|
||||
_n, _c, h, w = img0.shape
|
||||
ph = ((h - 1) // 32 + 1) * 32
|
||||
pw = ((w - 1) // 32 + 1) * 32
|
||||
pad = (0, pw - w, 0, ph - h)
|
||||
img0 = F.pad(img0, pad)
|
||||
img1 = F.pad(img1, pad)
|
||||
|
||||
imgs = torch.cat((img0, img1), 1)
|
||||
scale_list = [8 / scale, 4 / scale, 2 / scale, 1 / scale]
|
||||
with torch.no_grad():
|
||||
_flow_list, _mask, merged = self.flownet(
|
||||
imgs,
|
||||
timestep=timestep,
|
||||
scale_list=scale_list,
|
||||
)
|
||||
return merged[3][:, :, :h, :w]
|
||||
|
||||
|
||||
def _resolve_rife_model_path(model_path: str | None) -> str:
|
||||
model_path = model_path or _DEFAULT_RIFE_HF_REPO
|
||||
if os.path.isdir(model_path):
|
||||
return model_path
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import (
|
||||
download_weights_from_hf_specific,
|
||||
)
|
||||
|
||||
return download_weights_from_hf_specific(
|
||||
model_path,
|
||||
cache_dir=None,
|
||||
allow_patterns=["flownet.pkl"],
|
||||
require_all=True,
|
||||
)
|
||||
|
||||
|
||||
def _select_torch_device() -> torch.device:
|
||||
try:
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
return current_omni_platform.get_torch_device()
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to resolve current vLLM-Omni torch device: %s", exc)
|
||||
|
||||
if torch.cuda.is_available():
|
||||
return torch.device("cuda")
|
||||
return torch.device("cpu")
|
||||
|
||||
|
||||
def _normalize_video_tensor_layout(video: torch.Tensor) -> tuple[torch.Tensor, Any]:
|
||||
if video.ndim == 5:
|
||||
if video.shape[1] in (3, 4):
|
||||
return video, lambda out: out
|
||||
if video.shape[2] in (3, 4):
|
||||
return video.permute(0, 2, 1, 3, 4), lambda out: out.permute(0, 2, 1, 3, 4)
|
||||
elif video.ndim == 4:
|
||||
if video.shape[0] in (3, 4):
|
||||
return video.unsqueeze(0), lambda out: out.squeeze(0)
|
||||
if video.shape[1] in (3, 4):
|
||||
return video.permute(1, 0, 2, 3).unsqueeze(0), lambda out: out.squeeze(0).permute(1, 0, 2, 3)
|
||||
raise ValueError(f"Unsupported video tensor shape for interpolation: {tuple(video.shape)}")
|
||||
|
||||
|
||||
def _normalize_video_tensor_range(video: torch.Tensor) -> tuple[torch.Tensor, Any]:
|
||||
original_dtype = video.dtype
|
||||
video = video.detach()
|
||||
if video.is_floating_point():
|
||||
video = video.to(torch.float32)
|
||||
if torch.amin(video) < 0.0 or torch.amax(video) > 1.0:
|
||||
return video.clamp(-1.0, 1.0) * 0.5 + 0.5, lambda out: (out * 2.0 - 1.0).to(original_dtype)
|
||||
return video.clamp(0.0, 1.0), lambda out: out.to(original_dtype)
|
||||
return video.to(torch.float32) / 255.0, lambda out: (out * 255.0).round().clamp(0, 255).to(original_dtype)
|
||||
|
||||
|
||||
class FrameInterpolator:
|
||||
"""Lazy-loaded RIFE 4.22.lite frame interpolator."""
|
||||
|
||||
def __init__(self, model_path: str | None = None):
|
||||
self._model_path = model_path
|
||||
self._resolved_path: str | None = None
|
||||
|
||||
def _ensure_model_loaded(self, preferred_device: torch.device | None = None) -> Model:
|
||||
resolved_path = _resolve_rife_model_path(self._model_path)
|
||||
self._resolved_path = resolved_path
|
||||
device = preferred_device or _select_torch_device()
|
||||
cache_key = (resolved_path, str(device))
|
||||
|
||||
with _MODEL_CACHE_LOCK:
|
||||
if cache_key in _MODEL_CACHE:
|
||||
return _MODEL_CACHE[cache_key]
|
||||
|
||||
model = Model()
|
||||
model.load_model(resolved_path)
|
||||
model.eval()
|
||||
model.flownet = model.flownet.to(device)
|
||||
_MODEL_CACHE[cache_key] = model
|
||||
logger.info("RIFE model loaded on device: %s", device)
|
||||
return model
|
||||
|
||||
def _make_inference(
|
||||
self,
|
||||
model: Model,
|
||||
img0: torch.Tensor,
|
||||
img1: torch.Tensor,
|
||||
n: int,
|
||||
scale: float,
|
||||
) -> list[torch.Tensor]:
|
||||
if n == 1:
|
||||
return [model.inference(img0, img1, scale=scale)]
|
||||
mid = model.inference(img0, img1, scale=scale)
|
||||
return (
|
||||
self._make_inference(model, img0, mid, n // 2, scale)
|
||||
+ [mid]
|
||||
+ self._make_inference(model, mid, img1, n // 2, scale)
|
||||
)
|
||||
|
||||
def interpolate_tensor(
|
||||
self,
|
||||
video: torch.Tensor,
|
||||
exp: int = 1,
|
||||
scale: float = 1.0,
|
||||
) -> tuple[torch.Tensor, int]:
|
||||
if exp < 1:
|
||||
raise ValueError(f"frame interpolation exp must be >= 1, got {exp}")
|
||||
if scale <= 0:
|
||||
raise ValueError(f"frame interpolation scale must be > 0, got {scale}")
|
||||
|
||||
video, restore_layout = _normalize_video_tensor_layout(video)
|
||||
if video.shape[2] < 2:
|
||||
return restore_layout(video), 1
|
||||
|
||||
video, restore_range = _normalize_video_tensor_range(video)
|
||||
# A CPU tensor may be transport/offload state rather than an execution
|
||||
# choice, so only trust it when it is already on an accelerator.
|
||||
preferred_device = video.device
|
||||
if preferred_device.type == "cpu":
|
||||
preferred_device = _select_torch_device()
|
||||
model = self._ensure_model_loaded(preferred_device=preferred_device)
|
||||
video = video.to(model.device())
|
||||
intermediates_per_pair = 2**exp // 2
|
||||
|
||||
result_frames: list[torch.Tensor] = []
|
||||
for idx in range(video.shape[2] - 1):
|
||||
img0 = video[:, :, idx, :, :]
|
||||
img1 = video[:, :, idx + 1, :, :]
|
||||
result_frames.append(img0)
|
||||
result_frames.extend(self._make_inference(model, img0, img1, intermediates_per_pair, scale))
|
||||
result_frames.append(video[:, :, -1, :, :])
|
||||
result = torch.stack(result_frames, dim=2)
|
||||
return restore_layout(restore_range(result)), 2**exp
|
||||
|
||||
|
||||
def interpolate_video_tensor(
|
||||
video: torch.Tensor,
|
||||
exp: int = 1,
|
||||
scale: float = 1.0,
|
||||
model_path: str | None = None,
|
||||
) -> tuple[torch.Tensor, int]:
|
||||
"""Interpolate a video tensor and return the FPS multiplier."""
|
||||
interpolator = FrameInterpolator(model_path=model_path)
|
||||
return interpolator.interpolate_tensor(video, exp=exp, scale=scale)
|
||||
@@ -83,6 +83,16 @@ _DIFFUSION_MODELS = {
|
||||
"pipeline_ltx2_image2video",
|
||||
"LTX2ImageToVideoTwoStagesPipeline",
|
||||
),
|
||||
"LTX2T2VDMD2Pipeline": (
|
||||
"ltx2",
|
||||
"pipeline_ltx2",
|
||||
"LTX2T2VDMD2Pipeline",
|
||||
),
|
||||
"LTX2I2VDMD2Pipeline": (
|
||||
"ltx2",
|
||||
"pipeline_ltx2_image2video",
|
||||
"LTX2I2VDMD2Pipeline",
|
||||
),
|
||||
"StableAudioPipeline": (
|
||||
"stable_audio",
|
||||
"pipeline_stable_audio",
|
||||
@@ -93,6 +103,16 @@ _DIFFUSION_MODELS = {
|
||||
"pipeline_wan2_2_i2v",
|
||||
"Wan22I2VPipeline",
|
||||
),
|
||||
"WanT2VDMD2Pipeline": (
|
||||
"wan2_2",
|
||||
"pipeline_wan2_2",
|
||||
"WanT2VDMD2Pipeline",
|
||||
),
|
||||
"WanI2VDMD2Pipeline": (
|
||||
"wan2_2",
|
||||
"pipeline_wan2_2_i2v",
|
||||
"WanI2VDMD2Pipeline",
|
||||
),
|
||||
"LongCatImagePipeline": (
|
||||
"longcat_image",
|
||||
"pipeline_longcat_image",
|
||||
@@ -119,8 +139,8 @@ _DIFFUSION_MODELS = {
|
||||
"FluxKontextPipeline",
|
||||
),
|
||||
"HunyuanImage3ForCausalMM": (
|
||||
"hunyuan_image_3",
|
||||
"pipeline_hunyuan_image_3",
|
||||
"hunyuan_image3",
|
||||
"pipeline_hunyuan_image3",
|
||||
"HunyuanImage3Pipeline",
|
||||
),
|
||||
"Flux2KleinPipeline": (
|
||||
@@ -357,8 +377,12 @@ _DIFFUSION_POST_PROCESS_FUNCS = {
|
||||
"LTX2TwoStagesPipeline": "get_ltx2_post_process_func",
|
||||
"LTX2ImageToVideoPipeline": "get_ltx2_post_process_func",
|
||||
"LTX2ImageToVideoTwoStagesPipeline": "get_ltx2_post_process_func",
|
||||
"LTX2T2VDMD2Pipeline": "get_ltx2_post_process_func",
|
||||
"LTX2I2VDMD2Pipeline": "get_ltx2_post_process_func",
|
||||
"StableAudioPipeline": "get_stable_audio_post_process_func",
|
||||
"WanImageToVideoPipeline": "get_wan22_i2v_post_process_func",
|
||||
"WanT2VDMD2Pipeline": "get_wan22_post_process_func",
|
||||
"WanI2VDMD2Pipeline": "get_wan22_i2v_post_process_func",
|
||||
"LongCatImagePipeline": "get_longcat_image_post_process_func",
|
||||
"BagelPipeline": "get_bagel_post_process_func",
|
||||
"LongCatImageEditPipeline": "get_longcat_image_post_process_func",
|
||||
@@ -375,6 +399,7 @@ _DIFFUSION_POST_PROCESS_FUNCS = {
|
||||
"HunyuanVideo15ImageToVideoPipeline": "get_hunyuan_video_15_i2v_post_process_func",
|
||||
"MagiHumanPipeline": "get_magi_human_post_process_func",
|
||||
"OmniVoicePipeline": "get_omnivoice_post_process_func",
|
||||
"DreamIDOmniPipeline": "get_dreamid_omni_post_process_func",
|
||||
}
|
||||
|
||||
_DIFFUSION_PRE_PROCESS_FUNCS = {
|
||||
@@ -389,6 +414,8 @@ _DIFFUSION_PRE_PROCESS_FUNCS = {
|
||||
"WanPipeline": "get_wan22_pre_process_func",
|
||||
"WanVACEPipeline": "get_wan22_vace_pre_process_func",
|
||||
"WanImageToVideoPipeline": "get_wan22_i2v_pre_process_func",
|
||||
"WanT2VDMD2Pipeline": "get_wan22_pre_process_func",
|
||||
"WanI2VDMD2Pipeline": "get_wan22_i2v_pre_process_func",
|
||||
"OmniGen2Pipeline": "get_omnigen2_pre_process_func",
|
||||
"HeliosPipeline": "get_helios_pre_process_func",
|
||||
"HeliosPyramidPipeline": "get_helios_pre_process_func",
|
||||
|
||||
@@ -8,15 +8,20 @@ from any stage client.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import multiprocessing.connection
|
||||
import time
|
||||
import uuid
|
||||
import weakref
|
||||
from dataclasses import fields, is_dataclass
|
||||
from threading import Thread
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import zmq
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.engine.exceptions import EngineDeadError
|
||||
|
||||
from vllm_omni.diffusion.stage_diffusion_proc import (
|
||||
StageDiffusionProc,
|
||||
complete_diffusion_handshake,
|
||||
spawn_diffusion_proc,
|
||||
)
|
||||
@@ -34,6 +39,24 @@ if TYPE_CHECKING:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def create_diffusion_client(
|
||||
model: str,
|
||||
od_config: OmniDiffusionConfig,
|
||||
metadata: StageMetadata,
|
||||
stage_init_timeout: int,
|
||||
batch_size: int = 1,
|
||||
use_inline: bool = False,
|
||||
) -> Any:
|
||||
"""Factory to create either an inline or out-of-process diffusion client."""
|
||||
if use_inline:
|
||||
from vllm_omni.diffusion.inline_stage_diffusion_client import InlineStageDiffusionClient
|
||||
|
||||
return InlineStageDiffusionClient(model, od_config, metadata, batch_size=batch_size)
|
||||
return StageDiffusionClient(
|
||||
model, od_config, metadata, stage_init_timeout=stage_init_timeout, batch_size=batch_size
|
||||
)
|
||||
|
||||
|
||||
class StageDiffusionClient:
|
||||
"""Communicates with StageDiffusionProc via ZMQ for use inside the Orchestrator.
|
||||
|
||||
@@ -111,6 +134,12 @@ class StageDiffusionClient:
|
||||
self._pending_rpcs: set[str] = set()
|
||||
self._tasks: dict[str, asyncio.Task] = {}
|
||||
self._shutting_down = False
|
||||
self._engine_dead: bool = False
|
||||
|
||||
# Background thread to detect silent process death (SIGKILL, segfault)
|
||||
# where the subprocess cannot send the ZMQ death sentinel.
|
||||
# Mirrors MPClient.start_engine_core_monitor() in vLLM.
|
||||
self._start_proc_monitor()
|
||||
|
||||
logger.info(
|
||||
"[StageDiffusionClient] Stage-%s initialized (owns_process=%s, batch_size=%d)",
|
||||
@@ -119,6 +148,37 @@ class StageDiffusionClient:
|
||||
batch_size,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Process monitor (mirrors vLLM's MPClient.start_engine_core_monitor)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _start_proc_monitor(self) -> None:
|
||||
"""Start a daemon thread that watches the subprocess sentinel.
|
||||
|
||||
When the subprocess dies without sending the ZMQ death sentinel
|
||||
(e.g. SIGKILL, segfault), this thread sets ``_engine_dead`` so
|
||||
subsequent calls raise ``EngineDeadError``.
|
||||
"""
|
||||
proc = self._proc
|
||||
self_ref = weakref.ref(self)
|
||||
|
||||
def _monitor() -> None:
|
||||
try:
|
||||
multiprocessing.connection.wait([proc.sentinel])
|
||||
except Exception:
|
||||
return
|
||||
client = self_ref()
|
||||
if client is None or client._shutting_down or client._engine_dead:
|
||||
return
|
||||
client._engine_dead = True
|
||||
logger.error(
|
||||
"[StageDiffusionClient] Stage-%s StageDiffusionProc died unexpectedly (exit code %s).",
|
||||
client.stage_id,
|
||||
proc.exitcode,
|
||||
)
|
||||
|
||||
Thread(target=_monitor, daemon=True, name="DiffusionProcMonitor").start()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Internal helpers
|
||||
# ------------------------------------------------------------------
|
||||
@@ -131,6 +191,15 @@ class StageDiffusionClient:
|
||||
except zmq.Again:
|
||||
break
|
||||
|
||||
# Check for the death sentinel (raw bytes, not msgpack-encoded).
|
||||
if raw == StageDiffusionProc.DIFFUSION_PROC_DEAD:
|
||||
self._engine_dead = True
|
||||
logger.error(
|
||||
"[StageDiffusionClient] Stage-%s received DIFFUSION_PROC_DEAD sentinel from subprocess.",
|
||||
self.stage_id,
|
||||
)
|
||||
break
|
||||
|
||||
msg = self._decoder.decode(raw)
|
||||
msg_type = msg.get("type")
|
||||
|
||||
@@ -154,6 +223,10 @@ class StageDiffusionClient:
|
||||
"error": True,
|
||||
"reason": error_msg,
|
||||
}
|
||||
# Route request errors as error outputs so the Orchestrator
|
||||
# sees the request complete (instead of hanging forever).
|
||||
if req_id is not None:
|
||||
self._output_queue.put_nowait(OmniRequestOutput.from_error(req_id, error_msg))
|
||||
|
||||
# Fields that are subprocess-local and cannot be serialized across
|
||||
# process boundaries. They are recreated in the subprocess with
|
||||
@@ -217,6 +290,8 @@ class StageDiffusionClient:
|
||||
sampling_params: OmniDiffusionSamplingParams,
|
||||
kv_sender_info: dict[int, dict[str, Any]] | None = None,
|
||||
) -> None:
|
||||
if self._engine_dead:
|
||||
raise EngineDeadError()
|
||||
self._request_socket.send(
|
||||
self._encoder.encode(
|
||||
{
|
||||
@@ -244,6 +319,8 @@ class StageDiffusionClient:
|
||||
and the combined result is placed on the output queue with a single
|
||||
*request_id*.
|
||||
"""
|
||||
if self._engine_dead:
|
||||
raise EngineDeadError()
|
||||
task = asyncio.create_task(
|
||||
self._run_batch(
|
||||
request_id,
|
||||
@@ -281,6 +358,7 @@ class StageDiffusionClient:
|
||||
request_id,
|
||||
e,
|
||||
)
|
||||
await self._output_queue.put(OmniRequestOutput.from_error(request_id, str(e)))
|
||||
finally:
|
||||
self._tasks.pop(request_id, None)
|
||||
|
||||
@@ -289,7 +367,10 @@ class StageDiffusionClient:
|
||||
try:
|
||||
return self._output_queue.get_nowait()
|
||||
except asyncio.QueueEmpty:
|
||||
if self._engine_dead:
|
||||
raise EngineDeadError()
|
||||
if not self._shutting_down and self._owns_process and self._proc is not None and not self._proc.is_alive():
|
||||
self._engine_dead = True
|
||||
exitcode = self._proc.exitcode
|
||||
# One final drain – the last ZMQ frame may have arrived
|
||||
# between the first drain and the is_alive() check.
|
||||
@@ -303,7 +384,7 @@ class StageDiffusionClient:
|
||||
logger.warning("StageDiffusionProc was killed by signal %d; treating as external shutdown.", sig)
|
||||
self._shutting_down = True
|
||||
return None
|
||||
raise RuntimeError(f"StageDiffusionProc died unexpectedly (exit code {exitcode})")
|
||||
raise EngineDeadError(f"StageDiffusionProc died unexpectedly (exit code {exitcode})")
|
||||
return None
|
||||
|
||||
async def abort_requests_async(self, request_ids: list[str]) -> None:
|
||||
@@ -324,6 +405,9 @@ class StageDiffusionClient:
|
||||
kwargs: dict[str, Any] | None = None,
|
||||
) -> Any:
|
||||
"""Forward control RPCs to the diffusion subprocess."""
|
||||
if self._engine_dead:
|
||||
raise EngineDeadError()
|
||||
|
||||
# Inject a default profile_prefix that includes stage_id when profiling.
|
||||
if method == "profile":
|
||||
args_list = list(args)
|
||||
@@ -361,8 +445,9 @@ class StageDiffusionClient:
|
||||
self._drain_responses()
|
||||
if rpc_id in self._rpc_results:
|
||||
return self._rpc_results.pop(rpc_id)
|
||||
if self._owns_process and self._proc is not None and not self._proc.is_alive():
|
||||
raise RuntimeError(
|
||||
if self._engine_dead or (self._owns_process and self._proc is not None and not self._proc.is_alive()):
|
||||
self._engine_dead = True
|
||||
raise EngineDeadError(
|
||||
f"StageDiffusionProc died while waiting for "
|
||||
f"collective_rpc '{method}' (exit code {self._proc.exitcode})"
|
||||
)
|
||||
@@ -372,6 +457,19 @@ class StageDiffusionClient:
|
||||
finally:
|
||||
self._pending_rpcs.discard(rpc_id)
|
||||
|
||||
def check_health(self) -> None:
|
||||
"""Raise ``EngineDeadError`` if the diffusion engine is dead.
|
||||
|
||||
Mirrors the ``check_health`` protocol on vLLM's ``EngineClient``.
|
||||
"""
|
||||
if self._engine_dead:
|
||||
raise EngineDeadError(f"Stage-{self.stage_id} diffusion subprocess is dead")
|
||||
if self._proc is not None and not self._proc.is_alive():
|
||||
self._engine_dead = True
|
||||
raise EngineDeadError(
|
||||
f"Stage-{self.stage_id} diffusion subprocess is not alive (exit code: {self._proc.exitcode})."
|
||||
)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self._shutting_down = True
|
||||
try:
|
||||
|
||||
@@ -19,12 +19,11 @@ import zmq
|
||||
import zmq.asyncio
|
||||
from PIL import Image
|
||||
from vllm.logger import init_logger
|
||||
from vllm.transformers_utils.config import get_hf_file_to_dict
|
||||
from vllm.utils.network_utils import get_open_zmq_ipc_path, zmq_socket_ctx
|
||||
from vllm.utils.system_utils import get_mp_context
|
||||
from vllm.v1.utils import shutdown
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionRequestAbortedError, TransformerConfig
|
||||
from vllm_omni.diffusion.data import DiffusionRequestAbortedError
|
||||
from vllm_omni.diffusion.diffusion_engine import DiffusionEngine
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.distributed.omni_connectors.utils.serialization import (
|
||||
@@ -47,6 +46,8 @@ class StageDiffusionProc:
|
||||
and ZMQ-based communication with StageDiffusionClient.
|
||||
"""
|
||||
|
||||
DIFFUSION_PROC_DEAD = b"DIFFUSION_PROC_DEAD"
|
||||
|
||||
def __init__(self, model: str, od_config: OmniDiffusionConfig) -> None:
|
||||
self._model = model
|
||||
self._od_config = od_config
|
||||
@@ -66,47 +67,8 @@ class StageDiffusionProc:
|
||||
logger.info("StageDiffusionProc initialized with model: %s", self._model)
|
||||
|
||||
def _enrich_config(self) -> None:
|
||||
"""Load model metadata from HuggingFace and populate od_config fields.
|
||||
|
||||
Diffusers-style models expose ``model_index.json`` with ``_class_name``.
|
||||
Non-diffusers models (e.g. Bagel, NextStep) only have ``config.json``,
|
||||
so we fall back to reading that and mapping model_type manually.
|
||||
"""
|
||||
od_config = self._od_config
|
||||
|
||||
try:
|
||||
config_dict = get_hf_file_to_dict("model_index.json", od_config.model)
|
||||
if config_dict is not None:
|
||||
if od_config.model_class_name is None:
|
||||
od_config.model_class_name = config_dict.get("_class_name", None)
|
||||
od_config.update_multimodal_support()
|
||||
|
||||
tf_config_dict = get_hf_file_to_dict("transformer/config.json", od_config.model)
|
||||
od_config.tf_model_config = TransformerConfig.from_dict(tf_config_dict)
|
||||
else:
|
||||
raise FileNotFoundError("model_index.json not found")
|
||||
except (AttributeError, OSError, ValueError, FileNotFoundError):
|
||||
cfg = get_hf_file_to_dict("config.json", od_config.model)
|
||||
if cfg is None:
|
||||
raise ValueError(f"Could not find config.json or model_index.json for model {od_config.model}")
|
||||
|
||||
od_config.tf_model_config = TransformerConfig.from_dict(cfg)
|
||||
model_type = cfg.get("model_type")
|
||||
architectures = cfg.get("architectures") or []
|
||||
|
||||
if model_type == "bagel" or "BagelForConditionalGeneration" in architectures:
|
||||
od_config.model_class_name = "BagelPipeline"
|
||||
od_config.tf_model_config = TransformerConfig()
|
||||
od_config.update_multimodal_support()
|
||||
elif model_type == "nextstep":
|
||||
if od_config.model_class_name is None:
|
||||
od_config.model_class_name = "NextStep11Pipeline"
|
||||
od_config.tf_model_config = TransformerConfig()
|
||||
od_config.update_multimodal_support()
|
||||
elif architectures and len(architectures) == 1:
|
||||
od_config.model_class_name = architectures[0]
|
||||
else:
|
||||
raise
|
||||
"""Load model metadata from HuggingFace and populate od_config fields."""
|
||||
self._od_config.enrich_config()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Request processing
|
||||
@@ -490,6 +452,16 @@ class StageDiffusionProc:
|
||||
elif msg_type == "shutdown":
|
||||
break
|
||||
|
||||
except Exception:
|
||||
# Send the death sentinel so the client can detect the
|
||||
# fatal failure promptly (mirrors EngineCoreProc._send_engine_dead).
|
||||
try:
|
||||
response_socket.setsockopt(zmq.LINGER, 4000)
|
||||
await response_socket.send(StageDiffusionProc.DIFFUSION_PROC_DEAD)
|
||||
except Exception:
|
||||
logger.warning("Failed to send DIFFUSION_PROC_DEAD sentinel to client.")
|
||||
raise
|
||||
|
||||
finally:
|
||||
for task in tasks.values():
|
||||
task.cancel()
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import torch
|
||||
|
||||
|
||||
def validate_prompt_sequence_lengths(
|
||||
attention_mask: torch.Tensor,
|
||||
*,
|
||||
max_sequence_length: int,
|
||||
supported_max_sequence_length: int,
|
||||
prompt_name: str = "prompt",
|
||||
length_offset: int = 0,
|
||||
baseline_attention_mask: torch.Tensor | None = None,
|
||||
error_context: str,
|
||||
) -> None:
|
||||
sequence_lengths = attention_mask.sum(dim=1)
|
||||
if baseline_attention_mask is not None:
|
||||
# Some callers need to validate only the user-controlled portion of a
|
||||
# templated prompt. In those cases we subtract the fully-tokenized
|
||||
# template baseline instead of only removing a fixed prefix length,
|
||||
# because the template may also contribute a suffix or image markers.
|
||||
baseline_lengths = baseline_attention_mask.sum(dim=1)
|
||||
if baseline_lengths.shape[0] == 1 and sequence_lengths.shape[0] > 1:
|
||||
baseline_lengths = baseline_lengths.expand(sequence_lengths.shape[0])
|
||||
sequence_lengths = sequence_lengths - baseline_lengths
|
||||
if length_offset:
|
||||
sequence_lengths = sequence_lengths - length_offset
|
||||
sequence_lengths = torch.clamp(sequence_lengths, min=0)
|
||||
too_long = torch.nonzero(sequence_lengths > max_sequence_length, as_tuple=False)
|
||||
if too_long.numel() == 0:
|
||||
return
|
||||
|
||||
batch_idx = int(too_long[0].item())
|
||||
actual_length = int(sequence_lengths[batch_idx].item())
|
||||
prompt_ref = f"`{prompt_name}` at batch index {batch_idx}" if attention_mask.shape[0] > 1 else f"`{prompt_name}`"
|
||||
raise ValueError(
|
||||
f"{prompt_ref} is too long {error_context}: got {actual_length} tokens, but "
|
||||
f"`max_sequence_length` is {max_sequence_length}. Shorten the prompt or increase "
|
||||
f"`max_sequence_length` up to {supported_max_sequence_length}."
|
||||
)
|
||||
@@ -27,7 +27,10 @@ from vllm.v1.worker.workspace import init_workspace_manager
|
||||
|
||||
from vllm_omni.diffusion.data import (
|
||||
DiffusionOutput,
|
||||
OmniACK,
|
||||
OmniDiffusionConfig,
|
||||
OmniSleepTask,
|
||||
OmniWakeTask,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
destroy_distributed_env,
|
||||
@@ -77,6 +80,7 @@ class DiffusionWorker:
|
||||
self.model_runner: DiffusionModelRunner | None = None
|
||||
self._sleep_saved_buffers: dict[str, torch.Tensor] = {}
|
||||
self.lora_manager: DiffusionLoRAManager | None = None
|
||||
self.stage_id = getattr(od_config, "stage_id", 0)
|
||||
self.init_device()
|
||||
# Create model runner
|
||||
self.model_runner = DiffusionModelRunner(
|
||||
@@ -159,8 +163,10 @@ class DiffusionWorker:
|
||||
def _get_profiler(self) -> WorkerProfiler | None:
|
||||
return getattr(self, "profiler", None)
|
||||
|
||||
def load_model(self, load_format: str = "default", custom_pipeline_name: str | None = None) -> None:
|
||||
def load_model(self, load_format: str = "default", custom_pipeline_name: str | None = None, **kwargs) -> None:
|
||||
"""Load the diffusion model using DiffusionModelRunner."""
|
||||
load_format = kwargs.get("load_format", load_format)
|
||||
custom_pipeline_name = kwargs.get("custom_pipeline_name", custom_pipeline_name)
|
||||
with (
|
||||
set_forward_context(vllm_config=self.vllm_config, omni_diffusion_config=self.od_config),
|
||||
set_current_vllm_config(self.vllm_config),
|
||||
@@ -170,6 +176,8 @@ class DiffusionWorker:
|
||||
load_format=load_format,
|
||||
custom_pipeline_name=custom_pipeline_name,
|
||||
)
|
||||
current_omni_platform.synchronize()
|
||||
gc.collect()
|
||||
process_memory = get_process_gpu_memory(self.local_rank)
|
||||
if process_memory is not None:
|
||||
logger.info(
|
||||
@@ -284,77 +292,176 @@ class DiffusionWorker:
|
||||
"""
|
||||
from vllm.device_allocator.cumem import CuMemAllocator
|
||||
|
||||
process_memory_before_sleep = get_process_gpu_memory(self.local_rank)
|
||||
free_bytes_before_sleep = None
|
||||
if process_memory_before_sleep is None:
|
||||
free_bytes_before_sleep = current_omni_platform.get_free_memory()
|
||||
allocator = CuMemAllocator.get_instance()
|
||||
|
||||
usage_before = allocator.get_current_usage()
|
||||
|
||||
# Save the buffers before level 2 sleep
|
||||
if level == 2 and self.model_runner is not None:
|
||||
if hasattr(self.model_runner, "graph_runners"):
|
||||
self.model_runner.graph_runners.clear()
|
||||
logger.info(f"[Worker {self.rank}] CUDA Graphs cleared.")
|
||||
model = self.model_runner.pipeline
|
||||
self._sleep_saved_buffers = {name: buffer.cpu().clone() for name, buffer in model.named_buffers()}
|
||||
|
||||
allocator = CuMemAllocator.get_instance()
|
||||
allocator.sleep(offload_tags=("weights",) if level == 1 else tuple())
|
||||
process_memory_after_sleep = get_process_gpu_memory(self.local_rank)
|
||||
if process_memory_before_sleep is not None and process_memory_after_sleep is not None:
|
||||
freed_bytes = process_memory_before_sleep - process_memory_after_sleep
|
||||
used_bytes = process_memory_after_sleep
|
||||
accounting_scope = "process-scoped"
|
||||
free_mem_before = current_omni_platform.get_free_memory()
|
||||
|
||||
# Level 1: Offload weights; Level 2: Total Discard
|
||||
offload_tags = ("weights",) if level == 1 else tuple()
|
||||
allocator.sleep(offload_tags=offload_tags)
|
||||
|
||||
current_omni_platform.empty_cache()
|
||||
current_omni_platform.synchronize()
|
||||
|
||||
free_mem_after = current_omni_platform.get_free_memory()
|
||||
try:
|
||||
total_mem = current_omni_platform.get_device_total_memory()
|
||||
except (NotImplementedError, AttributeError):
|
||||
total_mem = torch.cuda.get_device_properties(self.device).total_memory
|
||||
|
||||
phys_freed_bytes = max(0, free_mem_after - free_mem_before)
|
||||
phys_used_bytes = total_mem - free_mem_after
|
||||
|
||||
if usage_before > 0:
|
||||
logger.info(
|
||||
f"[Diffusion Worker {self.rank}] Sleep Level {level}: "
|
||||
f"physically freed {phys_freed_bytes / GiB_bytes:.2f} GiB, "
|
||||
f"{phys_used_bytes / GiB_bytes:.2f} GiB is still in use."
|
||||
)
|
||||
else:
|
||||
free_bytes_after_sleep = current_omni_platform.get_free_memory()
|
||||
assert free_bytes_before_sleep is not None
|
||||
device_id = self.device.index if self.device.index is not None else 0
|
||||
total = current_omni_platform.get_device_total_memory(device_id)
|
||||
freed_bytes = free_bytes_after_sleep - free_bytes_before_sleep
|
||||
used_bytes = total - free_bytes_after_sleep
|
||||
accounting_scope = "device-scoped fallback"
|
||||
assert freed_bytes >= 0, "Memory usage increased after sleeping."
|
||||
logger.info(
|
||||
"Sleep mode (%s) freed %.2f GiB memory, %.2f GiB memory is still in use.",
|
||||
accounting_scope,
|
||||
freed_bytes / GiB_bytes,
|
||||
used_bytes / GiB_bytes,
|
||||
)
|
||||
return True
|
||||
logger.info(f"[Worker {self.rank}] Sleep Level {level} completed (GPU was already empty).")
|
||||
logger.info(f"[Worker {self.rank}] Memory usage before sleep: {usage_before / GiB_bytes:.2f} GiB.")
|
||||
return usage_before
|
||||
|
||||
def wake_up(self, tags: list[str] | None = None) -> bool:
|
||||
"""
|
||||
Wake up the worker from sleep mode. See the sleep function
|
||||
method for more details.
|
||||
Wake up the worker from sleep mode.
|
||||
|
||||
Re-activates the memory allocator for the specified tags and restores
|
||||
model buffers from CPU back to GPU if they were saved during Level 2 sleep.
|
||||
|
||||
Args:
|
||||
tags: An optional list of tags to reallocate the worker memory
|
||||
for specific memory allocations. Values must be in
|
||||
`("weights")`. If None, all memory is reallocated.
|
||||
wake_up should be called with all tags (or None) before the
|
||||
worker is used again.
|
||||
tags: List of memory pool tags to re-activate (e.g., ["weights"]
|
||||
to match Level 1 sleep). If None, all pools are re-activated.
|
||||
"""
|
||||
from vllm.device_allocator.cumem import CuMemAllocator
|
||||
|
||||
allocator = CuMemAllocator.get_instance()
|
||||
allocator.wake_up(tags)
|
||||
|
||||
# Restore the buffers after level 2 sleep
|
||||
current_omni_platform.synchronize()
|
||||
if len(self._sleep_saved_buffers) and self.model_runner is not None:
|
||||
model = self.model_runner.pipeline
|
||||
for name, buffer in model.named_buffers():
|
||||
if name in self._sleep_saved_buffers:
|
||||
buffer.data.copy_(self._sleep_saved_buffers[name].data)
|
||||
self._sleep_saved_buffers = {}
|
||||
logger.info(f"[Worker {self.rank}] Buffers restored from CPU.")
|
||||
logger.info(f"[Worker {self.rank}] Wake-up complete.")
|
||||
return True
|
||||
|
||||
def handle_sleep_task(self, task: OmniSleepTask) -> OmniACK:
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
try:
|
||||
if isinstance(task, dict):
|
||||
task = OmniSleepTask(**task)
|
||||
logger.info(f"[Worker {self.rank}] Handshake Received: Task {task.task_id}")
|
||||
|
||||
current_omni_platform.synchronize()
|
||||
usage_before = current_omni_platform.get_current_memory_usage(self.device)
|
||||
self.sleep(level=task.level)
|
||||
current_omni_platform.synchronize()
|
||||
usage_after = current_omni_platform.get_current_memory_usage(self.device)
|
||||
real_freed = max(0, usage_before - usage_after)
|
||||
logger.info(f"[Worker {self.rank}] Preparing ACK: freed_bytes={real_freed / GiB_bytes:.2f} GiB.")
|
||||
|
||||
# Ensure all ranks have completed sleep before measuring memory and sending ACK
|
||||
if torch.distributed.is_initialized():
|
||||
t_freed = torch.tensor([float(real_freed)], device=self.device)
|
||||
torch.distributed.all_reduce(t_freed)
|
||||
real_freed = int(t_freed.item())
|
||||
|
||||
if self.rank != 0:
|
||||
return None
|
||||
|
||||
ack = OmniACK(
|
||||
task_id=task.task_id,
|
||||
status="SUCCESS",
|
||||
stage_id=self.stage_id,
|
||||
rank=self.rank,
|
||||
freed_bytes=real_freed,
|
||||
# return RL need metadata
|
||||
metadata={
|
||||
"source": f"Platform_{current_omni_platform.get_device_name()}",
|
||||
"total_freed_gib": f"{real_freed / GiB_bytes:.2f}",
|
||||
"rank_residual_gib": f"{usage_after / GiB_bytes:.2f}",
|
||||
},
|
||||
)
|
||||
logger.info(f"[Worker {self.rank}] ACK emitted. Freed {real_freed / GiB_bytes:.2f} GiB.")
|
||||
return ack
|
||||
except Exception as e:
|
||||
logger.error(f"Sleep failed: {e}", exc_info=True)
|
||||
if torch.distributed.is_initialized():
|
||||
try:
|
||||
torch.distributed.barrier()
|
||||
except Exception:
|
||||
pass
|
||||
return OmniACK(task_id=task.task_id, status="ERROR", error_msg=str(e))
|
||||
|
||||
def handle_wake_task(self, task: OmniWakeTask) -> OmniACK:
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
try:
|
||||
if isinstance(task, dict):
|
||||
task = OmniWakeTask(**task)
|
||||
logger.info(f"[Worker {self.rank}] Responding to Wake-up Task: {task.task_id}")
|
||||
self.wake_up(tags=task.tags)
|
||||
|
||||
logger.info(f"[Worker {self.rank}] wake_up logic finished, entering barrier...")
|
||||
if torch.distributed.is_initialized():
|
||||
torch.distributed.barrier()
|
||||
|
||||
current_omni_platform.synchronize()
|
||||
usage_now = current_omni_platform.get_current_memory_usage(self.device)
|
||||
current_used_gib = usage_now / (1024**3)
|
||||
|
||||
if self.rank != 0:
|
||||
return None
|
||||
logger.info(f"[Worker {self.rank}] PASSED barrier, about to return to loop.")
|
||||
|
||||
return OmniACK(
|
||||
task_id=task.task_id,
|
||||
status="SUCCESS",
|
||||
stage_id=self.stage_id,
|
||||
rank=self.rank,
|
||||
metadata={
|
||||
"state": "WARM",
|
||||
"source": f"Platform_{current_omni_platform.get_device_name()}",
|
||||
"current_vram_gib": f"{current_used_gib:.2f}",
|
||||
},
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Wake-up failed on Rank {self.rank}: {e}", exc_info=True)
|
||||
if torch.distributed.is_initialized():
|
||||
try:
|
||||
torch.distributed.barrier()
|
||||
except Exception:
|
||||
pass
|
||||
return OmniACK(task_id=task.task_id, status="ERROR", error_msg=str(e))
|
||||
|
||||
def _maybe_get_memory_pool_context(self, tag: str) -> AbstractContextManager:
|
||||
"""Get memory pool context for sleep mode support."""
|
||||
if self.od_config.enable_sleep_mode:
|
||||
is_sleep_enabled = getattr(self.od_config, "enable_sleep_mode", False)
|
||||
if is_sleep_enabled:
|
||||
current_omni_platform.synchronize()
|
||||
gc.collect()
|
||||
from vllm.device_allocator.cumem import CuMemAllocator
|
||||
|
||||
allocator = CuMemAllocator.get_instance()
|
||||
if tag == "weights":
|
||||
assert allocator.get_current_usage() == 0, "Sleep mode can only be used for one instance per process."
|
||||
logger.info(f"[Worker {self.rank}] Activating Diffusion CuMem pool for tag: {tag}")
|
||||
return allocator.use_memory_pool(tag=tag)
|
||||
else:
|
||||
return nullcontext()
|
||||
return nullcontext()
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Shutdown the worker and cleanup distributed environment."""
|
||||
@@ -395,11 +502,13 @@ class WorkerProc:
|
||||
od_config: OmniDiffusionConfig,
|
||||
gpu_id: int,
|
||||
broadcast_handle,
|
||||
wake_event: mp.Event,
|
||||
worker_extension_cls: str | None = None,
|
||||
custom_pipeline_args: dict[str, Any] | None = None,
|
||||
):
|
||||
self.od_config = od_config
|
||||
self.gpu_id = gpu_id
|
||||
self.wake_event = wake_event
|
||||
|
||||
# Inter-process Communication
|
||||
self.context = zmq.Context(io_threads=2)
|
||||
@@ -414,7 +523,13 @@ class WorkerProc:
|
||||
if gpu_id == 0:
|
||||
self.result_mq = MessageQueue(n_reader=1, n_local_reader=1, local_reader_ranks=[0])
|
||||
self.result_mq_handle = self.result_mq.export_handle()
|
||||
WorkerProc._shared_result_handle = self.result_mq_handle
|
||||
logger.info(f"Worker {gpu_id} created result MessageQueue")
|
||||
else:
|
||||
handle = getattr(WorkerProc, "_shared_result_handle", None)
|
||||
if handle:
|
||||
self.result_mq = MessageQueue.create_from_handle(handle, gpu_id)
|
||||
logger.info(f"Worker {gpu_id} attached to shared result MessageQueue")
|
||||
|
||||
assert od_config.master_port is not None
|
||||
|
||||
@@ -438,13 +553,17 @@ class WorkerProc:
|
||||
)
|
||||
return wrapper
|
||||
|
||||
def return_result(self, output: object):
|
||||
def return_result(self, output: Any):
|
||||
"""Reply to client, only on rank 0."""
|
||||
if self.result_mq is not None:
|
||||
if isinstance(output, OmniACK):
|
||||
self.result_mq.enqueue(output)
|
||||
return
|
||||
try:
|
||||
pack_diffusion_output_shm(output)
|
||||
except Exception as e:
|
||||
logger.warning("SHM pack failed, falling back to raw enqueue: %s", e)
|
||||
if hasattr(output, "output"):
|
||||
logger.warning("SHM pack failed for model output: %s", e)
|
||||
self.result_mq.enqueue(output)
|
||||
|
||||
def recv_message(self):
|
||||
@@ -480,20 +599,31 @@ class WorkerProc:
|
||||
while self._running:
|
||||
msg = None
|
||||
try:
|
||||
msg = self.recv_message()
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error receiving message in worker loop: {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
msg = self.mq.dequeue(timeout=1.0)
|
||||
except Exception:
|
||||
if self.wake_event and self.wake_event.is_set():
|
||||
self.wake_event.clear()
|
||||
logger.info(f"Worker {self.gpu_id} caught OOB POKE, forcing wake-up sequence.")
|
||||
msg = {"type": "wake_up", "task_id": "recovery-task", "tags": None}
|
||||
else:
|
||||
continue
|
||||
if msg is None:
|
||||
continue
|
||||
|
||||
if msg is None or len(msg) == 0:
|
||||
logger.warning("Worker %s: Received empty payload, ignoring", self.gpu_id)
|
||||
continue
|
||||
|
||||
if isinstance(msg, dict) and msg.get("type") == "sleep":
|
||||
task = OmniSleepTask(level=msg.get("level", 2), task_id=msg.get("task_id", "local"))
|
||||
ack = self.worker.handle_sleep_task(task)
|
||||
self.return_result(ack)
|
||||
elif isinstance(msg, dict) and msg.get("type") == "wake_up":
|
||||
task = OmniWakeTask(tags=msg.get("tags"), task_id=msg.get("task_id", "local"))
|
||||
ack = self.worker.handle_wake_task(task)
|
||||
self.return_result(ack)
|
||||
# Route message based on type
|
||||
if isinstance(msg, dict) and msg.get("type") == "rpc":
|
||||
elif isinstance(msg, dict) and msg.get("type") == "rpc":
|
||||
try:
|
||||
result, should_reply = self.execute_rpc(msg)
|
||||
if should_reply:
|
||||
@@ -538,6 +668,7 @@ class WorkerProc:
|
||||
od_config: OmniDiffusionConfig,
|
||||
pipe_writer: mp.connection.Connection,
|
||||
broadcast_handle,
|
||||
wake_event: mp.Event,
|
||||
worker_extension_cls: str | None = None,
|
||||
custom_pipeline_args: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
@@ -549,6 +680,7 @@ class WorkerProc:
|
||||
od_config,
|
||||
gpu_id=rank,
|
||||
broadcast_handle=broadcast_handle,
|
||||
wake_event=wake_event,
|
||||
worker_extension_cls=worker_extension_cls,
|
||||
custom_pipeline_args=custom_pipeline_args,
|
||||
)
|
||||
@@ -574,6 +706,7 @@ class WorkerWrapperBase:
|
||||
gpu_id: int,
|
||||
od_config: OmniDiffusionConfig,
|
||||
base_worker_class: type = DiffusionWorker,
|
||||
wake_event: mp.Event = None,
|
||||
worker_extension_cls: str | None = None,
|
||||
custom_pipeline_args: dict[str, Any] | None = None,
|
||||
):
|
||||
@@ -734,6 +867,12 @@ class WorkerWrapperBase:
|
||||
"""
|
||||
return self.worker.wake_up(tags)
|
||||
|
||||
def handle_sleep_task(self, task):
|
||||
return self.worker.handle_sleep_task(task)
|
||||
|
||||
def handle_wake_task(self, task):
|
||||
return self.worker.handle_wake_task(task)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Shutdown the worker and cleanup resources."""
|
||||
return self.worker.shutdown()
|
||||
|
||||
@@ -14,8 +14,20 @@ from vllm.logger import init_logger
|
||||
|
||||
from .factory import OmniConnectorFactory
|
||||
from .utils.config import ConnectorSpec
|
||||
from .utils.initialization import KV_TRANSFER_PORT_OFFSET
|
||||
from .utils.kv_utils import normalize_layer_kv
|
||||
from .utils.initialization import KV_RANK_PORT_STRIDE
|
||||
from .utils.kv_utils import (
|
||||
KVTPTopology,
|
||||
build_rank_aware_recv_keys,
|
||||
build_rank_aware_send_keys,
|
||||
get_kv_target_ranks,
|
||||
get_local_tp_rank,
|
||||
get_tp_world_size,
|
||||
kv_zmq_port,
|
||||
merge_received_rank_shards,
|
||||
normalize_layer_kv,
|
||||
slice_layer_blocks,
|
||||
slice_received_rank_shard,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -57,6 +69,8 @@ class OmniKVCacheConfig:
|
||||
need_recv_cache: bool = False
|
||||
need_send_cache: bool = False
|
||||
recv_timeout: float = 30.0
|
||||
from_tp: int = 1
|
||||
to_tp: int = 1
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -72,82 +86,44 @@ class KVCacheTransferData:
|
||||
"""Convert to dictionary for serialization."""
|
||||
return asdict(self)
|
||||
|
||||
def to_bytes(self) -> bytes:
|
||||
"""Convert to compact binary format for fast transfer."""
|
||||
def _build_tensors_desc(self, *, cpu: bool) -> tuple[list[dict[str, Any]], list, int, torch.device | None]:
|
||||
"""Iterate layer blocks and build tensor descriptors + data chunks.
|
||||
|
||||
Returns ``(tensors_desc, chunks, total_bytes, device)``.
|
||||
*chunks* contains ``bytes`` when *cpu* is True, flat uint8 GPU tensors otherwise.
|
||||
"""
|
||||
tensors_desc: list[dict[str, Any]] = []
|
||||
tensor_bufs: list[bytes] = []
|
||||
data_offset = 0
|
||||
|
||||
for cache_name in ("key_cache", "value_cache"):
|
||||
cache_list = self.layer_blocks.get(cache_name, [])
|
||||
for layer_idx, tensor in enumerate(cache_list):
|
||||
if tensor is None:
|
||||
tensors_desc.append({"n": f"{cache_name}_{layer_idx}", "x": True})
|
||||
continue
|
||||
|
||||
t = tensor.detach().cpu().contiguous()
|
||||
dtype_str = str(t.dtype).removeprefix("torch.")
|
||||
raw = t.view(torch.uint8).numpy().tobytes()
|
||||
tensors_desc.append(
|
||||
{
|
||||
"n": f"{cache_name}_{layer_idx}",
|
||||
"i": layer_idx,
|
||||
"d": dtype_str,
|
||||
"s": list(t.shape),
|
||||
"o": data_offset,
|
||||
"b": len(raw),
|
||||
}
|
||||
)
|
||||
tensor_bufs.append(raw)
|
||||
data_offset += len(raw)
|
||||
|
||||
header = json.dumps(
|
||||
{
|
||||
"rid": self.request_id,
|
||||
"bids": self.block_ids,
|
||||
"meta": self.metadata,
|
||||
"td": tensors_desc,
|
||||
"nl": len(self.layer_blocks.get("key_cache", [])),
|
||||
},
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
return b"".join([struct.pack(">I", len(header)), header] + tensor_bufs)
|
||||
|
||||
def to_gpu_tensor(self) -> torch.Tensor:
|
||||
"""Convert to a packed GPU tensor for raw-data connectors."""
|
||||
tensors_desc: list[dict[str, Any]] = []
|
||||
gpu_tensors: list[torch.Tensor] = []
|
||||
chunks: list = []
|
||||
data_offset = 0
|
||||
device = None
|
||||
|
||||
for cache_name in ("key_cache", "value_cache"):
|
||||
cache_list = self.layer_blocks.get(cache_name, [])
|
||||
for layer_idx, tensor in enumerate(cache_list):
|
||||
for layer_idx, tensor in enumerate(self.layer_blocks.get(cache_name, [])):
|
||||
if tensor is None:
|
||||
tensors_desc.append({"n": f"{cache_name}_{layer_idx}", "x": True})
|
||||
continue
|
||||
|
||||
t = tensor.detach().contiguous()
|
||||
if device is None and t.is_cuda:
|
||||
if cpu:
|
||||
t = t.cpu()
|
||||
elif device is None and t.is_cuda:
|
||||
device = t.device
|
||||
dtype_str = str(t.dtype).removeprefix("torch.")
|
||||
nbytes = t.numel() * t.element_size()
|
||||
tensors_desc.append(
|
||||
{
|
||||
"n": f"{cache_name}_{layer_idx}",
|
||||
"i": layer_idx,
|
||||
"d": dtype_str,
|
||||
"d": str(t.dtype).removeprefix("torch."),
|
||||
"s": list(t.shape),
|
||||
"o": data_offset,
|
||||
"b": nbytes,
|
||||
}
|
||||
)
|
||||
gpu_tensors.append(t.view(torch.uint8).flatten())
|
||||
chunks.append(t.view(torch.uint8).numpy().tobytes() if cpu else t.view(torch.uint8).flatten())
|
||||
data_offset += nbytes
|
||||
|
||||
if device is None:
|
||||
raise RuntimeError("No CUDA tensors found, use to_bytes() instead")
|
||||
return tensors_desc, chunks, data_offset, device
|
||||
|
||||
def _build_header_bytes(self, tensors_desc: list[dict[str, Any]]) -> bytes:
|
||||
header = json.dumps(
|
||||
{
|
||||
"rid": self.request_id,
|
||||
@@ -158,19 +134,26 @@ class KVCacheTransferData:
|
||||
},
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
return struct.pack(">I", len(header)) + header
|
||||
|
||||
header_prefix = struct.pack(">I", len(header)) + header
|
||||
total_size = len(header_prefix) + data_offset
|
||||
output = torch.empty(total_size, dtype=torch.uint8, device=device)
|
||||
header_tensor = torch.frombuffer(bytearray(header_prefix), dtype=torch.uint8)
|
||||
output[: len(header_prefix)].copy_(header_tensor)
|
||||
def to_bytes(self) -> bytes:
|
||||
"""Convert to compact binary format for fast transfer."""
|
||||
tensors_desc, chunks, _, _ = self._build_tensors_desc(cpu=True)
|
||||
return b"".join([self._build_header_bytes(tensors_desc)] + chunks)
|
||||
|
||||
def to_gpu_tensor(self) -> torch.Tensor:
|
||||
"""Convert to a packed GPU tensor for raw-data connectors."""
|
||||
tensors_desc, chunks, data_offset, device = self._build_tensors_desc(cpu=False)
|
||||
if device is None:
|
||||
raise RuntimeError("No CUDA tensors found, use to_bytes() instead")
|
||||
header_prefix = self._build_header_bytes(tensors_desc)
|
||||
output = torch.empty(len(header_prefix) + data_offset, dtype=torch.uint8, device=device)
|
||||
output[: len(header_prefix)].copy_(torch.frombuffer(bytearray(header_prefix), dtype=torch.uint8))
|
||||
pos = len(header_prefix)
|
||||
for t_flat in gpu_tensors:
|
||||
for t_flat in chunks:
|
||||
n = t_flat.numel()
|
||||
output[pos : pos + n].copy_(t_flat)
|
||||
pos += n
|
||||
|
||||
return output
|
||||
|
||||
@staticmethod
|
||||
@@ -237,11 +220,8 @@ class KVCacheTransferData:
|
||||
return layer_idx
|
||||
|
||||
@staticmethod
|
||||
def from_bytes(raw: "bytes | bytearray | memoryview") -> dict[str, Any]:
|
||||
"""Reconstruct KV cache data from the packed bytes format."""
|
||||
raw_mv = memoryview(raw) if not isinstance(raw, memoryview) else raw
|
||||
header, tensor_data_mv = KVCacheTransferData._load_header_from_memoryview(raw_mv)
|
||||
|
||||
def _populate_caches(header: dict[str, Any], get_tensor: callable) -> dict[str, Any]:
|
||||
"""Shared deserialization loop for both CPU and GPU paths."""
|
||||
num_layers = header["nl"]
|
||||
key_cache: list[torch.Tensor | None] = [None] * num_layers
|
||||
value_cache: list[torch.Tensor | None] = [None] * num_layers
|
||||
@@ -249,20 +229,9 @@ class KVCacheTransferData:
|
||||
for info in header["td"]:
|
||||
if info.get("x"):
|
||||
continue
|
||||
|
||||
name: str = info["n"]
|
||||
torch_dtype = KVCacheTransferData._resolve_torch_dtype(info["d"])
|
||||
offset, nbytes = KVCacheTransferData._validate_tensor_span(name, info, len(tensor_data_mv))
|
||||
t = (
|
||||
torch.frombuffer(
|
||||
tensor_data_mv,
|
||||
dtype=torch.uint8,
|
||||
offset=offset,
|
||||
count=nbytes,
|
||||
)
|
||||
.view(torch_dtype)
|
||||
.reshape(info["s"])
|
||||
)
|
||||
t = get_tensor(info).view(torch_dtype).reshape(info["s"])
|
||||
layer_idx = KVCacheTransferData._resolve_layer_idx(info, num_layers)
|
||||
if name.startswith("key_cache_"):
|
||||
key_cache[layer_idx] = t
|
||||
@@ -276,37 +245,30 @@ class KVCacheTransferData:
|
||||
"metadata": header["meta"],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def from_bytes(raw: "bytes | bytearray | memoryview") -> dict[str, Any]:
|
||||
"""Reconstruct KV cache data from the packed bytes format."""
|
||||
raw_mv = memoryview(raw) if not isinstance(raw, memoryview) else raw
|
||||
header, tensor_data_mv = KVCacheTransferData._load_header_from_memoryview(raw_mv)
|
||||
data_len = len(tensor_data_mv)
|
||||
|
||||
def _get(info: dict) -> torch.Tensor:
|
||||
offset, nbytes = KVCacheTransferData._validate_tensor_span(info["n"], info, data_len)
|
||||
return torch.frombuffer(tensor_data_mv, dtype=torch.uint8, offset=offset, count=nbytes)
|
||||
|
||||
return KVCacheTransferData._populate_caches(header, _get)
|
||||
|
||||
@staticmethod
|
||||
def from_bytes_gpu(gpu_tensor: torch.Tensor) -> dict[str, Any]:
|
||||
"""Reconstruct KV cache data from a packed GPU tensor."""
|
||||
header, data_start = KVCacheTransferData._load_header_from_tensor(gpu_tensor)
|
||||
data_len = int(gpu_tensor.numel()) - data_start
|
||||
|
||||
num_layers = header["nl"]
|
||||
key_cache: list[torch.Tensor | None] = [None] * num_layers
|
||||
value_cache: list[torch.Tensor | None] = [None] * num_layers
|
||||
tensor_data_bytes = int(gpu_tensor.numel()) - data_start
|
||||
def _get(info: dict) -> torch.Tensor:
|
||||
offset, nbytes = KVCacheTransferData._validate_tensor_span(info["n"], info, data_len)
|
||||
return gpu_tensor[data_start + offset : data_start + offset + nbytes].clone()
|
||||
|
||||
for info in header["td"]:
|
||||
if info.get("x"):
|
||||
continue
|
||||
|
||||
name: str = info["n"]
|
||||
torch_dtype = KVCacheTransferData._resolve_torch_dtype(info["d"])
|
||||
offset, nbytes = KVCacheTransferData._validate_tensor_span(name, info, tensor_data_bytes)
|
||||
t = gpu_tensor[data_start + offset : data_start + offset + nbytes].clone()
|
||||
t = t.view(torch_dtype).reshape(info["s"])
|
||||
layer_idx = KVCacheTransferData._resolve_layer_idx(info, num_layers)
|
||||
if name.startswith("key_cache_"):
|
||||
key_cache[layer_idx] = t
|
||||
elif name.startswith("value_cache_"):
|
||||
value_cache[layer_idx] = t
|
||||
|
||||
return {
|
||||
"request_id": header["rid"],
|
||||
"layer_blocks": {"key_cache": key_cache, "value_cache": value_cache},
|
||||
"block_ids": header["bids"],
|
||||
"metadata": header["meta"],
|
||||
}
|
||||
return KVCacheTransferData._populate_caches(header, _get)
|
||||
|
||||
|
||||
class OmniKVTransferManager:
|
||||
@@ -341,6 +303,30 @@ class OmniKVTransferManager:
|
||||
else (None, None)
|
||||
)
|
||||
|
||||
local_rank = get_local_tp_rank()
|
||||
|
||||
if config.from_tp <= 1 and config.to_tp <= 1:
|
||||
detected_tp = get_tp_world_size()
|
||||
from_tp = detected_tp
|
||||
to_tp = detected_tp
|
||||
else:
|
||||
from_tp = config.from_tp
|
||||
to_tp = config.to_tp
|
||||
|
||||
self._tp_topo = KVTPTopology(source_tp_size=from_tp, target_tp_size=to_tp, local_rank=local_rank)
|
||||
|
||||
# Injectable hooks (compatible with PR #2677 OmniConnectorModelRunnerMixin).
|
||||
self.kv_send_key_builder: Callable | None = None
|
||||
self.kv_recv_key_builder: Callable | None = None
|
||||
self.kv_payload_merger: Callable | None = None
|
||||
self.kv_payload_slicer: Callable | None = None
|
||||
|
||||
# Base sender endpoint (rank-0 host/port) stored during
|
||||
# update_sender_info(). Used by the receive path to construct
|
||||
# per-rank metadata for heterogeneous TP without querying a registry.
|
||||
self._sender_base_host: str | None = None
|
||||
self._sender_base_zmq_port: int | None = None
|
||||
|
||||
if config.need_send_cache and config.connector_config:
|
||||
try:
|
||||
_ = self.connector
|
||||
@@ -348,11 +334,20 @@ class OmniKVTransferManager:
|
||||
except Exception as e:
|
||||
logger.warning("Failed to eagerly initialize sender connector: %s", e)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Factory helpers
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
@classmethod
|
||||
def _create(cls, cfg: dict | None) -> "OmniKVTransferManager":
|
||||
"""Create manager from raw config dict."""
|
||||
if not cfg or not isinstance(cfg, dict):
|
||||
return cls(OmniKVCacheConfig())
|
||||
|
||||
rank_mapping = cfg.get("rank_mapping", {})
|
||||
if not isinstance(rank_mapping, dict):
|
||||
rank_mapping = {}
|
||||
|
||||
return cls(
|
||||
OmniKVCacheConfig(
|
||||
connector_config=cfg.get("connector_config"),
|
||||
@@ -363,18 +358,17 @@ class OmniKVTransferManager:
|
||||
need_recv_cache=cfg.get("need_recv_cache", False),
|
||||
need_send_cache=cfg.get("need_send_cache", False),
|
||||
recv_timeout=cfg.get("recv_timeout", 30.0),
|
||||
from_tp=int(rank_mapping.get("from_tp", 1)),
|
||||
to_tp=int(rank_mapping.get("to_tp", 1)),
|
||||
)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_model_config(cls, config: Any) -> "OmniKVTransferManager":
|
||||
"""Create from model config (for AR model runner)."""
|
||||
def from_od_config(cls, config: Any) -> "OmniKVTransferManager":
|
||||
"""Create from model or OmniDiffusion config."""
|
||||
return cls._create(getattr(config, "omni_kv_config", None))
|
||||
|
||||
@classmethod
|
||||
def from_od_config(cls, config: Any) -> "OmniKVTransferManager":
|
||||
"""Create from OmniDiffusion config (for diffusion runner)."""
|
||||
return cls._create(getattr(config, "omni_kv_config", None))
|
||||
from_model_config = from_od_config
|
||||
|
||||
@classmethod
|
||||
def from_vllm_config(cls, vllm_config: Any, model_config: Any) -> "OmniKVTransferManager":
|
||||
@@ -417,45 +411,33 @@ class OmniKVTransferManager:
|
||||
)
|
||||
c_extra["to_stage"] = str(self.config.to_stage) if self.config.to_stage is not None else "1"
|
||||
|
||||
try:
|
||||
stage_int = int(self.config.from_stage) if self.config.from_stage is not None else 0
|
||||
except (TypeError, ValueError):
|
||||
stage_int = 0
|
||||
zmq_port = kv_zmq_port(base_port, stage_int, self._tp_topo.local_rank)
|
||||
|
||||
if self.config.need_send_cache:
|
||||
c_extra["role"] = "sender"
|
||||
from_stage = self.config.from_stage
|
||||
if from_stage is not None:
|
||||
try:
|
||||
c_extra["zmq_port"] = base_port + KV_TRANSFER_PORT_OFFSET + int(from_stage)
|
||||
except (TypeError, ValueError):
|
||||
c_extra["zmq_port"] = base_port + KV_TRANSFER_PORT_OFFSET
|
||||
c_extra["zmq_port"] = zmq_port
|
||||
elif self.config.need_recv_cache:
|
||||
c_extra["role"] = "receiver"
|
||||
from_stage = self.config.from_stage
|
||||
sender_port = base_port + KV_TRANSFER_PORT_OFFSET
|
||||
if from_stage is not None:
|
||||
try:
|
||||
sender_port = base_port + KV_TRANSFER_PORT_OFFSET + int(from_stage)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
c_extra.setdefault("sender_host", c_extra.get("host", "127.0.0.1"))
|
||||
c_extra.setdefault("sender_zmq_port", sender_port)
|
||||
c_extra.setdefault("sender_zmq_port", zmq_port)
|
||||
|
||||
logger.info(
|
||||
"Initializing OmniConnector (purpose=kv_transfer) with config: %s, role: %s",
|
||||
cfg,
|
||||
"Initializing OmniConnector type=%s role=%s",
|
||||
c_type,
|
||||
c_extra.get("role", "N/A"),
|
||||
)
|
||||
self._connector = OmniConnectorFactory.create_connector(ConnectorSpec(name=c_type, extra=c_extra))
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to initialize OmniConnector: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
# Cache failure sentinel to avoid repeated initialization attempts in hot paths.
|
||||
except Exception:
|
||||
logger.exception("Failed to initialize OmniConnector")
|
||||
self._connector = False
|
||||
|
||||
return self._connector if self._connector else None
|
||||
|
||||
def get_connector(self):
|
||||
"""Get connector (compatibility wrapper for existing code)."""
|
||||
return self.connector
|
||||
get_connector = property(lambda self: self.connector)
|
||||
|
||||
def _resolve_sender_info(
|
||||
self, sender_info: dict[str, Any], sender_stage_id: str | int | None = None
|
||||
@@ -513,8 +495,187 @@ class OmniKVTransferManager:
|
||||
cache_list[idx] = tensor.clone()
|
||||
return data
|
||||
|
||||
def _slice_transfer_data_for_target(self, kv_data: KVCacheTransferData, target_rank: int) -> KVCacheTransferData:
|
||||
"""Pre-slice sender payload for one target rank when sender TP < receiver TP."""
|
||||
topo = self._tp_topo
|
||||
ratio = topo.target_tp_size // topo.source_tp_size
|
||||
offset_in_sender = target_rank % ratio
|
||||
metadata = dict(kv_data.metadata) if isinstance(kv_data.metadata, dict) else {}
|
||||
metadata["tp_head_slice"] = {
|
||||
"applied": True,
|
||||
"side": "sender",
|
||||
"target_rank": target_rank,
|
||||
"source_rank": topo.local_rank,
|
||||
"from_tp": topo.source_tp_size,
|
||||
"to_tp": topo.target_tp_size,
|
||||
"offset_in_shard": offset_in_sender,
|
||||
"num_slices": ratio,
|
||||
}
|
||||
return KVCacheTransferData(
|
||||
request_id=kv_data.request_id,
|
||||
layer_blocks=slice_layer_blocks(kv_data.layer_blocks, offset_in_sender, ratio),
|
||||
block_ids=list(kv_data.block_ids),
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
def _serialize_transfer_payload(self, kv_data: KVCacheTransferData) -> torch.Tensor | bytes | dict[str, Any]:
|
||||
"""Serialize KV transfer data using the connector's fastest supported path."""
|
||||
if getattr(self.connector, "supports_raw_data", False):
|
||||
try:
|
||||
return kv_data.to_gpu_tensor()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
return kv_data.to_bytes()
|
||||
except Exception:
|
||||
return kv_data.to_dict()
|
||||
|
||||
@staticmethod
|
||||
def _collect_request_kv_payload(req: Any) -> dict[str, object]:
|
||||
"""Collect request-side KV objects for object broadcast."""
|
||||
kv_payload: dict[str, object] = {}
|
||||
for attr in ("past_key_values", "kv_metadata"):
|
||||
val = getattr(req, attr, None)
|
||||
if val is not None:
|
||||
kv_payload[attr] = val
|
||||
|
||||
if hasattr(req, "sampling_params") and req.sampling_params is not None:
|
||||
for key in list(vars(req.sampling_params).keys()):
|
||||
if key in ("past_key_values", "kv_metadata") or (
|
||||
key.startswith("cfg_")
|
||||
and (
|
||||
key.endswith("_past_key_values")
|
||||
or key.endswith("_kv_metadata")
|
||||
or key
|
||||
in (
|
||||
"cfg_kv_request_ids",
|
||||
"cfg_active_branch",
|
||||
"cfg_branch_roles",
|
||||
"cfg_branch_past_key_values",
|
||||
"cfg_branch_kv_metadata",
|
||||
)
|
||||
)
|
||||
):
|
||||
val = getattr(req.sampling_params, key, None)
|
||||
if val is not None:
|
||||
kv_payload[f"sp.{key}"] = val
|
||||
|
||||
return kv_payload
|
||||
|
||||
@staticmethod
|
||||
def _apply_request_kv_payload(
|
||||
req: Any,
|
||||
kv_payload: dict[str, object],
|
||||
target_device: torch.device | None = None,
|
||||
) -> None:
|
||||
"""Apply a broadcast KV payload back onto a request object."""
|
||||
for attr in ("past_key_values", "kv_metadata"):
|
||||
val = kv_payload.get(attr)
|
||||
if val is not None:
|
||||
if target_device is not None:
|
||||
val = _move_to_device(val, target_device)
|
||||
setattr(req, attr, val)
|
||||
|
||||
if hasattr(req, "sampling_params") and req.sampling_params is not None:
|
||||
for key, val in kv_payload.items():
|
||||
if key.startswith("sp."):
|
||||
if target_device is not None:
|
||||
val = _move_to_device(val, target_device)
|
||||
setattr(req.sampling_params, key[3:], val)
|
||||
|
||||
@staticmethod
|
||||
def _discover_cfg_branch_roles(req: Any) -> list[str]:
|
||||
"""Discover CFG branch roles in a stable order."""
|
||||
sampling_params = getattr(req, "sampling_params", None)
|
||||
if sampling_params is None:
|
||||
return []
|
||||
|
||||
roles: list[str] = []
|
||||
branch_map = getattr(sampling_params, "cfg_branch_past_key_values", None) or {}
|
||||
for preferred_role in ("cfg_text", "cfg_img"):
|
||||
if (
|
||||
preferred_role in branch_map
|
||||
or getattr(sampling_params, f"{preferred_role}_past_key_values", None) is not None
|
||||
):
|
||||
roles.append(preferred_role)
|
||||
|
||||
for role in branch_map.keys():
|
||||
if role not in roles and branch_map.get(role) is not None:
|
||||
roles.append(role)
|
||||
|
||||
for key in vars(sampling_params).keys():
|
||||
if not (key.startswith("cfg_") and key.endswith("_past_key_values")):
|
||||
continue
|
||||
role = key.removesuffix("_past_key_values")
|
||||
if role in ("cfg_branch",) or role in roles:
|
||||
continue
|
||||
if getattr(sampling_params, key, None) is not None:
|
||||
roles.append(role)
|
||||
|
||||
return roles
|
||||
|
||||
@classmethod
|
||||
def _build_cfg_rank_local_payloads(cls, req: Any, cfg_size: int) -> list[dict[str, object] | None]:
|
||||
"""Build per-cfg-rank payloads so each rank receives only its branch KV."""
|
||||
full_payload = cls._collect_request_kv_payload(req)
|
||||
payloads: list[dict[str, object] | None] = []
|
||||
|
||||
main_payload = {
|
||||
key: value
|
||||
for key, value in full_payload.items()
|
||||
if key in ("past_key_values", "kv_metadata", "sp.past_key_values", "sp.kv_metadata")
|
||||
}
|
||||
branch_roles = cls._discover_cfg_branch_roles(req)
|
||||
if branch_roles:
|
||||
main_payload["sp.cfg_branch_roles"] = list(branch_roles)
|
||||
main_payload["sp.cfg_active_branch"] = None
|
||||
payloads.append(main_payload or None)
|
||||
|
||||
sampling_params = getattr(req, "sampling_params", None)
|
||||
branch_map = getattr(sampling_params, "cfg_branch_past_key_values", None) or {}
|
||||
branch_metadata_map = getattr(sampling_params, "cfg_branch_kv_metadata", None) or {}
|
||||
|
||||
for role in branch_roles:
|
||||
if sampling_params is None:
|
||||
payloads.append(None)
|
||||
continue
|
||||
|
||||
branch_kv = branch_map.get(role)
|
||||
if branch_kv is None:
|
||||
branch_kv = getattr(sampling_params, f"{role}_past_key_values", None)
|
||||
branch_metadata = branch_metadata_map.get(role)
|
||||
if branch_metadata is None:
|
||||
branch_metadata = getattr(sampling_params, f"{role}_kv_metadata", None)
|
||||
if branch_kv is None:
|
||||
payloads.append(None)
|
||||
continue
|
||||
|
||||
local_payload = dict(main_payload)
|
||||
local_payload["sp.cfg_active_branch"] = role
|
||||
local_payload["sp.cfg_branch_roles"] = list(branch_roles)
|
||||
local_payload["sp.cfg_branch_past_key_values"] = {role: branch_kv}
|
||||
local_payload[f"sp.{role}_past_key_values"] = branch_kv
|
||||
if branch_metadata is not None:
|
||||
local_payload["sp.cfg_branch_kv_metadata"] = {role: branch_metadata}
|
||||
local_payload[f"sp.{role}_kv_metadata"] = branch_metadata
|
||||
|
||||
payloads.append(local_payload)
|
||||
|
||||
while len(payloads) < cfg_size:
|
||||
payloads.append(None)
|
||||
|
||||
return payloads[:cfg_size]
|
||||
|
||||
def update_sender_info(self, sender_info: dict[str, Any], sender_stage_id: str | int | None = None) -> None:
|
||||
"""Update receiver-side sender info before loading remote KV cache."""
|
||||
"""Update receiver-side sender info before loading remote KV cache.
|
||||
|
||||
The orchestrator always reports rank-0's ZMQ port. When TP > 1 the
|
||||
receiver must offset the port so that each TP rank connects to the
|
||||
corresponding sender rank's port.
|
||||
|
||||
The base host/port are also stored so that the receive path can
|
||||
construct per-rank metadata for heterogeneous TP scenarios.
|
||||
"""
|
||||
if not self.config.need_recv_cache:
|
||||
return
|
||||
|
||||
@@ -523,18 +684,39 @@ class OmniKVTransferManager:
|
||||
logger.warning("Invalid sender_info format: %s", sender_info)
|
||||
return
|
||||
|
||||
sender_host = actual_info.get("host")
|
||||
base_zmq_port = actual_info.get("zmq_port")
|
||||
|
||||
# Store base sender info for per-rank metadata construction.
|
||||
self._sender_base_host = sender_host
|
||||
if base_zmq_port is not None:
|
||||
self._sender_base_zmq_port = int(base_zmq_port)
|
||||
|
||||
# --- Default sender: offset to match this receiver's corresponding sender rank ---
|
||||
zmq_port = base_zmq_port
|
||||
if zmq_port is not None and self._tp_topo.local_rank > 0:
|
||||
zmq_port = int(zmq_port) + self._tp_topo.local_rank * KV_RANK_PORT_STRIDE
|
||||
|
||||
if self.config.connector_config:
|
||||
self.config.connector_config["sender_host"] = actual_info.get("host")
|
||||
self.config.connector_config["sender_zmq_port"] = actual_info.get("zmq_port")
|
||||
self.config.connector_config["sender_host"] = sender_host
|
||||
self.config.connector_config["sender_zmq_port"] = zmq_port
|
||||
|
||||
if self._connector and hasattr(self._connector, "update_sender_info"):
|
||||
try:
|
||||
self._connector.update_sender_info(actual_info.get("host"), actual_info.get("zmq_port"))
|
||||
self._connector.update_sender_info(sender_host, zmq_port)
|
||||
except Exception:
|
||||
if hasattr(self._connector, "sender_host"):
|
||||
self._connector.sender_host = actual_info.get("host")
|
||||
self._connector.sender_host = sender_host
|
||||
if hasattr(self._connector, "sender_zmq_port"):
|
||||
self._connector.sender_zmq_port = actual_info.get("zmq_port")
|
||||
self._connector.sender_zmq_port = zmq_port
|
||||
|
||||
logger.info(
|
||||
"Sender info updated: host=%s, base_port=%s, adjusted_port=%s (local_rank=%s)",
|
||||
sender_host,
|
||||
base_zmq_port,
|
||||
zmq_port,
|
||||
self._tp_topo.local_rank,
|
||||
)
|
||||
|
||||
def handle_finished_requests_kv_transfer(
|
||||
self,
|
||||
@@ -692,35 +874,54 @@ class OmniKVTransferManager:
|
||||
|
||||
kv_data.request_id = transfer_req_id
|
||||
serialization_start = time.perf_counter()
|
||||
transfer_data: torch.Tensor | bytes | dict[str, Any]
|
||||
supports_raw = getattr(self.connector, "supports_raw_data", False)
|
||||
topo = self._tp_topo
|
||||
send_keys = build_rank_aware_send_keys(
|
||||
transfer_req_id, from_stage, to_stage, topo, hook=self.kv_send_key_builder
|
||||
)
|
||||
sender_slice_active = (
|
||||
topo.source_tp_size < topo.target_tp_size and len(send_keys) > 1 and not callable(self.kv_send_key_builder)
|
||||
)
|
||||
per_key_payloads: list[tuple[str, torch.Tensor | bytes | dict[str, Any]]] = []
|
||||
|
||||
try:
|
||||
if supports_raw:
|
||||
transfer_data = kv_data.to_gpu_tensor()
|
||||
if sender_slice_active:
|
||||
target_ranks = get_kv_target_ranks(topo)
|
||||
if len(target_ranks) != len(send_keys):
|
||||
logger.warning(
|
||||
"Skip sender-side KV slicing because target rank count does not match send key count: "
|
||||
"target_ranks=%s send_keys=%s",
|
||||
len(target_ranks),
|
||||
len(send_keys),
|
||||
)
|
||||
sender_slice_active = False
|
||||
else:
|
||||
raise RuntimeError("Connector does not support raw tensor")
|
||||
except Exception:
|
||||
try:
|
||||
transfer_data = kv_data.to_bytes()
|
||||
except Exception:
|
||||
data_dict = kv_data.to_dict()
|
||||
data_dict["request_id"] = transfer_req_id
|
||||
transfer_data = data_dict
|
||||
for put_key, target_rank in zip(send_keys, target_ranks, strict=False):
|
||||
sliced_kv_data = self._slice_transfer_data_for_target(kv_data, target_rank)
|
||||
per_key_payloads.append((put_key, self._serialize_transfer_payload(sliced_kv_data)))
|
||||
|
||||
if not per_key_payloads:
|
||||
transfer_data = self._serialize_transfer_payload(kv_data)
|
||||
per_key_payloads = [(put_key, transfer_data) for put_key in send_keys]
|
||||
|
||||
serialization_ms = (time.perf_counter() - serialization_start) * 1000
|
||||
logger.info("KV cache serialized for %s in %.1f ms", transfer_req_id, serialization_ms)
|
||||
|
||||
transfer_start = time.perf_counter()
|
||||
success, size, _ = self._transfer_with_retry(from_stage, to_stage, f"kv_cache_{transfer_req_id}", transfer_data)
|
||||
total_size = 0
|
||||
all_succeeded = True
|
||||
for put_key, transfer_data in per_key_payloads:
|
||||
success, size, _ = self._transfer_with_retry(from_stage, to_stage, put_key, transfer_data)
|
||||
total_size += size
|
||||
all_succeeded = all_succeeded and success
|
||||
|
||||
elapsed = time.perf_counter() - transfer_start
|
||||
|
||||
if success:
|
||||
mbps = (size / 1024 / 1024) / elapsed if elapsed > 0 else 0
|
||||
if all_succeeded:
|
||||
mbps = (total_size / 1024 / 1024) / elapsed if elapsed > 0 else 0
|
||||
logger.info(
|
||||
"KV transfer OK: %s, %s bytes, %.3fs, %.1f MB/s",
|
||||
"KV transfer OK: %s, %s bytes across %s key(s), %.3fs, %.1f MB/s",
|
||||
transfer_req_id,
|
||||
size,
|
||||
total_size,
|
||||
len(send_keys),
|
||||
elapsed,
|
||||
mbps,
|
||||
)
|
||||
@@ -731,7 +932,7 @@ class OmniKVTransferManager:
|
||||
self,
|
||||
from_stage: str,
|
||||
to_stage: str,
|
||||
request_id: str,
|
||||
put_key: str,
|
||||
data: "dict[str, Any] | bytes | torch.Tensor",
|
||||
max_retries: int = 3,
|
||||
) -> tuple[bool, int, dict[str, Any] | None]:
|
||||
@@ -740,7 +941,7 @@ class OmniKVTransferManager:
|
||||
Args:
|
||||
from_stage: Source stage identifier
|
||||
to_stage: Target stage identifier
|
||||
request_id: Request identifier for the key
|
||||
put_key: Pre-built connector key (rank-aware when TP > 1)
|
||||
data: Data to transfer
|
||||
max_retries: Maximum number of retry attempts
|
||||
|
||||
@@ -749,14 +950,12 @@ class OmniKVTransferManager:
|
||||
"""
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
# Build the full key for connector
|
||||
full_request_id = f"omni_{from_stage}_to_{to_stage}_{request_id}"
|
||||
success, size, metadata = self.connector.put(
|
||||
from_stage=from_stage, to_stage=to_stage, put_key=full_request_id, data=data
|
||||
from_stage=from_stage, to_stage=to_stage, put_key=put_key, data=data
|
||||
)
|
||||
if success:
|
||||
return success, size, metadata
|
||||
logger.warning(f"Transfer attempt {attempt + 1} failed for {request_id}")
|
||||
logger.warning(f"Transfer attempt {attempt + 1} failed for {put_key}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Transfer attempt {attempt + 1} exception: {e}")
|
||||
|
||||
@@ -801,22 +1000,46 @@ class OmniKVTransferManager:
|
||||
poll_interval = 0.01
|
||||
max_poll_interval = 0.5
|
||||
|
||||
logger.info(f"Wait for KV cache for request {request_id} from stage {from_stage} to {to_stage}...")
|
||||
topo = self._tp_topo
|
||||
recv_key_pairs = build_rank_aware_recv_keys(
|
||||
request_id, from_stage, to_stage, topo, hook=self.kv_recv_key_builder
|
||||
)
|
||||
pending_pairs = list(recv_key_pairs)
|
||||
received_payloads: dict[str, tuple[dict[str, Any], int]] = {}
|
||||
|
||||
logger.info(
|
||||
"Wait for KV cache for request %s from stage %s to %s via %s key(s)...",
|
||||
request_id,
|
||||
from_stage,
|
||||
to_stage,
|
||||
len(recv_key_pairs),
|
||||
)
|
||||
|
||||
try:
|
||||
while True:
|
||||
# Build the full key for connector
|
||||
full_request_id = f"omni_{from_stage}_to_{to_stage}_kv_cache_{request_id}"
|
||||
link_start = time.perf_counter()
|
||||
result = self.connector.get(
|
||||
from_stage=from_stage,
|
||||
to_stage=to_stage,
|
||||
get_key=full_request_id,
|
||||
)
|
||||
if result:
|
||||
for get_key, from_rank in list(pending_pairs):
|
||||
# Construct per-rank metadata so the connector queries
|
||||
# the correct sender endpoint (heterogeneous TP path).
|
||||
# When from_rank is None (TP<=1), metadata stays None
|
||||
# and the connector falls back to its default sender.
|
||||
rank_metadata: dict[str, Any] | None = None
|
||||
if from_rank is not None and self._sender_base_host and self._sender_base_zmq_port is not None:
|
||||
rank_metadata = {
|
||||
"source_host": self._sender_base_host,
|
||||
"source_port": self._sender_base_zmq_port + from_rank * KV_RANK_PORT_STRIDE,
|
||||
}
|
||||
|
||||
result = self.connector.get(
|
||||
from_stage=from_stage,
|
||||
to_stage=to_stage,
|
||||
get_key=get_key,
|
||||
metadata=rank_metadata,
|
||||
)
|
||||
if not result:
|
||||
continue
|
||||
|
||||
raw_data, size = result
|
||||
elapsed = time.time() - start_time
|
||||
link_ms = (time.perf_counter() - link_start) * 1000
|
||||
managed_buffer = None
|
||||
|
||||
if hasattr(raw_data, "tensor") and hasattr(raw_data, "release"):
|
||||
@@ -844,6 +1067,21 @@ class OmniKVTransferManager:
|
||||
else:
|
||||
data = raw_data
|
||||
|
||||
received_payloads[get_key] = (data, size)
|
||||
pending_pairs.remove((get_key, from_rank))
|
||||
|
||||
if not pending_pairs and received_payloads:
|
||||
elapsed = time.time() - start_time
|
||||
link_ms = (time.perf_counter() - link_start) * 1000
|
||||
ordered_payloads = [received_payloads[key][0] for key, _ in recv_key_pairs]
|
||||
total_size = sum(received_payloads[key][1] for key, _ in recv_key_pairs)
|
||||
|
||||
if len(ordered_payloads) == 1:
|
||||
data = ordered_payloads[0]
|
||||
else:
|
||||
data = merge_received_rank_shards(ordered_payloads, merger=self.kv_payload_merger)
|
||||
data = slice_received_rank_shard(data, topo, slicer=self.kv_payload_slicer)
|
||||
|
||||
try:
|
||||
if isinstance(data, dict) and "layer_blocks" in data:
|
||||
layer_blocks = data["layer_blocks"]
|
||||
@@ -856,18 +1094,18 @@ class OmniKVTransferManager:
|
||||
continue
|
||||
if target_device is not None and tensor.device != target_device:
|
||||
cache_list[i] = tensor.to(target_device).contiguous()
|
||||
finally:
|
||||
if managed_buffer is not None:
|
||||
managed_buffer.release()
|
||||
except Exception:
|
||||
logger.exception("Failed to move KV cache tensors to target device")
|
||||
|
||||
logger.info(
|
||||
"Successfully received KV cache for %s, %s bytes, wait=%.3fs, link=%.1fms",
|
||||
"Successfully received KV cache for %s, %s bytes across %s key(s), wait=%.3fs, link=%.1fms",
|
||||
request_id,
|
||||
size,
|
||||
total_size,
|
||||
len(recv_key_pairs),
|
||||
elapsed,
|
||||
link_ms,
|
||||
)
|
||||
return data, size
|
||||
return data, total_size
|
||||
|
||||
if time.time() - start_time > timeout:
|
||||
logger.error(f"Timeout waiting for KV cache for request {request_id} after {timeout}s")
|
||||
@@ -876,11 +1114,8 @@ class OmniKVTransferManager:
|
||||
time.sleep(poll_interval)
|
||||
poll_interval = min(poll_interval * 2, max_poll_interval)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error receiving KV cache for {request_id}: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
except Exception:
|
||||
logger.exception("Error receiving KV cache for %s", request_id)
|
||||
return None, 0
|
||||
|
||||
def apply_kv_cache_to_request(self, req: Any, data: dict[str, Any]) -> None:
|
||||
@@ -994,73 +1229,79 @@ class OmniKVTransferManager:
|
||||
cfg_kv_collect_func: Callable | None = None,
|
||||
target_device: torch.device | None = None,
|
||||
) -> bool:
|
||||
"""Broadcast-aware wrapper around :meth:`receive_multi_kv_cache`.
|
||||
"""Distributed wrapper around :meth:`receive_multi_kv_cache`.
|
||||
|
||||
SharedMemory connector is single-reader: once rank 0 consumes the
|
||||
segment it is deleted. For multi-GPU stages (e.g. sequence-parallel)
|
||||
only rank 0 receives; the result is then broadcast to every other
|
||||
rank via the world process-group.
|
||||
|
||||
For single-worker stages this is equivalent to calling
|
||||
:meth:`receive_multi_kv_cache` directly.
|
||||
TP-aware path selection:
|
||||
- world size 1: direct receive
|
||||
- TP active, cfg size 1: each rank independently receives
|
||||
- TP active, cfg size > 1: cfg-rank 0 receives, then broadcasts to
|
||||
peers that share the same TP rank
|
||||
- TP inactive: legacy rank-0 receive then world broadcast
|
||||
"""
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_world_group
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
get_cfg_group,
|
||||
get_classifier_free_guidance_rank,
|
||||
get_classifier_free_guidance_world_size,
|
||||
get_world_group,
|
||||
)
|
||||
|
||||
world = get_world_group()
|
||||
|
||||
if world.world_size <= 1:
|
||||
return self.receive_multi_kv_cache(req, cfg_kv_collect_func, target_device)
|
||||
|
||||
# --- rank 0: receive to CPU (needed for pickle-based broadcast) ---
|
||||
topo = self._tp_topo
|
||||
tp_active = topo.source_tp_size > 1 or topo.target_tp_size > 1
|
||||
cfg_size = 1
|
||||
cfg_rank = 0
|
||||
cfg_group = None
|
||||
try:
|
||||
cfg_size = get_classifier_free_guidance_world_size()
|
||||
cfg_rank = get_classifier_free_guidance_rank()
|
||||
cfg_group = get_cfg_group()
|
||||
except Exception:
|
||||
cfg_size = 1
|
||||
cfg_rank = 0
|
||||
cfg_group = None
|
||||
|
||||
if tp_active and cfg_size <= 1:
|
||||
logger.info(
|
||||
"Rank-aware KV receive: rank %s independently receiving (from_tp=%s, to_tp=%s)",
|
||||
topo.local_rank,
|
||||
topo.source_tp_size,
|
||||
topo.target_tp_size,
|
||||
)
|
||||
return self.receive_multi_kv_cache(req, cfg_kv_collect_func, target_device)
|
||||
|
||||
if tp_active and cfg_size > 1 and cfg_group is not None:
|
||||
kv_payload: dict[str, object] | None = None
|
||||
if cfg_rank == 0:
|
||||
received = self.receive_multi_kv_cache(req, cfg_kv_collect_func, torch.device("cpu"))
|
||||
rank_payloads = self._build_cfg_rank_local_payloads(req, cfg_size) if received else [None] * cfg_size
|
||||
kv_payload = rank_payloads[0]
|
||||
for dst_rank in range(1, cfg_size):
|
||||
cfg_group.send_object(rank_payloads[dst_rank], dst_rank)
|
||||
else:
|
||||
kv_payload = cfg_group.recv_object(0)
|
||||
|
||||
if not kv_payload:
|
||||
return False
|
||||
|
||||
self._apply_request_kv_payload(req, kv_payload, target_device)
|
||||
return True
|
||||
|
||||
kv_payload: dict[str, object] | None = None
|
||||
if world.rank_in_group == 0:
|
||||
self.receive_multi_kv_cache(req, cfg_kv_collect_func, torch.device("cpu"))
|
||||
received = self.receive_multi_kv_cache(req, cfg_kv_collect_func, torch.device("cpu"))
|
||||
if received:
|
||||
kv_payload = self._collect_request_kv_payload(req)
|
||||
|
||||
kv_payload: dict[str, object] = {}
|
||||
for attr in ("past_key_values", "kv_metadata"):
|
||||
val = getattr(req, attr, None)
|
||||
if val is not None:
|
||||
kv_payload[attr] = val
|
||||
kv_payload = world.broadcast_object(kv_payload, src=0)
|
||||
|
||||
if hasattr(req, "sampling_params") and req.sampling_params is not None:
|
||||
for key in list(vars(req.sampling_params).keys()):
|
||||
if (key.startswith("cfg_") and key.endswith("_past_key_values")) or key in (
|
||||
"past_key_values",
|
||||
"kv_metadata",
|
||||
):
|
||||
val = getattr(req.sampling_params, key, None)
|
||||
if val is not None:
|
||||
kv_payload[f"sp.{key}"] = val
|
||||
|
||||
payload_list = [kv_payload]
|
||||
# Use broadcast_object_list (pickle-based) instead of broadcast_tensor_dict
|
||||
# because the KV cache is a heterogeneous nested structure (NaiveCache objects
|
||||
# with metadata + tensors), not a flat tensor dict. This runs once before
|
||||
# the denoising loop so the serialization cost is negligible.
|
||||
torch.distributed.broadcast_object_list(payload_list, src=world.ranks[0], group=world.cpu_group)
|
||||
kv_payload = payload_list[0]
|
||||
else:
|
||||
payload_list: list[dict[str, object] | None] = [None]
|
||||
torch.distributed.broadcast_object_list(payload_list, src=world.ranks[0], group=world.cpu_group)
|
||||
kv_payload = payload_list[0]
|
||||
|
||||
# --- apply on ALL ranks (rank 0 also needs CPU→GPU move) ---
|
||||
if not kv_payload:
|
||||
return False
|
||||
|
||||
for attr in ("past_key_values", "kv_metadata"):
|
||||
val = kv_payload.get(attr)
|
||||
if val is not None:
|
||||
if target_device is not None:
|
||||
val = _move_to_device(val, target_device)
|
||||
setattr(req, attr, val)
|
||||
|
||||
if hasattr(req, "sampling_params") and req.sampling_params is not None:
|
||||
for key, val in kv_payload.items():
|
||||
if key.startswith("sp."):
|
||||
if target_device is not None:
|
||||
val = _move_to_device(val, target_device)
|
||||
setattr(req.sampling_params, key[3:], val)
|
||||
|
||||
self._apply_request_kv_payload(req, kv_payload, target_device)
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ class OmniChunkTransferAdapter(OmniTransferAdapterBase):
|
||||
self.waiting_for_chunk_waiting_requests: deque[Any] = deque()
|
||||
self.waiting_for_chunk_running_requests: deque[Any] = deque()
|
||||
self.requests_with_ready_chunks = set()
|
||||
self.requests_origin_status = {}
|
||||
|
||||
@classmethod
|
||||
def create_connector(cls, model_config: Any):
|
||||
@@ -279,6 +280,7 @@ class OmniChunkTransferAdapter(OmniTransferAdapterBase):
|
||||
self.get_req_chunk.pop(request_id, None)
|
||||
self.requests_with_ready_chunks.discard(request_id)
|
||||
self.request_ids_mapping.pop(request_id, None)
|
||||
self.requests_origin_status.pop(request_id, None)
|
||||
|
||||
self._cancelled_load_reqs.add(request_id)
|
||||
self._finished_load_reqs.discard(request_id)
|
||||
@@ -408,6 +410,7 @@ class OmniChunkTransferAdapter(OmniTransferAdapterBase):
|
||||
self.requests_with_ready_chunks.add(request.request_id)
|
||||
continue
|
||||
queue.remove(request)
|
||||
self.requests_origin_status[request.request_id] = target_status
|
||||
waiting_for_chunk_list.append(request)
|
||||
|
||||
def _clear_chunk_ready(self, scheduler_output: Any) -> None:
|
||||
@@ -420,3 +423,23 @@ class OmniChunkTransferAdapter(OmniTransferAdapterBase):
|
||||
for req_id in scheduler_output.scheduled_cached_reqs.req_ids:
|
||||
if req_id in self.requests_with_ready_chunks:
|
||||
self.requests_with_ready_chunks.remove(req_id)
|
||||
|
||||
def finish_requests(
|
||||
self, request_ids: Any, finished_status: RequestStatus, requests: dict[str, Request] | None = None
|
||||
) -> list[tuple[str, int]]:
|
||||
assert RequestStatus.is_finished(finished_status)
|
||||
if isinstance(request_ids, str):
|
||||
request_ids = (request_ids,)
|
||||
elif request_ids is not None:
|
||||
request_ids = set(request_ids)
|
||||
else:
|
||||
request_ids = requests.keys()
|
||||
|
||||
# First pass: collect requests to remove from queues
|
||||
for req_id in request_ids:
|
||||
request = requests.get(req_id) if requests else None
|
||||
if request is None or request.is_finished():
|
||||
# Invalid request ID.
|
||||
continue
|
||||
if req_id in self.requests_origin_status:
|
||||
request.status = self.requests_origin_status.pop(req_id)
|
||||
@@ -206,6 +206,19 @@ def load_omni_transfer_config(
|
||||
if config_dict is None:
|
||||
return None
|
||||
|
||||
# Normalize new-schema (top-level ``connectors`` + ``stages``) into the
|
||||
# legacy ``runtime.connectors`` + ``stage_args`` shape the parser reads.
|
||||
if "stages" in config_dict and "stage_args" not in config_dict:
|
||||
normalized: dict[str, Any] = dict(config_dict)
|
||||
runtime = dict(normalized.get("runtime") or {})
|
||||
if "connectors" in normalized and "connectors" not in runtime:
|
||||
runtime["connectors"] = normalized["connectors"]
|
||||
if "edges" in normalized and "edges" not in runtime:
|
||||
runtime["edges"] = normalized["edges"]
|
||||
normalized["runtime"] = runtime
|
||||
normalized["stage_args"] = normalized["stages"]
|
||||
config_dict = normalized
|
||||
|
||||
# Parse connectors
|
||||
connectors = {}
|
||||
runtime_config = config_dict.get("runtime", {})
|
||||
|
||||
@@ -1,15 +1,380 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Utility helpers for KV cache manipulation."""
|
||||
"""Utility helpers for KV cache manipulation, TP routing, and merge/slice."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from vllm.distributed.parallel_state import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from .initialization import KV_RANK_PORT_STRIDE, KV_TRANSFER_PORT_OFFSET
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
LayerKV = torch.Tensor | tuple[torch.Tensor, torch.Tensor]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# TP Topology
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KVTPTopology:
|
||||
"""Immutable descriptor for a KV-transfer parallel mapping.
|
||||
|
||||
Captures sender/receiver parallel sizes and the local rank within
|
||||
that parallel dimension. Works for any divisible parallel dimension
|
||||
(TP, SP, Ring Attention).
|
||||
"""
|
||||
|
||||
source_tp_size: int
|
||||
target_tp_size: int
|
||||
local_rank: int
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.source_tp_size <= 0 or self.target_tp_size <= 0:
|
||||
raise ValueError(
|
||||
f"Parallel sizes must be positive: "
|
||||
f"source_tp_size={self.source_tp_size}, target_tp_size={self.target_tp_size}"
|
||||
)
|
||||
if self.local_rank < 0:
|
||||
raise ValueError(f"local_rank must be non-negative, got {self.local_rank}")
|
||||
|
||||
@property
|
||||
def is_heterogeneous(self) -> bool:
|
||||
return self.source_tp_size != self.target_tp_size
|
||||
|
||||
@property
|
||||
def ratio(self) -> int:
|
||||
"""Larger parallel size divided by smaller. Always >= 1."""
|
||||
return max(self.source_tp_size, self.target_tp_size) // min(self.source_tp_size, self.target_tp_size)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Runtime TP detection
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
|
||||
def get_local_tp_rank() -> int:
|
||||
"""Return the TP-local rank of this worker process.
|
||||
|
||||
Uses ``get_tensor_model_parallel_rank()`` which returns the rank
|
||||
within the TP group only, not the stage-global rank.
|
||||
"""
|
||||
try:
|
||||
return get_tensor_model_parallel_rank()
|
||||
except Exception:
|
||||
logger.debug("TP parallel state not initialized, falling back to LOCAL_RANK env", exc_info=True)
|
||||
try:
|
||||
return int(os.environ.get("LOCAL_RANK", "0"))
|
||||
except (ValueError, TypeError):
|
||||
return 0
|
||||
|
||||
|
||||
def get_tp_world_size() -> int:
|
||||
"""Return the TP world size (tensor-parallel dimension only).
|
||||
|
||||
Uses ``get_tensor_model_parallel_world_size()`` so that
|
||||
cfg_parallel, SP, PP etc. are not included in the count.
|
||||
"""
|
||||
try:
|
||||
return get_tensor_model_parallel_world_size()
|
||||
except Exception:
|
||||
logger.debug("TP parallel state not initialized, defaulting world_size=1", exc_info=True)
|
||||
return 1
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# ZMQ port computation
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
|
||||
def kv_zmq_port(base_port: int, from_stage: int, local_rank: int = 0) -> int:
|
||||
"""Compute the ZMQ port for a KV-transfer connector.
|
||||
|
||||
Each TP rank gets its own port so that TP > 1 deployments do not
|
||||
cause ``EADDRINUSE`` when multiple sender workers bind on the same
|
||||
host. The formula is backward-compatible: rank 0 produces the same
|
||||
port as the previous ``base + OFFSET + stage`` formula.
|
||||
"""
|
||||
return base_port + KV_TRANSFER_PORT_OFFSET + local_rank * KV_RANK_PORT_STRIDE + from_stage
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# TP topology validation and rank routing
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
|
||||
def validate_kv_tp_topology(topo: KVTPTopology) -> None:
|
||||
"""Reject heterogeneous TP mappings that cannot be routed losslessly."""
|
||||
larger = max(topo.source_tp_size, topo.target_tp_size)
|
||||
smaller = min(topo.source_tp_size, topo.target_tp_size)
|
||||
if larger % smaller != 0:
|
||||
raise ValueError(
|
||||
f"KV TP mapping must be divisible: "
|
||||
f"source_tp_size={topo.source_tp_size}, "
|
||||
f"target_tp_size={topo.target_tp_size}"
|
||||
)
|
||||
|
||||
|
||||
def get_kv_target_ranks(topo: KVTPTopology) -> list[int]:
|
||||
"""Which remote ranks this local rank sends KV shards to (send side)."""
|
||||
validate_kv_tp_topology(topo)
|
||||
if topo.source_tp_size == topo.target_tp_size:
|
||||
return [topo.local_rank]
|
||||
if topo.source_tp_size > topo.target_tp_size:
|
||||
return [topo.local_rank // (topo.source_tp_size // topo.target_tp_size)]
|
||||
ratio = topo.target_tp_size // topo.source_tp_size
|
||||
return [topo.local_rank * ratio + i for i in range(ratio)]
|
||||
|
||||
|
||||
def get_kv_source_ranks(topo: KVTPTopology) -> list[int]:
|
||||
"""Which remote ranks this local rank receives KV shards from (recv side)."""
|
||||
validate_kv_tp_topology(topo)
|
||||
if topo.source_tp_size == topo.target_tp_size:
|
||||
return [topo.local_rank]
|
||||
if topo.source_tp_size > topo.target_tp_size:
|
||||
ratio = topo.source_tp_size // topo.target_tp_size
|
||||
return [topo.local_rank * ratio + i for i in range(ratio)]
|
||||
return [topo.local_rank // (topo.target_tp_size // topo.source_tp_size)]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Rank-aware connector key building
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
|
||||
def get_kv_connector_key(
|
||||
req_id: str,
|
||||
from_stage: int | str,
|
||||
chunk_id: int,
|
||||
from_rank: int,
|
||||
to_rank: int,
|
||||
) -> str:
|
||||
"""Build connector key that includes rank info for KV transfers.
|
||||
|
||||
Format matches PR #2677: ``{req_id}_{from_stage}_{chunk_id}_{from_rank}_{to_rank}``
|
||||
"""
|
||||
return f"{req_id}_{from_stage}_{chunk_id}_{from_rank}_{to_rank}"
|
||||
|
||||
|
||||
def build_rank_aware_send_keys(
|
||||
request_id: str,
|
||||
from_stage: str,
|
||||
to_stage: str,
|
||||
topo: KVTPTopology,
|
||||
hook: Callable | None = None,
|
||||
) -> list[str]:
|
||||
"""Build send-side connector keys, checking injectable hook first."""
|
||||
if callable(hook):
|
||||
keys = list(hook(request_id, from_stage, to_stage))
|
||||
if keys:
|
||||
return keys
|
||||
if topo.source_tp_size <= 1 and topo.target_tp_size <= 1:
|
||||
return [f"omni_{from_stage}_to_{to_stage}_kv_cache_{request_id}"]
|
||||
target_ranks = get_kv_target_ranks(topo)
|
||||
return [get_kv_connector_key(request_id, from_stage, 0, topo.local_rank, r) for r in target_ranks]
|
||||
|
||||
|
||||
def build_rank_aware_recv_keys(
|
||||
request_id: str,
|
||||
from_stage: str,
|
||||
to_stage: str,
|
||||
topo: KVTPTopology,
|
||||
hook: Callable | None = None,
|
||||
) -> list[tuple[str, int | None]]:
|
||||
"""Build recv-side connector keys with sender rank info.
|
||||
|
||||
Returns a list of ``(key, from_rank)`` tuples. ``from_rank`` is
|
||||
``None`` when TP <= 1 (single sender, no per-rank routing needed).
|
||||
For TP > 1, ``from_rank`` identifies which sender rank owns the
|
||||
key so that the connector can route metadata queries to the
|
||||
correct endpoint.
|
||||
"""
|
||||
if callable(hook):
|
||||
raw = list(hook(request_id, from_stage, to_stage))
|
||||
if raw:
|
||||
if isinstance(raw[0], tuple):
|
||||
return raw
|
||||
# Hook returned plain strings (e.g. OmniConnectorModelRunnerMixin.
|
||||
# get_rank_aware_kv_keys). Reconstruct from_rank from topology so
|
||||
# Mooncake connector can route metadata queries to the correct
|
||||
# sender endpoint in heterogeneous TP.
|
||||
# TODO: have the mixin return (key, from_rank) tuples directly
|
||||
# to avoid this indirect reconstruction.
|
||||
source_ranks = get_kv_source_ranks(topo)
|
||||
if len(raw) == len(source_ranks):
|
||||
return list(zip(raw, source_ranks))
|
||||
return [(k, None) for k in raw]
|
||||
if topo.source_tp_size <= 1 and topo.target_tp_size <= 1:
|
||||
return [(f"omni_{from_stage}_to_{to_stage}_kv_cache_{request_id}", None)]
|
||||
source_ranks = get_kv_source_ranks(topo)
|
||||
return [(get_kv_connector_key(request_id, from_stage, 0, r, topo.local_rank), r) for r in source_ranks]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# KV tensor head slicing (heterogeneous TP)
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
|
||||
def slice_kv_tensor_heads(
|
||||
tensor: torch.Tensor | None,
|
||||
offset_in_shard: int,
|
||||
num_slices: int,
|
||||
) -> torch.Tensor | None:
|
||||
"""Slice one KV tensor along its head dimension (dim 1)."""
|
||||
if tensor is None:
|
||||
return None
|
||||
if not isinstance(tensor, torch.Tensor):
|
||||
return tensor
|
||||
if tensor.dim() < 2:
|
||||
raise ValueError(f"Expected KV tensor with a head dimension, got shape={tuple(tensor.shape)}")
|
||||
if num_slices <= 0:
|
||||
raise ValueError(f"num_slices must be > 0, got {num_slices}")
|
||||
if not (0 <= offset_in_shard < num_slices):
|
||||
raise ValueError(f"offset_in_shard must be in [0, {num_slices}), got {offset_in_shard}")
|
||||
|
||||
heads_in_shard = tensor.shape[1]
|
||||
if heads_in_shard % num_slices != 0:
|
||||
raise ValueError(
|
||||
"KV head count must be divisible for heterogeneous TP slicing: "
|
||||
f"heads_in_shard={heads_in_shard}, num_slices={num_slices}"
|
||||
)
|
||||
|
||||
heads_per_slice = heads_in_shard // num_slices
|
||||
start = offset_in_shard * heads_per_slice
|
||||
end = start + heads_per_slice
|
||||
return tensor[:, start:end, ...].contiguous()
|
||||
|
||||
|
||||
def slice_layer_blocks(
|
||||
layer_blocks: dict[str, Any],
|
||||
offset_in_shard: int,
|
||||
num_slices: int,
|
||||
) -> dict[str, list[torch.Tensor | None]]:
|
||||
"""Slice all KV layers for one logical receiver rank."""
|
||||
sliced_blocks: dict[str, list[torch.Tensor | None]] = {}
|
||||
for cache_name in ("key_cache", "value_cache"):
|
||||
cache_list = layer_blocks.get(cache_name, [])
|
||||
sliced_blocks[cache_name] = [
|
||||
slice_kv_tensor_heads(tensor, offset_in_shard, num_slices) for tensor in cache_list
|
||||
]
|
||||
return sliced_blocks
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Multi-rank merge and receiver-side slice
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
|
||||
def merge_received_rank_shards(
|
||||
payloads: list[dict[str, Any]],
|
||||
merger: Callable | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Merge multiple source-rank KV shards for one target rank.
|
||||
|
||||
When *merger* is provided (injectable hook), it is called directly.
|
||||
Otherwise the default merges along the head dimension (dim 1).
|
||||
"""
|
||||
if callable(merger):
|
||||
return merger(payloads)
|
||||
if not payloads:
|
||||
return None
|
||||
if len(payloads) == 1:
|
||||
return payloads[0]
|
||||
|
||||
base_payload = payloads[0]
|
||||
if not isinstance(base_payload, dict) or "layer_blocks" not in base_payload:
|
||||
return base_payload
|
||||
|
||||
merged: dict[str, Any] = {
|
||||
"request_id": base_payload.get("request_id"),
|
||||
"block_ids": list(base_payload.get("block_ids", [])),
|
||||
"metadata": dict(base_payload.get("metadata", {})),
|
||||
}
|
||||
merged_layer_blocks: dict[str, list[torch.Tensor | None]] = {}
|
||||
|
||||
for cache_name in ("key_cache", "value_cache"):
|
||||
cache_lists = [payload.get("layer_blocks", {}).get(cache_name, []) for payload in payloads]
|
||||
num_layers = max((len(cache_list) for cache_list in cache_lists), default=0)
|
||||
merged_cache: list[torch.Tensor | None] = []
|
||||
|
||||
for layer_idx in range(num_layers):
|
||||
layer_tensors = [
|
||||
cache_list[layer_idx]
|
||||
for cache_list in cache_lists
|
||||
if layer_idx < len(cache_list) and cache_list[layer_idx] is not None
|
||||
]
|
||||
if not layer_tensors:
|
||||
merged_cache.append(None)
|
||||
elif len(layer_tensors) == 1 or not isinstance(layer_tensors[0], torch.Tensor):
|
||||
merged_cache.append(layer_tensors[0])
|
||||
else:
|
||||
merged_cache.append(torch.cat(layer_tensors, dim=1).contiguous())
|
||||
|
||||
merged_layer_blocks[cache_name] = merged_cache
|
||||
|
||||
merged["layer_blocks"] = merged_layer_blocks
|
||||
return merged
|
||||
|
||||
|
||||
def slice_received_rank_shard(
|
||||
payload: dict[str, Any] | None,
|
||||
topo: KVTPTopology,
|
||||
slicer: Callable | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Optionally slice a received payload to extract this rank's portion.
|
||||
|
||||
Used when ``to_tp > from_tp``: the sender sent full heads and each
|
||||
receiver rank slices out its own subset.
|
||||
"""
|
||||
if callable(slicer):
|
||||
return slicer(payload)
|
||||
if not payload or topo.target_tp_size <= topo.source_tp_size or "layer_blocks" not in payload:
|
||||
return payload
|
||||
|
||||
metadata = payload.get("metadata", {})
|
||||
slice_metadata = metadata.get("tp_head_slice") if isinstance(metadata, dict) else None
|
||||
if isinstance(slice_metadata, dict) and slice_metadata.get("applied"):
|
||||
tagged_rank = slice_metadata.get("target_rank")
|
||||
if tagged_rank is not None and tagged_rank != topo.local_rank:
|
||||
logger.warning(
|
||||
"Received pre-sliced KV payload for unexpected target rank: expected=%s got=%s",
|
||||
topo.local_rank,
|
||||
tagged_rank,
|
||||
)
|
||||
return payload
|
||||
|
||||
ratio = topo.target_tp_size // topo.source_tp_size
|
||||
offset_in_sender = topo.local_rank % ratio
|
||||
updated_metadata = dict(metadata) if isinstance(metadata, dict) else {}
|
||||
updated_metadata["tp_head_slice"] = {
|
||||
"applied": True,
|
||||
"side": "receiver",
|
||||
"target_rank": topo.local_rank,
|
||||
"from_tp": topo.source_tp_size,
|
||||
"to_tp": topo.target_tp_size,
|
||||
"offset_in_shard": offset_in_sender,
|
||||
"num_slices": ratio,
|
||||
}
|
||||
return {
|
||||
"request_id": payload.get("request_id"),
|
||||
"layer_blocks": slice_layer_blocks(payload["layer_blocks"], offset_in_sender, ratio),
|
||||
"block_ids": list(payload.get("block_ids", [])),
|
||||
"metadata": updated_metadata,
|
||||
}
|
||||
|
||||
|
||||
def normalize_layer_kv(
|
||||
layer_kv: LayerKV,
|
||||
*,
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from .load_balancer import (
|
||||
LeastQueueLengthBalancer,
|
||||
LoadBalancer,
|
||||
LoadBalancingPolicy,
|
||||
RandomBalancer,
|
||||
RoundRobinBalancer,
|
||||
Task,
|
||||
)
|
||||
from .messages import InstanceEvent, InstanceInfo, InstanceList, StageStatus
|
||||
@@ -24,4 +26,6 @@ __all__ = [
|
||||
"LoadBalancer",
|
||||
"LoadBalancingPolicy",
|
||||
"RandomBalancer",
|
||||
"RoundRobinBalancer",
|
||||
"LeastQueueLengthBalancer",
|
||||
]
|
||||
@@ -4,6 +4,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import threading
|
||||
from abc import ABC, abstractmethod
|
||||
from enum import Enum
|
||||
from typing import Any, TypedDict
|
||||
@@ -26,11 +27,16 @@ class Task(TypedDict, total=False):
|
||||
class LoadBalancingPolicy(str, Enum):
|
||||
"""Enumeration for load balancing policies.
|
||||
|
||||
Only ``RANDOM`` is implemented. Additional policies (e.g. round-robin,
|
||||
least-connections) can be added in the future.
|
||||
These policies are used by :class:`LoadBalancer` implementations to route
|
||||
tasks to a subset of available instances.
|
||||
|
||||
TODO(NumberWan): Map enum values to balancer classes when OmniCoordinator
|
||||
integration lands. Tracked in https://github.com/vllm-project/vllm-omni/pull/2448
|
||||
"""
|
||||
|
||||
RANDOM = "random"
|
||||
ROUND_ROBIN = "round-robin"
|
||||
LEAST_QUEUE_LENGTH = "least-queue-length"
|
||||
|
||||
|
||||
class LoadBalancer(ABC):
|
||||
@@ -61,10 +67,10 @@ class LoadBalancer(ABC):
|
||||
class RandomBalancer(LoadBalancer):
|
||||
"""Load balancer that selects an instance uniformly at random.
|
||||
|
||||
This is the initial and only policy supported. It intentionally ignores
|
||||
the task payload and chooses a random index from the provided instance
|
||||
list. More sophisticated policies (e.g. round-robin, least-connections)
|
||||
can be implemented as additional subclasses of :class:`LoadBalancer`.
|
||||
It intentionally ignores the task payload and chooses a random index from
|
||||
the provided instance list. More sophisticated policies (e.g. round-robin,
|
||||
least-queue-length) can be implemented as additional subclasses of
|
||||
:class:`LoadBalancer`.
|
||||
"""
|
||||
|
||||
def select(self, task: Task, instances: list[InstanceInfo]) -> int: # noqa: ARG002
|
||||
@@ -74,9 +80,69 @@ class RandomBalancer(LoadBalancer):
|
||||
return random.randrange(len(instances))
|
||||
|
||||
|
||||
class RoundRobinBalancer(LoadBalancer):
|
||||
"""Load balancer that selects instances in a round-robin fashion.
|
||||
|
||||
This implementation keeps a running index modulo ``len(instances)``. It
|
||||
therefore depends on the **order and stable meaning** of the ``instances``
|
||||
list between calls. If the list length or ordering changes, the sequence
|
||||
of picks may skip or repeat entries relative to a fixed set of backends.
|
||||
|
||||
When instance membership changes dynamically, callers should reset routing
|
||||
state—for example by constructing a new ``RoundRobinBalancer`` or resetting
|
||||
``_next_index``—similar to rebuilding ``itertools.cycle`` after mutating
|
||||
the instance list (as in vLLM's disaggregated proxy examples).
|
||||
|
||||
Concurrency: ``select`` is synchronous and is expected to run on the
|
||||
coordinator asyncio event loop thread without ``await`` inside this
|
||||
method, so a single invocation is not interleaved with another on that
|
||||
thread. A :class:`threading.Lock` still serializes updates to
|
||||
``_next_index`` for callers that might invoke ``select`` from multiple
|
||||
threads or alongside threaded infrastructure (e.g. ZMQ receive threads).
|
||||
"""
|
||||
|
||||
def __init__(self, start_index: int = 0) -> None:
|
||||
self._next_index = start_index
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def select(self, task: Task, instances: list[InstanceInfo]) -> int: # noqa: ARG002
|
||||
if not instances:
|
||||
raise ValueError("instances must not be empty")
|
||||
|
||||
n = len(instances)
|
||||
with self._lock:
|
||||
idx = self._next_index % n
|
||||
self._next_index = (self._next_index + 1) % n
|
||||
return idx
|
||||
|
||||
|
||||
class LeastQueueLengthBalancer(LoadBalancer):
|
||||
"""Select the instance with the smallest ``queue_length``.
|
||||
|
||||
If multiple instances share the same minimum queue length, one of them is
|
||||
chosen uniformly at random.
|
||||
|
||||
Raises:
|
||||
ValueError: If any instance has a negative ``queue_length``.
|
||||
"""
|
||||
|
||||
def select(self, task: Task, instances: list[InstanceInfo]) -> int: # noqa: ARG002
|
||||
if not instances:
|
||||
raise ValueError("instances must not be empty")
|
||||
|
||||
queue_lengths = [inst.queue_length for inst in instances]
|
||||
if any(q < 0 for q in queue_lengths):
|
||||
raise ValueError("queue_length must be non-negative for all instances")
|
||||
min_q = min(queue_lengths)
|
||||
candidates = [i for i, q in enumerate(queue_lengths) if q == min_q]
|
||||
return random.choice(candidates)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"Task",
|
||||
"LoadBalancingPolicy",
|
||||
"LoadBalancer",
|
||||
"RandomBalancer",
|
||||
"RoundRobinBalancer",
|
||||
"LeastQueueLengthBalancer",
|
||||
]
|
||||
@@ -79,6 +79,10 @@ class OmniEngineCoreRequest(EngineCoreRequest):
|
||||
|
||||
class OmniEngineCoreOutput(EngineCoreOutput):
|
||||
pooling_output: dict[str, torch.Tensor] | None = None
|
||||
# Finished flag for streaming input segment
|
||||
is_segment_finished: bool | None = False
|
||||
# Streaming update prompt length
|
||||
new_prompt_len_snapshot: int | None = None
|
||||
|
||||
|
||||
class OmniEngineCoreOutputs(EngineCoreOutputs):
|
||||
|
||||
@@ -3,14 +3,15 @@ import dataclasses
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass, field, fields
|
||||
from typing import Any
|
||||
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs, EngineArgs
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.config import OmniModelConfig
|
||||
from vllm_omni.engine.output_modality import OutputModality
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
from vllm_omni.plugins import load_omni_general_plugins
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -21,6 +22,7 @@ _ARCH_TO_MODEL_TYPE: dict[str, str] = {
|
||||
"CosyVoice3Model": "cosyvoice3",
|
||||
"OmniVoiceModel": "omnivoice",
|
||||
"VoxCPM2TalkerForConditionalGeneration": "voxcpm2",
|
||||
"VoxCPMForConditionalGeneration": "voxcpm",
|
||||
}
|
||||
|
||||
# Maps model architecture names to tokenizer subfolder paths within HF repos.
|
||||
@@ -41,6 +43,7 @@ def _register_omni_hf_configs() -> None:
|
||||
from vllm_omni.model_executor.models.voxtral_tts.configuration_voxtral_tts import (
|
||||
VoxtralTTSConfig,
|
||||
)
|
||||
from vllm_omni.transformers_utils.configs.voxcpm import VoxCPMConfig
|
||||
from vllm_omni.transformers_utils.configs.voxcpm2 import VoxCPM2Config
|
||||
except Exception as exc: # pragma: no cover - best-effort optional registration
|
||||
logger.warning("Skipping omni HF config registration due to import error: %s", exc)
|
||||
@@ -59,6 +62,7 @@ def _register_omni_hf_configs() -> None:
|
||||
("cosyvoice3", CosyVoice3Config),
|
||||
("omnivoice", OmniVoiceConfig),
|
||||
("voxtral_tts", VoxtralTTSConfig),
|
||||
("voxcpm", VoxCPMConfig),
|
||||
("voxcpm2", VoxCPM2Config),
|
||||
]:
|
||||
try:
|
||||
@@ -136,11 +140,30 @@ class OmniEngineArgs(EngineArgs):
|
||||
hf_config_name: str | None = None
|
||||
custom_process_next_stage_input_func: str | None = None
|
||||
stage_connector_spec: dict[str, Any] = field(default_factory=dict)
|
||||
subtalker_sampling_params: dict[str, Any] | None = None
|
||||
async_chunk: bool = False
|
||||
omni_kv_config: dict | None = None
|
||||
quantization_config: Any | None = None
|
||||
worker_type: str | None = None
|
||||
task_type: str | None = None
|
||||
worker_cls: str = None
|
||||
enable_sleep_mode: bool = False
|
||||
omni: bool = False
|
||||
|
||||
@classmethod
|
||||
def _add_omni_specific_args(cls, parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
|
||||
try:
|
||||
parser.add_argument("--omni", action="store_true", default=False, help="Enable Omni engine features.")
|
||||
except argparse.ArgumentError:
|
||||
pass
|
||||
try:
|
||||
parser.add_argument(
|
||||
"--enable-sleep-mode", action="store_true", default=False, help="Enable GPU memory pool for sleep mode."
|
||||
)
|
||||
except argparse.ArgumentError:
|
||||
pass
|
||||
return parser
|
||||
|
||||
omni_master_address: str | None = None
|
||||
omni_master_port: int | None = None
|
||||
stage_configs_path: str | None = None
|
||||
@@ -149,6 +172,11 @@ class OmniEngineArgs(EngineArgs):
|
||||
custom_pipeline_args: dict[str, Any] | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.worker_cls is None:
|
||||
if self.worker_type == "ar":
|
||||
self.worker_cls = current_omni_platform.get_omni_ar_worker_cls()
|
||||
elif self.worker_type == "generation":
|
||||
self.worker_cls = current_omni_platform.get_omni_generation_worker_cls()
|
||||
load_omni_general_plugins()
|
||||
super().__post_init__()
|
||||
|
||||
@@ -288,12 +316,273 @@ class OmniEngineArgs(EngineArgs):
|
||||
hf_config_name=self.hf_config_name,
|
||||
custom_process_next_stage_input_func=self.custom_process_next_stage_input_func,
|
||||
stage_connector_config=stage_connector_config,
|
||||
subtalker_sampling_params=self.subtalker_sampling_params,
|
||||
omni_kv_config=self.omni_kv_config,
|
||||
task_type=self.task_type,
|
||||
)
|
||||
return omni_config
|
||||
|
||||
|
||||
@dataclass
|
||||
class OmniAsyncEngineArgs(AsyncEngineArgs, OmniEngineArgs):
|
||||
@classmethod
|
||||
def add_cli_args(cls, parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
|
||||
parser = AsyncEngineArgs.add_cli_args(parser)
|
||||
parser = OmniEngineArgs._add_omni_specific_args(parser)
|
||||
return parser
|
||||
|
||||
@property
|
||||
def output_modality(self) -> OutputModality:
|
||||
"""Parse engine_output_type into a type-safe OutputModality flag."""
|
||||
return OutputModality.from_string(self.engine_output_type)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# CLI argument routing
|
||||
# ============================================================================
|
||||
#
|
||||
# vLLM-Omni's CLI flags live in three buckets:
|
||||
#
|
||||
# ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
|
||||
# │ OrchestratorArgs │ │ OmniEngineArgs │ │ (upstream vllm) │
|
||||
# │ │ │ │ │ server/api │
|
||||
# │ stage_timeout │ │ max_num_seqs │ │ host, port │
|
||||
# │ worker_backend │ │ gpu_mem_util │ │ ssl_keyfile │
|
||||
# │ deploy_config │ │ dtype, quant │ │ api_key │
|
||||
# │ ... │ │ ... │ │ ... │
|
||||
# └──────────────────┘ └──────────────────┘ └──────────────────┘
|
||||
# │ │ │
|
||||
# ▼ ▼ ▼
|
||||
# orchestrator each stage uvicorn /
|
||||
# consumes engine FastAPI
|
||||
#
|
||||
# Fields in ``SHARED_FIELDS`` (e.g. ``model``, ``log_stats``) flow to BOTH
|
||||
# orchestrator and engine by design.
|
||||
#
|
||||
# Invariants enforced by ``tests/test_arg_utils.py``:
|
||||
#
|
||||
# 1. ``OrchestratorArgs`` ∩ ``OmniEngineArgs`` ⊆ ``SHARED_FIELDS``
|
||||
# 2. Every CLI flag is classifiable into one of the three buckets
|
||||
# 3. User-typed flags that match none of the above are logged as dropped
|
||||
#
|
||||
# Adding a new orchestrator-only flag → add a field to ``OrchestratorArgs``.
|
||||
# Everything else is automatic.
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OrchestratorArgs:
|
||||
"""CLI flags consumed by the orchestrator.
|
||||
|
||||
Contract: every field here is either
|
||||
(a) orchestrator-only (never needed by a stage engine), OR
|
||||
(b) orchestrator-read-then-redistributed (e.g. ``async_chunk`` is read
|
||||
from CLI, written to ``DeployConfig``, then propagated to every
|
||||
stage via ``merge_pipeline_deploy`` — not via direct kwargs
|
||||
forwarding).
|
||||
|
||||
Fields that BOTH orchestrator and engine genuinely need (e.g. ``model``,
|
||||
``log_stats``) should be listed in ``SHARED_FIELDS`` below; ``split_kwargs``
|
||||
will copy them to both buckets.
|
||||
"""
|
||||
|
||||
# === Lifecycle ===
|
||||
stage_init_timeout: int = 300
|
||||
init_timeout: int = 600
|
||||
|
||||
# === Cross-stage Communication ===
|
||||
shm_threshold_bytes: int = 65536
|
||||
batch_timeout: int = 10
|
||||
|
||||
# === Cluster / Backend ===
|
||||
worker_backend: str = "multi_process"
|
||||
ray_address: str | None = None
|
||||
|
||||
# === Config Files ===
|
||||
stage_configs_path: str | None = None
|
||||
deploy_config: str | None = None
|
||||
stage_overrides: str | None = None # raw JSON string; parsed downstream
|
||||
|
||||
# === Mode Switches (orchestrator reads, DeployConfig redistributes) ===
|
||||
async_chunk: bool | None = None
|
||||
|
||||
# === Observability ===
|
||||
log_stats: bool = False
|
||||
|
||||
# === Headless Mode (also forwarded to engine — see SHARED_FIELDS) ===
|
||||
stage_id: int | None = None
|
||||
|
||||
# === Pre-built Objects ===
|
||||
parallel_config: Any = None
|
||||
|
||||
# === Multi-stage guards ===
|
||||
# --tokenizer is captured here so it does not propagate to every stage
|
||||
# uniformly (different stages often need different tokenizers, e.g.
|
||||
# qwen3_omni thinker vs talker). Users wanting a per-stage tokenizer
|
||||
# should set it in the deploy YAML.
|
||||
tokenizer: str | None = None
|
||||
|
||||
|
||||
# Fields that live in BOTH OrchestratorArgs and OmniEngineArgs by design.
|
||||
# Changes to this set are a review red flag — revisit the contract.
|
||||
SHARED_FIELDS: frozenset[str] = frozenset(
|
||||
{
|
||||
"model", # orch: detect model_type; engine: load weights
|
||||
"stage_id", # orch: route (headless); engine: identity
|
||||
"log_stats", # both want the flag
|
||||
"stage_configs_path", # orch: load legacy YAML; engine: may reference for validation
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def orchestrator_field_names() -> frozenset[str]:
|
||||
"""Return the names of every field on OrchestratorArgs."""
|
||||
return frozenset(f.name for f in fields(OrchestratorArgs))
|
||||
|
||||
|
||||
def internal_blacklist_keys() -> frozenset[str]:
|
||||
"""Return the set of CLI keys that must never be forwarded as per-stage
|
||||
engine overrides.
|
||||
|
||||
Derived from ``OrchestratorArgs`` fields minus ``SHARED_FIELDS``, so
|
||||
adding a new orchestrator-owned flag is a one-line change to the
|
||||
dataclass — this function updates automatically.
|
||||
"""
|
||||
return orchestrator_field_names() - SHARED_FIELDS
|
||||
|
||||
|
||||
def split_kwargs(
|
||||
kwargs: dict[str, Any],
|
||||
*,
|
||||
engine_cls: type | None = None,
|
||||
user_typed: set[str] | None = None,
|
||||
strict: bool = False,
|
||||
) -> tuple[OrchestratorArgs, dict[str, Any]]:
|
||||
"""Partition CLI kwargs into (orchestrator, engine) buckets.
|
||||
|
||||
Args:
|
||||
kwargs: Raw dict, typically ``vars(args)``.
|
||||
engine_cls: Engine dataclass used to whitelist-filter the engine
|
||||
bucket. Defaults to ``OmniEngineArgs``. Pass a custom class
|
||||
for testing.
|
||||
user_typed: Keys the user actually typed on the command line. Used
|
||||
to warn when a user-typed flag is unclassifiable.
|
||||
strict: If True, raise ``ValueError`` on ambiguous (double-classified
|
||||
but not in ``SHARED_FIELDS``) fields. Default False to keep the
|
||||
rollout non-breaking; flip to True in tests and CI.
|
||||
|
||||
Returns:
|
||||
``(orchestrator_args, engine_kwargs)``. ``engine_kwargs`` has already
|
||||
been whitelist-filtered against ``engine_cls`` — safe to pass directly
|
||||
to ``engine_cls(**engine_kwargs)``.
|
||||
"""
|
||||
if engine_cls is None:
|
||||
engine_cls = OmniEngineArgs
|
||||
|
||||
orch_fields = orchestrator_field_names()
|
||||
engine_fields = {f.name for f in fields(engine_cls)}
|
||||
|
||||
orch_kwargs: dict[str, Any] = {}
|
||||
engine_candidate: dict[str, Any] = {}
|
||||
shared_values: dict[str, Any] = {}
|
||||
unclassified: dict[str, Any] = {}
|
||||
|
||||
for key, value in kwargs.items():
|
||||
in_orch = key in orch_fields
|
||||
in_engine = key in engine_fields
|
||||
is_shared = key in SHARED_FIELDS
|
||||
|
||||
if is_shared:
|
||||
shared_values[key] = value
|
||||
elif in_orch and in_engine:
|
||||
# Declared in both but not marked shared → ambiguous.
|
||||
msg = (
|
||||
f"Field {key!r} is defined on both OrchestratorArgs and "
|
||||
f"{engine_cls.__name__} but is not in SHARED_FIELDS. "
|
||||
f"This causes double-routing. Either remove the duplicate or "
|
||||
f"add {key!r} to SHARED_FIELDS if the sharing is intentional."
|
||||
)
|
||||
if strict:
|
||||
raise ValueError(msg)
|
||||
logger.error(msg)
|
||||
# Default: treat as orchestrator-only to preserve existing behavior.
|
||||
orch_kwargs[key] = value
|
||||
elif in_orch:
|
||||
orch_kwargs[key] = value
|
||||
elif in_engine:
|
||||
engine_candidate[key] = value
|
||||
else:
|
||||
unclassified[key] = value
|
||||
|
||||
# Warn on user-typed but unclassifiable flags so we don't silently drop
|
||||
# something the user cared about (fixes the class of bug that spawned #873).
|
||||
if unclassified and user_typed:
|
||||
user_typed_unknown = sorted(k for k in unclassified if k in user_typed)
|
||||
if user_typed_unknown:
|
||||
logger.warning(
|
||||
"CLI flags not consumed by vllm-omni and dropped before "
|
||||
"per-stage engine construction: %s. If these are vllm "
|
||||
"frontend/uvicorn flags (host, port, ssl_*, api_key, …) this "
|
||||
"is expected; otherwise check your spelling.",
|
||||
user_typed_unknown,
|
||||
)
|
||||
|
||||
# Engine bucket: shared + engine-only. We do NOT pass through unclassified
|
||||
# fields — that's exactly the server/uvicorn noise we want to shed.
|
||||
engine_kwargs = {**shared_values, **engine_candidate}
|
||||
|
||||
# Construct the orchestrator dataclass. Shared fields that OrchestratorArgs
|
||||
# also declares get copied into its constructor.
|
||||
orch_init: dict[str, Any] = dict(orch_kwargs)
|
||||
for key, value in shared_values.items():
|
||||
if key in orch_fields:
|
||||
orch_init[key] = value
|
||||
orch_args = OrchestratorArgs(**orch_init)
|
||||
|
||||
return orch_args, engine_kwargs
|
||||
|
||||
|
||||
def derive_server_dests_from_vllm_parser() -> frozenset[str]:
|
||||
"""Derive the set of argparse dests that belong to vllm's frontend/server.
|
||||
|
||||
Returns every dest registered by ``make_arg_parser`` that is NOT a field
|
||||
of ``OmniEngineArgs`` and NOT a field of ``OrchestratorArgs``. Useful for
|
||||
CI tests to assert all CLI flags are classifiable without maintaining
|
||||
a hardcoded server list.
|
||||
|
||||
Returns empty frozenset if vllm's parser cannot be built (e.g. in a
|
||||
minimal test environment).
|
||||
"""
|
||||
try:
|
||||
from vllm.entrypoints.openai.cli_args import make_arg_parser
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
except ImportError:
|
||||
logger.debug("Cannot import vllm parser — server-dest derivation skipped")
|
||||
return frozenset()
|
||||
|
||||
try:
|
||||
parser = make_arg_parser(FlexibleArgumentParser())
|
||||
all_dests = {a.dest for a in parser._actions if a.dest and a.dest != "help"}
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to build vllm parser: %s", exc)
|
||||
return frozenset()
|
||||
|
||||
engine_fields = {f.name for f in fields(OmniEngineArgs)}
|
||||
orch_fields = orchestrator_field_names()
|
||||
|
||||
return frozenset(all_dests - engine_fields - orch_fields - SHARED_FIELDS)
|
||||
|
||||
|
||||
def orchestrator_args_from_argparse(args: Any) -> OrchestratorArgs:
|
||||
"""Build an ``OrchestratorArgs`` from an ``argparse.Namespace``.
|
||||
|
||||
Only copies attributes that exist on the namespace — missing fields fall
|
||||
back to the dataclass default. Useful when the full parser is already
|
||||
built and ``vars(args)`` would include noise.
|
||||
"""
|
||||
kwargs: dict[str, Any] = {}
|
||||
for f in fields(OrchestratorArgs):
|
||||
if hasattr(args, f.name):
|
||||
value = getattr(args, f.name)
|
||||
if value is not None or f.default is None:
|
||||
kwargs[f.name] = value
|
||||
return OrchestratorArgs(**kwargs)
|
||||
@@ -25,6 +25,7 @@ from typing import TYPE_CHECKING, Any
|
||||
import janus
|
||||
import torch
|
||||
from omegaconf import OmegaConf
|
||||
from vllm import envs as vllm_envs
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.inputs import PromptType
|
||||
from vllm.logger import init_logger
|
||||
@@ -32,6 +33,7 @@ from vllm.tokenizers import cached_tokenizer_from_config
|
||||
from vllm.v1.engine import EngineCoreRequest
|
||||
from vllm.v1.engine.input_processor import InputProcessor
|
||||
|
||||
from vllm_omni.config.stage_config import strip_parent_engine_args
|
||||
from vllm_omni.diffusion.data import DiffusionParallelConfig
|
||||
from vllm_omni.diffusion.stage_diffusion_client import StageDiffusionClient
|
||||
from vllm_omni.diffusion.stage_diffusion_proc import (
|
||||
@@ -61,6 +63,7 @@ from vllm_omni.engine.stage_engine_startup import (
|
||||
)
|
||||
from vllm_omni.engine.stage_init_utils import (
|
||||
StartedLlmStage,
|
||||
_inject_inferred_kv_tp_topology,
|
||||
acquire_device_locks,
|
||||
build_diffusion_config,
|
||||
build_engine_args_dict,
|
||||
@@ -78,7 +81,11 @@ from vllm_omni.engine.stage_init_utils import (
|
||||
setup_stage_devices,
|
||||
terminate_alive_proc,
|
||||
)
|
||||
from vllm_omni.entrypoints.utils import load_and_resolve_stage_configs
|
||||
from vllm_omni.entrypoints.pd_utils import PDDisaggregationMixin
|
||||
from vllm_omni.entrypoints.utils import (
|
||||
inject_omni_kv_config,
|
||||
load_and_resolve_stage_configs,
|
||||
)
|
||||
from vllm_omni.inputs.preprocess import OmniInputPreprocessor
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
@@ -87,6 +94,29 @@ if TYPE_CHECKING:
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_STARTUP_POLL_INTERVAL_S = 1.0
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Parent-EngineArgs field-routing contracts (consumed by
|
||||
# AsyncOmniEngine._strip_parent_engine_args when ``stage_configs_path`` is set).
|
||||
# ============================================================================
|
||||
|
||||
# Fields that must survive the "equal to default → strip" filter because
|
||||
# diffusion stages need them even when equal to vllm's default value
|
||||
# (e.g. colocate worker setup relies on worker_extension_cls being forwarded).
|
||||
_PARENT_ARGS_KEEP: frozenset[str] = frozenset({"worker_extension_cls"})
|
||||
|
||||
# Omni orchestrator-level fields consumed by ``_resolve_stage_configs`` that
|
||||
# must never leak into per-stage EngineArgs (``stage_configs_path`` would
|
||||
# trigger the ``create_model_config`` guard).
|
||||
_PARENT_ARGS_STRIP: frozenset[str] = frozenset({"stage_configs_path"})
|
||||
|
||||
# Fields always populated by callers (via ``from_cli_args`` / ``asdict``) so
|
||||
# their presence as an override is never a surprise — suppress the
|
||||
# "override ignored" warning for these.
|
||||
_PARENT_ARGS_NO_WARN: frozenset[str] = frozenset({"model"})
|
||||
|
||||
|
||||
def _patch_generation_config_if_needed(model_config: Any) -> None:
|
||||
"""Ensure try_get_generation_config won't crash for models whose HF
|
||||
@@ -313,22 +343,7 @@ class AsyncOmniEngine:
|
||||
name="orchestrator",
|
||||
)
|
||||
self.orchestrator_thread.start()
|
||||
|
||||
# Wait for stage/runtime initialization result from orchestrator thread.
|
||||
try:
|
||||
startup_future.result(timeout=startup_timeout)
|
||||
except concurrent.futures.TimeoutError as e:
|
||||
try:
|
||||
self.shutdown()
|
||||
except Exception:
|
||||
logger.exception("[AsyncOmniEngine] Failed to cleanup after orchestrator startup timeout")
|
||||
raise TimeoutError(f"Orchestrator did not become ready within {startup_timeout}s") from e
|
||||
except Exception:
|
||||
try:
|
||||
self.shutdown()
|
||||
except Exception:
|
||||
logger.exception("[AsyncOmniEngine] Failed to cleanup after orchestrator startup failure")
|
||||
raise
|
||||
self._wait_for_orchestrator_init(startup_future, startup_timeout)
|
||||
|
||||
# Stage runtime fields are assigned directly on self by the bootstrap thread.
|
||||
self._weak_finalizer = weakref.finalize(
|
||||
@@ -378,6 +393,12 @@ class AsyncOmniEngine:
|
||||
omni_kv["omni_to_stage"] = omni_to
|
||||
omni_kv.setdefault("stage_id", metadata.stage_id)
|
||||
engine_args_dict["omni_kv_config"] = omni_kv
|
||||
if self.stage_configs:
|
||||
_inject_inferred_kv_tp_topology(
|
||||
engine_args_dict.get("omni_kv_config"),
|
||||
metadata.stage_id,
|
||||
self.stage_configs,
|
||||
)
|
||||
vllm_config, executor_class = build_vllm_config(
|
||||
stage_cfg,
|
||||
self.model,
|
||||
@@ -747,10 +768,8 @@ class AsyncOmniEngine:
|
||||
setup_stage_devices(configured_stage_id, metadata.runtime_cfg)
|
||||
omni_conn_cfg, omni_from, omni_to = omni_kv_connector
|
||||
if omni_conn_cfg:
|
||||
from vllm_omni.entrypoints.utils import inject_omni_kv_config
|
||||
|
||||
inject_omni_kv_config(stage_cfg, omni_conn_cfg, omni_from, omni_to)
|
||||
inject_kv_stage_info(stage_cfg, configured_stage_id)
|
||||
inject_kv_stage_info(stage_cfg, configured_stage_id, self.stage_configs)
|
||||
if self.single_stage_mode:
|
||||
assert self._omni_master_server is not None
|
||||
stage_clients[stage_idx] = self._launch_diffusion_stage(
|
||||
@@ -759,12 +778,15 @@ class AsyncOmniEngine:
|
||||
self._omni_master_server,
|
||||
)
|
||||
else:
|
||||
use_inline = True if self.num_stages == 1 else False
|
||||
stage_clients[stage_idx] = initialize_diffusion_stage(
|
||||
configured_stage_id,
|
||||
self.model,
|
||||
stage_cfg,
|
||||
metadata,
|
||||
stage_init_timeout=stage_init_timeout,
|
||||
batch_size=self.diffusion_batch_size,
|
||||
use_inline=use_inline,
|
||||
)
|
||||
logger.info(
|
||||
"[AsyncOmniEngine] Stage %s initialized (diffusion, batch_size=%d)",
|
||||
@@ -892,6 +914,7 @@ class AsyncOmniEngine:
|
||||
self._initialize_janus_queues()
|
||||
|
||||
self._initialize_stages(stage_init_timeout)
|
||||
pd_config = self._detect_pd_config()
|
||||
orchestrator = Orchestrator(
|
||||
request_async_queue=self.request_queue.async_q,
|
||||
output_async_queue=self.output_queue.async_q,
|
||||
@@ -900,6 +923,7 @@ class AsyncOmniEngine:
|
||||
stage_clients=self.stage_clients,
|
||||
output_processors=self.output_processors,
|
||||
stage_vllm_configs=self.stage_vllm_configs,
|
||||
pd_config=pd_config,
|
||||
)
|
||||
if not startup_future.done():
|
||||
startup_future.set_result(asyncio.get_running_loop())
|
||||
@@ -909,13 +933,17 @@ class AsyncOmniEngine:
|
||||
loop.run_until_complete(_run_orchestrator())
|
||||
except Exception as e:
|
||||
if not startup_future.done():
|
||||
startup_future.set_exception(RuntimeError(f"Orchestrator initialization failed: {e}"))
|
||||
wrapped = RuntimeError(f"Orchestrator initialization failed: {e}")
|
||||
wrapped.__cause__ = e
|
||||
startup_future.set_exception(wrapped)
|
||||
logger.exception("[AsyncOmniEngine] Orchestrator thread crashed")
|
||||
error_text = str(e) or "Orchestrator thread crashed"
|
||||
try:
|
||||
error_msg = {"type": "error", "error": error_text, "fatal": True}
|
||||
if self.output_queue is not None:
|
||||
self.output_queue.sync_q.put_nowait({"type": "error", "error": "Orchestrator thread crashed"})
|
||||
self.output_queue.sync_q.put_nowait(error_msg)
|
||||
if self.rpc_output_queue is not None:
|
||||
self.rpc_output_queue.sync_q.put_nowait({"type": "error", "error": "Orchestrator thread crashed"})
|
||||
self.rpc_output_queue.sync_q.put_nowait(error_msg)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
@@ -935,6 +963,31 @@ class AsyncOmniEngine:
|
||||
asyncio.set_event_loop(None)
|
||||
loop.close()
|
||||
|
||||
def _wait_for_orchestrator_init(self, startup_future: concurrent.futures.Future, startup_timeout: int) -> None:
|
||||
"""
|
||||
Wait for orchestrator startup future to return ready. Raises exception on any failures to the init process.
|
||||
"""
|
||||
deadline = time.monotonic() + startup_timeout
|
||||
while True:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
self._try_shutdown("[AsyncOmniEngine] Failed to cleanup after orchestrator startup timeout")
|
||||
raise TimeoutError(f"Orchestrator did not become ready within {startup_timeout}s")
|
||||
try:
|
||||
startup_future.result(
|
||||
timeout=min(remaining, _STARTUP_POLL_INTERVAL_S),
|
||||
)
|
||||
break
|
||||
except concurrent.futures.TimeoutError:
|
||||
if not self.orchestrator_thread.is_alive():
|
||||
self._try_shutdown("[AsyncOmniEngine] Failed to cleanup after orchestrator startup failure")
|
||||
if startup_future.done():
|
||||
startup_future.result() # re-raises the real exception
|
||||
raise RuntimeError("Orchestrator thread died during startup")
|
||||
except Exception:
|
||||
self._try_shutdown("[AsyncOmniEngine] Failed to cleanup after orchestrator startup failure")
|
||||
raise
|
||||
|
||||
# ---- request helpers ----
|
||||
|
||||
def _build_add_request_message(
|
||||
@@ -1062,7 +1115,6 @@ class AsyncOmniEngine:
|
||||
params=companion_params,
|
||||
supported_tasks=self.supported_tasks,
|
||||
)
|
||||
request = _upgrade_to_omni_request(request, companion_prompt)
|
||||
request.external_req_id = cid
|
||||
|
||||
self.output_processors[0].add_request(
|
||||
@@ -1122,12 +1174,64 @@ class AsyncOmniEngine:
|
||||
cache_config = AsyncOmniEngine._get_default_cache_config(cache_backend)
|
||||
return cache_config
|
||||
|
||||
def _detect_pd_config(self) -> dict[str, Any] | None:
|
||||
"""Detect PD (Prefill-Decode) disaggregation config from stage_configs.
|
||||
Returns a dict with 'pd_pair' and 'bootstrap_addr', or None.
|
||||
"""
|
||||
pd_pair = PDDisaggregationMixin.detect_pd_separation_from_stage_configs(self.stage_configs)
|
||||
if pd_pair is None:
|
||||
return None
|
||||
prefill_idx, decode_idx = pd_pair
|
||||
|
||||
# Extract bootstrap address from prefill stage engine_args
|
||||
bootstrap_addr: str | None = None
|
||||
try:
|
||||
prefill_cfg = self.stage_configs[prefill_idx]
|
||||
ea = getattr(prefill_cfg, "engine_args", None)
|
||||
kv_cfg = getattr(ea, "kv_transfer_config", None) if ea is not None else None
|
||||
if kv_cfg is not None:
|
||||
port = vllm_envs.VLLM_MOONCAKE_BOOTSTRAP_PORT
|
||||
kv_ip = getattr(kv_cfg, "kv_ip", None) or "127.0.0.1"
|
||||
bootstrap_addr = f"http://{kv_ip}:{port}"
|
||||
except Exception as exc:
|
||||
logger.warning("[AsyncOmniEngine] Could not extract PD bootstrap address: %s", exc)
|
||||
|
||||
logger.info(
|
||||
"[AsyncOmniEngine] PD disaggregation detected: prefill=stage-%d, decode=stage-%d, bootstrap=%s",
|
||||
prefill_idx,
|
||||
decode_idx,
|
||||
bootstrap_addr,
|
||||
)
|
||||
prefill_engine_id: str | None = None
|
||||
try:
|
||||
prefill_client = self.stage_clients[prefill_idx]
|
||||
kv_cfg = getattr(getattr(prefill_client, "vllm_config", None), "kv_transfer_config", None)
|
||||
prefill_engine_id = getattr(kv_cfg, "engine_id", None)
|
||||
except Exception as exc:
|
||||
logger.warning("[AsyncOmniEngine] Could not extract prefill engine_id: %s", exc)
|
||||
|
||||
return {
|
||||
"pd_pair": (prefill_idx, decode_idx),
|
||||
"bootstrap_addr": bootstrap_addr,
|
||||
"prefill_engine_id": prefill_engine_id,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _create_default_diffusion_stage_cfg(kwargs: dict[str, Any]) -> list:
|
||||
"""Create a default single-stage diffusion config from kwargs."""
|
||||
# We temporally create a default config for diffusion stage.
|
||||
# In the future, we should merge the default config with the user-provided config.
|
||||
normalized_kwargs = dict(kwargs)
|
||||
default_sampling_params = normalized_kwargs.get("default_sampling_params")
|
||||
if isinstance(default_sampling_params, str):
|
||||
try:
|
||||
default_sampling_params = json.loads(default_sampling_params)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("Invalid default_sampling_params JSON, ignoring stage defaults.")
|
||||
default_sampling_params = None
|
||||
if not isinstance(default_sampling_params, dict):
|
||||
default_sampling_params = None
|
||||
stage_default_sampling_params = default_sampling_params.get("0", {}) if default_sampling_params else {}
|
||||
|
||||
# TODO: hack, convert dtype to string to avoid non-premitive omegaconf create error.
|
||||
if "dtype" in normalized_kwargs and not isinstance(normalized_kwargs["dtype"], str):
|
||||
@@ -1224,6 +1328,7 @@ class AsyncOmniEngine:
|
||||
"devices": devices,
|
||||
},
|
||||
"engine_args": stage_engine_args,
|
||||
"default_sampling_params": stage_default_sampling_params,
|
||||
"final_output": True,
|
||||
"final_output_type": "image",
|
||||
}
|
||||
@@ -1244,45 +1349,17 @@ class AsyncOmniEngine:
|
||||
|
||||
Logs a warning for any parent field whose value differs from the
|
||||
dataclass default, so users know their explicit overrides are ignored.
|
||||
See the module-level ``_PARENT_ARGS_*`` constants for the routing
|
||||
contracts this method enforces.
|
||||
"""
|
||||
# worker_extension_cls is a parent field but must pass through to
|
||||
# diffusion stages for colocate worker setup.
|
||||
_keep = {"worker_extension_cls"}
|
||||
# Orchestrator-level OmniEngineArgs fields that are consumed by
|
||||
# _resolve_stage_configs and must not leak into per-stage configs
|
||||
# (stage_configs_path would trigger the create_model_config guard).
|
||||
_strip_omni = {"stage_configs_path"}
|
||||
# Fields that are always set by callers (via from_cli_args / asdict)
|
||||
# and would always appear as overridden — suppress from the warning
|
||||
# so it only surfaces genuinely surprising overrides.
|
||||
_no_warn = {"model"}
|
||||
|
||||
parent_fields: dict[str, dataclasses.Field] = {f.name: f for f in dataclasses.fields(EngineArgs)}
|
||||
overridden: list[str] = []
|
||||
result: dict[str, Any] = {}
|
||||
for k, v in kwargs.items():
|
||||
if k in _strip_omni:
|
||||
continue
|
||||
if k not in parent_fields or k in _keep:
|
||||
result[k] = v
|
||||
continue
|
||||
# Detect explicitly-set values that differ from the default.
|
||||
# Values may have been through asdict() which converts dataclass
|
||||
# defaults to dicts, so normalise before comparing.
|
||||
field = parent_fields[k]
|
||||
if field.default is not dataclasses.MISSING:
|
||||
default = field.default
|
||||
elif field.default_factory is not dataclasses.MISSING:
|
||||
default = field.default_factory()
|
||||
else:
|
||||
default = dataclasses.MISSING
|
||||
if default is dataclasses.MISSING or v is None:
|
||||
continue
|
||||
# Normalise dataclass defaults to dicts for comparison
|
||||
if dataclasses.is_dataclass(default) and not isinstance(default, type):
|
||||
default = dataclasses.asdict(default)
|
||||
if v != default and k not in _no_warn:
|
||||
overridden.append(k)
|
||||
result, overridden = strip_parent_engine_args(
|
||||
kwargs,
|
||||
parent_fields=parent_fields,
|
||||
keep_keys=_PARENT_ARGS_KEEP,
|
||||
strip_keys=_PARENT_ARGS_STRIP,
|
||||
no_warn_keys=_PARENT_ARGS_NO_WARN,
|
||||
)
|
||||
|
||||
if overridden:
|
||||
logger.warning(
|
||||
@@ -1297,6 +1374,12 @@ class AsyncOmniEngine:
|
||||
"""Resolve stage configs and inject defaults shared by orchestrator/headless."""
|
||||
|
||||
stage_configs_path = kwargs.get("stage_configs_path", None)
|
||||
deploy_config_path = kwargs.pop("deploy_config", None)
|
||||
stage_overrides_json = kwargs.pop("stage_overrides", None)
|
||||
# Set of CLI keys the user actually typed; ``None`` means we have no
|
||||
# parser-level info (e.g. programmatic Omni() call) and the lower
|
||||
# layers should treat all kwargs as explicit.
|
||||
cli_explicit_keys = kwargs.pop("_cli_explicit_keys", None)
|
||||
explicit_stage_configs = kwargs.pop("stage_configs", None)
|
||||
if explicit_stage_configs is not None:
|
||||
logger.warning(
|
||||
@@ -1309,18 +1392,38 @@ class AsyncOmniEngine:
|
||||
else:
|
||||
base_kwargs = kwargs
|
||||
|
||||
# Use the legacy config loading path (load_and_resolve_stage_configs).
|
||||
# StageConfigFactory wiring will be done in config refactor [2/N].
|
||||
# Parse --stage-overrides JSON string if provided
|
||||
stage_overrides = None
|
||||
if stage_overrides_json:
|
||||
if isinstance(stage_overrides_json, str):
|
||||
try:
|
||||
stage_overrides = json.loads(stage_overrides_json)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(
|
||||
f"--stage-overrides is not valid JSON: {exc}. Got: {stage_overrides_json!r}"
|
||||
) from exc
|
||||
else:
|
||||
stage_overrides = stage_overrides_json
|
||||
|
||||
config_path, stage_configs = load_and_resolve_stage_configs(
|
||||
model,
|
||||
stage_configs_path,
|
||||
base_kwargs,
|
||||
default_stage_cfg_factory=lambda: self._create_default_diffusion_stage_cfg(kwargs),
|
||||
deploy_config_path=deploy_config_path,
|
||||
stage_overrides=stage_overrides,
|
||||
cli_explicit_keys=cli_explicit_keys,
|
||||
)
|
||||
|
||||
# Inject diffusion LoRA-related knobs from kwargs if not present in the stage config.
|
||||
for cfg in stage_configs:
|
||||
try:
|
||||
if not hasattr(cfg, "engine_args") or cfg.engine_args is None:
|
||||
cfg.engine_args = OmegaConf.create({})
|
||||
global_sleep_mode = kwargs.get("enable_sleep_mode")
|
||||
if global_sleep_mode is not None:
|
||||
if not hasattr(cfg.engine_args, "enable_sleep_mode") or cfg.engine_args.enable_sleep_mode is None:
|
||||
cfg.engine_args.enable_sleep_mode = global_sleep_mode
|
||||
if getattr(cfg, "stage_type", None) != "diffusion":
|
||||
continue
|
||||
if not hasattr(cfg, "engine_args") or cfg.engine_args is None:
|
||||
@@ -1642,3 +1745,9 @@ class AsyncOmniEngine:
|
||||
except Exception:
|
||||
logger.exception("[AsyncOmniEngine] Failed to stop OmniMasterServer during shutdown")
|
||||
self._omni_master_server = None
|
||||
|
||||
def _try_shutdown(self, *args, **kwargs) -> None:
|
||||
try:
|
||||
self.shutdown()
|
||||
except Exception:
|
||||
logger.exception(*args, **kwargs)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""CFG companion request tracker for the Omni orchestrator.
|
||||
|
||||
Encapsulates all bookkeeping for Classifier-Free Guidance companion
|
||||
requests (parent/companion ID mapping, completion tracking,
|
||||
deferred forwarding, and cleanup).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CfgCompanionTracker:
|
||||
"""Manages CFG companion request lifecycle in the orchestrator scheduling loop."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._companion_map: dict[str, dict[str, str]] = {} # parent -> {role: companion_id}
|
||||
self._companion_ids: set[str] = set()
|
||||
self._companion_to_parent: dict[str, str] = {} # companion -> parent
|
||||
self._done: dict[str, set[str]] = {} # parent -> completed companion ids
|
||||
self._pending_parents: dict[str, dict[str, Any]] = {} # parent -> deferred result
|
||||
|
||||
def is_companion(self, req_id: str) -> bool:
|
||||
return req_id in self._companion_ids
|
||||
|
||||
def has_companions(self, parent_id: str) -> bool:
|
||||
return parent_id in self._companion_map
|
||||
|
||||
def all_companions_done(self, parent_id: str) -> bool:
|
||||
role_map = self._companion_map.get(parent_id, {})
|
||||
done_set = self._done.get(parent_id, set())
|
||||
return all(cid in done_set for cid in role_map.values())
|
||||
|
||||
def get_companion_request_ids(self, parent_id: str) -> dict[str, str]:
|
||||
"""Return ``{role: companion_request_id}`` for a parent."""
|
||||
return self._companion_map.get(parent_id, {})
|
||||
|
||||
def register_parent(self, parent_id: str) -> None:
|
||||
self._companion_map.setdefault(parent_id, {})
|
||||
self._done.setdefault(parent_id, set())
|
||||
|
||||
def register_companion(self, parent_id: str, role: str, companion_id: str) -> None:
|
||||
self.register_parent(parent_id)
|
||||
self._companion_map[parent_id][role] = companion_id
|
||||
self._companion_ids.add(companion_id)
|
||||
self._companion_to_parent[companion_id] = parent_id
|
||||
|
||||
def attach_cfg_request_ids(self, parent_id: str, sampling_params: Any) -> Any:
|
||||
cfg_ids = self.get_companion_request_ids(parent_id)
|
||||
if not cfg_ids:
|
||||
return sampling_params
|
||||
|
||||
if isinstance(sampling_params, OmniDiffusionSamplingParams):
|
||||
sampling_params = sampling_params.clone()
|
||||
sampling_params.cfg_kv_request_ids = cfg_ids
|
||||
logger.info(
|
||||
"Attaching cfg_kv_request_ids=%s to request %s",
|
||||
cfg_ids,
|
||||
parent_id,
|
||||
)
|
||||
return sampling_params
|
||||
|
||||
def on_companion_completed(self, companion_id: str) -> str | None:
|
||||
"""Mark done. Returns parent_id only if parent is pending and all companions finished."""
|
||||
parent_id = self._companion_to_parent.get(companion_id)
|
||||
if parent_id is None:
|
||||
return None
|
||||
done_set = self._done.get(parent_id)
|
||||
assert done_set is not None, f"Companion {companion_id} completed before parent {parent_id} was registered"
|
||||
if companion_id in done_set:
|
||||
return None
|
||||
done_set.add(companion_id)
|
||||
logger.debug("CFG companion %s completed (parent=%s)", companion_id, parent_id)
|
||||
if parent_id in self._pending_parents and self.all_companions_done(parent_id):
|
||||
return parent_id
|
||||
return None
|
||||
|
||||
def defer_parent(self, parent_id: str, engine_outputs: Any, stage_id: int) -> None:
|
||||
"""Hold parent result while waiting for companions to finish."""
|
||||
# TODO: Add timeout/error recovery when the orchestrator grows a
|
||||
# companion-failure path. Today deferred parents are released only when
|
||||
# companions finish or the external layer aborts the request.
|
||||
self._pending_parents[parent_id] = {
|
||||
"engine_outputs": engine_outputs,
|
||||
"stage_id": stage_id,
|
||||
}
|
||||
logger.debug("Parent %s deferred, waiting for CFG companions", parent_id)
|
||||
|
||||
def pop_pending_parent(self, parent_id: str) -> dict[str, Any] | None:
|
||||
return self._pending_parents.pop(parent_id, None)
|
||||
|
||||
def cleanup_parent(self, parent_id: str) -> list[str]:
|
||||
companion_ids = list(self._companion_map.pop(parent_id, {}).values())
|
||||
for companion_id in companion_ids:
|
||||
self._companion_ids.discard(companion_id)
|
||||
self._companion_to_parent.pop(companion_id, None)
|
||||
self._done.pop(parent_id, None)
|
||||
self._pending_parents.pop(parent_id, None)
|
||||
return companion_ids
|
||||
|
||||
def abort_parents(self, request_ids: list[str]) -> list[str]:
|
||||
all_request_ids = list(request_ids)
|
||||
seen = set(all_request_ids)
|
||||
parents_to_cleanup: set[str] = set()
|
||||
|
||||
for req_id in request_ids:
|
||||
# The orchestrator calls this with parent request IDs. If a raw
|
||||
# companion ID is passed here, keep it as a direct abort target and
|
||||
# avoid tearing down parent tracking state implicitly.
|
||||
if req_id not in self._companion_ids:
|
||||
parents_to_cleanup.add(req_id)
|
||||
|
||||
for parent_id in parents_to_cleanup:
|
||||
companion_ids = self.cleanup_parent(parent_id)
|
||||
for companion_id in companion_ids:
|
||||
if companion_id not in seen:
|
||||
seen.add(companion_id)
|
||||
all_request_ids.append(companion_id)
|
||||
|
||||
return all_request_ids
|
||||
@@ -22,11 +22,13 @@ from vllm.outputs import RequestOutput
|
||||
from vllm.pooling_params import PoolingParams
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.engine import EngineCoreOutputs
|
||||
from vllm.v1.engine.exceptions import EngineDeadError
|
||||
|
||||
from vllm_omni.distributed.omni_connectors.adapter import compute_talker_prompt_ids_length
|
||||
from vllm_omni.engine import (
|
||||
OmniEngineCoreRequest,
|
||||
)
|
||||
from vllm_omni.engine.cfg_companion_tracker import CfgCompanionTracker
|
||||
from vllm_omni.engine.serialization import serialize_additional_information
|
||||
from vllm_omni.metrics.stats import StageRequestStats as StageRequestMetrics
|
||||
from vllm_omni.metrics.stats import StageStats
|
||||
@@ -41,6 +43,8 @@ def build_engine_core_request_from_tokens(
|
||||
params: SamplingParams | PoolingParams,
|
||||
arrival_time: float | None = None,
|
||||
model_config: ModelConfig | None = None,
|
||||
resumable: bool = False,
|
||||
mm_features: list | None = None,
|
||||
) -> OmniEngineCoreRequest:
|
||||
"""Build an OmniEngineCoreRequest directly from an OmniTokensPrompt.
|
||||
|
||||
@@ -75,7 +79,7 @@ def build_engine_core_request_from_tokens(
|
||||
return OmniEngineCoreRequest(
|
||||
request_id=request_id,
|
||||
prompt_token_ids=prompt_token_ids,
|
||||
mm_features=None,
|
||||
mm_features=mm_features,
|
||||
sampling_params=sampling_params,
|
||||
pooling_params=pooling_params,
|
||||
arrival_time=arrival_time,
|
||||
@@ -83,6 +87,7 @@ def build_engine_core_request_from_tokens(
|
||||
cache_salt=None,
|
||||
data_parallel_rank=None,
|
||||
prompt_embeds=prompt_embeds,
|
||||
resumable=resumable,
|
||||
additional_information=additional_info_payload,
|
||||
)
|
||||
|
||||
@@ -103,6 +108,22 @@ class OrchestratorRequestState:
|
||||
|
||||
# Metrics: timestamp when request was submitted to each stage
|
||||
stage_submit_ts: dict[int, float] = field(default_factory=dict)
|
||||
mm_processor_kwargs: dict | None = None
|
||||
mm_features: list | None = None
|
||||
|
||||
streaming: StreamingInputState = field(default_factory=lambda: StreamingInputState())
|
||||
|
||||
|
||||
@dataclass
|
||||
class StreamingInputState:
|
||||
# Flag of streaming input request
|
||||
enabled: bool = False
|
||||
# Flag of segment of streaming input finished
|
||||
segment_finished: bool = False
|
||||
# Streaming update prompt length
|
||||
new_prompt_len_snapshot: int | None = None
|
||||
# Model/bridge-specific runtime states (e.g., thinker->talker)
|
||||
bridge_states: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
@@ -122,6 +143,7 @@ class Orchestrator:
|
||||
stage_vllm_configs: list[Any],
|
||||
*,
|
||||
async_chunk: bool = False,
|
||||
pd_config: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
self.request_async_queue = request_async_queue
|
||||
self.output_async_queue = output_async_queue
|
||||
@@ -134,15 +156,21 @@ class Orchestrator:
|
||||
self.output_processors: list[Any] = output_processors
|
||||
self.stage_vllm_configs: list[Any] = stage_vllm_configs
|
||||
|
||||
# PD disaggregation state
|
||||
self._pd_pair: tuple[int, int] | None = None
|
||||
self._pd_bootstrap_addr: str | None = None
|
||||
self._pd_prefill_engine_id: str | None = None
|
||||
self._pd_kv_params: dict[str, Any] = {}
|
||||
if pd_config is not None:
|
||||
self._pd_pair = pd_config.get("pd_pair")
|
||||
self._pd_bootstrap_addr = pd_config.get("bootstrap_addr")
|
||||
self._pd_prefill_engine_id = pd_config.get("prefill_engine_id")
|
||||
|
||||
# Per-request state
|
||||
self.request_states: dict[str, OrchestratorRequestState] = {}
|
||||
|
||||
# CFG companion tracking
|
||||
self._companion_map: dict[str, dict[str, str]] = {}
|
||||
self._companion_to_parent: dict[str, str] = {}
|
||||
self._companion_ids: set[str] = set()
|
||||
self._companion_done: dict[str, set[str]] = {}
|
||||
self._deferred_parents: dict[str, dict[str, Any]] = {}
|
||||
self._cfg_tracker = CfgCompanionTracker()
|
||||
|
||||
# Per-stage metrics accumulators.
|
||||
self._batch_seq: list[int] = [0] * self.num_stages
|
||||
@@ -152,6 +180,7 @@ class Orchestrator:
|
||||
# Shutdown coordination
|
||||
self._shutdown_event = asyncio.Event()
|
||||
self._stages_shutdown = False
|
||||
self._fatal_error: str | None = None
|
||||
|
||||
async def run(self) -> None:
|
||||
"""Main entry point for the Orchestrator event loop."""
|
||||
@@ -181,6 +210,12 @@ class Orchestrator:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# If a fatal error caused the shutdown, drain any pending
|
||||
# add_request messages that were never processed and broadcast
|
||||
# fatal error responses so callers are not left hanging.
|
||||
if self._fatal_error is not None:
|
||||
await self._drain_pending_requests_on_fatal()
|
||||
|
||||
self._shutdown_stages()
|
||||
|
||||
# Cancel any remaining tasks spawned by wait_for / gather so
|
||||
@@ -244,8 +279,40 @@ class Orchestrator:
|
||||
output = stage_client.get_diffusion_output_nowait()
|
||||
if output is not None:
|
||||
idle = False
|
||||
|
||||
if getattr(output, "error", None) is not None:
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "output",
|
||||
"request_id": output.request_id,
|
||||
"stage_id": stage_id,
|
||||
"engine_outputs": output,
|
||||
"metrics": None,
|
||||
"finished": True,
|
||||
}
|
||||
)
|
||||
self.request_states.pop(output.request_id, None)
|
||||
continue
|
||||
|
||||
req_state = self.request_states.get(output.request_id)
|
||||
if req_state is not None:
|
||||
if getattr(output, "error", None) is not None:
|
||||
parent_id = self._companion_to_parent.get(output.request_id, output.request_id)
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "error",
|
||||
"request_id": parent_id,
|
||||
"stage_id": stage_id,
|
||||
"error": output.error,
|
||||
}
|
||||
)
|
||||
role_map = self._companion_map.get(parent_id, {})
|
||||
for cid in role_map.values():
|
||||
self.request_states.pop(cid, None)
|
||||
self._cleanup_companion_state(parent_id)
|
||||
self.request_states.pop(parent_id, None)
|
||||
continue
|
||||
|
||||
stage_metrics = self._build_stage_metrics(stage_id, output.request_id, [output], req_state)
|
||||
await self._route_output(stage_id, output, req_state, stage_metrics)
|
||||
continue
|
||||
@@ -257,6 +324,26 @@ class Orchestrator:
|
||||
continue
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except EngineDeadError as e:
|
||||
logger.error(
|
||||
"[Orchestrator] Stage-%s is dead: %s",
|
||||
stage_id,
|
||||
e,
|
||||
)
|
||||
self._fatal_error = str(e)
|
||||
for req_id, req_state in list(self.request_states.items()):
|
||||
if stage_id in req_state.stage_submit_ts:
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "error",
|
||||
"error": str(e),
|
||||
"fatal": True,
|
||||
"request_id": req_id,
|
||||
}
|
||||
)
|
||||
self.request_states.pop(req_id, None)
|
||||
self._shutdown_event.set()
|
||||
raise
|
||||
except Exception:
|
||||
if self._shutdown_event.is_set():
|
||||
return
|
||||
@@ -317,7 +404,7 @@ class Orchestrator:
|
||||
|
||||
# CFG companion handling: companions don't produce user-visible output
|
||||
# and don't forward to the next stage directly.
|
||||
if finished and req_id in self._companion_ids:
|
||||
if finished and self._cfg_tracker.is_companion(req_id):
|
||||
await self._handle_cfg_companion_ready(req_id)
|
||||
self.request_states.pop(req_id, None)
|
||||
return
|
||||
@@ -345,63 +432,80 @@ class Orchestrator:
|
||||
}
|
||||
)
|
||||
|
||||
# PD disaggregation: extract KV transfer params from prefill stage output
|
||||
if self._pd_pair is not None and finished and stage_id == self._pd_pair[0]:
|
||||
kv_params = getattr(output, "kv_transfer_params", None)
|
||||
if kv_params is not None:
|
||||
self._pd_kv_params[req_id] = kv_params if isinstance(kv_params, dict) else dict(kv_params)
|
||||
logger.debug(
|
||||
"[Orchestrator][PD] stored kv_transfer_params for req=%s (keys=%s)",
|
||||
req_id,
|
||||
list(self._pd_kv_params[req_id].keys()),
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"[Orchestrator][PD] prefill stage output for req=%s has no kv_transfer_params; "
|
||||
"KV transfer may fail. Ensure apply_mooncake_connector_patch() was called.",
|
||||
req_id,
|
||||
)
|
||||
|
||||
if (
|
||||
finished
|
||||
(finished or (req_state.streaming.enabled and req_state.streaming.segment_finished))
|
||||
and stage_id < req_state.final_stage_id
|
||||
and not self.async_chunk
|
||||
and not self._next_stage_already_submitted(stage_id, req_state)
|
||||
and (not self._next_stage_already_submitted(stage_id, req_state) or req_state.streaming.enabled)
|
||||
):
|
||||
if req_id in self._companion_map and not self._all_companions_done(req_id):
|
||||
self._deferred_parents[req_id] = {
|
||||
"stage_id": stage_id,
|
||||
"output": output,
|
||||
}
|
||||
if (
|
||||
finished
|
||||
and self._cfg_tracker.has_companions(req_id)
|
||||
and not self._cfg_tracker.all_companions_done(req_id)
|
||||
):
|
||||
self._cfg_tracker.defer_parent(req_id, output, stage_id)
|
||||
else:
|
||||
await self._forward_to_next_stage(req_id, stage_id, output, req_state)
|
||||
await self._forward_to_next_stage(
|
||||
req_id,
|
||||
stage_id,
|
||||
output,
|
||||
req_state,
|
||||
is_streaming_session=req_state.streaming.enabled,
|
||||
is_final_update=False,
|
||||
)
|
||||
if req_state.streaming.enabled and finished:
|
||||
# For streaming sessions, send the terminal (resumable=False) update only on a finish
|
||||
await self._forward_to_next_stage(
|
||||
req_id,
|
||||
stage_id,
|
||||
output,
|
||||
req_state,
|
||||
is_streaming_session=True,
|
||||
is_final_update=True,
|
||||
)
|
||||
|
||||
if finished and stage_id == req_state.final_stage_id:
|
||||
self._cleanup_companion_state(req_id)
|
||||
# PD: clean up any lingering KV params for this request
|
||||
self._pd_kv_params.pop(req_id, None)
|
||||
self._cfg_tracker.cleanup_parent(req_id)
|
||||
self.request_states.pop(req_id, None)
|
||||
|
||||
def _cleanup_companion_state(self, parent_id: str) -> None:
|
||||
"""Remove all companion tracking state for a completed parent."""
|
||||
role_map = self._companion_map.pop(parent_id, {})
|
||||
for cid in role_map.values():
|
||||
self._companion_ids.discard(cid)
|
||||
self._companion_to_parent.pop(cid, None)
|
||||
self._companion_done.pop(parent_id, None)
|
||||
self._deferred_parents.pop(parent_id, None)
|
||||
|
||||
def _all_companions_done(self, parent_id: str) -> bool:
|
||||
"""Check whether all CFG companions for a parent request have finished."""
|
||||
role_map = self._companion_map.get(parent_id, {})
|
||||
if not role_map:
|
||||
return True
|
||||
done_set = self._companion_done.get(parent_id, set())
|
||||
return all(cid in done_set for cid in role_map.values())
|
||||
|
||||
def _next_stage_already_submitted(self, stage_id: int, req_state: OrchestratorRequestState) -> bool:
|
||||
return (stage_id + 1) in req_state.stage_submit_ts
|
||||
|
||||
async def _handle_cfg_companion_ready(self, req_id: str) -> None:
|
||||
"""Mark a CFG companion as done; if all companions are done, flush deferred parent."""
|
||||
parent_id = self._companion_to_parent.get(req_id)
|
||||
parent_id = self._cfg_tracker.on_companion_completed(req_id)
|
||||
if parent_id is None:
|
||||
return
|
||||
done_set = self._companion_done.setdefault(parent_id, set())
|
||||
if req_id in done_set:
|
||||
deferred = self._cfg_tracker.pop_pending_parent(parent_id)
|
||||
if deferred is None:
|
||||
return
|
||||
done_set.add(req_id)
|
||||
if parent_id in self._deferred_parents and self._all_companions_done(parent_id):
|
||||
deferred = self._deferred_parents.pop(parent_id)
|
||||
parent_state = self.request_states.get(parent_id)
|
||||
if parent_state is not None and not self._next_stage_already_submitted(deferred["stage_id"], parent_state):
|
||||
await self._forward_to_next_stage(
|
||||
parent_id,
|
||||
deferred["stage_id"],
|
||||
deferred["output"],
|
||||
parent_state,
|
||||
)
|
||||
parent_state = self.request_states.get(parent_id)
|
||||
if parent_state is not None and not self._next_stage_already_submitted(deferred["stage_id"], parent_state):
|
||||
await self._forward_to_next_stage(
|
||||
parent_id,
|
||||
deferred["stage_id"],
|
||||
deferred["engine_outputs"],
|
||||
parent_state,
|
||||
)
|
||||
|
||||
async def _handle_kv_ready_raw_outputs(self, stage_id: int, raw_outputs: EngineCoreOutputs) -> None:
|
||||
"""Forward split requests once stage-0 KV is ready, not only when decode fully finishes."""
|
||||
@@ -415,21 +519,63 @@ class Orchestrator:
|
||||
req_state = self.request_states.get(req_id)
|
||||
if req_state is None:
|
||||
continue
|
||||
if req_id in self._companion_ids:
|
||||
if self._cfg_tracker.is_companion(req_id):
|
||||
await self._handle_cfg_companion_ready(req_id)
|
||||
continue
|
||||
if stage_id >= req_state.final_stage_id:
|
||||
continue
|
||||
if self._next_stage_already_submitted(stage_id, req_state):
|
||||
continue
|
||||
if req_id in self._companion_map and not self._all_companions_done(req_id):
|
||||
self._deferred_parents[req_id] = {
|
||||
"stage_id": stage_id,
|
||||
"output": raw_output,
|
||||
}
|
||||
if self._cfg_tracker.has_companions(req_id) and not self._cfg_tracker.all_companions_done(req_id):
|
||||
self._cfg_tracker.defer_parent(req_id, raw_output, stage_id)
|
||||
else:
|
||||
await self._forward_to_next_stage(req_id, stage_id, raw_output, req_state)
|
||||
|
||||
def _build_pd_decode_params(self, req_id: str, sp: Any) -> Any:
|
||||
"""Build decode-side sampling params with KV transfer params for PD routing.
|
||||
|
||||
Clones the sampling params and injects kv_transfer_params that tell the
|
||||
decode engine where to pull the KV cache from (prefill engine's bootstrap addr).
|
||||
"""
|
||||
sp = sp.clone()
|
||||
if sp.extra_args is None:
|
||||
sp.extra_args = {}
|
||||
|
||||
# Get KV params captured from the prefill output (must include remote_request_id).
|
||||
kv_prefill_params = self._pd_kv_params.pop(req_id, None)
|
||||
if not kv_prefill_params or "remote_request_id" not in kv_prefill_params:
|
||||
raise RuntimeError(
|
||||
f"[Orchestrator][PD] Missing prefill kv_transfer_params.remote_request_id for req={req_id}"
|
||||
)
|
||||
|
||||
decode_kv_params: dict[str, Any] = {
|
||||
"transfer_id": f"xfer-{req_id}",
|
||||
}
|
||||
|
||||
if self._pd_bootstrap_addr:
|
||||
decode_kv_params["remote_bootstrap_addr"] = self._pd_bootstrap_addr
|
||||
|
||||
if self._pd_prefill_engine_id:
|
||||
decode_kv_params["remote_engine_id"] = self._pd_prefill_engine_id
|
||||
|
||||
# Overlay params from prefill side (includes remote_request_id set by monkey patch).
|
||||
decode_kv_params.update(kv_prefill_params)
|
||||
|
||||
# Ensure these flags are set correctly after any overlay.
|
||||
decode_kv_params["do_remote_prefill"] = True
|
||||
decode_kv_params["do_remote_decode"] = False
|
||||
if not decode_kv_params.get("transfer_id"):
|
||||
decode_kv_params["transfer_id"] = f"xfer-{req_id}"
|
||||
|
||||
sp.extra_args["kv_transfer_params"] = decode_kv_params
|
||||
|
||||
logger.debug(
|
||||
"[Orchestrator][PD] decode kv_transfer_params for req=%s: %s",
|
||||
req_id,
|
||||
decode_kv_params,
|
||||
)
|
||||
return sp
|
||||
|
||||
def _build_stage_metrics(
|
||||
self,
|
||||
stage_id: int,
|
||||
@@ -507,6 +653,9 @@ class Orchestrator:
|
||||
stage_id: int,
|
||||
output: Any,
|
||||
req_state: OrchestratorRequestState,
|
||||
*,
|
||||
is_streaming_session: bool = False,
|
||||
is_final_update: bool = False,
|
||||
) -> None:
|
||||
"""Forward output from current stage to the next stage.
|
||||
|
||||
@@ -516,35 +665,32 @@ class Orchestrator:
|
||||
next_stage_id = stage_id + 1
|
||||
next_client = self.stage_clients[next_stage_id]
|
||||
params = req_state.sampling_params_list[next_stage_id]
|
||||
next_stage_resumable = is_streaming_session and not is_final_update
|
||||
|
||||
if next_client.stage_type == "diffusion":
|
||||
self.stage_clients[stage_id].set_engine_outputs([output])
|
||||
if next_client.custom_process_input_func is not None:
|
||||
_t_ar2d = _time.perf_counter()
|
||||
diffusion_prompt = next_client.custom_process_input_func(
|
||||
self.stage_clients,
|
||||
next_client.engine_input_source,
|
||||
req_state.prompt,
|
||||
False,
|
||||
)
|
||||
_dt_ar2d = (_time.perf_counter() - _t_ar2d) * 1000
|
||||
logger.info(
|
||||
"[Orchestrator] ar2diffusion req=%s wall_time=%.3fms stage=%d->%d",
|
||||
req_id,
|
||||
_dt_ar2d,
|
||||
stage_id,
|
||||
next_stage_id,
|
||||
)
|
||||
if isinstance(diffusion_prompt, list):
|
||||
diffusion_prompt = diffusion_prompt[0]
|
||||
else:
|
||||
diffusion_prompt = req_state.prompt
|
||||
|
||||
# Attach CFG companion KV request IDs so the diffusion model
|
||||
# runner can fetch companion KV caches alongside the primary one.
|
||||
cfg_ids = self._companion_map.get(req_id)
|
||||
if cfg_ids:
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
if isinstance(params, OmniDiffusionSamplingParams):
|
||||
params = copy.deepcopy(params)
|
||||
params.cfg_kv_request_ids = cfg_ids
|
||||
logger.info(
|
||||
"[Orchestrator] Attaching cfg_kv_request_ids=%s to req %s",
|
||||
cfg_ids,
|
||||
req_id,
|
||||
)
|
||||
params = self._cfg_tracker.attach_cfg_request_ids(req_id, params)
|
||||
|
||||
source_stage_ids = list(getattr(next_client, "engine_input_source", None) or [stage_id])
|
||||
kv_sender_info = self._build_kv_sender_info(sender_stage_ids=source_stage_ids)
|
||||
@@ -565,6 +711,52 @@ class Orchestrator:
|
||||
req_state.stage_submit_ts[next_stage_id] = _time.time()
|
||||
return
|
||||
|
||||
# PD disaggregation: prefill → decode routing uses original prompt + KV transfer params
|
||||
if self._pd_pair is not None and (stage_id, next_stage_id) == self._pd_pair:
|
||||
# Save prefill stage outputs so thinker2talker can merge embeddings later
|
||||
self.stage_clients[stage_id].set_engine_outputs([output])
|
||||
|
||||
params = self._build_pd_decode_params(req_id, params)
|
||||
|
||||
# Use the original user prompt for the decode stage (not processed embeddings)
|
||||
original_prompt = req_state.prompt
|
||||
raw_decode_inputs = [original_prompt] if not isinstance(original_prompt, list) else original_prompt
|
||||
|
||||
decode_inputs: list[dict[str, Any]] = []
|
||||
for decode_input in raw_decode_inputs:
|
||||
if isinstance(decode_input, dict):
|
||||
decode_inputs.append(decode_input)
|
||||
continue
|
||||
prompt_token_ids = getattr(decode_input, "prompt_token_ids", None)
|
||||
if prompt_token_ids is None:
|
||||
raise TypeError(
|
||||
"[Orchestrator][PD] decode input must be dict or have prompt_token_ids, "
|
||||
f"got {type(decode_input).__name__} for req={req_id}"
|
||||
)
|
||||
decode_inputs.append({"prompt_token_ids": list(prompt_token_ids)})
|
||||
|
||||
for decode_input in decode_inputs:
|
||||
request = build_engine_core_request_from_tokens(
|
||||
request_id=req_id,
|
||||
prompt=decode_input,
|
||||
params=params,
|
||||
model_config=self.stage_vllm_configs[next_stage_id].model_config,
|
||||
mm_features=req_state.mm_features, # Pass mm_features for M-RoPE
|
||||
)
|
||||
request.external_req_id = request.request_id
|
||||
|
||||
self.output_processors[next_stage_id].add_request(
|
||||
request=request,
|
||||
prompt=None,
|
||||
parent_req=None,
|
||||
request_index=0,
|
||||
queue=None,
|
||||
)
|
||||
await next_client.add_request_async(request)
|
||||
|
||||
req_state.stage_submit_ts[next_stage_id] = _time.time()
|
||||
return
|
||||
|
||||
self.stage_clients[stage_id].set_engine_outputs([output])
|
||||
|
||||
# Process inputs for next stage
|
||||
@@ -572,6 +764,7 @@ class Orchestrator:
|
||||
next_inputs = next_client.process_engine_inputs(
|
||||
stage_list=self.stage_clients,
|
||||
prompt=req_state.prompt,
|
||||
streaming_context=(req_state.streaming if req_state.streaming.enabled else None),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
@@ -583,11 +776,17 @@ class Orchestrator:
|
||||
|
||||
# Build and submit requests for each input
|
||||
for next_input in next_inputs:
|
||||
# Only AR thinker stages consume encoder mm_features; downstream
|
||||
# (talker/code2wav/…) must not see them (avoids encoder-cache misses).
|
||||
_ms = getattr(next_client, "model_stage", None)
|
||||
_mm_features = req_state.mm_features if _ms == "thinker" else None
|
||||
request = build_engine_core_request_from_tokens(
|
||||
request_id=req_id,
|
||||
prompt=next_input,
|
||||
params=params,
|
||||
model_config=self.stage_vllm_configs[next_stage_id].model_config,
|
||||
mm_features=_mm_features,
|
||||
resumable=next_stage_resumable,
|
||||
)
|
||||
|
||||
# TODO: Here we directly use the req id to assign.
|
||||
@@ -629,6 +828,13 @@ class Orchestrator:
|
||||
raw_outputs.timestamp,
|
||||
None,
|
||||
)
|
||||
for eco in raw_outputs.outputs:
|
||||
if not hasattr(eco, "request_id"):
|
||||
continue
|
||||
req_state = self.request_states.get(eco.request_id)
|
||||
if req_state:
|
||||
req_state.streaming.segment_finished = eco.is_segment_finished
|
||||
req_state.streaming.new_prompt_len_snapshot = eco.new_prompt_len_snapshot
|
||||
|
||||
if processed.reqs_to_abort:
|
||||
await self.stage_clients[stage_id].abort_requests_async(processed.reqs_to_abort)
|
||||
@@ -664,19 +870,22 @@ class Orchestrator:
|
||||
|
||||
# Track request state - use original_prompt so downstream stages
|
||||
# (e.g. thinker2talker) can access the raw dict with multi_modal_data.
|
||||
request = prompt
|
||||
is_streaming = bool(getattr(request, "resumable", False))
|
||||
req_state = OrchestratorRequestState(
|
||||
request_id=request_id,
|
||||
prompt=original_prompt,
|
||||
sampling_params_list=sampling_params_list,
|
||||
final_stage_id=final_stage_id,
|
||||
mm_features=getattr(prompt, "mm_features", None), # Save mm_features for PD
|
||||
)
|
||||
req_state.streaming.enabled = is_streaming
|
||||
req_state.stage_submit_ts[stage_id] = _time.time()
|
||||
self.request_states[request_id] = req_state
|
||||
|
||||
# Stage-0 prompt is already a fully-formed OmniEngineCoreRequest
|
||||
# (pre-processed by AsyncOmniEngine.add_request, output processor
|
||||
# already registered there) - submit directly.
|
||||
request = prompt
|
||||
stage_client = self.stage_clients[stage_id]
|
||||
if stage_client.stage_type == "diffusion":
|
||||
if isinstance(prompt, list):
|
||||
@@ -712,6 +921,7 @@ class Orchestrator:
|
||||
|
||||
if "sampling_params_list" in msg and msg["sampling_params_list"]:
|
||||
req_state.sampling_params_list = msg["sampling_params_list"]
|
||||
req_state.streaming.enabled = True
|
||||
|
||||
req_state.stage_submit_ts[stage_id] = _time.time()
|
||||
stage_client = self.stage_clients[stage_id]
|
||||
@@ -800,13 +1010,7 @@ class Orchestrator:
|
||||
companion_prompt = msg["prompt"]
|
||||
sampling_params_list = msg["sampling_params_list"]
|
||||
|
||||
# Register companion mapping
|
||||
if parent_id not in self._companion_map:
|
||||
self._companion_map[parent_id] = {}
|
||||
self._companion_map[parent_id][role] = companion_id
|
||||
self._companion_ids.add(companion_id)
|
||||
self._companion_to_parent[companion_id] = parent_id
|
||||
self._companion_done.setdefault(parent_id, set())
|
||||
self._cfg_tracker.register_companion(parent_id, role, companion_id)
|
||||
|
||||
companion_state = OrchestratorRequestState(
|
||||
request_id=companion_id,
|
||||
@@ -831,22 +1035,10 @@ class Orchestrator:
|
||||
async def _handle_abort(self, msg: dict[str, Any]) -> None:
|
||||
"""Handle an abort message from the main thread."""
|
||||
request_ids = msg["request_ids"]
|
||||
# Also abort any CFG companions for aborted parents
|
||||
companion_ids_to_abort: list[str] = []
|
||||
for req_id in request_ids:
|
||||
role_map = self._companion_map.pop(req_id, {})
|
||||
for cid in role_map.values():
|
||||
companion_ids_to_abort.append(cid)
|
||||
self._companion_ids.discard(cid)
|
||||
self._companion_to_parent.pop(cid, None)
|
||||
self.request_states.pop(cid, None)
|
||||
self._companion_done.pop(req_id, None)
|
||||
self._deferred_parents.pop(req_id, None)
|
||||
|
||||
all_ids_to_abort = list(request_ids) + companion_ids_to_abort
|
||||
all_ids_to_abort = self._cfg_tracker.abort_parents(request_ids)
|
||||
for stage_id in range(self.num_stages):
|
||||
await self.stage_clients[stage_id].abort_requests_async(all_ids_to_abort)
|
||||
for req_id in request_ids:
|
||||
for req_id in all_ids_to_abort:
|
||||
self.request_states.pop(req_id, None)
|
||||
logger.info("[Orchestrator] Aborted request(s) %s", request_ids)
|
||||
|
||||
@@ -915,6 +1107,53 @@ class Orchestrator:
|
||||
}
|
||||
)
|
||||
|
||||
async def _drain_pending_requests_on_fatal(self) -> None:
|
||||
"""Drain the request queue and broadcast fatal errors for any
|
||||
pending add_request messages that were never processed.
|
||||
|
||||
Called from the ``run()`` finally block when a fatal error
|
||||
(e.g. ``EngineDeadError``) caused the orchestrator to shut down
|
||||
before the request handler could process all queued messages.
|
||||
Also broadcasts for any already-tracked requests still in
|
||||
``request_states`` that were not yet notified.
|
||||
"""
|
||||
assert self._fatal_error is not None
|
||||
|
||||
notified: set[str] = set()
|
||||
|
||||
# 1) Drain pending messages from the request queue.
|
||||
while True:
|
||||
try:
|
||||
msg = self.request_async_queue.get_nowait()
|
||||
except Exception:
|
||||
break
|
||||
if msg.get("type") == "add_request":
|
||||
req_id = msg["request_id"]
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "error",
|
||||
"error": self._fatal_error,
|
||||
"fatal": True,
|
||||
"request_id": req_id,
|
||||
}
|
||||
)
|
||||
notified.add(req_id)
|
||||
|
||||
# 2) Broadcast for any tracked requests not already notified
|
||||
# (e.g. request was registered but the EngineDeadError handler
|
||||
# missed it because it wasn't submitted to the dead stage yet).
|
||||
for req_id in list(self.request_states):
|
||||
if req_id not in notified:
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "error",
|
||||
"error": self._fatal_error,
|
||||
"fatal": True,
|
||||
"request_id": req_id,
|
||||
}
|
||||
)
|
||||
self.request_states.pop(req_id, None)
|
||||
|
||||
def _shutdown_stages(self) -> None:
|
||||
"""Shutdown all stage clients."""
|
||||
if self._stages_shutdown:
|
||||
|
||||
Loaded 100 of 611 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user